@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.
- package/README.md +97 -6
- package/package.json +2 -2
- package/src/voip/WaVoipCoordinator.js +57 -1
- package/src/voip/call/WaCallManager.js +265 -6
- package/src/voip/call/WaCallMediaSession.js +929 -61
- 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 +212 -16
- package/src/voip/media/WaAudioEngine.js +35 -24
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/mlow-codec.js +12 -8
- package/src/voip/relay/WaManualRelay.js +504 -85
- package/src/voip/relay/relay-ack.js +66 -25
- package/src/voip/relay/sctp/association.js +14 -1
- package/src/voip/relay/stun.js +183 -16
- 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
|
@@ -15,6 +15,11 @@ export class CallInfo {
|
|
|
15
15
|
electedRelayIdx;
|
|
16
16
|
raisedHands = new Set();
|
|
17
17
|
peerScreenShare = null;
|
|
18
|
+
isGroup = false;
|
|
19
|
+
groupState = null;
|
|
20
|
+
waitingRoom = null;
|
|
21
|
+
linkToken = null;
|
|
22
|
+
linkUrl = null;
|
|
18
23
|
constructor(init) {
|
|
19
24
|
this.callId = init.callId;
|
|
20
25
|
this.peerJid = init.peerJid;
|
|
@@ -59,6 +64,27 @@ export class CallInfo {
|
|
|
59
64
|
}
|
|
60
65
|
});
|
|
61
66
|
}
|
|
67
|
+
static newGroupOutgoing(callId, callJid, ourJid, mediaType, groupJid) {
|
|
68
|
+
const info = CallInfo.newOutgoing(callId, callJid, ourJid, mediaType);
|
|
69
|
+
info.isGroup = true;
|
|
70
|
+
info.groupJid = groupJid;
|
|
71
|
+
return info;
|
|
72
|
+
}
|
|
73
|
+
static newGroupIncoming(callId, callJid, callCreator, callerPn, mediaType, groupJid) {
|
|
74
|
+
const info = CallInfo.newIncoming(callId, callJid, callCreator, callerPn, mediaType);
|
|
75
|
+
info.isGroup = true;
|
|
76
|
+
info.groupJid = groupJid;
|
|
77
|
+
return info;
|
|
78
|
+
}
|
|
79
|
+
static newLinkJoin(callId, callJid, ourJid, mediaType, linkToken) {
|
|
80
|
+
const info = CallInfo.newOutgoing(callId, callJid, ourJid, mediaType);
|
|
81
|
+
info.isGroup = true;
|
|
82
|
+
info.linkToken = linkToken;
|
|
83
|
+
return info;
|
|
84
|
+
}
|
|
85
|
+
get isWaiting() {
|
|
86
|
+
return this.stateData.state === CallState.WaitingRoom;
|
|
87
|
+
}
|
|
62
88
|
get isInitiator() {
|
|
63
89
|
return this.direction === CallDirection.Outgoing;
|
|
64
90
|
}
|
|
@@ -112,6 +138,25 @@ export class CallInfo {
|
|
|
112
138
|
s.state = CallState.Connecting;
|
|
113
139
|
s.acceptedAt = new Date();
|
|
114
140
|
break;
|
|
141
|
+
case 'group_joined':
|
|
142
|
+
if (s.state === CallState.Connecting) {
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
if (![CallState.Initiating, CallState.Ringing, CallState.IncomingRinging, CallState.WaitingRoom].includes(s.state)) {
|
|
146
|
+
throw new InvalidTransition(s.state, transition.type);
|
|
147
|
+
}
|
|
148
|
+
s.state = CallState.Connecting;
|
|
149
|
+
s.acceptedAt = new Date();
|
|
150
|
+
break;
|
|
151
|
+
case 'waiting_room_entered':
|
|
152
|
+
if (s.state === CallState.WaitingRoom) {
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
if (s.state !== CallState.Initiating && s.state !== CallState.Connecting) {
|
|
156
|
+
throw new InvalidTransition(s.state, transition.type);
|
|
157
|
+
}
|
|
158
|
+
s.state = CallState.WaitingRoom;
|
|
159
|
+
break;
|
|
115
160
|
case 'remote_rejected':
|
|
116
161
|
if (s.state !== CallState.Ringing) {
|
|
117
162
|
throw new InvalidTransition(s.state, transition.type);
|
package/src/voip/crypto/rtcp.js
CHANGED
|
@@ -27,6 +27,12 @@ export class SrtcpSendContext {
|
|
|
27
27
|
this.#salt = deriveKey(keying.masterKey, keying.masterSalt, SRTCP_LABEL.SALT, 14);
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
rekey(keying) {
|
|
31
|
+
this.#cipherKey = deriveKey(keying.masterKey, keying.masterSalt, SRTCP_LABEL.ENCRYPTION, 16);
|
|
32
|
+
this.#authKey = deriveKey(keying.masterKey, keying.masterSalt, SRTCP_LABEL.AUTH, 20);
|
|
33
|
+
this.#salt = deriveKey(keying.masterKey, keying.masterSalt, SRTCP_LABEL.SALT, 14);
|
|
34
|
+
}
|
|
35
|
+
|
|
30
36
|
#generateIv(ssrc, roc, seq) {
|
|
31
37
|
this.#ivBuffer.fill(0);
|
|
32
38
|
this.#ivBuffer.set(this.#salt.subarray(0, 14), 0);
|
package/src/voip/crypto/srtp.js
CHANGED
|
@@ -28,6 +28,11 @@ export class SrtpContext {
|
|
|
28
28
|
setAuthKeying(keying) {
|
|
29
29
|
this.authKey = deriveKey(keying.masterKey, keying.masterSalt, SRTP_LABEL.AUTH, 20);
|
|
30
30
|
}
|
|
31
|
+
rekey(keying) {
|
|
32
|
+
this.sessionKey = deriveKey(keying.masterKey, keying.masterSalt, SRTP_LABEL.ENCRYPTION, 16);
|
|
33
|
+
this.authKey = deriveKey(keying.masterKey, keying.masterSalt, SRTP_LABEL.AUTH, 20);
|
|
34
|
+
this.sessionSalt = deriveKey(keying.masterKey, keying.masterSalt, SRTP_LABEL.SALT, 14);
|
|
35
|
+
}
|
|
31
36
|
protect(packet) {
|
|
32
37
|
this.updateRoc(packet.header.sequenceNumber);
|
|
33
38
|
const index = this.packetIndex(packet.header.sequenceNumber);
|
package/src/voip/crypto/ssrc.js
CHANGED
|
@@ -13,3 +13,13 @@ export const WASM_RELAY_STREAM_SLOT_WORDS = [0, 1, 4, 2, 3, 5, 7, 8, 6];
|
|
|
13
13
|
export function deriveWasmRelayStreamSsrcs(callId, participantId) {
|
|
14
14
|
return WASM_RELAY_STREAM_SLOT_WORDS.map((slotWord) => generateSecureSsrc(callId, participantId, slotWord));
|
|
15
15
|
}
|
|
16
|
+
export function formatParticipantId(jid) {
|
|
17
|
+
const bare = String(jid ?? '').split('/')[0].trim();
|
|
18
|
+
const at = bare.lastIndexOf('@');
|
|
19
|
+
if (at <= 0) {
|
|
20
|
+
return bare;
|
|
21
|
+
}
|
|
22
|
+
const user = bare.slice(0, at);
|
|
23
|
+
const domain = bare.slice(at + 1);
|
|
24
|
+
return domain === 'lid' && !user.includes(':') ? `${user}:0@${domain}` : bare;
|
|
25
|
+
}
|
package/src/voip/index.js
CHANGED
|
@@ -60,13 +60,19 @@ async function downloadToTemp(url, extHint, maxBytes, tmpDirOverride) {
|
|
|
60
60
|
signal: AbortSignal.timeout(30_000),
|
|
61
61
|
});
|
|
62
62
|
if (!response.ok)
|
|
63
|
-
throw new Error(`Download failed
|
|
64
|
-
const declared = Number(response.headers.get('content-length')
|
|
65
|
-
if (declared && declared > maxBytes)
|
|
66
|
-
throw new Error(`Download
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
63
|
+
throw new Error(`Download failed with HTTP ${response.status}: ${url}`);
|
|
64
|
+
const declared = Number(response.headers.get('content-length'));
|
|
65
|
+
if (Number.isFinite(declared) && declared > maxBytes)
|
|
66
|
+
throw new Error(`Download exceeds ${maxBytes} bytes: ${url}`);
|
|
67
|
+
const chunks = [];
|
|
68
|
+
let total = 0;
|
|
69
|
+
for await (const chunk of response.body) {
|
|
70
|
+
total += chunk.length;
|
|
71
|
+
if (total > maxBytes)
|
|
72
|
+
throw new Error(`Download exceeds ${maxBytes} bytes: ${url}`);
|
|
73
|
+
chunks.push(chunk);
|
|
74
|
+
}
|
|
75
|
+
const data = Buffer.concat(chunks, total);
|
|
70
76
|
const os = await import('node:os');
|
|
71
77
|
const tmpDir = tmpDirOverride || os.tmpdir();
|
|
72
78
|
if (!fs.existsSync(tmpDir))
|
|
@@ -177,6 +183,7 @@ class VoipCall extends EventEmitter {
|
|
|
177
183
|
#startVideoOnFirst;
|
|
178
184
|
#videoDown = false;
|
|
179
185
|
#silenced = false;
|
|
186
|
+
#members = new Set();
|
|
180
187
|
#normalize = null;
|
|
181
188
|
#itemDeadline = 0;
|
|
182
189
|
#itemRemainingMs = null;
|
|
@@ -204,6 +211,16 @@ class VoipCall extends EventEmitter {
|
|
|
204
211
|
activeCall.on('ended', (reason) => this._finish(reason));
|
|
205
212
|
activeCall.on('audio_finished', () => this._onAudioFinished());
|
|
206
213
|
activeCall.on('error', (err) => this.emit('error', err));
|
|
214
|
+
activeCall.on('group_state', (state) => {
|
|
215
|
+
const change = participantChanges(this.#members, state?.participants ?? []);
|
|
216
|
+
this.#members = change.members;
|
|
217
|
+
if (change.added.length || change.removed.length) {
|
|
218
|
+
this.emit('participants_changed', {
|
|
219
|
+
added: change.added.map((participant) => ({ number: numberOf(participant), jid: participant.jid, state: participant.state })),
|
|
220
|
+
removed: change.removed.map((key) => ({ number: key })),
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
});
|
|
207
224
|
activeCall.on('peer_video', (change) => {
|
|
208
225
|
this._onPeerVideo(change).catch((err) => this.emit('error', err));
|
|
209
226
|
});
|
|
@@ -215,7 +232,7 @@ class VoipCall extends EventEmitter {
|
|
|
215
232
|
this.emit('connected');
|
|
216
233
|
this._advance().catch((err) => this.emit('error', err));
|
|
217
234
|
}
|
|
218
|
-
for (const ev of ['peer_mute', 'hand_raise', 'reaction', 'screen_share', 'peer_video', 'inbound_audio', 'inbound_video', 'audio_finished', 'reconnecting', 'reconnected']) {
|
|
235
|
+
for (const ev of ['peer_mute', 'hand_raise', 'reaction', 'screen_share', 'peer_video', 'inbound_audio', 'inbound_video', 'audio_finished', 'reconnecting', 'reconnected', 'group_state', 'waiting_room', 'participant_audio']) {
|
|
219
236
|
activeCall.on(ev, (...args) => this.emit(ev, ...args));
|
|
220
237
|
}
|
|
221
238
|
}
|
|
@@ -237,6 +254,42 @@ class VoipCall extends EventEmitter {
|
|
|
237
254
|
react(emoji) {
|
|
238
255
|
return this.#activeCall?.react(emoji) ?? false;
|
|
239
256
|
}
|
|
257
|
+
get isGroup() {
|
|
258
|
+
return this.#activeCall?.isGroup ?? false;
|
|
259
|
+
}
|
|
260
|
+
get link() {
|
|
261
|
+
return this.#coordinator?.getCall(this.callId)?.linkUrl ?? null;
|
|
262
|
+
}
|
|
263
|
+
get participants() {
|
|
264
|
+
return this.#activeCall?.participants ?? [];
|
|
265
|
+
}
|
|
266
|
+
get waitingRoom() {
|
|
267
|
+
return this.#activeCall?.waitingRoom ?? null;
|
|
268
|
+
}
|
|
269
|
+
get connected() {
|
|
270
|
+
return !!this.#activeCall?.connected;
|
|
271
|
+
}
|
|
272
|
+
get ended() {
|
|
273
|
+
return this.#ended;
|
|
274
|
+
}
|
|
275
|
+
get silenced() {
|
|
276
|
+
return this.#silenced;
|
|
277
|
+
}
|
|
278
|
+
addParticipant(target) {
|
|
279
|
+
return this.#activeCall?.addParticipant(target);
|
|
280
|
+
}
|
|
281
|
+
ringParticipant(target) {
|
|
282
|
+
return this.#activeCall?.ringParticipant(target);
|
|
283
|
+
}
|
|
284
|
+
setApprovalRequired(enabled) {
|
|
285
|
+
return this.#activeCall?.setApprovalRequired(enabled);
|
|
286
|
+
}
|
|
287
|
+
admit(jid) {
|
|
288
|
+
return this.#activeCall?.admit(jid);
|
|
289
|
+
}
|
|
290
|
+
deny(jid) {
|
|
291
|
+
return this.#activeCall?.deny(jid);
|
|
292
|
+
}
|
|
240
293
|
async upgradeToVideo() {
|
|
241
294
|
await this.#activeCall?.upgradeToVideo();
|
|
242
295
|
this.#videoDown = false;
|
|
@@ -457,7 +510,7 @@ class VoipCall extends EventEmitter {
|
|
|
457
510
|
}
|
|
458
511
|
}
|
|
459
512
|
|
|
460
|
-
export
|
|
513
|
+
export class Voip {
|
|
461
514
|
#conn;
|
|
462
515
|
#client = null;
|
|
463
516
|
#clientForConn = null;
|
|
@@ -470,8 +523,8 @@ export default class Voip {
|
|
|
470
523
|
constructor(conn, opts = {}) {
|
|
471
524
|
this.#conn = conn;
|
|
472
525
|
this.#ffprobePath = opts.ffprobePath || 'ffprobe';
|
|
473
|
-
this.#voipLogLevel = opts.voipLogLevel ?? 'warn';
|
|
474
|
-
this.#maxConcurrentCalls = opts.maxConcurrentCalls ??
|
|
526
|
+
this.#voipLogLevel = opts.voipLogLevel ?? opts.level ?? 'warn';
|
|
527
|
+
this.#maxConcurrentCalls = opts.maxConcurrentCalls ?? Number.MAX_SAFE_INTEGER;
|
|
475
528
|
if (!Number.isSafeInteger(this.#maxConcurrentCalls) || this.#maxConcurrentCalls < 1)
|
|
476
529
|
throw new Error('maxConcurrentCalls must be a positive integer.');
|
|
477
530
|
this.#tmpDir = opts.tmpDir;
|
|
@@ -530,16 +583,27 @@ export default class Voip {
|
|
|
530
583
|
await this.listen();
|
|
531
584
|
return this.coordinator.rejectCall(callId, reason);
|
|
532
585
|
}
|
|
533
|
-
|
|
534
|
-
return (this.coordinator?.getCalls() ?? [])
|
|
586
|
+
incoming() {
|
|
587
|
+
return (this.coordinator?.getCalls() ?? [])
|
|
588
|
+
.filter((info) => info.direction === CallDirection.Incoming && info.isRinging)
|
|
589
|
+
.map((info) => ({
|
|
590
|
+
id: info.callId,
|
|
591
|
+
from: numberOf({ pn: info.callerPn, jid: info.peerJid }),
|
|
592
|
+
isVideo: info.mediaType === CallMediaType.Video,
|
|
593
|
+
isGroup: info.isGroup,
|
|
594
|
+
canAccept: info.canAccept,
|
|
595
|
+
}));
|
|
535
596
|
}
|
|
536
597
|
onIncoming(listener) {
|
|
537
598
|
const coordinator = this.#requireCoordinator();
|
|
538
599
|
const wrapped = (info) => listener({
|
|
600
|
+
id: info.callId,
|
|
601
|
+
from: numberOf({ pn: info.callerPn, jid: info.peerJid }),
|
|
539
602
|
callId: info.callId,
|
|
540
603
|
jid: info.peerJid,
|
|
541
604
|
creator: info.callCreator,
|
|
542
605
|
isVideo: info.mediaType === CallMediaType.Video,
|
|
606
|
+
isGroup: info.isGroup,
|
|
543
607
|
canAccept: info.canAccept,
|
|
544
608
|
info,
|
|
545
609
|
});
|
|
@@ -601,7 +665,7 @@ export default class Voip {
|
|
|
601
665
|
});
|
|
602
666
|
this.#calls.add(call);
|
|
603
667
|
releaseReservation();
|
|
604
|
-
scheduleSafety(105_000);
|
|
668
|
+
scheduleSafety(options.safetyMs ?? 105_000);
|
|
605
669
|
let activeCall;
|
|
606
670
|
try {
|
|
607
671
|
activeCall = await begin(client, first, videoConfig);
|
|
@@ -644,6 +708,50 @@ export default class Voip {
|
|
|
644
708
|
: { jid: list[index], error: result.reason });
|
|
645
709
|
}
|
|
646
710
|
|
|
711
|
+
async groupCall(targets, media, resolution, options = {}) {
|
|
712
|
+
this.#assertCapacity();
|
|
713
|
+
const list = [...new Set((Array.isArray(targets) ? targets : [targets]).map((target) => String(target ?? '').trim()).filter(Boolean))];
|
|
714
|
+
if (list.length < 2)
|
|
715
|
+
throw new Error('A group call needs at least two participants besides yourself.');
|
|
716
|
+
await this.listen();
|
|
717
|
+
return this.#launch(list.join(','), media, resolution, options, (client, first, videoConfig) => client.groupCall(list, {
|
|
718
|
+
groupJid: options.groupJid,
|
|
719
|
+
audioSource: first.source,
|
|
720
|
+
isVideo: first.kind === 'video',
|
|
721
|
+
...(first.kind === 'video' ? { videoSource: first.source } : {}),
|
|
722
|
+
durationMs: 0,
|
|
723
|
+
videoConfig,
|
|
724
|
+
}));
|
|
725
|
+
}
|
|
726
|
+
async getLink(callOrId) {
|
|
727
|
+
return this.#requireCoordinator().getCallLink(typeof callOrId === 'object' ? callOrId?.callId : callOrId);
|
|
728
|
+
}
|
|
729
|
+
async previewLink(link, options = {}) {
|
|
730
|
+
await this.listen();
|
|
731
|
+
return this.#getClient().queryLink(link, { isVideo: options.isVideo });
|
|
732
|
+
}
|
|
733
|
+
async joinLink(link, media, resolution, options = {}) {
|
|
734
|
+
this.#assertCapacity();
|
|
735
|
+
await this.listen();
|
|
736
|
+
return this.#launch(String(link), media, resolution, { ...options, safetyMs: options.safetyMs ?? 10 * 60_000 }, (client, first, videoConfig) => client.joinLink(link, {
|
|
737
|
+
audioSource: first.source,
|
|
738
|
+
isVideo: options.isVideo,
|
|
739
|
+
...(first.kind === 'video' ? { videoSource: first.source } : {}),
|
|
740
|
+
durationMs: 0,
|
|
741
|
+
videoConfig,
|
|
742
|
+
}));
|
|
743
|
+
}
|
|
744
|
+
async createRoom(media, resolution, options = {}) {
|
|
745
|
+
await this.listen();
|
|
746
|
+
const link = await this.#getClient().createLink({ isVideo: options.isVideo ?? detectKind(String((Array.isArray(media) ? media[0] : media) ?? '')) === 'video' });
|
|
747
|
+
const call = await this.joinLink(link.url, media, resolution, { autoEndCall: false, ...options, isVideo: link.isVideo });
|
|
748
|
+
if (options.requireApproval !== undefined) {
|
|
749
|
+
call.once('connected', () => {
|
|
750
|
+
Promise.resolve(call.setApprovalRequired(!!options.requireApproval)).catch((err) => call.emit('error', err));
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
return call;
|
|
754
|
+
}
|
|
647
755
|
async listen() {
|
|
648
756
|
await this.#getClient().connect();
|
|
649
757
|
return this;
|
|
@@ -675,11 +783,99 @@ export default class Voip {
|
|
|
675
783
|
throw new Error('Call listen() first.');
|
|
676
784
|
return this.coordinator;
|
|
677
785
|
}
|
|
678
|
-
|
|
679
|
-
|
|
786
|
+
#find(id) {
|
|
787
|
+
return [...this.#calls].find((call) => call.callId === String(id)) ?? null;
|
|
788
|
+
}
|
|
789
|
+
#require(id) {
|
|
790
|
+
const call = this.#find(id);
|
|
791
|
+
if (!call)
|
|
792
|
+
throw new Error(`No active call with id ${id}.`);
|
|
793
|
+
return call;
|
|
794
|
+
}
|
|
795
|
+
activeCalls() {
|
|
796
|
+
return [...this.#calls].filter((call) => call.callId).map(summarizeCall);
|
|
797
|
+
}
|
|
798
|
+
info(id) {
|
|
799
|
+
const call = this.#find(id);
|
|
800
|
+
return call ? describeCall(call) : null;
|
|
801
|
+
}
|
|
802
|
+
silent(id, value) {
|
|
803
|
+
return this.#require(id).silent(value);
|
|
804
|
+
}
|
|
805
|
+
mute(id, value = true) {
|
|
806
|
+
return this.#require(id).mute(value);
|
|
807
|
+
}
|
|
808
|
+
react(id, emoji) {
|
|
809
|
+
return this.#require(id).react(emoji);
|
|
810
|
+
}
|
|
811
|
+
hand(id, value = true) {
|
|
812
|
+
return this.#require(id).raiseHand(value);
|
|
813
|
+
}
|
|
814
|
+
add(id, number) {
|
|
815
|
+
return this.#require(id).addParticipant(number);
|
|
816
|
+
}
|
|
817
|
+
admit(id, jid) {
|
|
818
|
+
return this.#require(id).admit(jid);
|
|
819
|
+
}
|
|
820
|
+
deny(id, jid) {
|
|
821
|
+
return this.#require(id).deny(jid);
|
|
822
|
+
}
|
|
823
|
+
approval(id, enabled) {
|
|
824
|
+
return this.#require(id).setApprovalRequired(enabled);
|
|
825
|
+
}
|
|
826
|
+
link(id) {
|
|
827
|
+
return this.#require(id).link;
|
|
828
|
+
}
|
|
829
|
+
async end(target = false) {
|
|
830
|
+
if (typeof target === 'string')
|
|
831
|
+
return this.#require(target).hangup();
|
|
832
|
+
if (target) {
|
|
680
833
|
this.#calls.clear();
|
|
681
834
|
return;
|
|
682
835
|
}
|
|
683
836
|
await Promise.all([...this.#calls].map((call) => call.hangup()));
|
|
684
837
|
}
|
|
685
838
|
}
|
|
839
|
+
|
|
840
|
+
function numberOf(entry) {
|
|
841
|
+
return String(entry?.pn || entry?.jid || '').split('@')[0].split(':')[0];
|
|
842
|
+
}
|
|
843
|
+
function accountOf(entry) {
|
|
844
|
+
return String(entry?.jid || '').split('@')[0].split(':')[0];
|
|
845
|
+
}
|
|
846
|
+
const joinedStates = new Set(['connected', 'receipt', 'outgoing', 'creating', 'visible', 'invisible']);
|
|
847
|
+
function participantChanges(members, participants) {
|
|
848
|
+
const joined = participants.filter((participant) => !participant.isSelf && joinedStates.has(participant.state));
|
|
849
|
+
const keys = new Set(joined.map(accountOf));
|
|
850
|
+
return {
|
|
851
|
+
members: keys,
|
|
852
|
+
added: joined.filter((participant) => !members.has(accountOf(participant))),
|
|
853
|
+
removed: [...members].filter((key) => !keys.has(key)),
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
function kindOf(call) {
|
|
857
|
+
if (call.link)
|
|
858
|
+
return 'link';
|
|
859
|
+
return call.isGroup ? 'group' : 'direct';
|
|
860
|
+
}
|
|
861
|
+
function summarizeCall(call) {
|
|
862
|
+
return {
|
|
863
|
+
id: call.callId,
|
|
864
|
+
kind: kindOf(call),
|
|
865
|
+
connected: call.connected,
|
|
866
|
+
silenced: call.silenced,
|
|
867
|
+
ended: call.ended,
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
function describeCall(call) {
|
|
871
|
+
return {
|
|
872
|
+
...summarizeCall(call),
|
|
873
|
+
link: call.link,
|
|
874
|
+
target: call.target,
|
|
875
|
+
participants: call.participants
|
|
876
|
+
.filter((participant) => participant.state !== 'terminated' && participant.state !== 'invalid')
|
|
877
|
+
.map((participant) => ({ number: numberOf(participant), state: participant.state, self: !!participant.isSelf })),
|
|
878
|
+
waiting: (call.waitingRoom?.users ?? []).map((user) => numberOf(user)),
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
export default Voip;
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { execFile, spawn } from 'node:child_process';
|
|
2
2
|
import { access } from 'node:fs/promises';
|
|
3
3
|
import { createNoopLogger } from '../shim/core.js';
|
|
4
|
-
import {
|
|
5
|
-
import { concatBytes, TEXT_DECODER } from '../bytes.js';
|
|
4
|
+
import { TEXT_DECODER } from '../bytes.js';
|
|
6
5
|
import { DEFAULT_AUDIO_CONFIG } from '../types.js';
|
|
7
6
|
const FFMPEG_BIN = 'ffmpeg';
|
|
8
7
|
const MAX_DECODE_BYTES = 128 * 1024 * 1024;
|
|
@@ -48,6 +47,7 @@ export class WaAudioEngine {
|
|
|
48
47
|
logger;
|
|
49
48
|
audioSender = null;
|
|
50
49
|
audioBuffer = null;
|
|
50
|
+
audioScale = 1;
|
|
51
51
|
audioPosition = 0;
|
|
52
52
|
audioFinished = false;
|
|
53
53
|
onAudioFinished = null;
|
|
@@ -101,6 +101,7 @@ export class WaAudioEngine {
|
|
|
101
101
|
this.extMaxBuffer = Math.floor(this.sampleRate);
|
|
102
102
|
this.streamPreBufferSize = Math.floor(this.sampleRate * 0.3);
|
|
103
103
|
this.streamHighWater = Math.floor(this.sampleRate * 0.6);
|
|
104
|
+
this.streamMaxBacklog = Math.floor(this.sampleRate * 1);
|
|
104
105
|
}
|
|
105
106
|
setAudioSender(sender) {
|
|
106
107
|
this.audioSender = sender;
|
|
@@ -117,6 +118,7 @@ export class WaAudioEngine {
|
|
|
117
118
|
this.extStarted = false;
|
|
118
119
|
if (enabled) {
|
|
119
120
|
this.audioBuffer = new Float32Array(this.extMaxBuffer);
|
|
121
|
+
this.audioScale = 1;
|
|
120
122
|
this.audioPosition = 0;
|
|
121
123
|
this.liveWritePos = 0;
|
|
122
124
|
this.audioFinished = false;
|
|
@@ -187,18 +189,12 @@ export class WaAudioEngine {
|
|
|
187
189
|
if (!(await hasFfmpeg(FFMPEG_BIN))) {
|
|
188
190
|
throw new Error('ffmpeg not found on PATH (install ffmpeg to load audio files)');
|
|
189
191
|
}
|
|
190
|
-
|
|
191
|
-
this.audioBuffer = this.
|
|
192
|
+
this.audioBuffer = null;
|
|
193
|
+
this.audioBuffer = await this.decodeWithFFmpeg(audioPath);
|
|
194
|
+
this.audioScale = 1 / 32768;
|
|
192
195
|
this.audioPosition = 0;
|
|
193
196
|
this.audioFinished = false;
|
|
194
197
|
}
|
|
195
|
-
int16ToFloat32(pcmData) {
|
|
196
|
-
const float32 = new Float32Array(pcmData.length);
|
|
197
|
-
for (let i = 0; i < pcmData.length; i++) {
|
|
198
|
-
float32[i] = pcmData[i] / 32768.0;
|
|
199
|
-
}
|
|
200
|
-
return float32;
|
|
201
|
-
}
|
|
202
198
|
async decodeWithFFmpeg(inputPath) {
|
|
203
199
|
return new Promise((resolve, reject) => {
|
|
204
200
|
const proc = spawn(FFMPEG_BIN, [
|
|
@@ -217,7 +213,7 @@ export class WaAudioEngine {
|
|
|
217
213
|
's16le',
|
|
218
214
|
'pipe:1'
|
|
219
215
|
], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
220
|
-
|
|
216
|
+
let pcm = Buffer.allocUnsafeSlow(1 << 20);
|
|
221
217
|
let decodedBytes = 0;
|
|
222
218
|
let stderr = '';
|
|
223
219
|
let aborted = false;
|
|
@@ -231,7 +227,12 @@ export class WaAudioEngine {
|
|
|
231
227
|
reject(new Error(`ffmpeg output exceeded ${MAX_DECODE_BYTES} bytes: ${inputPath}`));
|
|
232
228
|
return;
|
|
233
229
|
}
|
|
234
|
-
|
|
230
|
+
if (decodedBytes > pcm.length) {
|
|
231
|
+
const grown = Buffer.allocUnsafeSlow(Math.max(pcm.length * 2, decodedBytes));
|
|
232
|
+
pcm.copy(grown, 0, 0, decodedBytes - chunk.length);
|
|
233
|
+
pcm = grown;
|
|
234
|
+
}
|
|
235
|
+
chunk.copy(pcm, decodedBytes - chunk.length);
|
|
235
236
|
});
|
|
236
237
|
proc.stderr?.on('data', (chunk) => {
|
|
237
238
|
stderr = (stderr + TEXT_DECODER.decode(chunk)).slice(0, MAX_STDERR_CHARS);
|
|
@@ -244,14 +245,16 @@ export class WaAudioEngine {
|
|
|
244
245
|
reject(new Error(`ffmpeg exited with code ${code}: ${stderr.trim()}`));
|
|
245
246
|
return;
|
|
246
247
|
}
|
|
247
|
-
const
|
|
248
|
-
resolve(new Int16Array(
|
|
248
|
+
const exact = pcm.length - decodedBytes > 1048576 ? Buffer.from(pcm.subarray(0, decodedBytes - (decodedBytes % 2))) : pcm;
|
|
249
|
+
resolve(new Int16Array(exact.buffer, exact.byteOffset, (exact === pcm ? decodedBytes : exact.length) >> 1));
|
|
250
|
+
pcm = null;
|
|
249
251
|
});
|
|
250
252
|
});
|
|
251
253
|
}
|
|
252
254
|
generateTestTone(frequency = 440, duration = 3, amplitude = 0.3) {
|
|
253
255
|
const samples = this.sampleRate * duration;
|
|
254
256
|
this.audioBuffer = new Float32Array(samples);
|
|
257
|
+
this.audioScale = 1;
|
|
255
258
|
this.audioPosition = 0;
|
|
256
259
|
this.audioFinished = false;
|
|
257
260
|
for (let i = 0; i < samples; i++) {
|
|
@@ -267,6 +270,8 @@ export class WaAudioEngine {
|
|
|
267
270
|
if (WaAudioEngine.isRemoteSource(source)) {
|
|
268
271
|
args.push('-user_agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0', '-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5');
|
|
269
272
|
}
|
|
273
|
+
if (/\.m3u8/i.test(source))
|
|
274
|
+
args.push('-live_start_index', '-1');
|
|
270
275
|
args.push('-i', source, '-vn', '-map', '0:a:0', '-ac', '1', '-ar', String(this.sampleRate), '-acodec', 'pcm_s16le', '-f', 's16le', 'pipe:1');
|
|
271
276
|
const proc = spawn(FFMPEG_BIN, args, { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
272
277
|
this.streamProc = proc;
|
|
@@ -327,15 +332,14 @@ export class WaAudioEngine {
|
|
|
327
332
|
this.streamQueue.shift();
|
|
328
333
|
}
|
|
329
334
|
}
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
+
let queued = 0;
|
|
336
|
+
for (const chunk of this.streamQueue)
|
|
337
|
+
queued += chunk.length;
|
|
338
|
+
if (queued > this.streamMaxBacklog) {
|
|
339
|
+
proc.stdout?.pause();
|
|
335
340
|
}
|
|
336
|
-
else
|
|
337
|
-
|
|
338
|
-
proc.stdout.resume();
|
|
341
|
+
else {
|
|
342
|
+
proc.stdout?.resume();
|
|
339
343
|
}
|
|
340
344
|
}
|
|
341
345
|
isStreamFinished() {
|
|
@@ -427,6 +431,13 @@ export class WaAudioEngine {
|
|
|
427
431
|
this.stopCapture();
|
|
428
432
|
this.stopStream();
|
|
429
433
|
}
|
|
434
|
+
release() {
|
|
435
|
+
this.stop();
|
|
436
|
+
this.audioBuffer = null;
|
|
437
|
+
this.audioPosition = 0;
|
|
438
|
+
this.liveWritePos = 0;
|
|
439
|
+
this.resetBuffer();
|
|
440
|
+
}
|
|
430
441
|
hasAudio() {
|
|
431
442
|
return this.audioBuffer !== null && this.audioBuffer.length > 0;
|
|
432
443
|
}
|
|
@@ -506,7 +517,7 @@ export class WaAudioEngine {
|
|
|
506
517
|
}
|
|
507
518
|
break;
|
|
508
519
|
}
|
|
509
|
-
this.captureChunkBuffer[i] = this.audioBuffer[this.audioPosition];
|
|
520
|
+
this.captureChunkBuffer[i] = this.audioBuffer[this.audioPosition] * this.audioScale;
|
|
510
521
|
this.audioPosition++;
|
|
511
522
|
}
|
|
512
523
|
return this.captureChunkBuffer;
|
|
Binary file
|
|
@@ -8,7 +8,6 @@ const APPLICATION_VOIP = 2048;
|
|
|
8
8
|
const SIGNAL_VOICE = 3001;
|
|
9
9
|
const CONCEAL_QUANTUM = MLOW_SAMPLE_RATE / 400;
|
|
10
10
|
const DEFAULT_BITRATE = 24_000;
|
|
11
|
-
const DEFAULT_COMPLEXITY = 9;
|
|
12
11
|
const DEFAULT_MAX_CONCEAL_FRAMES = 5;
|
|
13
12
|
const MAX_LOSS_HINT = 20;
|
|
14
13
|
const SEQ_SPACE = 0x1_0000;
|
|
@@ -71,12 +70,17 @@ export class MLowCodec {
|
|
|
71
70
|
: DEFAULT_MAX_CONCEAL_FRAMES));
|
|
72
71
|
const lib = await loadMlowModule();
|
|
73
72
|
this.lib = lib;
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
73
|
+
if (!opts.encodeOnly) {
|
|
74
|
+
this.decoder = await lib.createDecoder({
|
|
75
|
+
channels: MLOW_CHANNELS,
|
|
76
|
+
sampleRate: MLOW_SAMPLE_RATE,
|
|
77
|
+
useSmpl: true,
|
|
78
|
+
maxFrameSize: MAX_FRAME_SIZE
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (opts.decodeOnly) {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
80
84
|
try {
|
|
81
85
|
this.encoderOptions = {
|
|
82
86
|
channels: MLOW_CHANNELS,
|
|
@@ -88,7 +92,7 @@ export class MLowCodec {
|
|
|
88
92
|
fec: opts.fec ?? true,
|
|
89
93
|
packetLossPercent: this.packetLossPercent,
|
|
90
94
|
bitrate: opts.bitrate ?? DEFAULT_BITRATE,
|
|
91
|
-
complexity: opts.complexity ??
|
|
95
|
+
complexity: opts.complexity ?? 5,
|
|
92
96
|
signal: SIGNAL_VOICE
|
|
93
97
|
};
|
|
94
98
|
this.encoder = await lib.createEncoder(this.encoderOptions);
|