From 8abd2d6228685256987bbeaa8db89a6b80068fcc Mon Sep 17 00:00:00 2001 From: illusia <64828020+EchoSixHIYA@users.noreply.github.com> Date: Thu, 3 Sep 2026 00:47:51 +0800 Subject: [PATCH] feat(audio): add experimental WebRTC transport --- package-lock.json | 525 +++++++++++++++++++++++ package.json | 1 + src/index.ts | 20 + src/server/voice-bridge.ts | 82 +++- src/server/webrtc-audio.ts | 209 +++++++++ web/src/composables/useVoiceWebSocket.ts | 172 +++++++- 6 files changed, 1000 insertions(+), 9 deletions(-) create mode 100644 src/server/webrtc-audio.ts diff --git a/package-lock.json b/package-lock.json index 9828a1d..ca1a3c0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,7 @@ "@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6", "express": "^5.2.1", "pino": "^10.3.1", + "werift": "0.24.4", "ws": "^8.20.0" }, "devDependencies": { @@ -513,6 +514,28 @@ "node": ">=18" } }, + "node_modules/@fidm/asn1": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@fidm/asn1/-/asn1-1.0.4.tgz", + "integrity": "sha512-esd1jyNvRb2HVaQGq2Gg8Z0kbQPXzV9Tq5Z14KNIov6KfFD6PTaRIO8UpcsYiTNzOqJpmyzWgVTrUwFV3UF4TQ==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@fidm/x509": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@fidm/x509/-/x509-1.2.1.tgz", + "integrity": "sha512-nwc2iesjyc9hkuzcrMCBXQRn653XuAUKorfWM8PZyJawiy1QzLj4vahwzaI25+pfpwOLvMzbJ0uKpWLDNmo16w==", + "license": "MIT", + "dependencies": { + "@fidm/asn1": "^1.0.4", + "tweetnacl": "^1.0.1" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/@isaacs/fs-minipass": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", @@ -525,6 +548,12 @@ "node": ">=18.0.0" } }, + "node_modules/@leichtgewicht/ip-codec": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz", + "integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==", + "license": "MIT" + }, "node_modules/@noble/curves": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.2.0.tgz", @@ -552,12 +581,212 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@peculiar/asn1-cms": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.9.4.tgz", + "integrity": "sha512-cben7oxmQsUGZqotus7yt0srYdncOT6RNWcTQ77T2RFOXejYVYkXadrfePdRcrVpO9K95IRLKKglG2k38jKXuw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.4", + "@peculiar/asn1-x509": "^2.9.4", + "@peculiar/asn1-x509-attr": "^2.9.4", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-csr": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.9.4.tgz", + "integrity": "sha512-xd4YN4vpRjkDAQWVfZZkeu12IEND7DOpkqaHSIHxZl1uggUNa9Ju0QxY2jHvDAS9pP0zhRBytg8ifsnGo3V0jw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.4", + "@peculiar/asn1-x509": "^2.9.4", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-ecc": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.9.4.tgz", + "integrity": "sha512-JJXefFshRAuVAjWQo/39bkg1ywc1VaiO44S8RRC+Ykvf/u2KDmYffoDb0ZBPCR5uJy4AGKQhl8mX+Q8ShcWaXQ==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.4", + "@peculiar/asn1-x509": "^2.9.4", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pfx": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.9.4.tgz", + "integrity": "sha512-khuGzHTzNzk4GDlIBEILyIs6Lce0yn0ZBdoI9v93kmNncfZRhD+AQ5ODFqdhvoE8cMJF/JMTQ8yA+t1D14kqCw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.9.4", + "@peculiar/asn1-pkcs8": "^2.9.4", + "@peculiar/asn1-rsa": "^2.9.4", + "@peculiar/asn1-schema": "^2.9.4", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pkcs8": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.9.4.tgz", + "integrity": "sha512-duRdotlUx9eDZe6QrQpQKl61RbWykCHBCkKayP8V8XdEFwlKHZ8qGGDMyS6Pye7OX7nLFttTTpRkJeet78ckwQ==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.4", + "@peculiar/asn1-x509": "^2.9.4", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-pkcs9": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.9.4.tgz", + "integrity": "sha512-kaL4cNxBpdQE2dKlyZBqz4ygCrwffO+8wfoxTEqM1Z8RadvCeELBRzcv0dzM8aY9azHMwODO5nxU65zXmhToOQ==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.9.4", + "@peculiar/asn1-pfx": "^2.9.4", + "@peculiar/asn1-pkcs8": "^2.9.4", + "@peculiar/asn1-schema": "^2.9.4", + "@peculiar/asn1-x509": "^2.9.4", + "@peculiar/asn1-x509-attr": "^2.9.4", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-rsa": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.9.4.tgz", + "integrity": "sha512-pZ96eD1PptovcWQ/GSmuNFXd/7EQJNlKfDaNCyE2rx3W0v6QFelkzquVqRSRyyDXXCYD69ZXJDzZ8GhIiQzKoA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.4", + "@peculiar/asn1-x509": "^2.9.4", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-schema": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.9.4.tgz", + "integrity": "sha512-GjzePcT9Iw8NzeOPf73iNS9xM+TBhd/FilAfP+RQGkTMQJTVWtytN3JHJACCjf/ABNau5S7mS3g+DcuxmRgYEg==", + "license": "MIT", + "dependencies": { + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-x509": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.9.4.tgz", + "integrity": "sha512-CxhBo/RdEbMMob7T31ZdQjGuoyRFLVwrDzTn25bihzBasRg9kRm/0IxIPvhgQtcK/9dNcO1XQL2fuPugwELL0Q==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.4", + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/asn1-x509-attr": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.9.4.tgz", + "integrity": "sha512-ehQXbpQaQYycgu8OrvigwSPTFfVRcu0ECNYCWw+yzBp02Lw5paRqzzhUpfOgO2K38+WfFZuEz/0RPtam5g0OMg==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.9.4", + "@peculiar/asn1-x509": "^2.9.4", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@peculiar/utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz", + "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/@peculiar/x509": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz", + "integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-cms": "^2.6.0", + "@peculiar/asn1-csr": "^2.6.0", + "@peculiar/asn1-ecc": "^2.6.0", + "@peculiar/asn1-pkcs9": "^2.6.0", + "@peculiar/asn1-rsa": "^2.6.0", + "@peculiar/asn1-schema": "^2.6.0", + "@peculiar/asn1-x509": "^2.6.0", + "pvtsutils": "^1.3.6", + "reflect-metadata": "^0.2.2", + "tslib": "^2.8.1", + "tsyringe": "^4.10.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/@pinojs/redact": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", "license": "MIT" }, + "node_modules/@shinyoshiaki/binary-data": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/@shinyoshiaki/binary-data/-/binary-data-0.6.1.tgz", + "integrity": "sha512-7HDb/fQAop2bCmvDIzU5+69i+UJaFgIVp99h1VzK1mpg1JwSODOkjbqD7ilTYnqlnadF8C4XjpwpepxDsGY6+w==", + "license": "MIT", + "dependencies": { + "generate-function": "^2.3.1", + "is-plain-object": "^2.0.3" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/@types/body-parser": { "version": "1.19.6", "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", @@ -579,6 +808,21 @@ "@types/node": "*" } }, + "node_modules/@types/dom-mediacapture-transform": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz", + "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==", + "license": "MIT", + "dependencies": { + "@types/dom-webcodecs": "*" + } + }, + "node_modules/@types/dom-webcodecs": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz", + "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==", + "license": "MIT" + }, "node_modules/@types/express": { "version": "5.0.6", "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz", @@ -726,6 +970,20 @@ "node": ">=10" } }, + "node_modules/asn1js": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz", + "integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==", + "license": "BSD-3-Clause", + "dependencies": { + "pvtsutils": "^1.3.6", + "pvutils": "^1.1.5", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/atomic-sleep": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", @@ -741,6 +999,26 @@ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "license": "MIT" }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/body-parser": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", @@ -788,6 +1066,30 @@ "concat-map": "0.0.1" } }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -937,6 +1239,18 @@ "node": ">=8" } }, + "node_modules/dns-packet": { + "version": "5.6.1", + "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz", + "integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==", + "license": "MIT", + "dependencies": { + "@leichtgewicht/ip-codec": "^2.0.1" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -1192,6 +1506,15 @@ "node": ">=10" } }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -1341,6 +1664,26 @@ "url": "https://opencollective.com/express" } }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -1376,12 +1719,39 @@ "node": ">=8" } }, + "node_modules/is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "license": "MIT", + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", "license": "MIT" }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "license": "MIT" + }, + "node_modules/isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/make-dir": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", @@ -1424,6 +1794,24 @@ "node": ">= 0.8" } }, + "node_modules/mediabunny": { + "version": "1.55.5", + "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.55.5.tgz", + "integrity": "sha512-m0v6y8FGXiK+HKOc3AZqU+kJPLYsSKaLitmQNQIIHZKIGlTwQ34OF+X6Ul0K8iV4b03oPse10apwuoqbvmKeAA==", + "license": "MPL-2.0", + "workspaces": [ + ".", + "packages/*" + ], + "dependencies": { + "@types/dom-mediacapture-transform": "^0.1.11", + "@types/dom-webcodecs": "0.1.13" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/Vanilagy" + } + }, "node_modules/merge-descriptors": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", @@ -1500,6 +1888,19 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/multicast-dns": { + "version": "7.2.5", + "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-7.2.5.tgz", + "integrity": "sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==", + "license": "MIT", + "dependencies": { + "dns-packet": "^5.2.2", + "thunky": "^1.0.2" + }, + "bin": { + "multicast-dns": "cli.js" + } + }, "node_modules/negotiator": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", @@ -1711,6 +2112,24 @@ "node": ">= 0.10" } }, + "node_modules/pvtsutils": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz", + "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/pvutils": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz", + "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==", + "license": "MIT", + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/qs": { "version": "6.15.2", "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz", @@ -1779,6 +2198,12 @@ "node": ">= 12.13.0" } }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0" + }, "node_modules/rimraf": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", @@ -2089,6 +2514,12 @@ "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==", "license": "MIT" }, + "node_modules/thunky": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz", + "integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==", + "license": "MIT" + }, "node_modules/toidentifier": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", @@ -2104,6 +2535,12 @@ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", "license": "MIT" }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, "node_modules/tsx": { "version": "4.22.3", "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.3.tgz", @@ -2123,6 +2560,30 @@ "fsevents": "~2.3.3" } }, + "node_modules/tsyringe": { + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz", + "integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==", + "license": "MIT", + "dependencies": { + "tslib": "^1.9.3" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/tsyringe/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "license": "Unlicense" + }, "node_modules/type-is": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", @@ -2205,6 +2666,70 @@ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", "license": "BSD-2-Clause" }, + "node_modules/werift": { + "version": "0.24.4", + "resolved": "https://registry.npmjs.org/werift/-/werift-0.24.4.tgz", + "integrity": "sha512-NoROZ11L/ZqAB5ombCB4VBuVNdIZfwI493zlxlIX7BlwfWRy55eDJdtWMC2VX35yBXFaWwA8NtYbmJ8qWtVk9Q==", + "license": "MIT", + "dependencies": { + "@fidm/x509": "^1.2.1", + "@noble/curves": "^1.8.1", + "@peculiar/x509": "^1.12.3", + "@shinyoshiaki/binary-data": "^0.6.1", + "buffer": "^6.0.3", + "debug": "4.4.0", + "mediabunny": "^1.45.2", + "multicast-dns": "^7.2.5", + "tweetnacl": "^1.0.3" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/werift/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/werift/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/werift/node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, "node_modules/whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", diff --git a/package.json b/package.json index 33b285a..78469a2 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6", "express": "^5.2.1", "pino": "^10.3.1", + "werift": "0.24.4", "ws": "^8.20.0" }, "devDependencies": { diff --git a/src/index.ts b/src/index.ts index c439071..8faa161 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,6 +8,7 @@ import { WebSpeakDatabase } from "./persistence/database.js"; import { loadOrCreateMasterSecret } from "./security/master-secret.js"; import { AdminService } from "./admin/admin-service.js"; import { JoinTicketStore } from "./server/join-ticket.js"; +import type { WebRtcAudioOptions } from "./server/webrtc-audio.js"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.resolve(__dirname, ".."); @@ -19,6 +20,7 @@ const DATA_DIR = process.env.WEBSPEAK_DATA_DIR?.trim() || path.join(ROOT_DIR, "d const LOG_DIR = path.join(DATA_DIR, "logs"); const STATIC_DIR = path.join(ROOT_DIR, "web", "dist"); const APP_VERSION = readPackageVersion(); +const WEBRTC_OPTIONS = readWebRtcOptions(); async function main() { const logger = createLogger(LOG_DIR); @@ -48,6 +50,7 @@ async function main() { certDir: hasCert ? CERT_DIR : undefined, voiceBridgeOptions: { joinTickets, + webRtc: WEBRTC_OPTIONS, }, adminService, logger, @@ -83,6 +86,23 @@ function removeObsoleteBootstrapFile(): void { } } +function readWebRtcOptions(): WebRtcAudioOptions { + const enabled = /^(1|true|yes)$/i.test(process.env.WEBSPEAK_WEBRTC?.trim() ?? ""); + const publicHost = process.env.WEBSPEAK_WEBRTC_PUBLIC_HOST?.trim() || undefined; + const start = parsePort(process.env.WEBSPEAK_WEBRTC_UDP_START, 40_000); + const end = parsePort(process.env.WEBSPEAK_WEBRTC_UDP_END, 40_099); + return { + enabled, + ...(publicHost ? { publicHost } : {}), + ...(start <= end ? { icePortRange: [start, end] as [number, number] } : {}), + }; +} + +function parsePort(value: string | undefined, fallback: number): number { + const port = Number(value); + return Number.isInteger(port) && port >= 1 && port <= 65_535 ? port : fallback; +} + main().catch((err) => { console.error("Fatal error:", err); process.exit(1); diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index f8a397e..f60906e 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -11,6 +11,7 @@ import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js"; import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js"; import { parseClientCommand, type ClientCommand } from "./voice-protocol.js"; import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js"; +import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcSessionDescription } from "./webrtc-audio.js"; const require = createRequire(import.meta.url); const { OpusEncoder } = require("@discordjs/opus") as { @@ -29,6 +30,7 @@ const MAX_SERVER_AUDIO_BUFFERED_BYTES = 4_096; export interface VoiceBridgeOptions { joinTickets: JoinTicketStore; + webRtc?: WebRtcAudioOptions; } export interface AdminSessionSummary { @@ -94,6 +96,7 @@ interface WebClientEntry { isAlive: boolean; reconnectTimer: ReturnType | null; audio: AudioFlowStats; + webrtc: WebRtcAudioSession | null; } export class VoiceBridge { @@ -169,6 +172,7 @@ export class VoiceBridge { isAlive: true, reconnectTimer: null, audio: createAudioFlowStats(), + webrtc: null, }; this.entries.set(entryId, entry!); try { @@ -263,6 +267,7 @@ export class VoiceBridge { serverEventLog: entry!.eventLog, whisperTargetIds: [...entry!.whisperTargetIds], whisperActive: entry!.whisperActive, + webrtcAvailable: this.options.webRtc?.enabled === true, ...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}), }); sendJson({ type: "channelList", channels: entry!.channelTree }); @@ -418,6 +423,7 @@ export class VoiceBridge { tsClient.on("voiceData", (data: TSVoiceData) => { if (ws.readyState !== WebSocket.OPEN || data.clientId === selfId) return; + entry!.webrtc?.pushTeamSpeakVoice(data); const now = Date.now(); if (entry!.audio.egressLastAt !== null) entry!.audio.egressMaxGapMs = Math.max(entry!.audio.egressMaxGapMs, now - entry!.audio.egressLastAt); entry!.audio.egressFirstAt ??= now; @@ -497,7 +503,21 @@ export class VoiceBridge { return; } - const command = parseClientCommand(typeof data === "string" ? data : data.toString("utf-8")); + const rawMessage = typeof data === "string" ? data : data.toString("utf-8"); + const webRtcOffer = parseWebRtcOffer(rawMessage); + if (webRtcOffer) { + if (this.options.webRtc?.enabled !== true) { + sendProtocolError(sendJson, "WEBRTC_DISABLED", "WebRTC 音频传输未启用"); + return; + } + if (!tsReady || session.state !== "connected") { + sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪"); + return; + } + void this.handleWebRtcOffer(entry!, webRtcOffer, sendJson); + return; + } + const command = parseClientCommand(rawMessage); if ("error" in command) { sendProtocolError(sendJson, command.error.code, command.error.message); return; @@ -607,6 +627,11 @@ export class VoiceBridge { entry.reconnectTimer = null; } entry.opusEncoder = null; + const webRtc = entry.webrtc; + entry.webrtc = null; + if (webRtc) { + try { await webRtc.close(); } catch { /* peer teardown is idempotent */ } + } entry.whisperTargetIds.clear(); entry.whisperActive = false; entry.channelTree = []; @@ -642,6 +667,48 @@ export class VoiceBridge { const token = url.searchParams.get("ticket"); return token ? this.options.joinTickets.consume(token) : null; } + + private async handleWebRtcOffer( + entry: WebClientEntry, + offer: WebRtcSessionDescription, + sendJson: (message: Record) => void, + ): Promise { + if (entry.webrtc) { + try { await entry.webrtc.close(); } catch { /* replace a retried offer */ } + entry.webrtc = null; + } + const config = this.options.webRtc; + if (!config?.enabled) return; + const peer = new WebRtcAudioSession({ + connectionId: entry.id, + config, + logger: this.logger, + onVoiceFrame: (data) => { + try { + if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], 4); + else entry.tsClient.sendVoice(data, 4); + } catch { + // A packet arriving while the TeamSpeak session is being replaced + // is discarded; the WebRTC peer remains independently closable. + } + }, + onVoiceActivity: (clientIds) => { + if (entry.ws.readyState === WebSocket.OPEN) sendJson({ type: "voiceActivity", clientIds }); + }, + }); + entry.webrtc = peer; + try { + const answer = await peer.createAnswer(offer); + if (entry.webrtc !== peer || entry.ws.readyState !== WebSocket.OPEN) return; + sendJson({ type: "webrtcAnswer", payload: { sdp: answer } }); + this.logger.info({ entryId: entry.id }, "WebRTC audio negotiation completed"); + } catch (error: unknown) { + if (entry.webrtc === peer) entry.webrtc = null; + try { await peer.close(); } catch { /* best effort */ } + this.logger.warn({ entryId: entry.id, err: error instanceof Error ? error.message : String(error) }, "WebRTC audio negotiation failed"); + if (entry.ws.readyState === WebSocket.OPEN) sendJson({ type: "webrtcError", code: "WEBRTC_NEGOTIATION_FAILED" }); + } + } } async function handleCommand( @@ -734,6 +801,19 @@ function sendProtocolError(sendJson: (message: Record) => void, sendJson({ type: "error", error: { code, message, recoverable: false } }); } +function parseWebRtcOffer(raw: string): WebRtcSessionDescription | null { + let value: unknown; + try { value = JSON.parse(raw); } catch { return null; } + if (!isRecord(value) || value.type !== "webrtcOffer" || !isRecord(value.payload) || !isRecord(value.payload.sdp)) return null; + const description = value.payload.sdp; + if (description.type !== "offer" || typeof description.sdp !== "string" || description.sdp.length > 256 * 1024) return null; + return { type: "offer", sdp: description.sdp }; +} + +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + function isChannelRecord(value: unknown): value is { id: string; name: string } { return Boolean(value) && typeof value === "object" && typeof (value as { id?: unknown }).id === "string" && typeof (value as { name?: unknown }).name === "string"; } diff --git a/src/server/webrtc-audio.ts b/src/server/webrtc-audio.ts new file mode 100644 index 0000000..2336d0a --- /dev/null +++ b/src/server/webrtc-audio.ts @@ -0,0 +1,209 @@ +import { randomInt } from "node:crypto"; +import { createRequire } from "node:module"; +import { + MediaStreamTrack, + RtpHeader, + RtpPacket, + RTCPeerConnection, +} from "werift"; +import type { Logger as LoggerType } from "../logger.js"; +import type { TSVoiceData } from "./ts-client.js"; + +const require = createRequire(import.meta.url); +const { OpusDecoder, OpusEncoder } = require("@discordjs/opus") as { + OpusDecoder: new (sampleRate: number, channels: number) => { decode(data: Buffer): Buffer }; + OpusEncoder: new (sampleRate: number, channels: number) => { encode(data: Buffer): Buffer }; +}; + +const AUDIO_SAMPLE_RATE = 48_000; +const AUDIO_FRAME_SAMPLES = 960; +const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2; +const WEBRTC_OPUS_PAYLOAD_TYPE = 111; +const AUDIO_CLOCK_INTERVAL_MS = 20; +const SPEAKER_ACTIVITY_INTERVAL_MS = 100; + +export interface WebRtcAudioOptions { + enabled: boolean; + publicHost?: string; + icePortRange?: [number, number]; +} + +export interface WebRtcSessionDescription { + type: "offer" | "answer"; + sdp: string; +} + +export interface WebRtcAudioSessionOptions { + connectionId: string; + config: WebRtcAudioOptions; + logger: LoggerType; + onVoiceFrame: (data: Buffer) => void; + onVoiceActivity: (clientIds: number[]) => void; +} + +/** + * One low-latency WebRTC audio session for one browser connection. + * + * TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated + * audio track in this first transport, so this class mixes only the newest + * 20 ms frame from each active speaker and packetizes the result as RTP. The + * map is deliberately bounded to one frame per speaker; an old frame is + * replaced instead of becoming a playback queue. + */ +export class WebRtcAudioSession { + readonly peer: RTCPeerConnection; + private readonly logger: LoggerType; + private readonly onVoiceFrame: (data: Buffer) => void; + private readonly onVoiceActivity: (clientIds: number[]) => void; + private readonly outgoingTrack: MediaStreamTrack; + private readonly decoderByClient = new Map(); + private readonly pendingFrames = new Map(); + private readonly activeSpeakerIds = new Set(); + private readonly audioTimer: ReturnType; + private readonly activityTimer: ReturnType; + private encoder: { encode(data: Buffer): Buffer } | null; + private sequenceNumber = randomInt(0, 65_536); + private timestamp = randomInt(0, 0x1_0000_0000) >>> 0; + private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0; + private closed = false; + + constructor(options: WebRtcAudioSessionOptions) { + this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId }); + this.onVoiceFrame = options.onVoiceFrame; + this.onVoiceActivity = options.onVoiceActivity; + this.outgoingTrack = new MediaStreamTrack({ kind: "audio" }); + + const iceAdditionalHostAddresses = options.config.publicHost ? [options.config.publicHost] : undefined; + this.peer = new RTCPeerConnection({ + iceServers: [], + iceUseIpv4: true, + iceUseIpv6: false, + iceUseTcp: false, + ...(options.config.icePortRange ? { icePortRange: options.config.icePortRange } : {}), + ...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}), + }); + + const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" }); + audio.onTrack.subscribe((track) => { + track.onReceiveRtp.subscribe((rtp) => { + if (this.closed || rtp.header.payloadType !== WEBRTC_OPUS_PAYLOAD_TYPE) return; + this.onVoiceFrame(Buffer.from(rtp.payload)); + }); + void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => { + this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not attach WebRTC output track"); + }); + }); + void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => { + this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track"); + }); + + try { + this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1); + } catch (error: unknown) { + this.encoder = null; + this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer encoder"); + } + if (!this.encoder) { + this.outgoingTrack.stop(); + throw new Error("WebRTC mixer encoder is unavailable"); + } + + this.audioTimer = setInterval(() => this.flushAudio(), AUDIO_CLOCK_INTERVAL_MS); + this.audioTimer.unref?.(); + this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS); + this.activityTimer.unref?.(); + this.peer.onconnectionstatechange = () => { + this.logger.info({ state: this.peer.connectionState }, "WebRTC connection state changed"); + }; + } + + async createAnswer(offer: WebRtcSessionDescription): Promise { + if (this.closed) throw new Error("WebRTC session is closed"); + await this.peer.setRemoteDescription(offer); + const transceiver = this.peer.getTransceivers().find((candidate) => candidate.kind === "audio"); + if (transceiver) await transceiver.sender.replaceTrack(this.outgoingTrack); + const answer = await this.peer.createAnswer(); + await this.peer.setLocalDescription(answer); + const description = this.peer.localDescription; + if (!description) throw new Error("WebRTC answer was not created"); + if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type"); + return { type: description.type, sdp: description.sdp }; + } + + pushTeamSpeakVoice(data: TSVoiceData): void { + if (this.closed || data.codec !== 4) return; + this.activeSpeakerIds.add(data.clientId); + let decoder = this.decoderByClient.get(data.clientId); + if (!decoder) { + try { + decoder = new OpusDecoder(AUDIO_SAMPLE_RATE, 1); + this.decoderByClient.set(data.clientId, decoder); + } catch (error: unknown) { + this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder"); + return; + } + } + try { + const pcm = decoder.decode(data.data); + if (pcm.length >= AUDIO_FRAME_BYTES) this.pendingFrames.set(data.clientId, pcm.subarray(0, AUDIO_FRAME_BYTES)); + } catch { + // A malformed or codec-transition packet is discarded without touching + // the peer connection. The next valid Opus frame can recover the stream. + } + } + + async close(): Promise { + if (this.closed) return; + this.closed = true; + clearInterval(this.audioTimer); + clearInterval(this.activityTimer); + this.pendingFrames.clear(); + this.activeSpeakerIds.clear(); + this.decoderByClient.clear(); + this.encoder = null; + this.outgoingTrack.stop(); + await this.peer.close(); + } + + private flushAudio(): void { + if (this.closed || !this.encoder || !this.pendingFrames.size) return; + const mixed = new Int32Array(AUDIO_FRAME_SAMPLES); + let sourceCount = 0; + for (const pcm of this.pendingFrames.values()) { + sourceCount++; + for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) mixed[index] += pcm.readInt16LE(index * 2); + } + this.pendingFrames.clear(); + if (!sourceCount) return; + + const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES); + const scale = 1 / Math.sqrt(sourceCount); + for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) { + const sample = Math.max(-32_768, Math.min(32_767, Math.round(mixed[index]! * scale))); + pcm.writeInt16LE(sample, index * 2); + } + try { + const encoded = this.encoder.encode(pcm); + const packet = new RtpPacket(new RtpHeader({ + payloadType: WEBRTC_OPUS_PAYLOAD_TYPE, + sequenceNumber: this.sequenceNumber, + timestamp: this.timestamp, + ssrc: this.ssrc, + marker: true, + }), encoded); + this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff; + this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0; + this.outgoingTrack.writeRtp(packet); + } catch { + // A peer closing concurrently may reject a packet; teardown owns the + // session lifecycle and no per-frame error needs to reach the logs. + } + } + + private flushSpeakerActivity(): void { + if (this.closed || !this.activeSpeakerIds.size) return; + const ids = [...this.activeSpeakerIds]; + this.activeSpeakerIds.clear(); + this.onVoiceActivity(ids); + } +} diff --git a/web/src/composables/useVoiceWebSocket.ts b/web/src/composables/useVoiceWebSocket.ts index a1b29c1..5f73ef5 100644 --- a/web/src/composables/useVoiceWebSocket.ts +++ b/web/src/composables/useVoiceWebSocket.ts @@ -82,13 +82,19 @@ export function useVoiceWebSocket() { const pokeNotifications = reactive<{ id: string; invokerId: number; invokerUid: string; invokerName: string; message: string; timestamp: number }[]>([]); let connectionSequence = 0; let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string; identity?: string; rememberIdentity: boolean } | null = null; + let webrtcPeer: RTCPeerConnection | null = null; + let webrtcOutputSource: MediaStreamAudioSourceNode | null = null; + let webrtcOutputGain: GainNode | null = null; + let webrtcNegotiationPromise: Promise | null = null; + let webrtcFallbackStarted = false; + const webrtcActive = ref(false); const identityMaterial = ref(""); const storedVolumesByUid = reactive>({}); let microphoneStartPromise: Promise | null = null; - // Audio capture. The ScriptProcessor path remains the most compatible option - // for the current browser support matrix, but the graph now has an explicit - // input gain and a silent output to avoid monitoring the microphone locally. + // WebRTC carries audio when the gateway advertises it. The bounded PCM + // WebSocket path remains the compatibility fallback for older browsers and + // for deployments that have not opened the gateway's UDP media range. let audioCtx: SinkAudioContext | null = null; let micStream: MediaStream | null = null; let scriptNode: ScriptProcessorNode | null = null; @@ -334,6 +340,7 @@ export function useVoiceWebSocket() { const socket = ws.value; const shouldSend = !microphoneMuted.value && !microphoneTestActive.value + && !webrtcActive.value && socket?.readyState === WebSocket.OPEN && voxGate(input); if (!shouldSend) { @@ -445,7 +452,119 @@ export function useVoiceWebSocket() { return false; } - function stopMicrophone(closeContext = true): void { + async function startWebRtcTransport(sequence: number, socket: WebSocket): Promise { + if (typeof RTCPeerConnection === "undefined") throw new Error("当前浏览器不支持 WebRTC"); + await ensureMicrophone(); + if (sequence !== connectionSequence || socket.readyState !== WebSocket.OPEN || !micStream) return; + const track = micStream.getAudioTracks()[0]; + if (!track) throw new Error("没有可用的麦克风音轨"); + + stopCaptureGraph(); + const peer = new RTCPeerConnection({ iceServers: [] }); + webrtcPeer = peer; + webrtcFallbackStarted = false; + track.enabled = !microphoneMuted.value; + peer.addTrack(track, micStream); + peer.ontrack = (event) => { + const stream = event.streams[0] ?? new MediaStream([event.track]); + const ctx = getAudioCtx(); + if (ctx.state === "suspended") void ctx.resume(); + webrtcOutputSource?.disconnect(); + webrtcOutputGain?.disconnect(); + webrtcOutputSource = ctx.createMediaStreamSource(stream); + webrtcOutputGain = ctx.createGain(); + webrtcOutputGain.gain.value = outputVolume.value; + webrtcOutputSource.connect(webrtcOutputGain); + webrtcOutputGain.connect(ctx.destination); + }; + peer.onconnectionstatechange = () => { + if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket); + }; + + const negotiation = (async () => { + webrtcActive.value = true; + const offer = await peer.createOffer(); + await peer.setLocalDescription(offer); + await waitForIceGathering(peer); + if (sequence !== connectionSequence || webrtcPeer !== peer || socket.readyState !== WebSocket.OPEN) return; + const description = peer.localDescription; + if (!description) throw new Error("WebRTC offer was not created"); + socket.send(JSON.stringify({ type: "webrtcOffer", payload: { sdp: { type: description.type, sdp: description.sdp } } })); + window.setTimeout(() => { + if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket); + }, 8_000); + })(); + webrtcNegotiationPromise = negotiation; + try { + await negotiation; + } catch (error) { + if (webrtcPeer === peer) await fallbackFromWebRtc(sequence, socket); + throw error; + } finally { + if (webrtcNegotiationPromise === negotiation) webrtcNegotiationPromise = null; + } + } + + async function waitForIceGathering(peer: RTCPeerConnection): Promise { + if (peer.iceGatheringState === "complete") return; + await new Promise((resolve) => { + let settled = false; + const finish = () => { + if (settled) return; + settled = true; + window.clearTimeout(timer); + peer.removeEventListener("icegatheringstatechange", onStateChange); + resolve(); + }; + const onStateChange = () => { + if (peer.iceGatheringState === "complete") finish(); + }; + const timer = window.setTimeout(finish, 5_000); + peer.addEventListener("icegatheringstatechange", onStateChange); + }); + } + + async function applyWebRtcAnswer(description: unknown): Promise { + if (!webrtcPeer || !isSessionDescription(description, "answer")) return; + try { + await webrtcPeer.setRemoteDescription(description); + webrtcActive.value = true; + } catch { + if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value); + } + } + + async function fallbackFromWebRtc(sequence: number, socket: WebSocket): Promise { + if (sequence !== connectionSequence || webrtcFallbackStarted) return; + webrtcFallbackStarted = true; + webrtcActive.value = false; + stopWebRtcTransport(); + if (socket.readyState === WebSocket.OPEN && state.connected) { + try { await startMicrophone(); } catch (error: unknown) { + state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; + } + } + } + + function stopWebRtcTransport(): void { + const peer = webrtcPeer; + webrtcPeer = null; + webrtcActive.value = false; + webrtcNegotiationPromise = null; + webrtcOutputSource?.disconnect(); + webrtcOutputGain?.disconnect(); + webrtcOutputSource = null; + webrtcOutputGain = null; + if (peer) void peer.close(); + } + + function isSessionDescription(value: unknown, type: "answer"): value is RTCSessionDescriptionInit { + return Boolean(value) && typeof value === "object" + && (value as { type?: unknown }).type === type + && typeof (value as { sdp?: unknown }).sdp === "string"; + } + + function stopCaptureGraph(): void { accumLen = 0; voxAttack = 0; voxRelease = 0; @@ -461,6 +580,10 @@ export function useVoiceWebSocket() { micGain = null; micSource = null; silentGain = null; + } + + function stopMicrophone(closeContext = true): void { + stopCaptureGraph(); micStream?.getTracks().forEach((track) => track.stop()); micStream = null; if (closeContext) { @@ -478,11 +601,17 @@ export function useVoiceWebSocket() { async function setInputDevice(deviceId: string): Promise { const previousDeviceId = selectedInputDeviceId.value; + const shouldRestartWebRtc = webrtcActive.value && Boolean(ws.value); selectedInputDeviceId.value = deviceId; localStorage.setItem("webspeak:input-device", deviceId); void saveAudioPreferences(); try { + if (shouldRestartWebRtc) stopWebRtcTransport(); if (micStream) await startMicrophone(); + if (shouldRestartWebRtc && ws.value) { + stopWebRtcTransport(); + await startWebRtcTransport(connectionSequence, ws.value); + } await refreshAudioDevices(); } catch (error) { selectedInputDeviceId.value = previousDeviceId; @@ -739,9 +868,6 @@ export function useVoiceWebSocket() { socket.close(1000); return; } - ensureMicrophone().catch((error: unknown) => { - state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; - }); }; socket.onmessage = (event) => { if (typeof event.data === "string") { @@ -760,6 +886,7 @@ export function useVoiceWebSocket() { state.connecting = false; state.reconnecting = false; if (event.code !== 1000 && !state.error && !state.reconnectFailed) state.error = closeReason(event.code); + stopWebRtcTransport(); stopMicrophone(); whisperTargetIds.clear(); whisperActive.value = false; @@ -791,6 +918,7 @@ export function useVoiceWebSocket() { stopMicrophone(); const socket = ws.value; ws.value = null; + stopWebRtcTransport(); if (socket && socket.readyState < WebSocket.CLOSING) socket.close(1000); state.connected = false; state.connecting = false; @@ -842,7 +970,18 @@ export function useVoiceWebSocket() { if (lastConnection) lastConnection.identity = msg.identity; } if (wasReconnecting) { - ensureMicrophone().catch((error: unknown) => { + const start = msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined" + ? (ws.value ? startWebRtcTransport(connectionSequence, ws.value) : Promise.resolve()) + : ensureMicrophone(); + start.catch((error: unknown) => { + state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; + }); + } else if (msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined" && ws.value) { + void startWebRtcTransport(connectionSequence, ws.value).catch((error: unknown) => { + state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; + }); + } else { + void ensureMicrophone().catch((error: unknown) => { state.error = `麦克风访问失败:${error instanceof Error ? error.message : "请检查浏览器权限"}`; }); } @@ -904,6 +1043,7 @@ export function useVoiceWebSocket() { state.reconnecting = Boolean(msg.recoverable !== false); state.reconnectFailed = false; if (!state.reconnecting) state.error = "TeamSpeak 连接已断开"; + stopWebRtcTransport(); stopMicrophone(); whisperTargetIds.clear(); whisperActive.value = false; @@ -914,6 +1054,7 @@ export function useVoiceWebSocket() { state.reconnecting = true; state.reconnectFailed = false; state.reconnectAttempt = Number(msg.attempt) || state.reconnectAttempt + 1; + stopWebRtcTransport(); stopMicrophone(); whisperTargetIds.clear(); whisperActive.value = false; @@ -934,6 +1075,19 @@ export function useVoiceWebSocket() { case "whisperTargets": applyWhisperState(msg.targetIds, msg.active); break; + case "webrtcAnswer": + void applyWebRtcAnswer(msg.payload?.sdp); + break; + case "webrtcError": + if (ws.value) void fallbackFromWebRtc(connectionSequence, ws.value); + break; + case "voiceActivity": + if (Array.isArray(msg.clientIds)) { + for (const clientId of msg.clientIds) { + if (typeof clientId === "number" && Number.isInteger(clientId) && clientId > 0) markSpeaking(clientId); + } + } + break; case "error": state.errorCode = String(msg.error?.code || ""); state.error = protocolErrorMessage(state.errorCode, String(msg.error?.message || msg.message || "操作失败")); @@ -1031,6 +1185,7 @@ export function useVoiceWebSocket() { voxAttack = 0; voxRelease = 0; accumLen = 0; + if (webrtcActive.value) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; }); void saveAudioPreferences(); } @@ -1088,6 +1243,7 @@ export function useVoiceWebSocket() { function setOutputVolume(volume: number): void { outputVolume.value = Math.max(0, Math.min(1, volume)); for (const [clientId, gain] of remoteGains) gain.gain.value = (volumes[clientId] ?? 1) * outputVolume.value; + if (webrtcOutputGain) webrtcOutputGain.gain.value = outputVolume.value; void saveAudioPreferences(); }