lolka.js 0.4.3 → 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.
Files changed (45) hide show
  1. package/README.md +279 -11
  2. package/package.json +3 -5
  3. package/src/client/voice/AudioPlayer.js +358 -0
  4. package/src/client/voice/AudioResource.js +137 -0
  5. package/src/client/voice/VoiceConnection.js +419 -290
  6. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libdatachannel.txt +373 -0
  7. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libjuice.txt +373 -0
  8. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libsrtp.txt +35 -0
  9. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-nlohmann-json.txt +21 -0
  10. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-node-addon-api.txt +9 -0
  11. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-node-api-headers.txt +21 -0
  12. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-openssl.txt +177 -0
  13. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-opus.txt +44 -0
  14. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-plog.txt +21 -0
  15. package/src/client/voice/_lolka_voice/LICENSES/LICENSE-usrsctp.txt +27 -0
  16. package/src/client/voice/_lolka_voice/LICENSES/THIRD-PARTY.txt +16 -0
  17. package/src/client/voice/_lolka_voice/MANIFEST.json +47 -0
  18. package/src/client/voice/_lolka_voice/_loader.js +103 -0
  19. package/src/client/voice/_lolka_voice/_native/linux-aarch64/core.node +0 -0
  20. package/src/client/voice/_lolka_voice/_native/linux-aarch64-musl/core.node +0 -0
  21. package/src/client/voice/_lolka_voice/_native/linux-x86_64/core.node +0 -0
  22. package/src/client/voice/_lolka_voice/_native/linux-x86_64-musl/core.node +0 -0
  23. package/src/client/voice/_lolka_voice/_native/macos-arm64/core.node +0 -0
  24. package/src/client/voice/_lolka_voice/_native/macos-x86_64/core.node +0 -0
  25. package/src/client/voice/_lolka_voice/_native/windows-x86_64/core.node +0 -0
  26. package/src/client/voice/_lolka_voice/_version.js +4 -0
  27. package/src/client/voice/_lolka_voice/caps.js +56 -0
  28. package/src/client/voice/_lolka_voice/core.d.ts +200 -0
  29. package/src/client/voice/_lolka_voice/errors.js +22 -0
  30. package/src/client/voice/_lolka_voice/events.js +119 -0
  31. package/src/client/voice/_lolka_voice/index.d.ts +226 -0
  32. package/src/client/voice/_lolka_voice/index.js +35 -0
  33. package/src/client/voice/_lolka_voice/player.js +606 -0
  34. package/src/client/voice/_lolka_voice/receive.js +387 -0
  35. package/src/client/voice/_lolka_voice/sdp.js +137 -0
  36. package/src/client/voice/_lolka_voice/session.js +335 -0
  37. package/src/client/voice/_lolka_voice/signaling.js +120 -0
  38. package/src/client/voice/_lolka_voice/transport.js +260 -0
  39. package/src/client/voice/media/OpusPlayback.js +199 -0
  40. package/src/client/voice/media/Receiver.js +245 -0
  41. package/src/client/voice/media/deps.js +27 -0
  42. package/src/index.js +11 -0
  43. package/src/structures/Guild.js +5 -2
  44. package/typings/index.d.mts +256 -4
  45. package/typings/index.d.ts +256 -4
@@ -0,0 +1,606 @@
1
+ 'use strict';
2
+
3
+ // Воспроизведение: `SourcePump` (поток Opus-пакетов -> нативный источник), `SendPlayer` (отправитель
4
+ // соединения) и `FeedPlayer` (один источник на много соединений).
5
+ //
6
+ // Пейсинг, RTP и SRTP – в ядре, в нативном потоке; JS на пакет не выполняется. Главный поток только читает вход
7
+ // (ffmpeg, демуксеры) и кладёт пакеты в нативную очередь на 1 с. `write()` никогда не ждёт: на 50 кадрах ядро
8
+ // отвечает FULL, поток входа ставится на паузу до события `writable`.
9
+ //
10
+ // Каждое событие ядра сверяется с текущим поколением (`gen`) или `token` прогона: устаревшее игнорируется.
11
+ // Маршруты событий живут только пока идёт прогон (от play до события конца или stop) и держат объекты сильной
12
+ // ссылкой, поэтому играющий плеер без ссылок пользователя доигрывает до конца.
13
+
14
+ const { getRuntime } = require('./events');
15
+
16
+ const WRITE_FULL = 1;
17
+ const WRITE_STALE = 2;
18
+
19
+ const PRE_BUFFER_PACKETS = 50; // 1 с до подключения к источнику
20
+ const START_PACKETS = 5; // 100 мс: достаточно, чтобы начать
21
+
22
+ // Поколения и токены уникальны в процессе; у нового нативного источника поколение 1
23
+ let nextGeneration = 2;
24
+ let nextToken = 1;
25
+
26
+ const noop = () => {};
27
+
28
+ /**
29
+ * Поток Opus-пакетов (Buffer = пакет) -> нативный источник.
30
+ *
31
+ * До `attach` держит предбуфер до 50 пакетов и на полном ставит поток на паузу. `attach` сливает буфер, дальше
32
+ * пишет вживую: на FULL – пауза потока, на `writable` – продолжение. На конец потока (и после выхода ffmpeg)
33
+ * пишет в источник маркер конца. Ошибка запоминается и уходит владельцу после события конца, то есть сначала
34
+ * доигрываются готовые кадры.
35
+ */
36
+ class SourcePump {
37
+ /**
38
+ * @param {import('node:stream').Readable} stream поток пакетов (читает сразу, как только есть слушатель 'data')
39
+ * @param {Object} [options]
40
+ * @param {(callback: (error: Error | null) => void) => void} [options.afterExit] вызвать `callback`, когда
41
+ * источник целиком завершился (ffmpeg вышел); без неё поток считается законченным по 'end'
42
+ * @param {() => void} [options.destroy] разобрать цепочку источника (процесс, демуксеры); чужой Readable не уничтожать
43
+ */
44
+ constructor(stream, { afterExit, destroy } = {}) {
45
+ this._stream = stream;
46
+ this._afterExit = afterExit ?? (callback => callback(null));
47
+ this._destroy = destroy ?? noop;
48
+ this._buffer = [];
49
+ this._count = 0; // пакетов принято из потока
50
+ this._ended = false; // новых пакетов не будет
51
+ this._streamEnded = false;
52
+ this._error = null;
53
+ this._stopped = false;
54
+ this._destroyed = false;
55
+ this._paused = false; // поток поставлен на паузу нами
56
+ this._waiting = false; // ждём 'writable' нативного источника
57
+ this._endSent = false;
58
+ this._target = null;
59
+ this._gen = 0;
60
+ this._token = 0;
61
+ this._onData = chunk => this._data(chunk);
62
+ this._onEnd = () => this._streamEnd();
63
+ this._onError = error => this.fail(error);
64
+ stream.on('data', this._onData);
65
+ stream.once('end', this._onEnd);
66
+ stream.once('close', this._onEnd);
67
+ stream.on('error', this._onError);
68
+ }
69
+
70
+ /** Накоплено 5 пакетов или поток закончился: можно начинать играть. Не сбрасывается. */
71
+ get started() {
72
+ return this._count >= START_PACKETS || this._ended;
73
+ }
74
+
75
+ /** Новых пакетов не будет (конец потока, выход источника или ошибка). */
76
+ get ended() {
77
+ return this._ended;
78
+ }
79
+
80
+ get stopped() {
81
+ return this._stopped;
82
+ }
83
+
84
+ /** Ошибка источника; читать в `onEnd`. */
85
+ get error() {
86
+ return this._error;
87
+ }
88
+
89
+ /** Пакетов принято из потока за всё время (пустой ресурс: 0, хотя `started` у закончившегося потока true). */
90
+ get packets() {
91
+ return this._count;
92
+ }
93
+
94
+ /** Pump уже подключён к источнику или остановлен: второй `play` с ним невозможен. */
95
+ get used() {
96
+ return this._target !== null || this._stopped;
97
+ }
98
+
99
+ /** Пакетов в предбуфере (ещё не в нативной очереди). */
100
+ get queued() {
101
+ return this._buffer.length;
102
+ }
103
+
104
+ /**
105
+ * Подключить нативный источник и слить предбуфер.
106
+ * @param {{ write(packet: Uint8Array, gen: number): number, end(gen: number, token: number): void }} target
107
+ */
108
+ attach(target, gen, token) {
109
+ if (this._stopped || this._target) return;
110
+ this._target = target;
111
+ this._gen = gen;
112
+ this._token = token;
113
+ this._flush();
114
+ }
115
+
116
+ /** Событие `writable` своего поколения: можно писать дальше. */
117
+ onWritable() {
118
+ if (this._stopped || !this._waiting) return;
119
+ this._waiting = false;
120
+ this._flush();
121
+ }
122
+
123
+ /**
124
+ * Источник сломался: больше данных не будет, готовые кадры доигрываются, потом `onEnd(error)`.
125
+ * @param {Error} error
126
+ */
127
+ fail(error) {
128
+ if (this._stopped || this._endSent) return;
129
+ if (!this._error) this._error = error instanceof Error ? error : new Error(String(error));
130
+ this._finishInput();
131
+ this._flush();
132
+ }
133
+
134
+ /** Остановить и разобрать источник; события конца и ошибки больше не придут. Идемпотентно. */
135
+ stop() {
136
+ if (this._stopped) return;
137
+ this._stopped = true;
138
+ this._detachStream();
139
+ this._buffer.length = 0;
140
+ this._target = null;
141
+ this._teardown();
142
+ }
143
+
144
+ _detachStream() {
145
+ this._stream.off('data', this._onData);
146
+ this._stream.off('end', this._onEnd);
147
+ this._stream.off('close', this._onEnd);
148
+ // после разбора цепочки поток может ещё выдать ошибку: она уже никому не нужна, но и процесс ронять не должна
149
+ this._stream.off('error', this._onError);
150
+ this._stream.on('error', noop);
151
+ }
152
+
153
+ _teardown() {
154
+ if (this._destroyed) return;
155
+ this._destroyed = true;
156
+ try {
157
+ this._destroy();
158
+ } catch {
159
+ // ignore
160
+ }
161
+ }
162
+
163
+ _data(chunk) {
164
+ if (this._stopped || this._ended) return;
165
+ const packet = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
166
+ this._count++;
167
+ if (this._target && !this._waiting && this._buffer.length === 0) {
168
+ this._write(packet);
169
+ return;
170
+ }
171
+ this._buffer.push(packet);
172
+ if (this._buffer.length >= PRE_BUFFER_PACKETS) this._pause();
173
+ }
174
+
175
+ _streamEnd() {
176
+ if (this._streamEnded) return;
177
+ this._streamEnded = true;
178
+ // конец потока при упавшем ffmpeg – ошибка источника, а не обычный конец
179
+ this._afterExit(error => {
180
+ if (this._stopped) return;
181
+ if (error && !this._error) this._error = error;
182
+ this._finishInput();
183
+ this._flush();
184
+ });
185
+ }
186
+
187
+ _finishInput() {
188
+ if (this._ended) return;
189
+ this._ended = true;
190
+ this._detachInput();
191
+ }
192
+
193
+ // Вход закончился: слушатели данных больше не нужны, цепочку источника можно разбирать.
194
+ _detachInput() {
195
+ this._stream.off('data', this._onData);
196
+ this._teardown();
197
+ }
198
+
199
+ _pause() {
200
+ if (this._paused) return;
201
+ this._paused = true;
202
+ this._stream.pause();
203
+ }
204
+
205
+ _resume() {
206
+ if (!this._paused || this._ended || this._stopped) return;
207
+ this._paused = false;
208
+ this._stream.resume();
209
+ }
210
+
211
+ // Записать пакет в источник; FULL ставит вход на паузу до 'writable', STALE – поколение уже сменили.
212
+ _write(packet) {
213
+ const result = this._target.write(packet, this._gen);
214
+ if (result === WRITE_FULL) {
215
+ this._waiting = true;
216
+ this._pause();
217
+ } else if (result === WRITE_STALE) {
218
+ this.stop();
219
+ }
220
+ }
221
+
222
+ _flush() {
223
+ const target = this._target;
224
+ if (!target || this._stopped) return;
225
+ while (this._buffer.length > 0 && !this._waiting && !this._stopped) this._write(this._buffer.shift());
226
+ if (this._stopped) return;
227
+ if (this._buffer.length === 0) {
228
+ if (this._ended) {
229
+ if (!this._endSent) {
230
+ this._endSent = true;
231
+ target.end(this._gen, this._token);
232
+ }
233
+ } else if (!this._waiting) {
234
+ this._resume();
235
+ }
236
+ }
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Общее для отправителя и трансляции: прогон одного источника по поколениям.
242
+ * @private
243
+ */
244
+ class NativeSource {
245
+ constructor(runtime, source, endKind) {
246
+ this._runtime = runtime;
247
+ this._source = source;
248
+ this._endKind = endKind;
249
+ this._run = null;
250
+ this._gen = 1;
251
+ this._frozenPlayed = 0;
252
+ this._closed = false;
253
+ }
254
+
255
+ get id() {
256
+ return this._source.id;
257
+ }
258
+
259
+ get closed() {
260
+ return this._closed;
261
+ }
262
+
263
+ _check() {
264
+ if (this._closed) throw new Error('the player is closed');
265
+ }
266
+
267
+ /** Идёт ли прогон: источник поставлен и событие его конца ещё не пришло. */
268
+ get playing() {
269
+ return this._run !== null;
270
+ }
271
+
272
+ /** Своя пауза источника (нативная). */
273
+ get paused() {
274
+ return this._source.paused;
275
+ }
276
+
277
+ pause() {
278
+ this._check();
279
+ return this._source.pause();
280
+ }
281
+
282
+ resume() {
283
+ this._check();
284
+ return this._source.resume();
285
+ }
286
+
287
+ /** Кадров в очереди: нативная очередь и предбуфер потока. */
288
+ get queued() {
289
+ if (this._closed) return 0;
290
+ return this._source.queued() + (this._run ? this._run.pump.queued : 0);
291
+ }
292
+
293
+ /** Сколько сэмплов (48 кГц) взято из источника в поколении `gen` (по умолчанию текущее; после конца – зафиксированное). */
294
+ playedSamples(gen) {
295
+ if (this._closed) return this._frozenPlayed;
296
+ if (gen === undefined) return this._run ? this._source.playedSamples(this._run.gen) : this._frozenPlayed;
297
+ return this._source.playedSamples(gen);
298
+ }
299
+
300
+ /**
301
+ * Поставить источник на новое поколение. Прежний прогон останавливается без колбэков.
302
+ * @returns {number} поколение
303
+ */
304
+ _start(pump, handlers) {
305
+ this._check();
306
+ this._checkPump(pump);
307
+ this._endRun();
308
+ const gen = nextGeneration++;
309
+ this._gen = gen;
310
+ this._source.setGeneration(gen);
311
+ const run = { gen, token: nextToken++, pump, handlers, started: false, starved: false, unroutes: [], hold: null };
312
+ this._run = run;
313
+ const { router } = this._runtime;
314
+ const id = this._source.id;
315
+ run.hold = router.hold();
316
+ run.unroutes.push(
317
+ router.route('started', id, ev => this._onStarted(run, ev)),
318
+ router.route('writable', id, ev => this._onWritable(run, ev)),
319
+ router.route(this._endKind, id, ev => this._onEnd(run, ev)),
320
+ ...this._extraRoutes(router, id, run),
321
+ );
322
+ this._beforeAttach();
323
+ pump.attach(this._source, gen, run.token);
324
+ return gen;
325
+ }
326
+
327
+ // Один pump – один прогон: подключённый или остановленный pump молча не стартует и повесил бы прогон.
328
+ _checkPump(pump) {
329
+ if (!(pump instanceof SourcePump)) throw new TypeError('play() requires a SourcePump');
330
+ if (pump.used) throw new Error('the SourcePump is already used: create a new one for every play()');
331
+ }
332
+
333
+ _extraRoutes() {
334
+ return [];
335
+ }
336
+
337
+ // Перед подключением pump: состояние источника для нового прогона (автопауза Feed).
338
+ _beforeAttach() {}
339
+
340
+ // Снять прогон без колбэков: маршруты, удержание loop, поток входа.
341
+ _endRun() {
342
+ const run = this._run;
343
+ if (!run) return null;
344
+ this._run = null;
345
+ this._frozenPlayed = this._source.playedSamples(run.gen);
346
+ for (const unroute of run.unroutes) unroute();
347
+ run.hold.release();
348
+ run.pump.stop();
349
+ return run;
350
+ }
351
+
352
+ /**
353
+ * Остановить источник: очередь прежнего поколения сбрасывается, колбэки не вызываются.
354
+ * @returns {boolean} шёл ли прогон
355
+ */
356
+ stop() {
357
+ if (this._closed || !this._endRun()) return false;
358
+ this._gen = nextGeneration++;
359
+ this._source.setGeneration(this._gen);
360
+ return true;
361
+ }
362
+
363
+ _onStarted(run, ev) {
364
+ if (this._run !== run || ev[2] !== run.gen || run.started) return;
365
+ // пустой ресурс: ядро шлёт started на маркер конца, но играть нечему (buffering -> idle, без playing)
366
+ if (run.pump.packets === 0) return;
367
+ run.started = true;
368
+ run.handlers.onStarted?.();
369
+ }
370
+
371
+ _onWritable(run, ev) {
372
+ if (this._run !== run || ev[2] !== run.gen) return;
373
+ run.pump.onWritable();
374
+ }
375
+
376
+ _onEnd(run, ev) {
377
+ if (this._run !== run || ev[2] !== run.token) return;
378
+ const error = run.pump.error;
379
+ this._endRun();
380
+ run.handlers.onEnd?.(error);
381
+ }
382
+
383
+ close() {
384
+ if (this._closed) return;
385
+ this._endRun();
386
+ this._closed = true;
387
+ this._source.close();
388
+ }
389
+ }
390
+
391
+ /** Отправитель соединения: один на VoiceConnection, переживает сессии и переезды. */
392
+ class SendPlayer extends NativeSource {
393
+ /** @param {{ runtime?: { core: Object, router: Object } }} [options] */
394
+ constructor({ runtime = getRuntime() } = {}) {
395
+ super(runtime, new runtime.core.Sender(), 'sender_end');
396
+ this._feed = null;
397
+ this._track = null;
398
+ }
399
+
400
+ /**
401
+ * Подключить send-трек новой сессии: часы отправки и RTP-состояние переживают смену сессии.
402
+ * @param {Object} track `SendTrack` (или `testing.FakeSink`)
403
+ * @param {{ pt: number, ssrc: number, mid: string, midExt: number, levelExt: number }} rtp
404
+ */
405
+ attach(track, rtp) {
406
+ this._check();
407
+ this._source.attach(track, rtp);
408
+ this._track = track;
409
+ }
410
+
411
+ /** Отключить send-трек; с `track` – только если он всё ещё текущий (старая сессия не отключит новую). */
412
+ detach(track) {
413
+ if (this._closed) return;
414
+ if (track !== undefined && this._track !== track) return;
415
+ this._track = null;
416
+ this._source.detach();
417
+ }
418
+
419
+ /**
420
+ * Играть `pump` вместо трансляции или прежнего источника.
421
+ * @param {SourcePump} pump
422
+ * @param {(error: Error | null) => void} onEnd источник доигран (после хвоста) или сломался; не вызывается после `stop()`
423
+ * @param {{ onStarted?: () => void }} [options] набралось 5 кадров, пейсер начал отдавать
424
+ * @returns {number} поколение
425
+ */
426
+ play(pump, onEnd, { onStarted } = {}) {
427
+ this._check();
428
+ this._checkPump(pump);
429
+ this.leave();
430
+ return this._start(pump, { onEnd, onStarted });
431
+ }
432
+
433
+ /** Играть то, что играет `feed`, с текущего места, вместо своего источника или прежней трансляции. */
434
+ follow(feed) {
435
+ this._check();
436
+ if (!(feed instanceof FeedPlayer)) throw new TypeError('follow() requires a FeedPlayer');
437
+ if (feed.closed) throw new Error('the feed is closed');
438
+ this.stop();
439
+ this._feed = feed;
440
+ this._source.follow(feed._source);
441
+ }
442
+
443
+ /** Выйти из трансляции: уйдёт хвост из 5 тихих пакетов. */
444
+ leave() {
445
+ if (this._closed || !this._feed) return false;
446
+ this._feed = null;
447
+ this._source.follow(null);
448
+ return true;
449
+ }
450
+
451
+ /** Трансляция, за которой идёт отправитель. */
452
+ get feed() {
453
+ return this._feed;
454
+ }
455
+
456
+ /** Есть трансляция, нет своей паузы, трек открыт. */
457
+ get playable() {
458
+ return !this._closed && this._source.playable;
459
+ }
460
+
461
+ stats() {
462
+ const data = this._source.stats();
463
+ return { ...data, queuedFrames: data.queuedFrames + (this._run ? this._run.pump.queued : 0), broadcast: this._feed !== null };
464
+ }
465
+
466
+ close() {
467
+ if (this._closed) return;
468
+ this._feed = null;
469
+ super.close();
470
+ }
471
+ }
472
+
473
+ const NO_SUBSCRIBER = ['pause', 'play'];
474
+
475
+ /**
476
+ * Один источник на много соединений: читается и кодируется один раз, кадры раздаёт ядро подписанным
477
+ * `SendPlayer` (`sendPlayer.follow(feedPlayer)`).
478
+ *
479
+ * Автопауза (`noSubscriber: 'pause'`): без играбельных подписчиков (трек открыт, нет своей паузы) нативная
480
+ * пауза Feed включена и источник не тратится. Оценка идёт при старте прогона и на каждом `feed_playable`,
481
+ * берётся живое `feed.playable`, а не число из события, поэтому устаревшее событие не вредит.
482
+ */
483
+ class FeedPlayer extends NativeSource {
484
+ /**
485
+ * @param {Object} [options]
486
+ * @param {'pause' | 'play'} [options.noSubscriber]
487
+ * @param {number} [options.maxMissedFrames] 0 – без события `starved`
488
+ * @param {{ core: Object, router: Object }} [options.runtime]
489
+ */
490
+ constructor({ noSubscriber = 'pause', maxMissedFrames = 0, runtime = getRuntime() } = {}) {
491
+ if (!NO_SUBSCRIBER.includes(noSubscriber)) throw new TypeError(`noSubscriber must be one of ${NO_SUBSCRIBER.join(', ')}`);
492
+ super(runtime, new runtime.core.Feed({ maxMissedFrames }), 'feed_end');
493
+ this.noSubscriber = noSubscriber;
494
+ /**
495
+ * Колбэк владельца: число играбельных подписчиков изменилось (после оценки автопаузы). Только во время прогона.
496
+ * @type {((playable: number) => void) | null}
497
+ */
498
+ this.onPlayable = null;
499
+ this._manualPaused = false;
500
+ this._autoPaused = false;
501
+ }
502
+
503
+ /**
504
+ * Играть `pump` на всех подписчиков. Прежний прогон останавливается без колбэков; пауза сбрасывается.
505
+ * @param {SourcePump} pump
506
+ * @param {{ onStarted?: () => void, onEnd?: (error: Error | null) => void, onStarved?: () => void }} [handlers]
507
+ * @returns {number} поколение
508
+ */
509
+ play(pump, handlers = {}) {
510
+ this._check();
511
+ this._checkPump(pump);
512
+ this._manualPaused = false;
513
+ return this._start(pump, handlers);
514
+ }
515
+
516
+ _extraRoutes(router, id, run) {
517
+ return [
518
+ router.route('starved', id, ev => {
519
+ if (this._run !== run || ev[2] !== run.gen || run.starved) return;
520
+ run.starved = true;
521
+ run.handlers.onStarved?.();
522
+ }),
523
+ router.route('feed_playable', id, () => {
524
+ if (this._run !== run) return;
525
+ this._evaluate();
526
+ this.onPlayable?.(this.playable);
527
+ }),
528
+ ];
529
+ }
530
+
531
+ _beforeAttach() {
532
+ this._evaluate();
533
+ }
534
+
535
+ // Нативная пауза = ручная пауза или автопауза без играбельных подписчиков.
536
+ _evaluate() {
537
+ if (this._closed) return;
538
+ this._autoPaused = this.noSubscriber === 'pause' && this._run !== null && this._source.playable === 0;
539
+ const pause = this._manualPaused || this._autoPaused;
540
+ if (pause !== this._source.paused) {
541
+ if (pause) this._source.pause();
542
+ else this._source.resume();
543
+ }
544
+ }
545
+
546
+ stop() {
547
+ const stopped = super.stop();
548
+ this._manualPaused = false;
549
+ this._autoPaused = false;
550
+ this._evaluate();
551
+ return stopped;
552
+ }
553
+
554
+ _onEnd(run, ev) {
555
+ if (this._run !== run || ev[2] !== run.token) return;
556
+ this._autoPaused = false;
557
+ super._onEnd(run, ev);
558
+ }
559
+
560
+ /** Ручная пауза для всех подписчиков. */
561
+ setPaused(paused) {
562
+ this._check();
563
+ this._manualPaused = Boolean(paused);
564
+ this._evaluate();
565
+ }
566
+
567
+ pause() {
568
+ this.setPaused(true);
569
+ return true;
570
+ }
571
+
572
+ resume() {
573
+ this.setPaused(false);
574
+ return true;
575
+ }
576
+
577
+ /** Ручная пауза. */
578
+ get paused() {
579
+ return this._manualPaused;
580
+ }
581
+
582
+ /** Автопауза: нет играбельных подписчиков. */
583
+ get autoPaused() {
584
+ return this._autoPaused;
585
+ }
586
+
587
+ /** Подписчиков, которым Feed сейчас раздаёт кадры: трек открыт и нет своей паузы. */
588
+ get playable() {
589
+ return this._closed ? 0 : this._source.playable;
590
+ }
591
+
592
+ get subscribers() {
593
+ return this._closed ? 0 : this._source.subscribers;
594
+ }
595
+
596
+ missedFrames() {
597
+ return this._closed ? 0 : this._source.missedFrames();
598
+ }
599
+
600
+ stats() {
601
+ const data = this._source.stats();
602
+ return { ...data, queuedFrames: data.queuedFrames + (this._run ? this._run.pump.queued : 0) };
603
+ }
604
+ }
605
+
606
+ module.exports = { SourcePump, SendPlayer, FeedPlayer, PRE_BUFFER_PACKETS, START_PACKETS };