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,260 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Транспорты mediasoup поверх нативного Peer. Порт NativeTransport.js lolka.js.
|
|
4
|
+
//
|
|
5
|
+
// Транспорт mediasoup – ICE-lite: SDP собираем сами из ответа createWebRtcTransport (sdp.js), клиентом
|
|
6
|
+
// DTLS становимся мы (`connectTransport` с role `client` и отпечатком из локального SDP) ровно один раз.
|
|
7
|
+
// Ловушки libdatachannel учтены в ядре: `setLocalDescription` вызывается внутри createOffer/answerOffer,
|
|
8
|
+
// пакеты шлются только после открытия трека, объекты Track держит ядро, закрытая последняя секция
|
|
9
|
+
// не пересогласуется (см. closeConsumer). Event loop держится, пока Peer не закрылся до конца.
|
|
10
|
+
|
|
11
|
+
const { debuglog } = require('node:util');
|
|
12
|
+
const { OPUS_SEND_PARAMETERS } = require('./caps');
|
|
13
|
+
const { buildSendAnswer, buildRecvOffer, fingerprintFromSdp, fmtpString } = require('./sdp');
|
|
14
|
+
|
|
15
|
+
const debug = debuglog('lolkajs-voice');
|
|
16
|
+
|
|
17
|
+
const CONNECT_TIMEOUT_MS = 15000;
|
|
18
|
+
const NEGOTIATION_TIMEOUT_MS = 10000;
|
|
19
|
+
|
|
20
|
+
class PeerTransport {
|
|
21
|
+
/** @param {{ core: Object, router: import('./events').EventRouter }} runtime */
|
|
22
|
+
constructor(runtime, name) {
|
|
23
|
+
this.peer = new runtime.core.Peer(name);
|
|
24
|
+
this.closed = false;
|
|
25
|
+
this.state = 'new';
|
|
26
|
+
this._waiters = new Set();
|
|
27
|
+
this._hold = runtime.router.hold();
|
|
28
|
+
this._unroute = runtime.router.route('state', this.peer.id, ev => this._onState(ev[2]));
|
|
29
|
+
/** Promise, который выполняется, когда нативный Peer закрыт до конца (после `close()`). */
|
|
30
|
+
this.closePromise = null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
_onState(state) {
|
|
34
|
+
if (this.closed) return;
|
|
35
|
+
if ((state === 'failed' || state === 'disconnected') && this.state === 'connected') {
|
|
36
|
+
debug('transport %s went %s', this.peer.id, state);
|
|
37
|
+
}
|
|
38
|
+
this.state = state;
|
|
39
|
+
for (const waiter of [...this._waiters]) waiter(state);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Дождаться connected; failed/closed и таймаут – ошибка. */
|
|
43
|
+
waitConnected(timeout = CONNECT_TIMEOUT_MS) {
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const check = state => {
|
|
46
|
+
if (state === 'connected') done(resolve);
|
|
47
|
+
else if (state === 'failed' || state === 'closed') done(() => reject(new Error(`voice transport ${state}`)));
|
|
48
|
+
};
|
|
49
|
+
const timer = setTimeout(() => done(() => reject(new Error('voice transport connect timeout'))), timeout);
|
|
50
|
+
const done = fn => {
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
this._waiters.delete(check);
|
|
53
|
+
fn();
|
|
54
|
+
};
|
|
55
|
+
this._waiters.add(check);
|
|
56
|
+
check(this.closed ? 'closed' : this.state);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
close() {
|
|
61
|
+
if (this.closed) return this.closePromise;
|
|
62
|
+
this.closed = true;
|
|
63
|
+
for (const waiter of [...this._waiters]) waiter('closed');
|
|
64
|
+
this._unroute();
|
|
65
|
+
let closing;
|
|
66
|
+
try {
|
|
67
|
+
closing = Promise.resolve(this.peer.close());
|
|
68
|
+
} catch (error) {
|
|
69
|
+
closing = Promise.reject(error);
|
|
70
|
+
}
|
|
71
|
+
this.closePromise = closing
|
|
72
|
+
.catch(error => debug('peer close failed: %s', error?.message))
|
|
73
|
+
.finally(() => this._hold.release());
|
|
74
|
+
return this.closePromise;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Send-транспорт: один Opus-трек SendOnly, пакеты собирает и шлёт ядро. */
|
|
79
|
+
class SendTransport extends PeerTransport {
|
|
80
|
+
/**
|
|
81
|
+
* @param {{ core: Object, router: Object }} runtime
|
|
82
|
+
* @param {Object} options
|
|
83
|
+
* @param {string} options.name
|
|
84
|
+
* @param {Object} options.params ответ createWebRtcTransport
|
|
85
|
+
* @param {Object} options.opus результат opusFromCaps()
|
|
86
|
+
* @param {number} options.ssrc
|
|
87
|
+
* @param {string} options.cname
|
|
88
|
+
* @param {Object} [options.parameters] fmtp Opus
|
|
89
|
+
*/
|
|
90
|
+
constructor(runtime, { name, params, opus, ssrc, cname, parameters = OPUS_SEND_PARAMETERS }) {
|
|
91
|
+
super(runtime, name);
|
|
92
|
+
this.params = params;
|
|
93
|
+
this.opus = opus;
|
|
94
|
+
this.parameters = parameters;
|
|
95
|
+
this.ssrc = ssrc;
|
|
96
|
+
try {
|
|
97
|
+
this.track = this.peer.addSendAudio({
|
|
98
|
+
mid: '0',
|
|
99
|
+
pt: opus.pt,
|
|
100
|
+
fmtp: fmtpString(parameters),
|
|
101
|
+
ssrc,
|
|
102
|
+
cname,
|
|
103
|
+
midExt: opus.midId,
|
|
104
|
+
levelExt: opus.levelId,
|
|
105
|
+
});
|
|
106
|
+
} catch (error) {
|
|
107
|
+
this.close();
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Трек открыт: можно слать RTP. */
|
|
113
|
+
get ready() {
|
|
114
|
+
return this.track.isOpen && !this.closed;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* ICE + DTLS. `request` – сигналинг (JSON-RPC); connectTransport вызывается ровно один раз.
|
|
119
|
+
* @param {(method: string, data: Object) => Promise<Object>} request
|
|
120
|
+
*/
|
|
121
|
+
async connect(request) {
|
|
122
|
+
const offer = await this.peer.createOffer(NEGOTIATION_TIMEOUT_MS);
|
|
123
|
+
await request('connectTransport', {
|
|
124
|
+
transportId: this.params.id,
|
|
125
|
+
dtlsParameters: { role: 'client', fingerprints: [fingerprintFromSdp(offer)] },
|
|
126
|
+
});
|
|
127
|
+
if (this.closed) throw new Error('voice transport closed');
|
|
128
|
+
await this.peer.setRemoteDescription(buildSendAnswer(this.params, this.opus, this.parameters), 'answer');
|
|
129
|
+
await this.waitConnected();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Recv-транспорт: по m-секции на консьюмер, пересогласование при добавлении и закрытии.
|
|
135
|
+
* Закрытая секция остаётся в SDP как `m=audio 0` (порядок и mid не меняются); число закрытых
|
|
136
|
+
* секций растёт, поэтому выше порога RecvSession пересоздаёт транспорт целиком.
|
|
137
|
+
*/
|
|
138
|
+
class RecvTransport extends PeerTransport {
|
|
139
|
+
constructor(runtime, { name, params }) {
|
|
140
|
+
super(runtime, name);
|
|
141
|
+
this.params = params;
|
|
142
|
+
this.sections = []; // { consumer, closed, released }
|
|
143
|
+
this._version = 1;
|
|
144
|
+
this._connectedOnce = false;
|
|
145
|
+
this._chain = Promise.resolve();
|
|
146
|
+
this._closeQueued = false;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Число закрытых (m=audio 0) секций. */
|
|
150
|
+
get closedCount() {
|
|
151
|
+
let count = 0;
|
|
152
|
+
for (const section of this.sections) if (section.closed) count++;
|
|
153
|
+
return count;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Добавить консьюмер: новая m-секция и пересогласование. SSRC привязывается в ядре до ответа,
|
|
158
|
+
* то есть до resumeConsumer. Возвращает управление, когда answer применён и (для первого консьюмера)
|
|
159
|
+
* транспорт соединён. Неудавшаяся секция помечается закрытой, а не вычёркивается: mid и порядок
|
|
160
|
+
* секций должны сохраняться.
|
|
161
|
+
* @param {Object} consumer ответ consume
|
|
162
|
+
* @param {(method: string, data: Object) => Promise<Object>} request
|
|
163
|
+
* @param {number} mode режим приёма
|
|
164
|
+
*/
|
|
165
|
+
addConsumer(consumer, request, mode) {
|
|
166
|
+
const section = { consumer, closed: false, released: false };
|
|
167
|
+
this.sections.push(section);
|
|
168
|
+
const ssrc = consumer.rtpParameters.encodings[0].ssrc;
|
|
169
|
+
try {
|
|
170
|
+
this.peer.addConsumer({ ssrc, key: ssrc, mode });
|
|
171
|
+
} catch (error) {
|
|
172
|
+
section.closed = true;
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
const task = this._chain.then(() => this._negotiate(request));
|
|
176
|
+
this._chain = task.catch(() => {});
|
|
177
|
+
return task.catch(error => {
|
|
178
|
+
this._markClosed(section);
|
|
179
|
+
throw error;
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
_markClosed(section) {
|
|
184
|
+
if (section.closed) return;
|
|
185
|
+
section.closed = true;
|
|
186
|
+
if (this.closed) return;
|
|
187
|
+
try {
|
|
188
|
+
this.peer.removeConsumer(section.consumer.rtpParameters.encodings[0].ssrc);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
debug('removeConsumer failed: %s', error?.message);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Сменить режим приёма консьюмера; закрытый транспорт и закрытая секция игнорируются. */
|
|
195
|
+
setMode(ssrc, mode) {
|
|
196
|
+
if (this.closed) return;
|
|
197
|
+
const section = this.sections.find(s => !s.closed && s.consumer.rtpParameters.encodings[0].ssrc === ssrc);
|
|
198
|
+
if (!section) return;
|
|
199
|
+
this.peer.setConsumerMode(ssrc, mode);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Закрыть секцию консьюмера (`m=audio 0`); близкие по времени закрытия сливаются в одно
|
|
204
|
+
* пересогласование. Сервер консьюмер не закрывает (closeConsumer нет).
|
|
205
|
+
* @param {string} consumerId
|
|
206
|
+
* @param {(method: string, data: Object) => Promise<Object>} request
|
|
207
|
+
* @returns {Promise<void>}
|
|
208
|
+
*/
|
|
209
|
+
closeConsumer(consumerId, request) {
|
|
210
|
+
const section = this.sections.find(s => s.consumer.id === consumerId && !s.closed);
|
|
211
|
+
if (!section) return Promise.resolve();
|
|
212
|
+
this._markClosed(section);
|
|
213
|
+
if (this._closeQueued) return this._chain;
|
|
214
|
+
this._closeQueued = true;
|
|
215
|
+
const task = this._chain.then(() => {
|
|
216
|
+
this._closeQueued = false;
|
|
217
|
+
// libdatachannel не принимает offer без активных секций: закрытие последней ждёт следующего consume
|
|
218
|
+
if (this.closed || !this.sections.some(s => !s.closed)) return undefined;
|
|
219
|
+
return this._negotiate(request);
|
|
220
|
+
});
|
|
221
|
+
this._chain = task.catch(() => {});
|
|
222
|
+
return task;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async _negotiate(request) {
|
|
226
|
+
if (this.closed) throw new Error('voice transport closed');
|
|
227
|
+
const offer = buildRecvOffer(this.params, this.sections, this._version++);
|
|
228
|
+
const answer = await this.peer.answerOffer(offer, NEGOTIATION_TIMEOUT_MS);
|
|
229
|
+
if (this.closed) throw new Error('voice transport closed');
|
|
230
|
+
if (!this._connectedOnce) {
|
|
231
|
+
this._connectedOnce = true;
|
|
232
|
+
try {
|
|
233
|
+
await request('connectTransport', {
|
|
234
|
+
transportId: this.params.id,
|
|
235
|
+
dtlsParameters: { role: 'client', fingerprints: [fingerprintFromSdp(answer)] },
|
|
236
|
+
});
|
|
237
|
+
await this.waitConnected();
|
|
238
|
+
} catch (error) {
|
|
239
|
+
this._connectedOnce = false;
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
await this._releaseClosedTracks();
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Track и RtcpReceivingSession закрытых секций больше не нужны.
|
|
247
|
+
async _releaseClosedTracks() {
|
|
248
|
+
if (this.closed) return;
|
|
249
|
+
const sections = this.sections.filter(s => s.closed && !s.released);
|
|
250
|
+
if (sections.length === 0) return;
|
|
251
|
+
try {
|
|
252
|
+
await this.peer.releaseTracks(sections.map(s => s.consumer.rtpParameters.mid));
|
|
253
|
+
for (const section of sections) section.released = true;
|
|
254
|
+
} catch (error) {
|
|
255
|
+
debug('releaseTracks failed: %s', error?.message);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
module.exports = { PeerTransport, SendTransport, RecvTransport, CONNECT_TIMEOUT_MS, NEGOTIATION_TIMEOUT_MS };
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Вход -> Opus-пакеты -> `SourcePump` вложенного слоя (поток пакетов -> нативный источник).
|
|
4
|
+
// Пейсинг, RTP и отправка – в нативном ядре; здесь только цепочка входа (ffmpeg, демуксеры).
|
|
5
|
+
//
|
|
6
|
+
// 'arbitrary' (по умолчанию): путь или Readable любого формата, ffmpeg перекодирует в Ogg/Opus
|
|
7
|
+
// 'raw': путь или Readable с PCM s16le 48 кГц стерео без заголовка; ffmpeg кодирует в Opus
|
|
8
|
+
// 'ogg/opus': Ogg/Opus без ffmpeg (путь или Readable)
|
|
9
|
+
// 'webm/opus': WebM/Opus без ffmpeg (путь или Readable)
|
|
10
|
+
// 'opus': объектный Readable с готовыми Opus-пакетами
|
|
11
|
+
//
|
|
12
|
+
|
|
13
|
+
const { createReadStream, readdirSync } = require('node:fs');
|
|
14
|
+
const os = require('node:os');
|
|
15
|
+
const { debuglog } = require('node:util');
|
|
16
|
+
const { ensureVoiceDeps } = require('./deps');
|
|
17
|
+
|
|
18
|
+
const debug = debuglog('lolkajs-voice');
|
|
19
|
+
|
|
20
|
+
// ffmpeg ниже приоритета бота: при нехватке ядер он не отнимает время у отправки пакетов
|
|
21
|
+
const FFMPEG_NICE = 10;
|
|
22
|
+
|
|
23
|
+
const INPUT_TYPES = ['arbitrary', 'raw', 'ogg/opus', 'webm/opus', 'opus'];
|
|
24
|
+
|
|
25
|
+
function lowerPriority(child) {
|
|
26
|
+
const pid = child && child.pid;
|
|
27
|
+
if (!pid) return;
|
|
28
|
+
let nice;
|
|
29
|
+
try {
|
|
30
|
+
nice = Math.min(19, os.getPriority() + FFMPEG_NICE);
|
|
31
|
+
os.setPriority(pid, nice);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
debug('ffmpeg priority not lowered: %s', error.message);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (process.platform !== 'linux') return;
|
|
37
|
+
// на Linux nice поштоковый: потоки, которые ffmpeg уже успел создать, остаются со старым значением
|
|
38
|
+
let tids;
|
|
39
|
+
try {
|
|
40
|
+
tids = readdirSync(`/proc/${pid}/task`);
|
|
41
|
+
} catch {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
for (const tid of tids) {
|
|
45
|
+
try {
|
|
46
|
+
os.setPriority(Number(tid), nice);
|
|
47
|
+
} catch {
|
|
48
|
+
// поток мог завершиться
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function ffmpegArgs(input, bitrate, raw) {
|
|
54
|
+
return [
|
|
55
|
+
'-analyzeduration', '0', '-loglevel', '0',
|
|
56
|
+
...(raw ? ['-f', 's16le', '-ar', '48000', '-ac', '2'] : []),
|
|
57
|
+
'-i', typeof input === 'string' ? input : 'pipe:0',
|
|
58
|
+
'-vn', '-map_metadata', '-1',
|
|
59
|
+
'-c:a', 'libopus', '-b:a', `${bitrate}k`, '-ar', '48000', '-ac', '2',
|
|
60
|
+
'-application', 'audio', '-frame_duration', '20', '-vbr', 'on', '-fec', '1', '-packet_loss', '10',
|
|
61
|
+
'-f', 'opus',
|
|
62
|
+
];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Собрать цепочку потоков. Возвращает объект: `stream` отдаёт Buffer с Opus-пакетами,
|
|
67
|
+
* `destroy()` разбирает цепочку (чужой Readable не уничтожается, только отсоединяется).
|
|
68
|
+
*/
|
|
69
|
+
function createSource(input, inputType, bitrate) {
|
|
70
|
+
const { prism } = ensureVoiceDeps();
|
|
71
|
+
const isPath = typeof input === 'string';
|
|
72
|
+
if (!isPath && !(input && typeof input.pipe === 'function' && typeof input.on === 'function')) {
|
|
73
|
+
throw new TypeError('play() input must be a file path or a Readable stream');
|
|
74
|
+
}
|
|
75
|
+
const owned = [];
|
|
76
|
+
let unpipe = null;
|
|
77
|
+
let stream;
|
|
78
|
+
let ffmpeg = null; // потомок ffmpeg: его неудачный выход – ошибка источника, а не тихий конец
|
|
79
|
+
let exit = null;
|
|
80
|
+
let destroyed = false;
|
|
81
|
+
const exitWaiters = [];
|
|
82
|
+
|
|
83
|
+
if (inputType === 'opus') {
|
|
84
|
+
if (isPath) throw new TypeError("inputType 'opus' requires a Readable stream of Opus packets");
|
|
85
|
+
stream = input;
|
|
86
|
+
input.on('error', onInputError);
|
|
87
|
+
} else {
|
|
88
|
+
let head;
|
|
89
|
+
if (inputType === 'arbitrary' || inputType === 'raw') {
|
|
90
|
+
head = new prism.FFmpeg({ args: ffmpegArgs(input, bitrate, inputType === 'raw') });
|
|
91
|
+
ffmpeg = head.process;
|
|
92
|
+
ffmpeg.once('close', (code, signal) => {
|
|
93
|
+
exit = { code, signal };
|
|
94
|
+
for (const waiter of exitWaiters.splice(0)) waiter();
|
|
95
|
+
});
|
|
96
|
+
lowerPriority(head.process);
|
|
97
|
+
owned.push(head);
|
|
98
|
+
if (!isPath) {
|
|
99
|
+
input.pipe(head);
|
|
100
|
+
unpipe = () => input.unpipe(head);
|
|
101
|
+
input.on('error', onInputError);
|
|
102
|
+
}
|
|
103
|
+
const demuxer = new prism.opus.OggDemuxer();
|
|
104
|
+
head.pipe(demuxer);
|
|
105
|
+
owned.push(demuxer);
|
|
106
|
+
stream = demuxer;
|
|
107
|
+
} else {
|
|
108
|
+
const demuxer = inputType === 'ogg/opus' ? new prism.opus.OggDemuxer() : new prism.opus.WebmDemuxer();
|
|
109
|
+
owned.push(demuxer);
|
|
110
|
+
if (isPath) {
|
|
111
|
+
head = createReadStream(input);
|
|
112
|
+
owned.push(head);
|
|
113
|
+
head.on('error', onInputError);
|
|
114
|
+
} else {
|
|
115
|
+
head = input;
|
|
116
|
+
input.on('error', onInputError);
|
|
117
|
+
}
|
|
118
|
+
head.pipe(demuxer);
|
|
119
|
+
if (!isPath) unpipe = () => input.unpipe(demuxer);
|
|
120
|
+
stream = demuxer;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
let errorHandler = null;
|
|
125
|
+
function onInputError(error) {
|
|
126
|
+
errorHandler?.(error);
|
|
127
|
+
}
|
|
128
|
+
const exitError = () => {
|
|
129
|
+
if (exit.code === 0) return null;
|
|
130
|
+
return new Error(exit.signal ? `ffmpeg was killed by signal ${exit.signal}` : `ffmpeg exited with code ${exit.code}`);
|
|
131
|
+
};
|
|
132
|
+
return {
|
|
133
|
+
stream,
|
|
134
|
+
child: ffmpeg,
|
|
135
|
+
// Вызвать `callback(error|null)`, когда ffmpeg завершился (сразу, если ffmpeg не используется).
|
|
136
|
+
afterExit(callback) {
|
|
137
|
+
if (!ffmpeg) callback(null);
|
|
138
|
+
else if (exit) callback(exitError());
|
|
139
|
+
else exitWaiters.push(() => !destroyed && callback(exitError()));
|
|
140
|
+
},
|
|
141
|
+
onError(handler) {
|
|
142
|
+
errorHandler = handler;
|
|
143
|
+
for (const s of owned) s.on('error', handler);
|
|
144
|
+
},
|
|
145
|
+
destroy() {
|
|
146
|
+
destroyed = true;
|
|
147
|
+
try {
|
|
148
|
+
unpipe?.();
|
|
149
|
+
} catch {
|
|
150
|
+
// ignore
|
|
151
|
+
}
|
|
152
|
+
input.off?.('error', onInputError);
|
|
153
|
+
for (const s of owned) {
|
|
154
|
+
try {
|
|
155
|
+
s.destroy();
|
|
156
|
+
} catch {
|
|
157
|
+
// ignore
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Источник Opus-пакетов для плеера или соединения: цепочка входа и `SourcePump` на ней. Предбуфер до 50 пакетов,
|
|
166
|
+
* backpressure и старт после 5 пакетов – в `SourcePump`, время и отправку ведёт ядро.
|
|
167
|
+
*
|
|
168
|
+
* Ошибка источника (ffmpeg, пользовательский Readable) не эмитится: она запоминается в `pump.error` и уходит
|
|
169
|
+
* владельцу после доигрыша готовых кадров (событие конца источника).
|
|
170
|
+
*/
|
|
171
|
+
class OpusPlayback {
|
|
172
|
+
/**
|
|
173
|
+
* @param {string|import('node:stream').Readable} input
|
|
174
|
+
* @param {Object} [options]
|
|
175
|
+
* @param {'arbitrary'|'raw'|'ogg/opus'|'webm/opus'|'opus'} [options.inputType]
|
|
176
|
+
* @param {number} [options.bitrate] кбит/с, только для 'arbitrary' и 'raw'
|
|
177
|
+
*/
|
|
178
|
+
constructor(input, { inputType = 'arbitrary', bitrate = 128 } = {}) {
|
|
179
|
+
if (!INPUT_TYPES.includes(inputType)) throw new TypeError(`unknown inputType: ${inputType}`);
|
|
180
|
+
if (!Number.isFinite(bitrate) || bitrate < 6 || bitrate > 510) throw new RangeError('bitrate must be 6..510 kbit/s');
|
|
181
|
+
const { voice } = ensureVoiceDeps();
|
|
182
|
+
const source = createSource(input, inputType, bitrate);
|
|
183
|
+
/** Поток Opus-пакетов, из которого читает источник. */
|
|
184
|
+
this.stream = source.stream;
|
|
185
|
+
/** @type {import('../_lolka_voice').SourcePump} */
|
|
186
|
+
this.pump = new voice.SourcePump(source.stream, {
|
|
187
|
+
afterExit: callback => source.afterExit(callback),
|
|
188
|
+
destroy: () => source.destroy(),
|
|
189
|
+
});
|
|
190
|
+
source.onError(error => this.pump.fail(error));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Остановить и разобрать источник; события конца и ошибки больше не придут. */
|
|
194
|
+
stop() {
|
|
195
|
+
this.pump.stop();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
module.exports = { OpusPlayback, INPUT_TYPES };
|