lolka.js 0.4.4 → 0.5.2
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 +242 -12
- package/package.json +3 -5
- package/src/client/voice/AudioPlayer.js +358 -0
- package/src/client/voice/AudioResource.js +137 -0
- package/src/client/voice/VoiceConnection.js +296 -383
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libdatachannel.txt +373 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libjuice.txt +373 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libsrtp.txt +35 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-nlohmann-json.txt +21 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-node-addon-api.txt +9 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-node-api-headers.txt +21 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-openssl.txt +177 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-opus.txt +44 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-plog.txt +21 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-usrsctp.txt +27 -0
- package/src/client/voice/_lolka_voice/LICENSES/THIRD-PARTY.txt +16 -0
- package/src/client/voice/_lolka_voice/MANIFEST.json +47 -0
- package/src/client/voice/_lolka_voice/_loader.js +103 -0
- package/src/client/voice/_lolka_voice/_native/linux-aarch64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/linux-aarch64-musl/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/linux-x86_64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/linux-x86_64-musl/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/macos-arm64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/macos-x86_64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/windows-x86_64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_version.js +4 -0
- package/src/client/voice/_lolka_voice/caps.js +56 -0
- package/src/client/voice/_lolka_voice/core.d.ts +200 -0
- package/src/client/voice/_lolka_voice/errors.js +22 -0
- package/src/client/voice/_lolka_voice/events.js +119 -0
- package/src/client/voice/_lolka_voice/index.d.ts +226 -0
- package/src/client/voice/_lolka_voice/index.js +35 -0
- package/src/client/voice/_lolka_voice/player.js +606 -0
- package/src/client/voice/_lolka_voice/receive.js +387 -0
- package/src/client/voice/_lolka_voice/sdp.js +137 -0
- package/src/client/voice/_lolka_voice/session.js +335 -0
- package/src/client/voice/_lolka_voice/signaling.js +120 -0
- package/src/client/voice/_lolka_voice/transport.js +260 -0
- package/src/client/voice/media/OpusPlayback.js +199 -0
- package/src/client/voice/media/Receiver.js +245 -0
- package/src/client/voice/media/deps.js +27 -0
- package/src/index.js +11 -0
- package/typings/index.d.mts +248 -4
- package/typings/index.d.ts +248 -4
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Приём чужого звука. Порт RecvSession из Receiver.js lolka.js и RemoteAudio (внутренняя ручка консьюмера).
|
|
4
|
+
//
|
|
5
|
+
// Приём включается только по запросу: recv-транспорт создаётся, когда сессии нужно слушать (`requestReceive`).
|
|
6
|
+
// Ядро отдаёт Opus-пакеты как есть (MODE_OPUS), пачками раз в ≤ 40 мс: на пачку один Buffer с payload всех
|
|
7
|
+
// пакетов и Uint32Array [len, seq, ts]×n; слой режет `subarray` без копий. Пока слушателя нет (MODE_NONE),
|
|
8
|
+
// ядро не будит JS вообще.
|
|
9
|
+
|
|
10
|
+
const { debuglog } = require('node:util');
|
|
11
|
+
const { recvCapabilities } = require('./caps');
|
|
12
|
+
const { RecvTransport } = require('./transport');
|
|
13
|
+
|
|
14
|
+
const debug = debuglog('lolkajs-voice');
|
|
15
|
+
|
|
16
|
+
// режимы консьюмера в ядре; versions.test.js сверяет их с core.MODE_*
|
|
17
|
+
const MODE_NONE = 0;
|
|
18
|
+
const MODE_OPUS = 3;
|
|
19
|
+
|
|
20
|
+
const DEFAULT_MAX_CLOSED_SECTIONS = 128;
|
|
21
|
+
const CLOSE_GRACE_MS = 100;
|
|
22
|
+
|
|
23
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Входящий звук одного продюсера: переживает пересоздание recv-транспорта (меняются consumerId и ssrc).
|
|
27
|
+
* Пока `setListening(true)` не вызван, ядро не отдаёт пакеты и JS не просыпается.
|
|
28
|
+
*/
|
|
29
|
+
class RemoteAudio {
|
|
30
|
+
constructor({ userId, producerId, consumerId, ssrc, peerId = null }) {
|
|
31
|
+
this.userId = userId;
|
|
32
|
+
this.producerId = producerId;
|
|
33
|
+
this.consumerId = consumerId;
|
|
34
|
+
this.ssrc = ssrc;
|
|
35
|
+
this.peerId = peerId;
|
|
36
|
+
this.mode = MODE_NONE;
|
|
37
|
+
this.listening = false;
|
|
38
|
+
this.ended = false;
|
|
39
|
+
this.announced = false; // onTrack уже вызван
|
|
40
|
+
/** Пакетов выброшено: переполнение очереди ядра и накопленной пачки (нативные `dropped`). */
|
|
41
|
+
this.dropped = 0;
|
|
42
|
+
/**
|
|
43
|
+
* Колбэк владельца: пачка пакетов `[{ payload: Buffer, sequence, timestamp, ssrc }]` в порядке прихода.
|
|
44
|
+
* `payload` – `subarray` общей пачки, без копий.
|
|
45
|
+
* @type {((packets: Array<{ payload: Buffer, sequence: number, timestamp: number, ssrc: number }>) => void) | null}
|
|
46
|
+
*/
|
|
47
|
+
this.onPackets = null;
|
|
48
|
+
this._applyMode = null; // RecvSession: (remote, mode) => void
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Слушать (MODE_OPUS) или нет (MODE_NONE). Закончившийся звук режим не меняет. */
|
|
52
|
+
setListening(on) {
|
|
53
|
+
on = Boolean(on);
|
|
54
|
+
if (this.ended || on === this.listening) return;
|
|
55
|
+
this.listening = on;
|
|
56
|
+
this.mode = on ? MODE_OPUS : MODE_NONE;
|
|
57
|
+
this._applyMode?.(this, this.mode);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Пачка ядра. Событие после setListening(false) или после конца звука устарело: тихо игнорируется.
|
|
61
|
+
_receive(payload, meta, dropped, ssrc) {
|
|
62
|
+
if (this.ended || !this.listening) return;
|
|
63
|
+
this.dropped += dropped;
|
|
64
|
+
const packets = [];
|
|
65
|
+
let offset = 0;
|
|
66
|
+
for (let i = 0; i + 2 < meta.length; i += 3) {
|
|
67
|
+
const length = meta[i];
|
|
68
|
+
packets.push({ payload: payload.subarray(offset, offset + length), sequence: meta[i + 1], timestamp: meta[i + 2], ssrc });
|
|
69
|
+
offset += length;
|
|
70
|
+
}
|
|
71
|
+
if (packets.length === 0) return;
|
|
72
|
+
this.onPackets?.(packets);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
_end() {
|
|
76
|
+
if (this.ended) return;
|
|
77
|
+
this.ended = true;
|
|
78
|
+
this.listening = false;
|
|
79
|
+
this.mode = MODE_NONE;
|
|
80
|
+
this.onPackets = null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Recv-сессия с одним голосовым сервером: транспорт и консьюмеры.
|
|
86
|
+
*
|
|
87
|
+
* Закрытые консьюмеры остаются в SDP как `m=audio 0`; когда их больше порога, транспорт пересоздаётся
|
|
88
|
+
* (новый recv-транспорт, активные продюсеры consume заново, объекты RemoteAudio и их слушатели сохраняются,
|
|
89
|
+
* меняются только consumerId и ssrc).
|
|
90
|
+
*/
|
|
91
|
+
class RecvSession {
|
|
92
|
+
/**
|
|
93
|
+
* @param {Object} options
|
|
94
|
+
* @param {{ core: Object, router: import('./events').EventRouter }} options.runtime
|
|
95
|
+
* @param {(method: string, data?: Object) => Promise<Object>} options.request
|
|
96
|
+
* @param {Object} options.opus результат opusFromCaps()
|
|
97
|
+
* @param {string} options.name
|
|
98
|
+
* @param {(remote: RemoteAudio) => void} options.onTrack
|
|
99
|
+
* @param {(remote: RemoteAudio) => void} [options.onTrackEnded] продюсер закрылся (после `onTrack`)
|
|
100
|
+
* @param {(error: Error) => void} [options.onError] ошибки фоновых операций (закрытие, пересоздание)
|
|
101
|
+
* @param {number} [options.maxClosedSections]
|
|
102
|
+
*/
|
|
103
|
+
constructor({ runtime, request, opus, name, onTrack, onTrackEnded, onError, maxClosedSections = DEFAULT_MAX_CLOSED_SECTIONS }) {
|
|
104
|
+
this._runtime = runtime;
|
|
105
|
+
this._request = request;
|
|
106
|
+
this._opus = opus;
|
|
107
|
+
this._name = name;
|
|
108
|
+
this._onTrack = onTrack;
|
|
109
|
+
this._onTrackEnded = onTrackEnded ?? (() => {});
|
|
110
|
+
this._onError = onError ?? (() => {});
|
|
111
|
+
this._maxClosed = maxClosedSections;
|
|
112
|
+
this._consumers = new Map(); // producerId -> RemoteAudio
|
|
113
|
+
this._byConsumerId = new Map();
|
|
114
|
+
this._bySsrc = new Map();
|
|
115
|
+
this._pending = new Map(); // producerId -> { closed, consumerId, peerId, done }
|
|
116
|
+
this._transport = null;
|
|
117
|
+
this._starting = null;
|
|
118
|
+
this._rebuilding = null;
|
|
119
|
+
this._unroutes = new Map(); // транспорт -> отписка от событий opus
|
|
120
|
+
this.rebuilds = 0;
|
|
121
|
+
this.closed = false;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
get consumerCount() {
|
|
125
|
+
return this._consumers.size;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
get consumers() {
|
|
129
|
+
return this._consumers;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
get transport() {
|
|
133
|
+
return this._transport;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
start() {
|
|
137
|
+
this._starting = this._start();
|
|
138
|
+
return this._starting;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
_newTransport(params) {
|
|
142
|
+
const transport = new RecvTransport(this._runtime, { name: `${this._name}-recv`, params });
|
|
143
|
+
this._unroutes.set(
|
|
144
|
+
transport,
|
|
145
|
+
this._runtime.router.route('opus', transport.peer.id, ev => {
|
|
146
|
+
// событие закрытого транспорта устарело: маршрут снят в _closeTransport, здесь – запоздавшая пачка
|
|
147
|
+
if (!transport.closed) this._onOpus(ev);
|
|
148
|
+
}),
|
|
149
|
+
);
|
|
150
|
+
return transport;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
_closeTransport(transport) {
|
|
154
|
+
this._unroutes.get(transport)?.();
|
|
155
|
+
this._unroutes.delete(transport);
|
|
156
|
+
return transport.close();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async _start() {
|
|
160
|
+
const params = await this._request('createWebRtcTransport', { direction: 'recv', bwe: false });
|
|
161
|
+
if (this.closed) return;
|
|
162
|
+
this._transport = this._newTransport(params);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
_onOpus(ev) {
|
|
166
|
+
// SSRC консьюмера не равен SSRC продюсера: ищем по encodings[0].ssrc из ответа consume
|
|
167
|
+
const remote = this._bySsrc.get(ev[2]);
|
|
168
|
+
remote?._receive(ev[3], ev[4], ev[5], remote.ssrc);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
_setMode(remote, mode) {
|
|
172
|
+
this._transport?.setMode(remote.ssrc, mode);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async _ready() {
|
|
176
|
+
await this._starting;
|
|
177
|
+
while (this._rebuilding) await this._rebuilding;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Consume продюсера; закрытие продюсера по ходу тихо отменяет, ошибки пробрасываются. */
|
|
181
|
+
consume(producerId, userId, peerId = null) {
|
|
182
|
+
if (this.closed || this._consumers.has(producerId) || this._pending.has(producerId)) return Promise.resolve();
|
|
183
|
+
const entry = { closed: false, consumerId: null, peerId, done: null };
|
|
184
|
+
this._pending.set(producerId, entry);
|
|
185
|
+
entry.done = this._consume(entry, producerId, userId).finally(() => this._pending.delete(producerId));
|
|
186
|
+
return entry.done;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Закрытие продюсера/консьюмера во время consume: тихо выходим, трек не объявляем, ошибки не пробрасываем.
|
|
190
|
+
async _consume(entry, producerId, userId) {
|
|
191
|
+
const gone = () => this.closed || entry.closed;
|
|
192
|
+
// ответ-ошибка на consume может обогнать уведомление о закрытии продюсера: даём ему шанс дойти
|
|
193
|
+
const failed = async error => {
|
|
194
|
+
if (!gone()) await sleep(CLOSE_GRACE_MS);
|
|
195
|
+
if (gone()) return;
|
|
196
|
+
throw error;
|
|
197
|
+
};
|
|
198
|
+
await this._ready();
|
|
199
|
+
if (gone()) return;
|
|
200
|
+
const transport = this._transport;
|
|
201
|
+
let params;
|
|
202
|
+
try {
|
|
203
|
+
params = await this._request('consume', {
|
|
204
|
+
transportId: transport.params.id,
|
|
205
|
+
producerId,
|
|
206
|
+
rtpCapabilities: recvCapabilities(this._opus),
|
|
207
|
+
});
|
|
208
|
+
} catch (error) {
|
|
209
|
+
return failed(error);
|
|
210
|
+
}
|
|
211
|
+
entry.consumerId = params.id;
|
|
212
|
+
if (gone()) return;
|
|
213
|
+
const ssrc = params.rtpParameters.encodings[0].ssrc;
|
|
214
|
+
const remote = new RemoteAudio({
|
|
215
|
+
userId: userId === undefined || userId === null ? null : String(userId),
|
|
216
|
+
producerId,
|
|
217
|
+
consumerId: params.id,
|
|
218
|
+
ssrc,
|
|
219
|
+
peerId: entry.peerId,
|
|
220
|
+
});
|
|
221
|
+
remote._applyMode = (r, mode) => this._setMode(r, mode);
|
|
222
|
+
try {
|
|
223
|
+
await transport.addConsumer(params, this._request, remote.mode);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
return failed(error);
|
|
226
|
+
}
|
|
227
|
+
if (gone()) {
|
|
228
|
+
this._closeSection(transport, params.id);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
// привязка SSRC до resumeConsumer: первые пакеты не теряются (в lolka.js 0.5.0 привязка шла после resume)
|
|
232
|
+
this._consumers.set(producerId, remote);
|
|
233
|
+
this._byConsumerId.set(params.id, remote);
|
|
234
|
+
this._bySsrc.set(ssrc, remote);
|
|
235
|
+
try {
|
|
236
|
+
await this._request('resumeConsumer', { consumerId: params.id });
|
|
237
|
+
} catch (error) {
|
|
238
|
+
try {
|
|
239
|
+
await failed(error);
|
|
240
|
+
} finally {
|
|
241
|
+
this._discard(remote);
|
|
242
|
+
this._closeSection(transport, params.id);
|
|
243
|
+
}
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (gone() || this._consumers.get(producerId) !== remote) {
|
|
247
|
+
if (this._consumers.get(producerId) === remote) this._discard(remote);
|
|
248
|
+
this._closeSection(transport, params.id);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
remote.announced = true;
|
|
252
|
+
this._onTrack(remote);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
_discard(remote) {
|
|
256
|
+
if (this._consumers.get(remote.producerId) === remote) this._consumers.delete(remote.producerId);
|
|
257
|
+
this._byConsumerId.delete(remote.consumerId);
|
|
258
|
+
this._bySsrc.delete(remote.ssrc);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
producerClosed(producerId) {
|
|
262
|
+
const pending = this._pending.get(producerId);
|
|
263
|
+
if (pending) pending.closed = true;
|
|
264
|
+
const remote = this._consumers.get(producerId);
|
|
265
|
+
if (remote) this._drop(remote);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Участник вышел из комнаты: сервер шлёт peerClosed (producerClosed в этом случае нет).
|
|
269
|
+
peerClosed(peerId) {
|
|
270
|
+
if (!peerId) return;
|
|
271
|
+
for (const entry of this._pending.values()) if (entry.peerId === peerId) entry.closed = true;
|
|
272
|
+
for (const remote of [...this._consumers.values()]) if (remote.peerId === peerId) this._drop(remote);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
consumerClosed(consumerId) {
|
|
276
|
+
for (const entry of this._pending.values()) if (entry.consumerId === consumerId) entry.closed = true;
|
|
277
|
+
const remote = this._byConsumerId.get(consumerId);
|
|
278
|
+
if (remote) this._drop(remote);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Старый транспорт закрываем и на SFU (closeTransport), чтобы он не слал трафик в закрытый сокет.
|
|
282
|
+
// На SFU без этого метода ответ будет «неизвестный метод»: это только строка в debug-логе.
|
|
283
|
+
_closeServerTransport(transportId) {
|
|
284
|
+
this._request('closeTransport', { transportId }).catch(error => {
|
|
285
|
+
debug('closeTransport %s failed: %s', transportId, error?.message);
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// Пересогласование закрытой секции: сбой не важен, если транспорт уже закрыт или пересоздан.
|
|
290
|
+
_closeSection(transport, consumerId) {
|
|
291
|
+
transport.closeConsumer(consumerId, this._request).catch(error => {
|
|
292
|
+
if (!transport.closed && !this.closed) this._onError(error);
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
_drop(remote) {
|
|
297
|
+
this._discard(remote);
|
|
298
|
+
remote._end();
|
|
299
|
+
const transport = this._transport;
|
|
300
|
+
if (transport) {
|
|
301
|
+
this._closeSection(transport, remote.consumerId);
|
|
302
|
+
if (transport.closedCount > this._maxClosed) this._rebuild();
|
|
303
|
+
}
|
|
304
|
+
if (remote.announced) this._onTrackEnded(remote);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Пересоздание recv-стороны: новый транспорт, активные продюсеры consume заново, объекты сохраняются.
|
|
308
|
+
_rebuild() {
|
|
309
|
+
if (this._rebuilding || this.closed) return;
|
|
310
|
+
this._rebuilding = (async () => {
|
|
311
|
+
await Promise.allSettled([...this._pending.values()].map(entry => entry.done));
|
|
312
|
+
if (this.closed) return;
|
|
313
|
+
const params = await this._request('createWebRtcTransport', { direction: 'recv', bwe: false });
|
|
314
|
+
const fresh = this._newTransport(params);
|
|
315
|
+
try {
|
|
316
|
+
const bound = [];
|
|
317
|
+
for (const remote of [...this._consumers.values()]) {
|
|
318
|
+
if (this.closed) break;
|
|
319
|
+
try {
|
|
320
|
+
const consumer = await this._request('consume', {
|
|
321
|
+
transportId: params.id,
|
|
322
|
+
producerId: remote.producerId,
|
|
323
|
+
rtpCapabilities: recvCapabilities(this._opus),
|
|
324
|
+
});
|
|
325
|
+
await fresh.addConsumer(consumer, this._request, remote.mode);
|
|
326
|
+
await this._request('resumeConsumer', { consumerId: consumer.id });
|
|
327
|
+
bound.push([remote, consumer]);
|
|
328
|
+
} catch (error) {
|
|
329
|
+
// участник мог уйти за время пересоздания: уведомление о закрытии продюсера дойдёт с задержкой
|
|
330
|
+
await sleep(CLOSE_GRACE_MS);
|
|
331
|
+
if (this._consumers.get(remote.producerId) === remote) throw error;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
if (this.closed) throw new Error('voice session closed');
|
|
335
|
+
const old = this._transport;
|
|
336
|
+
this._transport = fresh;
|
|
337
|
+
for (const [remote, consumer] of bound) {
|
|
338
|
+
if (this._consumers.get(remote.producerId) !== remote) {
|
|
339
|
+
this._closeSection(fresh, consumer.id); // участник ушёл за время пересоздания
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
this._byConsumerId.delete(remote.consumerId);
|
|
343
|
+
this._bySsrc.delete(remote.ssrc);
|
|
344
|
+
remote.consumerId = consumer.id;
|
|
345
|
+
remote.ssrc = consumer.rtpParameters.encodings[0].ssrc;
|
|
346
|
+
this._byConsumerId.set(remote.consumerId, remote);
|
|
347
|
+
this._bySsrc.set(remote.ssrc, remote);
|
|
348
|
+
// режим мог смениться за время пересоздания (запросы шли в старый транспорт)
|
|
349
|
+
fresh.setMode(remote.ssrc, remote.mode);
|
|
350
|
+
}
|
|
351
|
+
if (old) {
|
|
352
|
+
this._closeTransport(old);
|
|
353
|
+
this._closeServerTransport(old.params.id);
|
|
354
|
+
}
|
|
355
|
+
this.rebuilds++;
|
|
356
|
+
} catch (error) {
|
|
357
|
+
this._closeTransport(fresh);
|
|
358
|
+
this._closeServerTransport(params.id);
|
|
359
|
+
throw error;
|
|
360
|
+
}
|
|
361
|
+
})()
|
|
362
|
+
.catch(error => {
|
|
363
|
+
if (!this.closed) this._onError(error);
|
|
364
|
+
})
|
|
365
|
+
.finally(() => {
|
|
366
|
+
this._rebuilding = null;
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Закрыть сессию приёма: звук всех консьюмеров заканчивается. Возвращает Promise закрытия нативных Peer. */
|
|
371
|
+
close() {
|
|
372
|
+
if (this.closed) return Promise.resolve();
|
|
373
|
+
this.closed = true;
|
|
374
|
+
for (const entry of this._pending.values()) entry.closed = true;
|
|
375
|
+
const ended = [...this._consumers.values()];
|
|
376
|
+
this._consumers.clear();
|
|
377
|
+
this._byConsumerId.clear();
|
|
378
|
+
this._bySsrc.clear();
|
|
379
|
+
const closing = [];
|
|
380
|
+
if (this._transport) closing.push(this._closeTransport(this._transport));
|
|
381
|
+
for (const transport of [...this._unroutes.keys()]) closing.push(this._closeTransport(transport));
|
|
382
|
+
for (const remote of ended) remote._end();
|
|
383
|
+
return Promise.all(closing).then(() => undefined);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
module.exports = { RemoteAudio, RecvSession, MODE_NONE, MODE_OPUS, DEFAULT_MAX_CLOSED_SECTIONS, CLOSE_GRACE_MS };
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Сборка remote SDP из ответов mediasoup (SFU — ICE-lite). Образец логики — RemoteSdp/MediaSection
|
|
4
|
+
// из mediasoup-client; здесь только аудио и Opus.
|
|
5
|
+
|
|
6
|
+
const { URI_MID, URI_LEVEL } = require('./caps');
|
|
7
|
+
|
|
8
|
+
function fmtpString(parameters) {
|
|
9
|
+
return Object.entries(parameters)
|
|
10
|
+
.map(([key, value]) => `${key}=${value}`)
|
|
11
|
+
.join(';');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function udpCandidates(transport) {
|
|
15
|
+
return (transport.iceCandidates ?? []).filter(c => String(c.protocol).toLowerCase() === 'udp');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function candidateAddress(c) {
|
|
19
|
+
return c.ip ?? c.address;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function connectionLine(transport) {
|
|
23
|
+
const first = udpCandidates(transport)[0];
|
|
24
|
+
if (!first) throw new Error('voice server returned no UDP ICE candidates');
|
|
25
|
+
const address = candidateAddress(first);
|
|
26
|
+
return `c=IN ${address.includes(':') ? 'IP6' : 'IP4'} ${address}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function iceLines(transport) {
|
|
30
|
+
const lines = [`a=ice-ufrag:${transport.iceParameters.usernameFragment}`, `a=ice-pwd:${transport.iceParameters.password}`];
|
|
31
|
+
for (const c of udpCandidates(transport)) {
|
|
32
|
+
lines.push(`a=candidate:${c.foundation} 1 udp ${c.priority} ${candidateAddress(c)} ${c.port} typ ${c.type}`);
|
|
33
|
+
}
|
|
34
|
+
lines.push('a=end-of-candidates', 'a=ice-options:renomination');
|
|
35
|
+
return lines;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function fingerprintLine(transport) {
|
|
39
|
+
const fingerprints = transport.dtlsParameters.fingerprints;
|
|
40
|
+
const fp = fingerprints.find(f => f.algorithm === 'sha-256') ?? fingerprints[0];
|
|
41
|
+
return `a=fingerprint:${fp.algorithm} ${fp.value}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Remote answer для send-транспорта: одна m-секция recvonly, `setup:passive` — клиентом DTLS становимся мы.
|
|
46
|
+
* @param {Object} transport ответ createWebRtcTransport
|
|
47
|
+
* @param {{ pt: number, midId: number, levelId: number }} opus
|
|
48
|
+
* @param {Object} parameters fmtp Opus
|
|
49
|
+
*/
|
|
50
|
+
function buildSendAnswer(transport, opus, parameters) {
|
|
51
|
+
return (
|
|
52
|
+
[
|
|
53
|
+
'v=0',
|
|
54
|
+
'o=lolka-voice 10000 1 IN IP4 0.0.0.0',
|
|
55
|
+
's=-',
|
|
56
|
+
't=0 0',
|
|
57
|
+
'a=ice-lite',
|
|
58
|
+
fingerprintLine(transport),
|
|
59
|
+
'a=msid-semantic: WMS *',
|
|
60
|
+
'a=group:BUNDLE 0',
|
|
61
|
+
`m=audio 7 UDP/TLS/RTP/SAVPF ${opus.pt}`,
|
|
62
|
+
connectionLine(transport),
|
|
63
|
+
`a=rtpmap:${opus.pt} opus/48000/2`,
|
|
64
|
+
`a=fmtp:${opus.pt} ${fmtpString(parameters)}`,
|
|
65
|
+
`a=extmap:${opus.midId} ${URI_MID}`,
|
|
66
|
+
`a=extmap:${opus.levelId} ${URI_LEVEL}`,
|
|
67
|
+
'a=setup:passive',
|
|
68
|
+
'a=mid:0',
|
|
69
|
+
'a=recvonly',
|
|
70
|
+
...iceLines(transport),
|
|
71
|
+
'a=rtcp-mux',
|
|
72
|
+
'a=rtcp-rsize',
|
|
73
|
+
].join('\r\n') + '\r\n'
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Remote offer для recv-транспорта: по m-секции на консьюмер (параметры — из ответа `consume`).
|
|
79
|
+
* Секции только добавляются, порядок не меняется; закрытая секция остаётся как `m=audio 0` + `a=inactive`
|
|
80
|
+
* и не входит в BUNDLE.
|
|
81
|
+
* @param {Object} transport ответ createWebRtcTransport
|
|
82
|
+
* @param {{ consumer: Object, closed: boolean }[]} sections
|
|
83
|
+
* @param {number} version номер версии SDP (растёт с каждым пересогласованием)
|
|
84
|
+
*/
|
|
85
|
+
function buildRecvOffer(transport, sections, version) {
|
|
86
|
+
const mids = sections.filter(section => !section.closed).map(section => section.consumer.rtpParameters.mid);
|
|
87
|
+
const head = [
|
|
88
|
+
'v=0',
|
|
89
|
+
`o=lolka-voice 10000 ${version} IN IP4 0.0.0.0`,
|
|
90
|
+
's=-',
|
|
91
|
+
't=0 0',
|
|
92
|
+
'a=ice-lite',
|
|
93
|
+
fingerprintLine(transport),
|
|
94
|
+
'a=msid-semantic: WMS *',
|
|
95
|
+
];
|
|
96
|
+
if (mids.length > 0) head.push(`a=group:BUNDLE ${mids.join(' ')}`);
|
|
97
|
+
const blocks = sections.map(({ consumer, closed }) => {
|
|
98
|
+
const rp = consumer.rtpParameters;
|
|
99
|
+
const codec = rp.codecs[0];
|
|
100
|
+
if (closed) {
|
|
101
|
+
return [
|
|
102
|
+
`m=audio 0 UDP/TLS/RTP/SAVPF ${codec.payloadType}`,
|
|
103
|
+
'c=IN IP4 0.0.0.0',
|
|
104
|
+
`a=rtpmap:${codec.payloadType} opus/48000/2`,
|
|
105
|
+
'a=inactive',
|
|
106
|
+
`a=mid:${rp.mid}`,
|
|
107
|
+
`a=ice-ufrag:${transport.iceParameters.usernameFragment}`,
|
|
108
|
+
`a=ice-pwd:${transport.iceParameters.password}`,
|
|
109
|
+
'a=setup:actpass',
|
|
110
|
+
'a=rtcp-mux',
|
|
111
|
+
].join('\r\n');
|
|
112
|
+
}
|
|
113
|
+
const lines = [
|
|
114
|
+
`m=audio 7 UDP/TLS/RTP/SAVPF ${codec.payloadType}`,
|
|
115
|
+
connectionLine(transport),
|
|
116
|
+
`a=rtpmap:${codec.payloadType} opus/48000/2`,
|
|
117
|
+
];
|
|
118
|
+
if (codec.parameters && Object.keys(codec.parameters).length) {
|
|
119
|
+
lines.push(`a=fmtp:${codec.payloadType} ${fmtpString(codec.parameters)}`);
|
|
120
|
+
}
|
|
121
|
+
for (const e of rp.headerExtensions ?? []) lines.push(`a=extmap:${e.id} ${e.uri}`);
|
|
122
|
+
lines.push('a=setup:actpass', `a=mid:${rp.mid}`, 'a=sendonly', ...iceLines(transport), 'a=rtcp-mux', 'a=rtcp-rsize');
|
|
123
|
+
lines.push(`a=msid:${consumer.producerId} ${consumer.id}`);
|
|
124
|
+
lines.push(`a=ssrc:${rp.encodings[0].ssrc} cname:${rp.rtcp.cname}`);
|
|
125
|
+
return lines.join('\r\n');
|
|
126
|
+
});
|
|
127
|
+
return [...head, ...blocks].join('\r\n') + '\r\n';
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Отпечаток DTLS из локального SDP (для connectTransport). */
|
|
131
|
+
function fingerprintFromSdp(sdp) {
|
|
132
|
+
const match = /a=fingerprint:(\S+) (\S+)/.exec(sdp);
|
|
133
|
+
if (!match) throw new Error('local SDP has no DTLS fingerprint');
|
|
134
|
+
return { algorithm: match[1].toLowerCase(), value: match[2].toUpperCase() };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
module.exports = { buildSendAnswer, buildRecvOffer, fingerprintFromSdp, fmtpString };
|