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,44 @@
1
+ Copyright 2001-2023 Xiph.Org, Skype Limited, Octasic,
2
+ Jean-Marc Valin, Timothy B. Terriberry,
3
+ CSIRO, Gregory Maxwell, Mark Borgerding,
4
+ Erik de Castro Lopo, Mozilla, Amazon
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions
8
+ are met:
9
+
10
+ - Redistributions of source code must retain the above copyright
11
+ notice, this list of conditions and the following disclaimer.
12
+
13
+ - Redistributions in binary form must reproduce the above copyright
14
+ notice, this list of conditions and the following disclaimer in the
15
+ documentation and/or other materials provided with the distribution.
16
+
17
+ - Neither the name of Internet Society, IETF or IETF Trust, nor the
18
+ names of specific contributors, may be used to endorse or promote
19
+ products derived from this software without specific prior written
20
+ permission.
21
+
22
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23
+ ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
26
+ OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
+
34
+ Opus is subject to the royalty-free patent licenses which are
35
+ specified at:
36
+
37
+ Xiph.Org Foundation:
38
+ https://datatracker.ietf.org/ipr/1524/
39
+
40
+ Microsoft Corporation:
41
+ https://datatracker.ietf.org/ipr/1914/
42
+
43
+ Broadcom Corporation:
44
+ https://datatracker.ietf.org/ipr/1526/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Sergey Podobry
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2015, Randall Stewart and Michael Tuexen
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of usrsctp nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,16 @@
1
+ Third-party components compiled into the lolka-voice native core and their licenses.
2
+ The full texts are in the LICENSE-*.txt files next to this one.
3
+
4
+ libdatachannel MPL-2.0 https://github.com/paullouisageneau/libdatachannel (tag v0.24.6)
5
+ libjuice MPL-2.0 https://github.com/paullouisageneau/libjuice (the revision pinned by libdatachannel v0.24.6)
6
+ libsrtp BSD-3-Clause https://github.com/cisco/libsrtp (the revision pinned by libdatachannel v0.24.6)
7
+ usrsctp BSD-3-Clause https://github.com/sctplab/usrsctp (the revision pinned by libdatachannel v0.24.6)
8
+ plog MIT https://github.com/SergiusTheBest/plog (the revision pinned by libdatachannel v0.24.6)
9
+ nlohmann/json MIT https://github.com/nlohmann/json (the revision pinned by libdatachannel v0.24.6)
10
+ Opus BSD-3-Clause https://github.com/xiph/opus (tag v1.5.2)
11
+ OpenSSL Apache-2.0 https://github.com/openssl/openssl (tag openssl-3.5.4, built statically)
12
+ node-addon-api MIT https://github.com/nodejs/node-addon-api (Node-API addon only)
13
+ node-api-headers MIT https://github.com/nodejs/node-api-headers (Node-API addon only)
14
+ nanobind BSD-3-Clause https://github.com/wjakob/nanobind (Python extension only)
15
+
16
+ The MPL-2.0 components (libdatachannel, libjuice) are used unmodified; their source is available at the URLs above.
@@ -0,0 +1,47 @@
1
+ {
2
+ "files": {
3
+ "LICENSES/LICENSE-libdatachannel.txt": "fab3dd6bdab226f1c08630b1dd917e11fcb4ec5e1e020e2c16f83a0a13863e85",
4
+ "LICENSES/LICENSE-libjuice.txt": "fab3dd6bdab226f1c08630b1dd917e11fcb4ec5e1e020e2c16f83a0a13863e85",
5
+ "LICENSES/LICENSE-libsrtp.txt": "8e19d42a1eec9561f3f347253ddf2e385c55f392f025bb0fd41b88dbf38db5ae",
6
+ "LICENSES/LICENSE-nlohmann-json.txt": "46a65cffd1ea955132d95a8dd921640714a8d6b537d2e4e482d31145ae95b603",
7
+ "LICENSES/LICENSE-node-addon-api.txt": "89024017b88a9f2b763f79b941a4f2db3b4428edfcacdc0b23866b2da633ad0c",
8
+ "LICENSES/LICENSE-node-api-headers.txt": "a553508f516031c91f3af1148d44970cb81bbae6c4f091be6835d39cc252238c",
9
+ "LICENSES/LICENSE-openssl.txt": "7d5450cb2d142651b8afa315b5f238efc805dad827d91ba367d8516bc9d49e7a",
10
+ "LICENSES/LICENSE-opus.txt": "01e1167d54a096d123cf6dfbbeb19587278845c6481d2d66d545669846079551",
11
+ "LICENSES/LICENSE-plog.txt": "e4d01796524cbc13b1571a1f0914823c6a23b316ba039e7014f47a4eef7fd4c3",
12
+ "LICENSES/LICENSE-usrsctp.txt": "fa53711b25af4b9a9b8dadfea3cb38166ec4b96760c8d62b284055554537d9ef",
13
+ "LICENSES/THIRD-PARTY.txt": "7285ae9a93e6abb58b2d2b97e36c759e8502a6e924cd011ff73ec4f187206b8d",
14
+ "_loader.js": "afe02e880b0fcfe56d623db426c3c34f7e817fd05dcc3386fac9929a8d8ab92e",
15
+ "_native/linux-aarch64-musl/core.node": "2f11d88451ad3b78ff348df71862a1763a725466862cf241a1c03181aa173c7a",
16
+ "_native/linux-aarch64/core.node": "cf967fba7ceaa0e1faad2cd09c723cc49b9e2e15144e85e83781da4ffab825b8",
17
+ "_native/linux-x86_64-musl/core.node": "4d748a365285df5627df9d2ead299dacad8a37d40a96d6c752e46b11adde7bc2",
18
+ "_native/linux-x86_64/core.node": "ddc44f3f8b502e35419e03d64730cc3c9410ac08ff73e6bb8da3b50984fdb89f",
19
+ "_native/macos-arm64/core.node": "ac8124408b7b23c321820b4996cb158675478dea3b0e64889803091f71f21f6f",
20
+ "_native/macos-x86_64/core.node": "bd49fdd9b978780c276e028334cd50d48d3c9d7c9fbcc0fd9a1e4e6715c10dcc",
21
+ "_native/windows-x86_64/core.node": "d761e5c510a61ae891ca4874d210b1d49d3d9ac7631b6e6ff47f353420fdd7f4",
22
+ "_version.js": "17d89c7713ddefb6824ac9802c87abfcb3e95b0074226134b62d5ce71f5c8496",
23
+ "caps.js": "b8fa4ab81cc9b0a0b10b8d337e8d5f9c77cc9505c839beea950e59e5b4ec5fb4",
24
+ "core.d.ts": "75a80faf872fd469480671ab65b89f6c0330e4c2ae8047c5415fca42b6e147a4",
25
+ "errors.js": "1b0cb8a313e302a534aa23bdad8ffabebfe1ac619205111456956f31d9aa11a0",
26
+ "events.js": "cb85d442decb064e4dc067afd867fbea7e37143dafae4696dd97b53f1d40b094",
27
+ "index.d.ts": "27882578ab6e5ce311973d79f849c98062e12b4c9daf9219ba93ee616fff7ecc",
28
+ "index.js": "5577998d790f4a64b18458de31a764cac831a06b0dba6699e47585ce6e67c6d6",
29
+ "player.js": "ff03bf86c960787c864441666439de6a54657b12413fe788c6f3b9e190381318",
30
+ "receive.js": "e8072f47189902e9edf8eeadd7b9f975ed269b6e4d8dc9c4f9325cfeea2a93e4",
31
+ "sdp.js": "ebadbf30af21d6f30fb869e48d55a6a1e45d04daf2a67b675f2dfcbb2a312a5f",
32
+ "session.js": "f650cda414c8301a07a3f9488e13507b82ab81aaa4fa1615b9fa0717050e4d7f",
33
+ "signaling.js": "08cdf34d886e8880bdda4c3e18779f4aec05a8d67637fcb518adc24b03d99af3",
34
+ "transport.js": "5fc2de45b5b8ba4267bdcfbbaaa307c2e0f8a23a0ab1d072f0bf645a5d9eb211"
35
+ },
36
+ "platforms": [
37
+ "linux-aarch64",
38
+ "linux-aarch64-musl",
39
+ "linux-x86_64",
40
+ "linux-x86_64-musl",
41
+ "macos-arm64",
42
+ "macos-x86_64",
43
+ "windows-x86_64"
44
+ ],
45
+ "source_commit": "16c4674f3ebe94ea93825d93cd64184347aade85",
46
+ "version": "0.3.0"
47
+ }
@@ -0,0 +1,103 @@
1
+ 'use strict';
2
+
3
+ // Единственное место, которое грузит core.node (правило зависимостей: lolka.js бинарь напрямую не require-ит).
4
+ //
5
+ // Два режима:
6
+ // - вложенный: рядом есть `_native/`, бинарь лежит в `_native/<платформа>/core.node`;
7
+ // - разработка: `../build/core.node` (scripts/build-node.sh); здесь же работает LOLKA_VOICE_NODE – путь к другому
8
+ // core.node (CI проверяет артефакт). Во вложенном режиме переменная игнорируется.
9
+ //
10
+ // Ядро в этом файле только загружается и проверяется; запускает его (`init`) слой лениво, при первом голосовом объекте.
11
+
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+ const { VERSION } = require('./_version');
15
+ const { unsupported } = require('./errors');
16
+
17
+ const NATIVE_DIR = '_native';
18
+ const MIN_NAPI = 8;
19
+
20
+ let cached = null;
21
+
22
+ function isMusl() {
23
+ let header;
24
+ try {
25
+ header = process.report.getReport().header;
26
+ } catch {
27
+ header = null;
28
+ }
29
+ // glibc – главный признак: файл загрузчика musl бывает и на glibc-системах
30
+ if (header && header.glibcVersionRuntime) return false;
31
+ return ['/lib', '/usr/lib'].some(dir => {
32
+ try {
33
+ return fs.readdirSync(dir).some(name => name.startsWith('ld-musl-'));
34
+ } catch {
35
+ return false;
36
+ }
37
+ });
38
+ }
39
+
40
+ /**
41
+ * Имя каталога с ядром: `linux-x86_64`, `linux-aarch64-musl`, `macos-arm64`, `windows-x86_64`.
42
+ * @param {{ platform?: string, arch?: string, musl?: () => boolean }} [env] подмена для тестов
43
+ */
44
+ function platformKey({ platform = process.platform, arch = process.arch, musl = isMusl } = {}) {
45
+ const cpu = arch === 'x64' ? 'x86_64' : arch;
46
+ if (platform === 'linux') return `linux-${cpu === 'arm64' ? 'aarch64' : cpu}${musl() ? '-musl' : ''}`;
47
+ if (platform === 'darwin') return `macos-${cpu}`;
48
+ if (platform === 'win32') return `windows-${cpu}`;
49
+ return `${platform}-${cpu}`;
50
+ }
51
+
52
+ /** Платформы, для которых во вложенном каталоге есть бинарь. */
53
+ function availablePlatforms(base = __dirname) {
54
+ try {
55
+ return fs
56
+ .readdirSync(path.join(base, NATIVE_DIR), { withFileTypes: true })
57
+ .filter(e => e.isDirectory() && fs.existsSync(path.join(base, NATIVE_DIR, e.name, 'core.node')))
58
+ .map(e => e.name)
59
+ .sort();
60
+ } catch {
61
+ return [];
62
+ }
63
+ }
64
+
65
+ /** Путь к core.node для этой машины; `LOLKA_VOICE_UNSUPPORTED`, если бинаря нет. */
66
+ function corePath({ base = __dirname, key = platformKey(), env = process.env } = {}) {
67
+ if (!fs.existsSync(path.join(base, NATIVE_DIR))) {
68
+ const file = env.LOLKA_VOICE_NODE || path.join(base, '..', 'build', 'core.node');
69
+ if (!fs.existsSync(file)) throw unsupported(`native voice core is not built (${file} not found); run scripts/build-node.sh`);
70
+ return file;
71
+ }
72
+ const file = path.join(base, NATIVE_DIR, key, 'core.node');
73
+ if (!fs.existsSync(file)) {
74
+ const available = availablePlatforms(base);
75
+ throw unsupported(`no native voice core for ${key}; available platforms: ${available.join(', ') || 'none'}`);
76
+ }
77
+ return file;
78
+ }
79
+
80
+ /**
81
+ * Загрузить нативное ядро (один раз на процесс). Ошибки – `code = 'LOLKA_VOICE_UNSUPPORTED'`:
82
+ * нет бинаря для платформы, Node-API старше 8, бинарь другой версии, чем слой.
83
+ */
84
+ function loadCore() {
85
+ if (cached) return cached;
86
+ if (Number(process.versions.napi) < MIN_NAPI) {
87
+ throw unsupported(`the native voice core needs Node-API ${MIN_NAPI} (Node 18.20+), this Node has ${process.versions.napi}`);
88
+ }
89
+ const file = corePath();
90
+ let core;
91
+ try {
92
+ core = require(file);
93
+ } catch (error) {
94
+ throw unsupported(`cannot load the native voice core ${file}: ${error.message}`, error);
95
+ }
96
+ if (core.version !== VERSION) {
97
+ throw unsupported(`stale native voice core ${core.version}: the layer expects ${VERSION}; re-vendor the binaries`);
98
+ }
99
+ cached = core;
100
+ return core;
101
+ }
102
+
103
+ module.exports = { loadCore, platformKey, corePath, availablePlatforms, isMusl };
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+
3
+ // Версия слоя = версия нативного ядра. Источник один: python/lolka_voice/_version.py; versions.test.js ловит расхождение.
4
+ module.exports = { VERSION: '0.3.0' };
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+
3
+ // Работа с routerRtpCapabilities mediasoup: Opus и расширения заголовка берутся из них,
4
+ // PT и id расширений не хардкодятся (PT назначает mediasoup).
5
+
6
+ const URI_MID = 'urn:ietf:params:rtp-hdrext:sdes:mid';
7
+ const URI_LEVEL = 'urn:ietf:params:rtp-hdrext:ssrc-audio-level';
8
+
9
+ // Параметры Opus, которые продюсер объявляет серверу и пишет в SDP: stereo/sprop-stereo
10
+ // доходят до консьюмеров, usedtx нужен, потому что в паузе и тишине пакетов нет.
11
+ const OPUS_SEND_PARAMETERS = Object.freeze({ minptime: 10, useinbandfec: 1, usedtx: 1, 'sprop-stereo': 1, stereo: 1 });
12
+
13
+ /**
14
+ * @param {Object} routerRtpCapabilities ответ getRouterRtpCapabilities
15
+ * @returns {{ codec: Object, pt: number, midId: number, levelId: number, midExt: Object, levelExt: Object }}
16
+ */
17
+ function opusFromCaps(routerRtpCapabilities) {
18
+ const codecs = routerRtpCapabilities?.codecs ?? [];
19
+ const extensions = routerRtpCapabilities?.headerExtensions ?? [];
20
+ const codec = codecs.find(c => String(c.mimeType).toLowerCase() === 'audio/opus');
21
+ if (!codec) throw new Error('voice server does not offer the Opus codec');
22
+ const ext = uri => extensions.find(e => e.kind === 'audio' && e.uri === uri);
23
+ const midExt = ext(URI_MID);
24
+ const levelExt = ext(URI_LEVEL);
25
+ if (!midExt || !levelExt) throw new Error('voice server does not offer the mid / ssrc-audio-level RTP extensions');
26
+ return { codec, pt: codec.preferredPayloadType, midId: midExt.preferredId, levelId: levelExt.preferredId, midExt, levelExt };
27
+ }
28
+
29
+ /**
30
+ * rtpCapabilities для `consume`: Opus как в router caps и расширения mid и ssrc-audio-level,
31
+ * в том же виде, что шлёт mediasoup-client (Rust-SFU валидирует строго).
32
+ */
33
+ function recvCapabilities(opus) {
34
+ return {
35
+ codecs: [{ ...opus.codec, rtcpFeedback: [] }],
36
+ headerExtensions: [opus.midExt, opus.levelExt],
37
+ };
38
+ }
39
+
40
+ /** rtpParameters для `produce`. */
41
+ function produceRtpParameters({ opus, ssrc, cname, mid = '0', parameters = OPUS_SEND_PARAMETERS }) {
42
+ return {
43
+ mid,
44
+ codecs: [
45
+ { mimeType: 'audio/opus', payloadType: opus.pt, clockRate: 48000, channels: 2, parameters: { ...parameters }, rtcpFeedback: [] },
46
+ ],
47
+ headerExtensions: [
48
+ { uri: URI_MID, id: opus.midId, encrypt: false, parameters: {} },
49
+ { uri: URI_LEVEL, id: opus.levelId, encrypt: false, parameters: {} },
50
+ ],
51
+ encodings: [{ ssrc }],
52
+ rtcp: { cname, reducedSize: true },
53
+ };
54
+ }
55
+
56
+ module.exports = { URI_MID, URI_LEVEL, OPUS_SEND_PARAMETERS, opusFromCaps, recvCapabilities, produceRtpParameters };
@@ -0,0 +1,200 @@
1
+ // Типы Node-API аддона core.node (аналог python/lolka_voice/_core.pyi). Загружает аддон только _loader.js слоя.
2
+ // Любое исключение ядра - Error с code = 'LOLKA_VOICE_NATIVE' (и reject у Promise); неверные аргументы - TypeError / RangeError.
3
+
4
+ export const version: string; // = _version.js; слой сверяет при загрузке
5
+ export const MODE_NONE: 0;
6
+ export const MODE_OPUS: 3;
7
+ export const WRITE_OK: 0;
8
+ export const WRITE_FULL: 1;
9
+ export const WRITE_STALE: 2;
10
+
11
+ export function buildInfo(): {
12
+ version: string;
13
+ commit: string;
14
+ openssl: string;
15
+ opus: string;
16
+ libdatachannel: string;
17
+ napiVersion: number;
18
+ };
19
+ // идемпотентно на процесс; запускает ядро, пейсер и поток событий. Классы без init() бросают Error LOLKA_VOICE_NATIVE.
20
+ export function init(o: { logLevel: number /* 0..6 */; threadPool?: number }): void;
21
+ // один обработчик на env; создаёт TSFN в состоянии unref (event loop он не держит). Вызывается одной пачкой на всё накопленное.
22
+ // Исключение обработчика уходит в uncaughtException (через setImmediate), следующие пачки продолжают приходить.
23
+ export function setEventHandler(fn: (batch: CoreEvent[]) => void): void;
24
+ // удержание loop этого env (счётчик): пока есть открытый Peer или источник с ещё не пришедшим событием конца
25
+ export function ref(): void;
26
+ export function unref(): void;
27
+ export function stats(): {
28
+ pacer: {
29
+ ticks: number;
30
+ lateTicks: number;
31
+ active: number;
32
+ lateP99Ms: number;
33
+ lateMaxMs: number;
34
+ cpuS: number;
35
+ tickWorkUs: { p50: number; p99: number; max: number };
36
+ };
37
+ peers: number; // живые объекты Peer в ядре (после gc незакрытые уходят в 0)
38
+ eventWakeups: number;
39
+ tsfnCalls: number;
40
+ pendingEvents: number;
41
+ envs: number;
42
+ routes: number; // маршруты id -> env (Peer и источники)
43
+ graveyardClosed: number; // закрыто «кладбищем» за всё время
44
+ };
45
+ export function resetStats(): void;
46
+ // только тесты: закрывает ядро и останавливает поток событий; после него снова init()
47
+ export function shutdown(timeoutMs?: number): Promise<void>;
48
+
49
+ export type CoreEvent =
50
+ | ['state', number /* peerId */, 'new' | 'connecting' | 'connected' | 'disconnected' | 'failed' | 'closed']
51
+ | ['track_open', number]
52
+ | ['sender_end', number /* senderId */, number /* token */]
53
+ | ['feed_end', number /* feedId */, number /* token */]
54
+ | ['feed_playable', number /* feedId */, number /* count */]
55
+ | ['started', number /* sourceId */, number /* gen */]
56
+ | ['writable', number /* sourceId */, number /* gen */]
57
+ | ['starved', number /* feedId */, number /* gen */]
58
+ // payload всех пакетов пачки склеены; meta = [len, seq, ts] на пакет; dropped - выброшенные из очереди (приём и pending)
59
+ | ['opus', number /* peerId */, number /* key */, Buffer, Uint32Array, number /* dropped */]
60
+ | ['log', number /* rtc level */, string];
61
+
62
+ export class Peer {
63
+ constructor(name: string);
64
+ readonly id: number;
65
+ readonly state: string;
66
+ addSendAudio(o: { mid: string; pt: number; fmtp: string; ssrc: number; cname: string; midExt: number; levelExt: number }): SendTrack;
67
+ createOffer(timeoutMs?: number, waitGathering?: boolean): Promise<string>;
68
+ setRemoteDescription(sdp: string, type: 'offer' | 'answer'): Promise<void>;
69
+ answerOffer(sdp: string, timeoutMs?: number, waitGathering?: boolean): Promise<string>;
70
+ addConsumer(o: { ssrc: number; key: number; mode: 0 | 3 }): void;
71
+ setConsumerMode(key: number, mode: 0 | 3): void;
72
+ removeConsumer(key: number): void;
73
+ consumerStats(key: number): { packetsReceived: number; packetsLost: number; droppedOverflow: number; emptyDropped: number };
74
+ releaseTracks(mids: string[]): Promise<void>;
75
+ trackCount(): number;
76
+ stats(): { unknownDropped: number; invalidDropped: number; tracks: number };
77
+ close(): Promise<void>; // идемпотентно
78
+ }
79
+
80
+ export class SendTrack {
81
+ // только Peer.addSendAudio
82
+ private constructor();
83
+ readonly isOpen: boolean;
84
+ }
85
+
86
+ interface Source {
87
+ readonly id: number;
88
+ readonly paused: boolean;
89
+ setGeneration(gen: number): void; // выбрасывает очередь старого поколения
90
+ write(packet: Uint8Array, gen: number): 0 | 1 | 2; // копия; никогда не ждёт; FULL - пауза потока до 'writable'
91
+ end(gen: number, token: number): void;
92
+ playedSamples(gen: number): number;
93
+ queued(): number;
94
+ pause(): boolean;
95
+ resume(): boolean;
96
+ close(): void; // синхронно, идемпотентно
97
+ }
98
+
99
+ export class Sender implements Source {
100
+ constructor();
101
+ readonly id: number;
102
+ readonly paused: boolean;
103
+ setGeneration(gen: number): void;
104
+ write(packet: Uint8Array, gen: number): 0 | 1 | 2;
105
+ end(gen: number, token: number): void;
106
+ playedSamples(gen: number): number;
107
+ queued(): number;
108
+ pause(): boolean;
109
+ resume(): boolean;
110
+ close(): void;
111
+ // pt 0..127, ssrc uint32, mid 1..16 байт, midExt и levelExt 1..14
112
+ attach(track: SendTrack | testing.FakeSink, o: { pt: number; ssrc: number; mid: string; midExt: number; levelExt: number }): void;
113
+ detach(): void;
114
+ follow(feed: Feed | null): void;
115
+ readonly playable: boolean; // есть Feed, нет своей паузы, sink открыт
116
+ stats(): {
117
+ packetsSent: number;
118
+ bytesSent: number;
119
+ underruns: number;
120
+ lateTicks: number;
121
+ bursts: number;
122
+ resyncs: number;
123
+ silentSkipped: number;
124
+ drops: number;
125
+ skipped: number;
126
+ queuedFrames: number;
127
+ };
128
+ }
129
+
130
+ export class Feed implements Source {
131
+ constructor(o?: { maxMissedFrames?: number }); // 0 - без 'starved'
132
+ readonly id: number;
133
+ readonly paused: boolean;
134
+ setGeneration(gen: number): void;
135
+ write(packet: Uint8Array, gen: number): 0 | 1 | 2;
136
+ end(gen: number, token: number): void;
137
+ playedSamples(gen: number): number;
138
+ queued(): number;
139
+ pause(): boolean;
140
+ resume(): boolean;
141
+ close(): void;
142
+ readonly subscribers: number;
143
+ readonly playable: number;
144
+ missedFrames(): number;
145
+ stats(): {
146
+ framesPublished: number;
147
+ underruns: number;
148
+ resyncs: number;
149
+ queuedFrames: number;
150
+ ringFrames: number;
151
+ headRefs: number;
152
+ subscribers: number;
153
+ playable: number;
154
+ paused: boolean;
155
+ publishing: boolean;
156
+ };
157
+ }
158
+
159
+ // только тесты и замер, как у Python
160
+ export namespace testing {
161
+ class ManualClock {
162
+ constructor();
163
+ advance(ms: number): void; // тики выполняются в вызывающем потоке
164
+ }
165
+ function useManualClock(clock: ManualClock | null): void;
166
+ // меньший лимит пакетов opus на консьюмер в pending позволяет проверить переполнение без многосекундной паузы потока
167
+ function setOpusPendingMax(n: number): void;
168
+ // пауза в миллисекундах между остановкой ядра и join потока событий (окно гонки смены env)
169
+ function setShutdownDelay(ms: number): void;
170
+ class FakeSink {
171
+ constructor();
172
+ open: boolean;
173
+ fail: boolean;
174
+ take(): Buffer[];
175
+ }
176
+ class RxProbe {
177
+ constructor(mode: 0 | 3);
178
+ push(rtp: Uint8Array): void;
179
+ drain(flush?: boolean): Array<[Buffer, Uint32Array, number /* dropped */]>;
180
+ stats(): { packetsReceived: number; droppedOverflow: number; emptyDropped: number; decodedFrames: number };
181
+ }
182
+ // всё поставленное в очередь до вызова уже отдано обработчику; нужен setEventHandler
183
+ function barrier(): Promise<void>;
184
+ function splitOpus(p: Uint8Array): Buffer[];
185
+ function opusInfo(p: Uint8Array): [number /* samples */, boolean /* silent */];
186
+ function buildRtp(o: {
187
+ pt: number;
188
+ seq: number;
189
+ timestamp: number;
190
+ ssrc: number;
191
+ marker: boolean;
192
+ mid: string;
193
+ midId: number;
194
+ levelId: number;
195
+ silent: boolean;
196
+ payload: Uint8Array;
197
+ level?: number;
198
+ }): Buffer;
199
+ function parseRtp(p: Uint8Array): { pt: number; marker: boolean; sequence: number; timestamp: number; ssrc: number; payload: Buffer } | null;
200
+ }
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ const NATIVE = 'LOLKA_VOICE_NATIVE';
4
+ const UNSUPPORTED = 'LOLKA_VOICE_UNSUPPORTED';
5
+
6
+ /** Ошибка ядра: Error с `code = 'LOLKA_VOICE_NATIVE'` (в том числе reject у Promise). */
7
+ function isNativeError(error) {
8
+ return error instanceof Error && error.code === NATIVE;
9
+ }
10
+
11
+ /** Ошибка загрузки ядра (платформа, Node-API, версия бинаря): `code = 'LOLKA_VOICE_UNSUPPORTED'`. */
12
+ function isUnsupportedError(error) {
13
+ return error instanceof Error && error.code === UNSUPPORTED;
14
+ }
15
+
16
+ function unsupported(message, cause) {
17
+ const error = new Error(message, cause === undefined ? undefined : { cause });
18
+ error.code = UNSUPPORTED;
19
+ return error;
20
+ }
21
+
22
+ module.exports = { NATIVE, UNSUPPORTED, isNativeError, isUnsupportedError, unsupported };