M7 (part 1): tsc-stream signalling and str0m peers
New crate tsc-stream for TeamSpeak 6 streams: - proto: typed StreamNotification from the notifystream* messages and builders for setupstream, joinstreamrequest, respondjoinstreamrequest, streamsignaling, removeclientfromstream and stopstream - signal: the JSON messages inside streamsignaling (offer, answer, iceCandidate, reconnect), accepting the known key spellings - stun: minimal STUN binding client for server-reflexive candidates - peer: a str0m peer connection driven by a tokio task, one UDP socket per host address; STUN lookups run in the background and found candidates are reported for trickling Declarations (verified against 6.0.0-beta13.1): joinstreamrequest; stopstream and removeclientfromstream require `reason`; is_remove/reason/return_code on the notifications. Tests: two peers over loopback exchange VP8 and Opus frames; with TSC_LIVE=1 a whole stream runs through the TS6 dev server (setup, join, offer, answer, media, kick, stop). it-smoke.sh runs it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
16 files changed
+1974
-37
No files matched your search
Generated
+302
-2
@@ -424,6 +424,45 @@ dependencies = [
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asn1-rs"
|
||||
version = "0.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
|
||||
dependencies = [
|
||||
"asn1-rs-derive",
|
||||
"asn1-rs-impl",
|
||||
"displaydoc",
|
||||
"nom 7.1.3",
|
||||
"num-traits",
|
||||
"rusticata-macros",
|
||||
"thiserror 2.0.21",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asn1-rs-derive"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"synstructure 0.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asn1-rs-impl"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-broadcast"
|
||||
version = "0.7.2"
|
||||
@@ -813,6 +852,9 @@ name = "bit-vec"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
@@ -1033,6 +1075,18 @@ dependencies = [
|
||||
"shlex 2.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ccm"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ae3c82e4355234767756212c570e29833699ab63e6ffd161887314cc5b43847"
|
||||
dependencies = [
|
||||
"aead 0.5.2",
|
||||
"cipher 0.4.4",
|
||||
"ctr 0.9.2",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cexpr"
|
||||
version = "0.6.0"
|
||||
@@ -1445,6 +1499,21 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc"
|
||||
version = "3.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
|
||||
dependencies = [
|
||||
"crc-catalog",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc-catalog"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
@@ -1760,6 +1829,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid 0.9.6",
|
||||
"der_derive",
|
||||
"flagset",
|
||||
"pem-rfc7468 0.7.0",
|
||||
"zeroize",
|
||||
]
|
||||
@@ -1775,6 +1846,31 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der-parser"
|
||||
version = "10.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
|
||||
dependencies = [
|
||||
"asn1-rs",
|
||||
"displaydoc",
|
||||
"nom 7.1.3",
|
||||
"num-bigint 0.4.8",
|
||||
"num-traits",
|
||||
"rusticata-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der_derive"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
@@ -1840,6 +1936,31 @@ dependencies = [
|
||||
"ctutils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dimpl"
|
||||
version = "0.7.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07d467d37bfdcc290bb8dcbedc8ca356eb730e46459b1687f98c3bae28aa6814"
|
||||
dependencies = [
|
||||
"aes 0.8.4",
|
||||
"arrayvec",
|
||||
"aws-lc-rs",
|
||||
"ccm",
|
||||
"der 0.7.10",
|
||||
"log",
|
||||
"nom 8.0.0",
|
||||
"once_cell",
|
||||
"pkcs8 0.10.2",
|
||||
"rand 0.9.5",
|
||||
"rcgen",
|
||||
"sec1 0.7.3",
|
||||
"signature 2.2.0",
|
||||
"spki 0.7.3",
|
||||
"subtle",
|
||||
"time",
|
||||
"x509-cert",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "6.0.0"
|
||||
@@ -2333,6 +2454,12 @@ version = "0.5.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
|
||||
|
||||
[[package]]
|
||||
name = "flagset"
|
||||
version = "0.4.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.10"
|
||||
@@ -3817,6 +3944,19 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d08f9118d003d441f79c1070e84d0a2a89f35721ca8ae0cd5e1f9026dc4a2517"
|
||||
dependencies = [
|
||||
"crc",
|
||||
"serde",
|
||||
"str0m-proto",
|
||||
"subtle",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
@@ -4997,6 +5137,15 @@ dependencies = [
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "oid-registry"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
|
||||
dependencies = [
|
||||
"asn1-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "omnom"
|
||||
version = "3.0.0"
|
||||
@@ -5971,6 +6120,19 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rcgen"
|
||||
version = "0.14.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"rustls-pki-types",
|
||||
"time",
|
||||
"x509-parser",
|
||||
"yasna",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.41.0"
|
||||
@@ -6434,6 +6596,15 @@ dependencies = [
|
||||
"transpose",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusticata-macros"
|
||||
version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
|
||||
dependencies = [
|
||||
"nom 7.1.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.44"
|
||||
@@ -6618,6 +6789,21 @@ dependencies = [
|
||||
"tiny-skia 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sctp-proto"
|
||||
version = "0.10.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "250132c5814c3d4f01269ee7a261450bc38dd5119280262d3c13a40062cfde55"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"crc",
|
||||
"log",
|
||||
"rand 0.9.5",
|
||||
"rustc-hash 2.1.3",
|
||||
"slab",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sec1"
|
||||
version = "0.7.3"
|
||||
@@ -7311,6 +7497,53 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
||||
|
||||
[[package]]
|
||||
name = "str0m"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8522aa06c731cfdc1488e32de7fcebcfc8d9d86d49a6ecc95a64779fe7b545f2"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"base64ct",
|
||||
"combine",
|
||||
"dimpl",
|
||||
"fastrand",
|
||||
"is",
|
||||
"sctp-proto",
|
||||
"serde",
|
||||
"str0m-aws-lc-rs",
|
||||
"str0m-proto",
|
||||
"subtle",
|
||||
"time",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "str0m-aws-lc-rs"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73269314334fc6bfa8024f09dd652b9f5068360bf623c871e3d8d18e26d8035a"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"dimpl",
|
||||
"str0m-proto",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "str0m-proto"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8f3d99f2cf6c76a502e45feb896ea71e54787ede8744bcdb215acfbfcb905dd"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"dimpl",
|
||||
"fastrand",
|
||||
"serde",
|
||||
"subtle",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strength_reduce"
|
||||
version = "0.2.4"
|
||||
@@ -7411,6 +7644,17 @@ dependencies = [
|
||||
"futures-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.14.0"
|
||||
@@ -8110,6 +8354,23 @@ dependencies = [
|
||||
"tsclientlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsc-stream"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"futures",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"str0m",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsclientlib",
|
||||
"tsproto-packets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsc-ui"
|
||||
version = "0.1.0"
|
||||
@@ -9422,6 +9683,35 @@ version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
|
||||
|
||||
[[package]]
|
||||
name = "x509-cert"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"
|
||||
dependencies = [
|
||||
"const-oid 0.9.6",
|
||||
"der 0.7.10",
|
||||
"spki 0.7.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-parser"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
|
||||
dependencies = [
|
||||
"asn1-rs",
|
||||
"aws-lc-rs",
|
||||
"data-encoding",
|
||||
"der-parser",
|
||||
"lazy_static",
|
||||
"nom 7.1.3",
|
||||
"oid-registry",
|
||||
"rusticata-macros",
|
||||
"thiserror 2.0.21",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xattr"
|
||||
version = "1.6.1"
|
||||
@@ -9480,6 +9770,16 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||
|
||||
[[package]]
|
||||
name = "yasna"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
|
||||
dependencies = [
|
||||
"bit-vec 0.9.1",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yazi"
|
||||
version = "0.2.1"
|
||||
@@ -9517,7 +9817,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
"synstructure",
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9681,7 +9981,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
"synstructure",
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -16,6 +16,7 @@ members = [
|
||||
"crates/tsc-observer",
|
||||
"crates/tsc-query",
|
||||
"crates/tsc-store",
|
||||
"crates/tsc-stream",
|
||||
"crates/tsc-ui",
|
||||
"tools/tsctl",
|
||||
]
|
||||
@@ -34,6 +35,7 @@ default-members = [
|
||||
"crates/tsc-observer",
|
||||
"crates/tsc-query",
|
||||
"crates/tsc-store",
|
||||
"crates/tsc-stream",
|
||||
"crates/tsc-ui",
|
||||
"tools/tsctl",
|
||||
]
|
||||
|
||||
@@ -39,6 +39,9 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
- `crates/tsc-core`: client engine; sessions merge voice, gateway and query sources, route chat, run audio
|
||||
- `crates/tsc-ui` (`tsc-desktop`): Slint desktop app: servers, channel tree with talking indicators,
|
||||
chat tabs (own channel via voice, other channels via relay), connect / observe invisibly, mute, push-to-talk
|
||||
- `crates/tsc-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
|
||||
WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two
|
||||
clients through a TS6 server
|
||||
- `tools/tsctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events,
|
||||
`query`, `observe` (invisible presence), `relay` (channel chat without joining) and `gateway`
|
||||
- `dev/`: TeamSpeak 3.13 and TeamSpeak 6 (6.0.0-beta13.1) servers; `scripts/it-smoke.sh`
|
||||
@@ -46,7 +49,8 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
|
||||
relay chat and the gateway on both
|
||||
- `fuzz/`: cargo-fuzz targets for packets, commands and the license chain
|
||||
|
||||
No screen sharing yet, and no Android build yet.
|
||||
Screen sharing has its protocol and transport layer (`tsc-stream`); capture, codecs and the UI
|
||||
for it are in progress. No Android build yet.
|
||||
|
||||
| Connected with voice | Observing invisibly through the gateway |
|
||||
|---|---|
|
||||
@@ -91,5 +95,5 @@ The vendored crates in `crates/proto/` are `MIT OR Apache-2.0` (upstream
|
||||
`LICENSE-MIT` / `LICENSE-APACHE` are kept there). New crates are declared under
|
||||
the same terms in `Cargo.toml`.
|
||||
|
||||
Third-party notices: the planned UI toolkit, Slint, is used under its
|
||||
royalty-free license, which requires an attribution in the app's About page.
|
||||
Third-party notices: the UI toolkit, Slint, is used under its royalty-free license, which
|
||||
requires an attribution in the app's About page.
|
||||
@@ -60,3 +60,10 @@ against or offered back to upstream.
|
||||
are bounds-checked now.
|
||||
- `tsproto-packets/src/packets.rs`: the invalid-codec error for short C2S audio
|
||||
packets read `content[4]` instead of the codec byte `content[2]`.
|
||||
7. **TeamSpeak 6 stream commands, verified against 6.0.0-beta13.1**
|
||||
(`tsproto-structs/declarations/Messages.toml`). New fields `is_remove` and
|
||||
`reason` (stream leave reason). New command `joinstreamrequest id clid msg is_remove`
|
||||
(`JoinStreamRequestRequest`); `stopstream` and `removeclientfromstream` take the
|
||||
required `reason`; `notifyjoinstreamrequest` carries `is_remove`,
|
||||
`notifystreamstopped` and `notifystreamclientleft` carry `reason`, the latter also
|
||||
`return_code`.
|
||||
@@ -428,6 +428,8 @@ fields = [
|
||||
{ map="json@stream", ts="json", pretty="Json", type="str" },
|
||||
{ map="offer@stream", ts="offer", pretty="Offer", type="str" },
|
||||
{ map="decision@stream", ts="decision", pretty="Accepted", type="bool" },
|
||||
{ map="is_remove@stream", ts="is_remove", pretty="IsRemove", type="bool" },
|
||||
{ map="reason@stream", ts="reason", pretty="LeaveReason", type="u8" },
|
||||
]
|
||||
|
||||
# The "msg_group: array specifies all messages which can be sent between client
|
||||
@@ -499,13 +501,13 @@ msg = [
|
||||
# reported by reverse engineering, so most attributes are optional.
|
||||
# notifystreamstarted clid=20 id=e7da957e-7ce0-46cf-bf6d-754d3446b4d4 name=probe type=3 access=1 mode=1 bitrate=4608 viewer_limit=0 audio=1
|
||||
{ name="StreamStarted", notify="notifystreamstarted", attributes=["clid", "id@stream", "name@stream?", "type@stream?", "access@stream?", "mode@stream?", "bitrate@stream?", "viewer_limit@stream?", "audio@stream?", "return_code?"] },
|
||||
{ name="StreamStopped", notify="notifystreamstopped", attributes=["id@stream", "clid?"] },
|
||||
{ name="StreamStopped", notify="notifystreamstopped", attributes=["id@stream", "clid?", "reason@stream?"] },
|
||||
{ name="StreamInfo", notify="notifystreaminfo", attributes=["id@stream", "clid?", "name@stream?", "type@stream?", "access@stream?", "mode@stream?", "bitrate@stream?", "viewer_limit@stream?", "audio@stream?"] },
|
||||
{ name="JoinStreamRequest", notify="notifyjoinstreamrequest", attributes=["id@stream", "clid", "msg?"] },
|
||||
{ name="JoinStreamRequest", notify="notifyjoinstreamrequest", attributes=["id@stream", "clid", "msg?", "is_remove@stream?"] },
|
||||
{ name="RespondJoinStreamRequest", notify="notifyrespondjoinstreamrequest", attributes=["id@stream", "clid?", "msg?", "offer@stream?", "decision@stream?"] },
|
||||
{ name="StreamSignaling", notify="notifystreamsignaling", attributes=["id@stream", "clid", "json@stream"] },
|
||||
{ name="StreamClientJoined", notify="notifystreamclientjoined", attributes=["id@stream", "clid"] },
|
||||
{ name="StreamClientLeft", notify="notifystreamclientleft", attributes=["id@stream", "clid"] },
|
||||
{ name="StreamClientLeft", notify="notifystreamclientleft", attributes=["id@stream", "clid", "reason@stream?", "return_code?"] },
|
||||
]
|
||||
|
||||
# Server to Client Notifications (Low)
|
||||
@@ -1057,8 +1059,12 @@ msg = [
|
||||
# setupstream name=probe type=3 bitrate=4608 accessibility=1 mode=1 viewer_limit=0 audio=1
|
||||
# -> {StreamStarted}
|
||||
{ name="SetupStream", notify="setupstream", attributes=["name@stream", "type@stream", "bitrate@stream", "accessibility@stream", "mode@stream", "viewer_limit@stream", "audio@stream"] },
|
||||
{ name="StopStream", notify="stopstream", attributes=["id@stream"] },
|
||||
# stopstream id=<uuid> reason=<StreamLeaveReason>; both required
|
||||
{ name="StopStream", notify="stopstream", attributes=["id@stream", "reason@stream"] },
|
||||
# joinstreamrequest id=<uuid> clid=<streamer> msg=<text> is_remove=0
|
||||
{ name="JoinStreamRequestRequest", notify="joinstreamrequest", attributes=["id@stream", "clid", "msg", "is_remove@stream"] },
|
||||
{ name="StreamSignalingRequest", notify="streamsignaling", attributes=["id@stream", "clid", "json@stream"] },
|
||||
{ name="RespondJoinStreamRequestRequest", notify="respondjoinstreamrequest", attributes=["id@stream", "clid", "msg?", "offer@stream?", "decision@stream"] },
|
||||
{ name="RemoveClientFromStream", notify="removeclientfromstream", attributes=["id@stream", "clid"] },
|
||||
# removeclientfromstream id=<uuid> clid=<viewer> reason=<StreamLeaveReason>; all required
|
||||
{ name="RemoveClientFromStream", notify="removeclientfromstream", attributes=["id@stream", "clid", "reason@stream"] },
|
||||
]
|
||||
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "tsc-stream"
|
||||
version = "0.1.0"
|
||||
description = "TeamSpeak 6 streams: signalling commands, JSON signal messages and WebRTC peers (str0m)."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
str0m = { version = "0.23.1", default-features = false, features = ["aws-lc-rs"] }
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["macros", "net", "rt", "sync", "time"] }
|
||||
tracing = "0.1"
|
||||
tsclientlib = { path = "../proto/tsclientlib" }
|
||||
tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = "1"
|
||||
futures = "0.3"
|
||||
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "sync", "time"] }
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,17 @@
|
||||
//! TeamSpeak 6 streams (screen sharing): the signalling commands the server
|
||||
//! relays, the JSON signal messages, and str0m WebRTC peer connections.
|
||||
//!
|
||||
//! Only TeamSpeak 6 servers support streams. Media flows peer to peer; the
|
||||
//! server only forwards `respondjoinstreamrequest` (the streamer's offer) and
|
||||
//! `streamsignaling` (answer and ICE candidates).
|
||||
|
||||
pub mod peer;
|
||||
pub mod proto;
|
||||
pub mod signal;
|
||||
pub mod stun;
|
||||
|
||||
pub use peer::{MediaFrame, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec};
|
||||
pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup};
|
||||
pub use signal::{Signal, SignalError};
|
||||
pub use str0m::format::Codec;
|
||||
pub use str0m::media::{Frequency, MediaKind, MediaTime};
|
||||
@@ -0,0 +1,585 @@
|
||||
//! One WebRTC peer connection (str0m) driven by a tokio task.
|
||||
//!
|
||||
//! TeamSpeak 6 streams are peer to peer: the streamer creates one connection per
|
||||
//! viewer and sends its offer through the server; the viewer answers. Host
|
||||
//! candidates go into the SDP; server-reflexive candidates found through STUN
|
||||
//! are reported later as [`PeerEvent::LocalCandidate`] for trickling.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{BuildHasher, RandomState};
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use str0m::change::{SdpAnswer, SdpOffer, SdpPendingOffer};
|
||||
use str0m::format::Codec;
|
||||
use str0m::media::{Direction, KeyframeRequestKind, MediaKind, MediaTime, Mid, Pt};
|
||||
use str0m::net::{Protocol, Receive};
|
||||
use str0m::{Candidate, Event, IceConnectionState, Input, Output, Rtc, RtcConfig, RtcError};
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tracing::{debug, trace, warn};
|
||||
|
||||
use crate::stun;
|
||||
|
||||
/// Video codecs a peer can negotiate.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum VideoCodec {
|
||||
Vp8,
|
||||
Vp9,
|
||||
H264,
|
||||
Av1,
|
||||
}
|
||||
|
||||
impl VideoCodec {
|
||||
pub fn from_codec(c: Codec) -> Option<Self> {
|
||||
match c {
|
||||
Codec::Vp8 => Some(Self::Vp8),
|
||||
Codec::Vp9 => Some(Self::Vp9),
|
||||
Codec::H264 => Some(Self::H264),
|
||||
Codec::Av1 => Some(Self::Av1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PeerConfig {
|
||||
/// Local addresses for host candidates. Empty: the primary IPv4 address.
|
||||
pub hosts: Vec<IpAddr>,
|
||||
/// STUN servers (`host:port`) for a server-reflexive candidate.
|
||||
pub stun_servers: Vec<String>,
|
||||
/// Video codecs, used for the streamer's offer; a viewer accepts all it knows.
|
||||
pub video_codecs: Vec<VideoCodec>,
|
||||
pub video: bool,
|
||||
pub audio: bool,
|
||||
}
|
||||
|
||||
impl Default for PeerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hosts: Vec::new(),
|
||||
stun_servers: stun::TEAMSPEAK_STUN.iter().map(|s| (*s).to_owned()).collect(),
|
||||
video_codecs: vec![VideoCodec::Vp8, VideoCodec::H264],
|
||||
video: true,
|
||||
audio: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PeerConfig {
|
||||
/// Loopback only, no STUN: for tests on one machine.
|
||||
pub fn loopback() -> Self {
|
||||
Self {
|
||||
hosts: vec![IpAddr::V4(Ipv4Addr::LOCALHOST)],
|
||||
stun_servers: Vec::new(),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PeerError {
|
||||
#[error("network: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("invalid SDP: {0}")]
|
||||
Sdp(String),
|
||||
#[error("WebRTC: {0}")]
|
||||
Rtc(#[from] RtcError),
|
||||
#[error("no usable local address")]
|
||||
NoAddress,
|
||||
#[error("no answer is expected")]
|
||||
NotOffering,
|
||||
#[error("peer connection closed")]
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// Something that happened on the connection.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum PeerEvent {
|
||||
/// ICE and DTLS are up; media can flow.
|
||||
Connected,
|
||||
/// A candidate found after the SDP was sent (server reflexive), as an SDP
|
||||
/// `candidate:` line for [`crate::Signal::IceCandidate`].
|
||||
LocalCandidate(String),
|
||||
/// A received frame (depacketized).
|
||||
Media(MediaFrame),
|
||||
/// The viewer asks for a keyframe.
|
||||
KeyframeRequest,
|
||||
/// The connection is gone.
|
||||
Closed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MediaFrame {
|
||||
pub kind: MediaKind,
|
||||
pub codec: Codec,
|
||||
/// RTP time (90 kHz for video, 48 kHz for Opus).
|
||||
pub time: MediaTime,
|
||||
pub network_time: Instant,
|
||||
/// `false` if frames were lost before this one.
|
||||
pub contiguous: bool,
|
||||
pub data: Arc<[u8]>,
|
||||
}
|
||||
|
||||
enum Cmd {
|
||||
Answer(String, oneshot::Sender<Result<(), PeerError>>),
|
||||
RemoteCandidate(String),
|
||||
Write { kind: MediaKind, time: MediaTime, data: Arc<[u8]> },
|
||||
RequestKeyframe,
|
||||
Close,
|
||||
}
|
||||
|
||||
/// Handle to a peer connection task. Dropping it closes the connection.
|
||||
pub struct Peer {
|
||||
cmd: mpsc::UnboundedSender<Cmd>,
|
||||
events: mpsc::UnboundedReceiver<PeerEvent>,
|
||||
}
|
||||
|
||||
impl Peer {
|
||||
/// Streamer side: create a connection that sends our media; returns the SDP
|
||||
/// offer for `respondjoinstreamrequest`.
|
||||
pub async fn offer(config: &PeerConfig, stream_id: &str) -> Result<(Self, String), PeerError> {
|
||||
let mut rtc = build_rtc(config, true);
|
||||
let net = Net::bind(config, &mut rtc).await?;
|
||||
let mut api = rtc.sdp_api();
|
||||
let msid = Some(stream_id.to_owned());
|
||||
let mut mids = Vec::new();
|
||||
if config.video {
|
||||
let mid =
|
||||
api.add_media(MediaKind::Video, Direction::SendOnly, msid.clone(), None, None);
|
||||
mids.push((mid, MediaKind::Video));
|
||||
}
|
||||
if config.audio {
|
||||
let mid = api.add_media(MediaKind::Audio, Direction::SendOnly, msid, None, None);
|
||||
mids.push((mid, MediaKind::Audio));
|
||||
}
|
||||
let (offer, pending) = api.apply().ok_or(PeerError::Sdp("nothing to offer".into()))?;
|
||||
let sdp = offer.to_sdp_string();
|
||||
Ok((Self::spawn(rtc, net, config, Some(pending), mids), sdp))
|
||||
}
|
||||
|
||||
/// Viewer side: accept the streamer's offer; returns our SDP answer.
|
||||
pub async fn answer(config: &PeerConfig, offer: &str) -> Result<(Self, String), PeerError> {
|
||||
let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?;
|
||||
let mut rtc = build_rtc(config, false);
|
||||
let net = Net::bind(config, &mut rtc).await?;
|
||||
let answer = rtc.sdp_api().accept_offer(offer)?;
|
||||
Ok((Self::spawn(rtc, net, config, None, Vec::new()), answer.to_sdp_string()))
|
||||
}
|
||||
|
||||
fn spawn(
|
||||
rtc: Rtc,
|
||||
net: Net,
|
||||
config: &PeerConfig,
|
||||
pending: Option<SdpPendingOffer>,
|
||||
mids: Vec<(Mid, MediaKind)>,
|
||||
) -> Self {
|
||||
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||
let (event_tx, event_rx) = mpsc::unbounded_channel();
|
||||
let task = Task {
|
||||
rtc,
|
||||
net,
|
||||
pending,
|
||||
cmd: cmd_rx,
|
||||
events: event_tx,
|
||||
mids,
|
||||
writers: HashMap::new(),
|
||||
stun: Vec::new(),
|
||||
};
|
||||
tokio::spawn(task.run(config.stun_servers.clone()));
|
||||
Self { cmd: cmd_tx, events: event_rx }
|
||||
}
|
||||
|
||||
/// Streamer side: apply the viewer's answer.
|
||||
pub async fn accept_answer(&self, sdp: &str) -> Result<(), PeerError> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.cmd.send(Cmd::Answer(sdp.to_owned(), tx)).map_err(|_| PeerError::Closed)?;
|
||||
rx.await.map_err(|_| PeerError::Closed)?
|
||||
}
|
||||
|
||||
/// Add a trickled remote candidate (`candidate:...`, `a=` prefix optional).
|
||||
pub fn add_remote_candidate(&self, candidate: &str) {
|
||||
let _ = self.cmd.send(Cmd::RemoteCandidate(candidate.to_owned()));
|
||||
}
|
||||
|
||||
/// Send one encoded frame (streamer). Dropped until connected.
|
||||
pub fn write(&self, kind: MediaKind, time: MediaTime, data: impl Into<Arc<[u8]>>) {
|
||||
let _ = self.cmd.send(Cmd::Write { kind, time, data: data.into() });
|
||||
}
|
||||
|
||||
/// Ask the streamer for a keyframe (viewer).
|
||||
pub fn request_keyframe(&self) {
|
||||
let _ = self.cmd.send(Cmd::RequestKeyframe);
|
||||
}
|
||||
|
||||
pub fn close(&self) {
|
||||
let _ = self.cmd.send(Cmd::Close);
|
||||
}
|
||||
|
||||
/// The next event; `None` once the task ended.
|
||||
pub async fn next_event(&mut self) -> Option<PeerEvent> {
|
||||
self.events.recv().await
|
||||
}
|
||||
|
||||
pub fn try_next_event(&mut self) -> Option<PeerEvent> {
|
||||
self.events.try_recv().ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Peer {
|
||||
fn drop(&mut self) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
fn build_rtc(config: &PeerConfig, offering: bool) -> Rtc {
|
||||
let mut rtc_config =
|
||||
RtcConfig::new().set_crypto_provider(Arc::new(str0m::crypto::from_feature_flags()));
|
||||
if offering {
|
||||
// Offer only the codecs we can encode, in our order of preference.
|
||||
rtc_config = rtc_config.clear_codecs().enable_opus(config.audio);
|
||||
for codec in &config.video_codecs {
|
||||
rtc_config = match codec {
|
||||
VideoCodec::Vp8 => rtc_config.enable_vp8(true),
|
||||
VideoCodec::Vp9 => rtc_config.enable_vp9(true),
|
||||
VideoCodec::H264 => rtc_config.enable_h264(true),
|
||||
VideoCodec::Av1 => rtc_config.enable_av1(true),
|
||||
};
|
||||
}
|
||||
}
|
||||
rtc_config.build(Instant::now())
|
||||
}
|
||||
|
||||
/// The primary local IPv4 address (the one used for the default route).
|
||||
fn primary_ipv4() -> Option<IpAddr> {
|
||||
let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
// Connecting a UDP socket sends nothing; it only picks the route.
|
||||
socket.connect("192.0.2.1:9").ok()?;
|
||||
let ip = socket.local_addr().ok()?.ip();
|
||||
(!ip.is_unspecified()).then_some(ip)
|
||||
}
|
||||
|
||||
struct Packet {
|
||||
data: Vec<u8>,
|
||||
source: SocketAddr,
|
||||
destination: SocketAddr,
|
||||
}
|
||||
|
||||
/// One UDP socket per local address; readers forward into one channel.
|
||||
struct Net {
|
||||
sockets: Vec<Arc<UdpSocket>>,
|
||||
incoming: mpsc::Receiver<Packet>,
|
||||
}
|
||||
|
||||
impl Net {
|
||||
async fn bind(config: &PeerConfig, rtc: &mut Rtc) -> Result<Self, PeerError> {
|
||||
let hosts = if config.hosts.is_empty() {
|
||||
primary_ipv4().into_iter().collect()
|
||||
} else {
|
||||
config.hosts.clone()
|
||||
};
|
||||
let (tx, incoming) = mpsc::channel(256);
|
||||
let mut sockets = Vec::new();
|
||||
for ip in hosts {
|
||||
let socket = Arc::new(UdpSocket::bind(SocketAddr::new(ip, 0)).await?);
|
||||
let local = socket.local_addr()?;
|
||||
match Candidate::host(local, "udp") {
|
||||
Ok(c) => {
|
||||
rtc.add_local_candidate(c);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(%local, "skipping host candidate: {e}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let reader = socket.clone();
|
||||
let tx = tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut buf = vec![0; 2000];
|
||||
loop {
|
||||
let (n, source) = match reader.recv_from(&mut buf).await {
|
||||
Ok(r) => r,
|
||||
// ICMP port unreachable surfaces as an error on some systems.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => continue,
|
||||
Err(e) => {
|
||||
debug!("UDP read failed: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
let packet = Packet { data: buf[..n].to_vec(), source, destination: local };
|
||||
if tx.send(packet).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
sockets.push(socket);
|
||||
}
|
||||
if sockets.is_empty() {
|
||||
return Err(PeerError::NoAddress);
|
||||
}
|
||||
Ok(Self { sockets, incoming })
|
||||
}
|
||||
|
||||
fn socket_for(&self, local: SocketAddr) -> Option<&Arc<UdpSocket>> {
|
||||
self.sockets.iter().find(|s| s.local_addr().is_ok_and(|a| a == local))
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingStun {
|
||||
id: stun::TransactionId,
|
||||
server: SocketAddr,
|
||||
base: SocketAddr,
|
||||
}
|
||||
|
||||
struct Task {
|
||||
rtc: Rtc,
|
||||
net: Net,
|
||||
pending: Option<SdpPendingOffer>,
|
||||
cmd: mpsc::UnboundedReceiver<Cmd>,
|
||||
events: mpsc::UnboundedSender<PeerEvent>,
|
||||
/// Media lines of the session.
|
||||
mids: Vec<(Mid, MediaKind)>,
|
||||
/// Negotiated (mid, pt) for sending each media kind.
|
||||
writers: HashMap<MediaKind, (Mid, Pt)>,
|
||||
stun: Vec<PendingStun>,
|
||||
}
|
||||
|
||||
fn transaction_id() -> stun::TransactionId {
|
||||
let state = RandomState::new();
|
||||
let a = state.hash_one(Instant::now()).to_le_bytes();
|
||||
let b = state.hash_one(std::process::id()).to_le_bytes();
|
||||
let mut id = [0; 12];
|
||||
id[..8].copy_from_slice(&a);
|
||||
id[8..].copy_from_slice(&b[..4]);
|
||||
id
|
||||
}
|
||||
|
||||
impl Task {
|
||||
async fn run(mut self, stun_servers: Vec<String>) {
|
||||
let stun_servers = Self::resolve_stun(stun_servers);
|
||||
if let Err(e) = self.run_loop(stun_servers).await {
|
||||
debug!("peer connection ended: {e}");
|
||||
}
|
||||
self.rtc.disconnect();
|
||||
let _ = self.events.send(PeerEvent::Closed);
|
||||
}
|
||||
|
||||
/// Resolve the STUN servers in the background; each first IPv4 address
|
||||
/// arrives on the returned channel.
|
||||
fn resolve_stun(servers: Vec<String>) -> mpsc::UnboundedReceiver<SocketAddr> {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
for server in servers {
|
||||
let tx = tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let lookup = tokio::net::lookup_host(server.as_str());
|
||||
match tokio::time::timeout(Duration::from_secs(3), lookup).await {
|
||||
Ok(Ok(mut addrs)) => {
|
||||
if let Some(addr) = addrs.find(SocketAddr::is_ipv4) {
|
||||
let _ = tx.send(addr);
|
||||
}
|
||||
}
|
||||
_ => debug!(server, "STUN server lookup failed"),
|
||||
}
|
||||
});
|
||||
}
|
||||
rx
|
||||
}
|
||||
|
||||
/// Send a binding request to `server` from every non-loopback socket.
|
||||
async fn send_stun(&mut self, server: SocketAddr) {
|
||||
for socket in &self.net.sockets {
|
||||
let Ok(base) = socket.local_addr() else { continue };
|
||||
if base.ip().is_loopback() {
|
||||
continue;
|
||||
}
|
||||
let id = transaction_id();
|
||||
if socket.send_to(&stun::binding_request(&id), server).await.is_ok() {
|
||||
self.stun.push(PendingStun { id, server, base });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the packet was a STUN answer for us.
|
||||
fn handle_stun(&mut self, packet: &Packet) -> bool {
|
||||
let Some(i) = self.stun.iter().position(|s| {
|
||||
s.server == packet.source
|
||||
&& s.base == packet.destination
|
||||
&& stun::parse_binding_response(&packet.data, &s.id).is_some()
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
let pending = self.stun.remove(i);
|
||||
let Some(mapped) = stun::parse_binding_response(&packet.data, &pending.id) else {
|
||||
return true;
|
||||
};
|
||||
// Several servers may report the same mapping.
|
||||
self.stun.retain(|s| s.base != pending.base);
|
||||
if mapped == pending.base {
|
||||
return true;
|
||||
}
|
||||
match Candidate::server_reflexive(mapped, pending.base, "udp") {
|
||||
Ok(c) => {
|
||||
let line = c.to_sdp_string();
|
||||
if self.rtc.add_local_candidate(c).is_some() {
|
||||
let _ = self.events.send(PeerEvent::LocalCandidate(line));
|
||||
}
|
||||
}
|
||||
Err(e) => debug!("bad reflexive candidate {mapped}: {e}"),
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
async fn run_loop(
|
||||
&mut self,
|
||||
mut stun_servers: mpsc::UnboundedReceiver<SocketAddr>,
|
||||
) -> Result<(), PeerError> {
|
||||
loop {
|
||||
self.rtc.handle_input(Input::Timeout(Instant::now()))?;
|
||||
let deadline = loop {
|
||||
if !self.rtc.is_alive() {
|
||||
return Ok(());
|
||||
}
|
||||
match self.rtc.poll_output()? {
|
||||
Output::Timeout(t) => break t,
|
||||
Output::Transmit(t) => {
|
||||
if let Some(socket) = self.net.socket_for(t.source)
|
||||
&& let Err(e) = socket.send_to(&t.contents, t.destination).await
|
||||
{
|
||||
trace!("UDP send to {} failed: {e}", t.destination);
|
||||
}
|
||||
}
|
||||
Output::Event(e) => {
|
||||
if !self.handle_event(e) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
|
||||
tokio::select! {
|
||||
packet = self.net.incoming.recv() => {
|
||||
let Some(packet) = packet else { return Ok(()) };
|
||||
if self.handle_stun(&packet) {
|
||||
continue;
|
||||
}
|
||||
let Ok(contents) = packet.data.as_slice().try_into() else { continue };
|
||||
let input = Input::Receive(Instant::now(), Receive {
|
||||
proto: Protocol::Udp,
|
||||
source: packet.source,
|
||||
destination: packet.destination,
|
||||
contents,
|
||||
});
|
||||
if self.rtc.accepts(&input) {
|
||||
self.rtc.handle_input(input)?;
|
||||
}
|
||||
}
|
||||
cmd = self.cmd.recv() => {
|
||||
let Some(cmd) = cmd else { return Ok(()) };
|
||||
if !self.handle_cmd(cmd)? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Some(server) = stun_servers.recv() => self.send_stun(server).await,
|
||||
() = sleep => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `false` when the connection ended.
|
||||
fn handle_event(&mut self, event: Event) -> bool {
|
||||
match event {
|
||||
Event::Connected => {
|
||||
let _ = self.events.send(PeerEvent::Connected);
|
||||
}
|
||||
Event::IceConnectionStateChange(IceConnectionState::Disconnected) => return false,
|
||||
Event::MediaAdded(m) => {
|
||||
if !self.mids.iter().any(|(mid, _)| *mid == m.mid) {
|
||||
self.mids.push((m.mid, m.kind));
|
||||
}
|
||||
}
|
||||
Event::MediaData(d) => {
|
||||
let kind = if d.params.spec().codec.is_audio() {
|
||||
MediaKind::Audio
|
||||
} else {
|
||||
MediaKind::Video
|
||||
};
|
||||
let _ = self.events.send(PeerEvent::Media(MediaFrame {
|
||||
kind,
|
||||
codec: d.params.spec().codec,
|
||||
time: d.time,
|
||||
network_time: d.network_time,
|
||||
contiguous: d.contiguous,
|
||||
data: d.data,
|
||||
}));
|
||||
}
|
||||
Event::KeyframeRequest(_) => {
|
||||
let _ = self.events.send(PeerEvent::KeyframeRequest);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Returns `false` to close.
|
||||
fn handle_cmd(&mut self, cmd: Cmd) -> Result<bool, PeerError> {
|
||||
match cmd {
|
||||
Cmd::Answer(sdp, reply) => {
|
||||
let result = self.accept_answer(&sdp);
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
Cmd::RemoteCandidate(line) => {
|
||||
let line = line.trim().trim_start_matches("a=");
|
||||
match Candidate::from_sdp_string(line) {
|
||||
Ok(c) => self.rtc.add_remote_candidate(c),
|
||||
Err(e) => debug!("ignoring remote candidate {line:?}: {e}"),
|
||||
}
|
||||
}
|
||||
Cmd::Write { kind, time, data } => self.write(kind, time, data)?,
|
||||
Cmd::RequestKeyframe => {
|
||||
for &(mid, _) in &self.mids {
|
||||
if let Some(mut w) = self.rtc.writer(mid) {
|
||||
let _ = w.request_keyframe(None, KeyframeRequestKind::Pli);
|
||||
}
|
||||
}
|
||||
}
|
||||
Cmd::Close => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn accept_answer(&mut self, sdp: &str) -> Result<(), PeerError> {
|
||||
let pending = self.pending.take().ok_or(PeerError::NotOffering)?;
|
||||
let answer = SdpAnswer::from_sdp_string(sdp).map_err(|e| PeerError::Sdp(e.to_string()))?;
|
||||
self.rtc.sdp_api().accept_answer(pending, answer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write(
|
||||
&mut self,
|
||||
kind: MediaKind,
|
||||
time: MediaTime,
|
||||
data: Arc<[u8]>,
|
||||
) -> Result<(), PeerError> {
|
||||
if !self.writers.contains_key(&kind) {
|
||||
let Some((mid, pt)) = self.find_writer(kind) else {
|
||||
trace!(?kind, "no negotiated media to write to");
|
||||
return Ok(());
|
||||
};
|
||||
self.writers.insert(kind, (mid, pt));
|
||||
}
|
||||
let (mid, pt) = self.writers[&kind];
|
||||
if let Some(writer) = self.rtc.writer(mid) {
|
||||
writer.write(pt, Instant::now(), time, data)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_writer(&mut self, kind: MediaKind) -> Option<(Mid, Pt)> {
|
||||
let mid = self.mids.iter().find(|(_, k)| *k == kind)?.0;
|
||||
let writer = self.rtc.writer(mid)?;
|
||||
// The first remote payload type in the answer is the peer's preference.
|
||||
let pt = writer.payload_params().find(|p| p.spec().codec.kind() == kind)?.pt();
|
||||
Some((mid, pt))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
//! TeamSpeak 6 stream commands and notifications on the client command channel.
|
||||
//!
|
||||
//! See `docs/protocol-notes/ts6-streaming.md` for how these were found.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::iter;
|
||||
|
||||
use tsclientlib::messages::c2s;
|
||||
use tsclientlib::{ClientId, InMessage};
|
||||
use tsproto_packets::packets::OutCommand;
|
||||
|
||||
/// `type` of a stream (`StreamType` in the server's protobuf schema).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StreamKind {
|
||||
Camera,
|
||||
Screen,
|
||||
Window,
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
impl StreamKind {
|
||||
pub fn from_u8(v: u8) -> Self {
|
||||
match v {
|
||||
2 => Self::Camera,
|
||||
3 => Self::Screen,
|
||||
4 => Self::Window,
|
||||
v => Self::Other(v),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_u8(self) -> u8 {
|
||||
match self {
|
||||
Self::Camera => 2,
|
||||
Self::Screen => 3,
|
||||
Self::Window => 4,
|
||||
Self::Other(v) => v,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a viewer left a stream (`StreamLeaveReason`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LeaveReason {
|
||||
None,
|
||||
Left,
|
||||
Denied,
|
||||
Failed,
|
||||
Kicked,
|
||||
Banned,
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
impl LeaveReason {
|
||||
pub fn to_u8(self) -> u8 {
|
||||
match self {
|
||||
Self::None => 1,
|
||||
Self::Left => 2,
|
||||
Self::Denied => 3,
|
||||
Self::Failed => 4,
|
||||
Self::Kicked => 5,
|
||||
Self::Banned => 6,
|
||||
Self::Other(v) => v,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_u8(v: u8) -> Self {
|
||||
match v {
|
||||
1 => Self::None,
|
||||
2 => Self::Left,
|
||||
3 => Self::Denied,
|
||||
4 => Self::Failed,
|
||||
5 => Self::Kicked,
|
||||
6 => Self::Banned,
|
||||
v => Self::Other(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters of `setupstream`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamSetup {
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
/// kbit/s; the server caps streams at 10 Mbit/s.
|
||||
pub bitrate: u32,
|
||||
/// `accessibility`: the official client and ts6-manager send 1.
|
||||
pub accessibility: u8,
|
||||
/// `mode`: 1 (none) is what clients send today; 2 is P2P, 3 SFU.
|
||||
pub mode: u8,
|
||||
/// 0 = unlimited.
|
||||
pub viewer_limit: u32,
|
||||
pub audio: bool,
|
||||
}
|
||||
|
||||
impl Default for StreamSetup {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
kind: StreamKind::Screen,
|
||||
bitrate: 4608,
|
||||
accessibility: 1,
|
||||
mode: 1,
|
||||
viewer_limit: 0,
|
||||
audio: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream as announced by `notifystreamstarted` / `notifystreaminfo`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamInfo {
|
||||
pub id: String,
|
||||
pub streamer: ClientId,
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
pub bitrate: u32,
|
||||
pub viewer_limit: u32,
|
||||
pub audio: bool,
|
||||
}
|
||||
|
||||
/// Stream notifications, decoded from [`InMessage`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum StreamNotification {
|
||||
/// A stream started in our channel. `return_code` is set on the answer to our own `setupstream`.
|
||||
Started {
|
||||
info: StreamInfo,
|
||||
return_code: Option<String>,
|
||||
},
|
||||
Info(StreamInfo),
|
||||
Stopped {
|
||||
id: String,
|
||||
streamer: Option<ClientId>,
|
||||
reason: Option<LeaveReason>,
|
||||
},
|
||||
/// (Streamer side) a viewer asks to watch, or withdraws (`remove`).
|
||||
JoinRequest {
|
||||
id: String,
|
||||
viewer: ClientId,
|
||||
message: String,
|
||||
remove: bool,
|
||||
},
|
||||
/// (Viewer side) the streamer answered our join request.
|
||||
JoinResponse {
|
||||
id: String,
|
||||
streamer: Option<ClientId>,
|
||||
accepted: bool,
|
||||
offer: Option<String>,
|
||||
message: String,
|
||||
},
|
||||
/// A `json` signalling message from `peer`.
|
||||
Signaling {
|
||||
id: String,
|
||||
peer: ClientId,
|
||||
json: String,
|
||||
},
|
||||
ViewerJoined {
|
||||
id: String,
|
||||
viewer: ClientId,
|
||||
},
|
||||
ViewerLeft {
|
||||
id: String,
|
||||
viewer: ClientId,
|
||||
reason: Option<LeaveReason>,
|
||||
},
|
||||
}
|
||||
|
||||
impl StreamNotification {
|
||||
/// Decode the stream notifications in `msg`; empty for other messages.
|
||||
pub fn from_message(msg: &InMessage) -> Vec<Self> {
|
||||
match msg {
|
||||
InMessage::StreamStarted(m) => m
|
||||
.iter()
|
||||
.map(|p| Self::Started {
|
||||
info: StreamInfo {
|
||||
id: p.stream_id.clone(),
|
||||
streamer: p.client_id,
|
||||
name: p.stream_name.clone().unwrap_or_default(),
|
||||
kind: StreamKind::from_u8(p.stream_type.unwrap_or(3)),
|
||||
bitrate: p.bitrate.unwrap_or(0),
|
||||
viewer_limit: p.viewer_limit.unwrap_or(0),
|
||||
audio: p.audio.unwrap_or(false),
|
||||
},
|
||||
return_code: p.return_code.clone(),
|
||||
})
|
||||
.collect(),
|
||||
InMessage::StreamInfo(m) => m
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
Some(Self::Info(StreamInfo {
|
||||
id: p.stream_id.clone(),
|
||||
streamer: p.client_id?,
|
||||
name: p.stream_name.clone().unwrap_or_default(),
|
||||
kind: StreamKind::from_u8(p.stream_type.unwrap_or(3)),
|
||||
bitrate: p.bitrate.unwrap_or(0),
|
||||
viewer_limit: p.viewer_limit.unwrap_or(0),
|
||||
audio: p.audio.unwrap_or(false),
|
||||
}))
|
||||
})
|
||||
.collect(),
|
||||
InMessage::StreamStopped(m) => m
|
||||
.iter()
|
||||
.map(|p| Self::Stopped {
|
||||
id: p.stream_id.clone(),
|
||||
streamer: p.client_id,
|
||||
reason: p.leave_reason.map(LeaveReason::from_u8),
|
||||
})
|
||||
.collect(),
|
||||
InMessage::JoinStreamRequest(m) => m
|
||||
.iter()
|
||||
.map(|p| Self::JoinRequest {
|
||||
id: p.stream_id.clone(),
|
||||
viewer: p.client_id,
|
||||
message: p.message.clone().unwrap_or_default(),
|
||||
remove: p.is_remove.unwrap_or(false),
|
||||
})
|
||||
.collect(),
|
||||
InMessage::RespondJoinStreamRequest(m) => m
|
||||
.iter()
|
||||
.map(|p| Self::JoinResponse {
|
||||
id: p.stream_id.clone(),
|
||||
streamer: p.client_id,
|
||||
accepted: p.accepted.unwrap_or(false),
|
||||
offer: p.offer.clone().filter(|o| !o.is_empty()),
|
||||
message: p.message.clone().unwrap_or_default(),
|
||||
})
|
||||
.collect(),
|
||||
InMessage::StreamSignaling(m) => m
|
||||
.iter()
|
||||
.map(|p| Self::Signaling {
|
||||
id: p.stream_id.clone(),
|
||||
peer: p.client_id,
|
||||
json: p.json.clone(),
|
||||
})
|
||||
.collect(),
|
||||
InMessage::StreamClientJoined(m) => m
|
||||
.iter()
|
||||
.map(|p| Self::ViewerJoined { id: p.stream_id.clone(), viewer: p.client_id })
|
||||
.collect(),
|
||||
InMessage::StreamClientLeft(m) => m
|
||||
.iter()
|
||||
.map(|p| Self::ViewerLeft {
|
||||
id: p.stream_id.clone(),
|
||||
viewer: p.client_id,
|
||||
reason: p.leave_reason.map(LeaveReason::from_u8),
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The stream id this notification is about.
|
||||
pub fn stream_id(&self) -> &str {
|
||||
match self {
|
||||
Self::Started { info, .. } | Self::Info(info) => &info.id,
|
||||
Self::Stopped { id, .. }
|
||||
| Self::JoinRequest { id, .. }
|
||||
| Self::JoinResponse { id, .. }
|
||||
| Self::Signaling { id, .. }
|
||||
| Self::ViewerJoined { id, .. }
|
||||
| Self::ViewerLeft { id, .. } => id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `setupstream`: start streaming in our channel. The server answers with
|
||||
/// `notifystreamstarted` carrying the stream id.
|
||||
pub fn setup(setup: &StreamSetup) -> OutCommand {
|
||||
c2s::OutSetupStreamMessage::new(&mut iter::once(c2s::OutSetupStreamPart {
|
||||
stream_name: Cow::Borrowed(&setup.name),
|
||||
stream_type: setup.kind.to_u8(),
|
||||
bitrate: setup.bitrate,
|
||||
access: setup.accessibility,
|
||||
stream_mode: setup.mode,
|
||||
viewer_limit: setup.viewer_limit,
|
||||
audio: setup.audio,
|
||||
}))
|
||||
}
|
||||
|
||||
/// `stopstream`: end our stream.
|
||||
pub fn stop(id: &str) -> OutCommand {
|
||||
c2s::OutStopStreamMessage::new(&mut iter::once(c2s::OutStopStreamPart {
|
||||
stream_id: Cow::Borrowed(id),
|
||||
leave_reason: LeaveReason::None.to_u8(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `joinstreamrequest`: ask `streamer` to let us watch (or withdraw with `remove`).
|
||||
pub fn join_request(id: &str, streamer: ClientId, message: &str, remove: bool) -> OutCommand {
|
||||
c2s::OutJoinStreamRequestRequestMessage::new(&mut iter::once(
|
||||
c2s::OutJoinStreamRequestRequestPart {
|
||||
stream_id: Cow::Borrowed(id),
|
||||
client_id: streamer,
|
||||
message: Cow::Borrowed(message),
|
||||
is_remove: remove,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// `respondjoinstreamrequest`: accept a viewer with our SDP offer, or deny.
|
||||
pub fn respond(id: &str, viewer: ClientId, offer: Option<&str>, accept: bool) -> OutCommand {
|
||||
c2s::OutRespondJoinStreamRequestRequestMessage::new(&mut iter::once(
|
||||
c2s::OutRespondJoinStreamRequestRequestPart {
|
||||
stream_id: Cow::Borrowed(id),
|
||||
client_id: viewer,
|
||||
message: Some(Cow::Borrowed("")),
|
||||
offer: offer.map(Cow::Borrowed),
|
||||
accepted: accept,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// `streamsignaling`: send a [`Signal`](crate::Signal) JSON to `peer`.
|
||||
pub fn signaling(id: &str, peer: ClientId, json: &str) -> OutCommand {
|
||||
c2s::OutStreamSignalingRequestMessage::new(&mut iter::once(
|
||||
c2s::OutStreamSignalingRequestPart {
|
||||
stream_id: Cow::Borrowed(id),
|
||||
client_id: peer,
|
||||
json: Cow::Borrowed(json),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// `removeclientfromstream`: end a viewer's session (`reason` is usually
|
||||
/// [`LeaveReason::Kicked`]; the viewer gets `notifystreamclientleft` with it).
|
||||
pub fn remove_viewer(id: &str, viewer: ClientId, reason: LeaveReason) -> OutCommand {
|
||||
c2s::OutRemoveClientFromStreamMessage::new(&mut iter::once(
|
||||
c2s::OutRemoveClientFromStreamPart {
|
||||
stream_id: Cow::Borrowed(id),
|
||||
client_id: viewer,
|
||||
leave_reason: reason.to_u8(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn text(cmd: OutCommand) -> String {
|
||||
String::from_utf8(cmd.0.content().to_vec()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands() {
|
||||
let s = StreamSetup { name: "my screen".into(), ..Default::default() };
|
||||
assert_eq!(
|
||||
text(setup(&s)),
|
||||
"setupstream name=my\\sscreen type=3 bitrate=4608 accessibility=1 mode=1 viewer_limit=0 \
|
||||
audio=1"
|
||||
);
|
||||
assert_eq!(
|
||||
text(join_request("u-1", ClientId(5), "", false)),
|
||||
"joinstreamrequest id=u-1 clid=5 msg is_remove=0"
|
||||
);
|
||||
assert_eq!(
|
||||
text(signaling("u-1", ClientId(5), r#"{"a":1}"#)),
|
||||
"streamsignaling id=u-1 clid=5 json={\"a\":1}"
|
||||
);
|
||||
assert_eq!(text(stop("u-1")), "stopstream id=u-1 reason=1");
|
||||
assert_eq!(
|
||||
text(remove_viewer("u-1", ClientId(7), LeaveReason::Kicked)),
|
||||
"removeclientfromstream id=u-1 clid=7 reason=5"
|
||||
);
|
||||
let r = text(respond("u-1", ClientId(7), Some("v=0"), true));
|
||||
assert!(r.starts_with("respondjoinstreamrequest id=u-1 clid=7"), "{r}");
|
||||
assert!(r.contains("offer=v=0") && r.contains("decision=1"), "{r}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! JSON messages carried in `streamsignaling` / `notifystreamsignaling`.
|
||||
//!
|
||||
//! The server passes the `json` parameter through unchanged. The format is
|
||||
//! `{"cmd": <name>, "args": {...}}`; different clients spell the argument keys
|
||||
//! differently, so parsing accepts every known variant and serializing uses the
|
||||
//! spelling the official client sends.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// One signalling message between streamer and viewer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Signal {
|
||||
/// SDP offer. `reconnect` is set for `reconnectOffer` (ICE restart).
|
||||
Offer { sdp: String, reconnect: bool },
|
||||
/// SDP answer to an offer.
|
||||
Answer { sdp: String },
|
||||
/// Trickled ICE candidate (`candidate:...` line, with or without the `a=` prefix).
|
||||
IceCandidate { candidate: String, mid: Option<String>, mline_index: Option<u32> },
|
||||
/// The other side asks for a new offer.
|
||||
Reconnect,
|
||||
/// A command this client does not know; kept for logging.
|
||||
Unknown { cmd: String, args: Value },
|
||||
}
|
||||
|
||||
/// The `json` parameter could not be understood.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SignalError {
|
||||
#[error("invalid JSON: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("missing \"cmd\"")]
|
||||
MissingCmd,
|
||||
#[error("{cmd}: missing argument {arg}")]
|
||||
MissingArg { cmd: String, arg: &'static str },
|
||||
}
|
||||
|
||||
fn string_arg(args: &Map<String, Value>, keys: &[&str]) -> Option<String> {
|
||||
keys.iter().find_map(|k| args.get(*k)).and_then(|v| v.as_str()).map(str::to_owned)
|
||||
}
|
||||
|
||||
impl Signal {
|
||||
pub fn parse(text: &str) -> Result<Self, SignalError> {
|
||||
let value: Value = serde_json::from_str(text)?;
|
||||
let cmd = value.get("cmd").and_then(Value::as_str).ok_or(SignalError::MissingCmd)?;
|
||||
let empty = Map::new();
|
||||
let args = value.get("args").and_then(Value::as_object).unwrap_or(&empty);
|
||||
let missing = |arg| SignalError::MissingArg { cmd: cmd.to_owned(), arg };
|
||||
Ok(match cmd {
|
||||
"offer" | "reconnectOffer" => Signal::Offer {
|
||||
sdp: string_arg(args, &["offer", "sdp"]).ok_or_else(|| missing("offer"))?,
|
||||
reconnect: cmd == "reconnectOffer",
|
||||
},
|
||||
"answer" => Signal::Answer {
|
||||
sdp: string_arg(args, &["answer", "sdp"]).ok_or_else(|| missing("answer"))?,
|
||||
},
|
||||
"iceCandidate" | "candidate" => Signal::IceCandidate {
|
||||
candidate: string_arg(args, &["candidate", "sdp"])
|
||||
.ok_or_else(|| missing("candidate"))?,
|
||||
mid: string_arg(args, &["mid", "sdpMid", "sdp_mid"]),
|
||||
mline_index: ["mLine", "sdpMLineIndex", "sdpMlineIndex", "sdp_mline_index"]
|
||||
.iter()
|
||||
.find_map(|k| args.get(*k))
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|v| u32::try_from(v).ok()),
|
||||
},
|
||||
"reconnect" => Signal::Reconnect,
|
||||
other => Signal::Unknown { cmd: other.to_owned(), args: Value::Object(args.clone()) },
|
||||
})
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> String {
|
||||
let value = match self {
|
||||
Signal::Offer { sdp, reconnect } => json!({
|
||||
"cmd": if *reconnect { "reconnectOffer" } else { "offer" },
|
||||
"args": { "offer": sdp },
|
||||
}),
|
||||
Signal::Answer { sdp } => json!({ "cmd": "answer", "args": { "answer": sdp } }),
|
||||
Signal::IceCandidate { candidate, mid, mline_index } => json!({
|
||||
"cmd": "iceCandidate",
|
||||
"args": { "candidate": candidate, "sdpMid": mid, "sdpMLineIndex": mline_index },
|
||||
}),
|
||||
Signal::Reconnect => json!({ "cmd": "reconnect", "args": {} }),
|
||||
Signal::Unknown { cmd, args } => json!({ "cmd": cmd, "args": args }),
|
||||
};
|
||||
value.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let signals = [
|
||||
Signal::Offer { sdp: "v=0\r\n".into(), reconnect: false },
|
||||
Signal::Offer { sdp: "v=0\r\n".into(), reconnect: true },
|
||||
Signal::Answer { sdp: "v=0\r\n".into() },
|
||||
Signal::IceCandidate {
|
||||
candidate: "candidate:1 1 udp 2130706431 10.0.0.2 50000 typ host".into(),
|
||||
mid: Some("0".into()),
|
||||
mline_index: Some(0),
|
||||
},
|
||||
Signal::Reconnect,
|
||||
];
|
||||
for s in signals {
|
||||
assert_eq!(Signal::parse(&s.to_json()).unwrap(), s);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_variants() {
|
||||
let s = Signal::parse(r#"{"cmd":"answer","args":{"sdp":"x"}}"#).unwrap();
|
||||
assert_eq!(s, Signal::Answer { sdp: "x".into() });
|
||||
let s = Signal::parse(r#"{"cmd":"iceCandidate","args":{"sdp":"c","mid":"1","mLine":1}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
s,
|
||||
Signal::IceCandidate {
|
||||
candidate: "c".into(),
|
||||
mid: Some("1".into()),
|
||||
mline_index: Some(1)
|
||||
}
|
||||
);
|
||||
let s = Signal::parse(r#"{"cmd":"reconnectOffer","args":{"offer":"o"}}"#).unwrap();
|
||||
assert_eq!(s, Signal::Offer { sdp: "o".into(), reconnect: true });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors() {
|
||||
assert!(matches!(Signal::parse("nope"), Err(SignalError::Json(_))));
|
||||
assert!(matches!(Signal::parse("{}"), Err(SignalError::MissingCmd)));
|
||||
assert!(matches!(
|
||||
Signal::parse(r#"{"cmd":"answer","args":{}}"#),
|
||||
Err(SignalError::MissingArg { arg: "answer", .. })
|
||||
));
|
||||
assert!(matches!(Signal::parse(r#"{"cmd":"future"}"#), Ok(Signal::Unknown { .. })));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Minimal STUN binding client (RFC 5389) to learn our public address.
|
||||
//!
|
||||
//! TeamSpeak streams use STUN only (`turn.teamspeak.com`), no TURN relay, so a
|
||||
//! server-reflexive candidate is all we need beyond host candidates.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
|
||||
|
||||
const MAGIC_COOKIE: u32 = 0x2112_A442;
|
||||
const BINDING_REQUEST: u16 = 0x0001;
|
||||
const BINDING_SUCCESS: u16 = 0x0101;
|
||||
const ATTR_MAPPED_ADDRESS: u16 = 0x0001;
|
||||
const ATTR_XOR_MAPPED_ADDRESS: u16 = 0x0020;
|
||||
|
||||
/// Default STUN servers of the TeamSpeak infrastructure.
|
||||
pub const TEAMSPEAK_STUN: &[&str] = &["turn.teamspeak.com:3478", "turn2.teamspeak.com:3478"];
|
||||
|
||||
pub type TransactionId = [u8; 12];
|
||||
|
||||
/// A binding request without attributes.
|
||||
pub fn binding_request(id: &TransactionId) -> Vec<u8> {
|
||||
let mut buf = Vec::with_capacity(20);
|
||||
buf.extend_from_slice(&BINDING_REQUEST.to_be_bytes());
|
||||
buf.extend_from_slice(&0u16.to_be_bytes());
|
||||
buf.extend_from_slice(&MAGIC_COOKIE.to_be_bytes());
|
||||
buf.extend_from_slice(id);
|
||||
buf
|
||||
}
|
||||
|
||||
/// The mapped address from a binding success response with transaction `id`.
|
||||
pub fn parse_binding_response(data: &[u8], id: &TransactionId) -> Option<SocketAddr> {
|
||||
if data.len() < 20
|
||||
|| u16::from_be_bytes([data[0], data[1]]) != BINDING_SUCCESS
|
||||
|| u32::from_be_bytes(data[4..8].try_into().ok()?) != MAGIC_COOKIE
|
||||
|| &data[8..20] != id
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let len = usize::from(u16::from_be_bytes([data[2], data[3]]));
|
||||
let attrs = data.get(20..20 + len)?;
|
||||
let mut pos = 0;
|
||||
let mut mapped = None;
|
||||
while pos + 4 <= attrs.len() {
|
||||
let kind = u16::from_be_bytes([attrs[pos], attrs[pos + 1]]);
|
||||
let alen = usize::from(u16::from_be_bytes([attrs[pos + 2], attrs[pos + 3]]));
|
||||
let value = attrs.get(pos + 4..pos + 4 + alen)?;
|
||||
match kind {
|
||||
ATTR_XOR_MAPPED_ADDRESS => return parse_address(value, Some(&data[4..20])),
|
||||
ATTR_MAPPED_ADDRESS => mapped = parse_address(value, None),
|
||||
_ => {}
|
||||
}
|
||||
pos += 4 + alen.div_ceil(4) * 4;
|
||||
}
|
||||
mapped
|
||||
}
|
||||
|
||||
/// Parse a (XOR-)MAPPED-ADDRESS value; `xor` is cookie + transaction id.
|
||||
fn parse_address(value: &[u8], xor: Option<&[u8]>) -> Option<SocketAddr> {
|
||||
if value.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
let family = value[1];
|
||||
let mut port = u16::from_be_bytes([value[2], value[3]]);
|
||||
let mut addr = value[4..].to_vec();
|
||||
if let Some(x) = xor {
|
||||
port ^= (MAGIC_COOKIE >> 16) as u16;
|
||||
for (b, k) in addr.iter_mut().zip(x) {
|
||||
*b ^= k;
|
||||
}
|
||||
}
|
||||
let ip = match family {
|
||||
1 => IpAddr::V4(Ipv4Addr::from(<[u8; 4]>::try_from(addr.get(..4)?).ok()?)),
|
||||
2 => IpAddr::V6(Ipv6Addr::from(<[u8; 16]>::try_from(addr.get(..16)?).ok()?)),
|
||||
_ => return None,
|
||||
};
|
||||
Some(SocketAddr::new(ip, port))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn xor_mapped_address() {
|
||||
let id = [7u8; 12];
|
||||
// Response for 203.0.113.5:40000.
|
||||
let mut resp = Vec::new();
|
||||
resp.extend_from_slice(&BINDING_SUCCESS.to_be_bytes());
|
||||
resp.extend_from_slice(&12u16.to_be_bytes());
|
||||
resp.extend_from_slice(&MAGIC_COOKIE.to_be_bytes());
|
||||
resp.extend_from_slice(&id);
|
||||
resp.extend_from_slice(&ATTR_XOR_MAPPED_ADDRESS.to_be_bytes());
|
||||
resp.extend_from_slice(&8u16.to_be_bytes());
|
||||
resp.extend_from_slice(&[0, 1]);
|
||||
resp.extend_from_slice(&(40000u16 ^ 0x2112).to_be_bytes());
|
||||
let ip = u32::from(Ipv4Addr::new(203, 0, 113, 5)) ^ MAGIC_COOKIE;
|
||||
resp.extend_from_slice(&ip.to_be_bytes());
|
||||
assert_eq!(parse_binding_response(&resp, &id), Some("203.0.113.5:40000".parse().unwrap()));
|
||||
assert_eq!(parse_binding_response(&resp, &[8u8; 12]), None);
|
||||
assert_eq!(binding_request(&id).len(), 20);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
//! A full stream between two clients through the TeamSpeak 6 dev server
|
||||
//! (dev/docker-compose.yml): `setupstream`, `joinstreamrequest`,
|
||||
//! `respondjoinstreamrequest` with our offer, `streamsignaling` with the answer,
|
||||
//! then media over loopback. Runs only with `TSC_LIVE=1`.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::prelude::*;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::time::timeout;
|
||||
use tsc_stream::{
|
||||
Frequency, LeaveReason, MediaKind, MediaTime, Peer, PeerConfig, PeerEvent, Signal,
|
||||
StreamNotification, StreamSetup, proto,
|
||||
};
|
||||
use tsclientlib::prelude::*;
|
||||
use tsclientlib::{ClientId, Connection, DisconnectOptions, MessageHandle, StreamItem};
|
||||
use tsproto_packets::packets::OutCommand;
|
||||
|
||||
fn live() -> bool {
|
||||
std::env::var("TSC_LIVE").is_ok_and(|v| v == "1")
|
||||
}
|
||||
|
||||
fn ts6_addr() -> String {
|
||||
std::env::var("TSC_TS6_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into())
|
||||
}
|
||||
|
||||
type Reply = oneshot::Sender<Result<(), String>>;
|
||||
|
||||
/// A connected client running in its own task.
|
||||
struct Client {
|
||||
id: ClientId,
|
||||
commands: mpsc::UnboundedSender<Option<(OutCommand, Option<Reply>)>>,
|
||||
notifications: mpsc::UnboundedReceiver<StreamNotification>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
async fn connect(nick: &str) -> Client {
|
||||
let mut con = Connection::build(ts6_addr()).name(nick.to_owned()).connect().unwrap();
|
||||
timeout(Duration::from_secs(30), async {
|
||||
con.events()
|
||||
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
|
||||
.next()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
})
|
||||
.await
|
||||
.expect("connect timeout");
|
||||
let id = con.get_state().unwrap().own_client;
|
||||
let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::<Option<(OutCommand, Option<Reply>)>>();
|
||||
let mut waiting: Vec<(MessageHandle, Reply)> = Vec::new();
|
||||
let (note_tx, note_rx) = mpsc::unbounded_channel();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let mut events = con.events();
|
||||
tokio::select! {
|
||||
item = events.next() => match item {
|
||||
Some(Ok(StreamItem::MessageEvent(msg))) => {
|
||||
for n in StreamNotification::from_message(&msg) {
|
||||
let _ = note_tx.send(n);
|
||||
}
|
||||
}
|
||||
Some(Ok(StreamItem::MessageResult(handle, result))) => {
|
||||
if let Some(i) = waiting.iter().position(|(h, _)| *h == handle) {
|
||||
let _ = waiting.remove(i).1.send(result.map_err(|e| e.to_string()));
|
||||
}
|
||||
}
|
||||
Some(Ok(_)) => {}
|
||||
_ => return,
|
||||
},
|
||||
cmd = cmd_rx.recv() => {
|
||||
drop(events);
|
||||
match cmd {
|
||||
Some(Some((cmd, None))) => cmd.send(&mut con).unwrap(),
|
||||
Some(Some((cmd, Some(reply)))) => {
|
||||
waiting.push((cmd.send_with_result(&mut con).unwrap(), reply));
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
con.disconnect(DisconnectOptions::new()).unwrap();
|
||||
let _ =
|
||||
timeout(Duration::from_secs(3), con.events().for_each(|_| future::ready(()))).await;
|
||||
});
|
||||
Client { id, commands: cmd_tx, notifications: note_rx }
|
||||
}
|
||||
|
||||
fn send(&self, cmd: OutCommand) {
|
||||
self.commands.send(Some((cmd, None))).unwrap();
|
||||
}
|
||||
|
||||
/// Send and wait for the server's answer.
|
||||
async fn call(&self, cmd: OutCommand) -> Result<(), String> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.commands.send(Some((cmd, Some(tx)))).unwrap();
|
||||
timeout(Duration::from_secs(10), rx).await.expect("no answer").unwrap()
|
||||
}
|
||||
|
||||
async fn next(&mut self, what: &str) -> StreamNotification {
|
||||
timeout(Duration::from_secs(15), self.notifications.recv())
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("timed out waiting for {what}"))
|
||||
.expect("client task ended")
|
||||
}
|
||||
|
||||
async fn quit(self) {
|
||||
let _ = self.commands.send(None);
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stream_through_ts6_server() {
|
||||
if !live() {
|
||||
eprintln!("skipped: set TSC_LIVE=1 with the dev servers running");
|
||||
return;
|
||||
}
|
||||
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
|
||||
let tag = std::process::id() % 10_000;
|
||||
let mut streamer = Client::connect(&format!("streamer-{tag}")).await;
|
||||
let mut viewer = Client::connect(&format!("viewer-{tag}")).await;
|
||||
|
||||
// 1. Start the stream.
|
||||
streamer.send(proto::setup(&StreamSetup { name: "live test".into(), ..Default::default() }));
|
||||
let stream_id = loop {
|
||||
if let StreamNotification::Started { info, return_code: Some(_) } =
|
||||
streamer.next("own notifystreamstarted").await
|
||||
{
|
||||
assert_eq!(info.streamer, streamer.id);
|
||||
break info.id;
|
||||
}
|
||||
};
|
||||
// The viewer, in the same channel, sees it.
|
||||
loop {
|
||||
if let StreamNotification::Started { info, .. } = viewer.next("notifystreamstarted").await
|
||||
&& info.id == stream_id
|
||||
{
|
||||
assert_eq!(info.name, "live test");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Viewer asks to join.
|
||||
viewer.send(proto::join_request(&stream_id, streamer.id, "let me watch", false));
|
||||
let viewer_id = loop {
|
||||
if let StreamNotification::JoinRequest { id, viewer: v, message, remove } =
|
||||
streamer.next("notifyjoinstreamrequest").await
|
||||
{
|
||||
assert_eq!(
|
||||
(id.as_str(), message.as_str(), remove),
|
||||
(stream_id.as_str(), "let me watch", false)
|
||||
);
|
||||
break v;
|
||||
}
|
||||
};
|
||||
assert_eq!(viewer_id, viewer.id);
|
||||
|
||||
// 3. Streamer accepts with an offer.
|
||||
let config = PeerConfig::loopback();
|
||||
let (mut send_peer, offer) = Peer::offer(&config, &stream_id).await.unwrap();
|
||||
streamer.send(proto::respond(&stream_id, viewer_id, Some(&offer), true));
|
||||
|
||||
// 4. Viewer answers through streamsignaling.
|
||||
let offer_in = loop {
|
||||
match viewer.next("notifyrespondjoinstreamrequest").await {
|
||||
StreamNotification::JoinResponse { accepted, offer: Some(offer), .. } => {
|
||||
assert!(accepted);
|
||||
break offer;
|
||||
}
|
||||
StreamNotification::JoinResponse { accepted, offer: None, message, .. } => {
|
||||
panic!("response without offer (accepted {accepted}, {message:?})")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
};
|
||||
assert_eq!(offer_in.trim(), offer.trim(), "offer must arrive unchanged");
|
||||
let (mut recv_peer, answer) = Peer::answer(&config, &offer_in).await.unwrap();
|
||||
viewer.send(proto::signaling(
|
||||
&stream_id,
|
||||
streamer.id,
|
||||
&Signal::Answer { sdp: answer }.to_json(),
|
||||
));
|
||||
|
||||
// 5. Streamer applies the answer.
|
||||
loop {
|
||||
if let StreamNotification::Signaling { peer, json, .. } =
|
||||
streamer.next("notifystreamsignaling").await
|
||||
{
|
||||
assert_eq!(peer, viewer_id);
|
||||
match Signal::parse(&json).unwrap() {
|
||||
Signal::Answer { sdp } => {
|
||||
send_peer.accept_answer(&sdp).await.unwrap();
|
||||
break;
|
||||
}
|
||||
other => panic!("unexpected signal {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Media.
|
||||
timeout(Duration::from_secs(10), async {
|
||||
while !matches!(send_peer.next_event().await, Some(PeerEvent::Connected)) {}
|
||||
})
|
||||
.await
|
||||
.expect("streamer peer did not connect");
|
||||
let sender = tokio::spawn(async move {
|
||||
for i in 0..60u64 {
|
||||
let mut frame = vec![0x10, 0x02, 0x00, 0x9d, 0x01, 0x2a, 0x80, 0x02, 0xe0, 0x01];
|
||||
frame.extend(std::iter::repeat_n(i as u8, 1500));
|
||||
send_peer.write(MediaKind::Video, MediaTime::from_90khz(i * 3000), frame);
|
||||
send_peer.write(
|
||||
MediaKind::Audio,
|
||||
MediaTime::new(i * 960, Frequency::FORTY_EIGHT_KHZ),
|
||||
vec![0xfc, i as u8],
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(33)).await;
|
||||
}
|
||||
send_peer
|
||||
});
|
||||
let (mut video, mut audio) = (0, 0);
|
||||
let _ = timeout(Duration::from_secs(6), async {
|
||||
while let Some(event) = recv_peer.next_event().await {
|
||||
match event {
|
||||
PeerEvent::Media(f) if f.kind == MediaKind::Video => video += 1,
|
||||
PeerEvent::Media(_) => audio += 1,
|
||||
_ => {}
|
||||
}
|
||||
if video >= 50 && audio >= 50 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let send_peer = sender.await.unwrap();
|
||||
assert!(video >= 50 && audio >= 50, "viewer got {video} video / {audio} audio frames");
|
||||
|
||||
drop((send_peer, recv_peer));
|
||||
// 7. The streamer ends the viewer's session, then the stream.
|
||||
streamer
|
||||
.call(proto::remove_viewer(&stream_id, viewer_id, LeaveReason::Kicked))
|
||||
.await
|
||||
.expect("removeclientfromstream");
|
||||
loop {
|
||||
if let StreamNotification::ViewerLeft { viewer: v, reason, .. } =
|
||||
viewer.next("notifystreamclientleft").await
|
||||
{
|
||||
assert_eq!((v, reason), (viewer_id, Some(LeaveReason::Kicked)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
streamer.call(proto::stop(&stream_id)).await.expect("stopstream");
|
||||
loop {
|
||||
if let StreamNotification::Stopped { id, .. } = viewer.next("notifystreamstopped").await {
|
||||
assert_eq!(id, stream_id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
viewer.quit().await;
|
||||
streamer.quit().await;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Two peers on loopback: offer/answer, then video and audio frames flow.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::time::timeout;
|
||||
use tsc_stream::{MediaKind, MediaTime, Peer, PeerConfig, PeerEvent};
|
||||
|
||||
/// Bytes that look like a VP8 keyframe (frame tag + start code), then filler.
|
||||
pub fn fake_vp8_keyframe(seq: u8, len: usize) -> Vec<u8> {
|
||||
let mut f = vec![0x10, 0x02, 0x00, 0x9d, 0x01, 0x2a, 0x80, 0x02, 0xe0, 0x01];
|
||||
f.extend((0..len).map(|i| (i as u8) ^ seq));
|
||||
f
|
||||
}
|
||||
|
||||
async fn wait_connected(peer: &mut Peer) {
|
||||
timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
match peer.next_event().await {
|
||||
Some(PeerEvent::Connected) => return,
|
||||
Some(PeerEvent::Closed) | None => panic!("closed before connecting"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("connect timeout");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn media_flows_over_loopback() {
|
||||
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
|
||||
let config = PeerConfig::loopback();
|
||||
let (mut streamer, offer) = Peer::offer(&config, "test-stream").await.unwrap();
|
||||
assert!(offer.contains("VP8"), "{offer}");
|
||||
let (mut viewer, answer) = Peer::answer(&config, &offer).await.unwrap();
|
||||
streamer.accept_answer(&answer).await.unwrap();
|
||||
assert!(streamer.accept_answer(&answer).await.is_err(), "second answer must fail");
|
||||
|
||||
let (a, b) = tokio::join!(wait_connected(&mut streamer), wait_connected(&mut viewer));
|
||||
let ((), ()) = (a, b);
|
||||
|
||||
// 1.5 s of 30 fps video (large frames need several packets) and 20 ms Opus frames.
|
||||
let sender = tokio::spawn(async move {
|
||||
for i in 0..45u64 {
|
||||
let frame = fake_vp8_keyframe(i as u8, 3000);
|
||||
streamer.write(MediaKind::Video, MediaTime::from_90khz(i * 3000), frame);
|
||||
for j in 0..2u64 {
|
||||
let n = i * 2 + j;
|
||||
streamer.write(
|
||||
MediaKind::Audio,
|
||||
MediaTime::new(n * 960, tsc_stream::Frequency::FORTY_EIGHT_KHZ),
|
||||
vec![0xfc, n as u8, 1, 2, 3],
|
||||
);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(33)).await;
|
||||
}
|
||||
streamer
|
||||
});
|
||||
|
||||
let (mut video, mut audio) = (0, 0);
|
||||
let _ = timeout(Duration::from_secs(5), async {
|
||||
while let Some(event) = viewer.next_event().await {
|
||||
if let PeerEvent::Media(frame) = event {
|
||||
match frame.kind {
|
||||
MediaKind::Video => {
|
||||
assert_eq!(frame.codec, tsc_stream::Codec::Vp8);
|
||||
assert_eq!(frame.data.len(), 3010, "whole frame reassembled");
|
||||
video += 1;
|
||||
}
|
||||
MediaKind::Audio => {
|
||||
assert_eq!(frame.data[0], 0xfc);
|
||||
audio += 1;
|
||||
}
|
||||
}
|
||||
if video >= 40 && audio >= 80 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let streamer = sender.await.unwrap();
|
||||
assert!(video >= 40 && audio >= 80, "received {video} video / {audio} audio frames");
|
||||
drop(streamer);
|
||||
}
|
||||
+21
-23
@@ -48,32 +48,30 @@ the admin grants them to the guest query group.
|
||||
|
||||
## Workspace layout
|
||||
|
||||
Present today:
|
||||
|
||||
```
|
||||
crates/proto/ vendored tsclientlib (tsproto, tsproto-packets, tsproto-types,
|
||||
tsproto-structs + declarations, ts-bookkeeping, tsclientlib)
|
||||
tools/tsctl headless CLI
|
||||
dev/ docker-compose TS3 + TS6 servers
|
||||
scripts/ it-smoke.sh
|
||||
crates/proto/ vendored tsclientlib (tsproto, tsproto-packets, tsproto-types,
|
||||
tsproto-structs + declarations, ts-bookkeeping, tsclientlib)
|
||||
crates/<tsc-*> our crates (table below)
|
||||
tools/tsctl headless CLI
|
||||
dev/ docker-compose TS3 + TS6 servers, gateway configs
|
||||
scripts/ it-smoke.sh, own-crates.sh
|
||||
fuzz/ cargo-fuzz targets
|
||||
```
|
||||
|
||||
Planned crates:
|
||||
|
||||
| Crate | Responsibility |
|
||||
|---|---|
|
||||
| `tsc-model` | UI-facing domain model (servers, channels, clients, chat, capabilities), no IO |
|
||||
| `tsc-query` | ServerQuery codec and transports: raw TCP, SSH (russh), HTTP WebQuery |
|
||||
| `tsc-observer` | Presence tracker + chat relay pool over `tsc-query` |
|
||||
| `tsc-gateway-proto`, `tsc-gateway` (`tsgw`) | Companion service for server admins: identity-challenge auth, permission-mirroring authorization, presence stream, chat relay, SQLite history, WebSocket + JSON (`tsgw.v1+json`) |
|
||||
| `tsc-store` | Identities, bookmarks, settings, chat cache, secrets (keyring / Android Keystore) |
|
||||
| `tsc-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk |
|
||||
| `tsc-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs |
|
||||
| `tsc-stream` | TS6 stream signalling state machine, str0m peer connections |
|
||||
| `tsc-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API |
|
||||
| `tsc-platform` | Global hotkeys, notifications, paths, Android JNI glue |
|
||||
| `tsc-ui` | Slint UI and the desktop binary |
|
||||
| `tsc-android` + `android/` | Android library + Gradle/Kotlin app (foreground services for voice and screen capture) |
|
||||
| Crate | Responsibility | State |
|
||||
|---|---|---|
|
||||
| `tsc-model` | UI-facing domain model (servers, channels, clients, chat, capabilities), no IO | done |
|
||||
| `tsc-query` | ServerQuery codec and transports: raw TCP, SSH (russh), HTTP WebQuery | done |
|
||||
| `tsc-observer` | Presence tracker + chat relay pool over `tsc-query` | done |
|
||||
| `tsc-gateway-proto`, `tsc-gateway` (`tsgw`) | Companion service for server admins: identity-challenge auth, permission-mirroring authorization, presence stream, chat relay, SQLite history, WebSocket + JSON (`tsgw.v1+json`) | done |
|
||||
| `tsc-store` | Identities, bookmarks, settings, chat cache, secrets (keyring / Android Keystore) | done |
|
||||
| `tsc-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk | v0 (no AEC yet) |
|
||||
| `tsc-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates | signalling + transport |
|
||||
| `tsc-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, event bus, command API | done (no streams yet) |
|
||||
| `tsc-ui` | Slint UI and the desktop binary | done (no streams yet) |
|
||||
| `tsc-media` | Screen and system-audio capture backends (PipeWire portal, X11, Windows Graphics Capture, Android MediaProjection), video codecs | planned |
|
||||
| `tsc-platform` | Global hotkeys, notifications, paths | planned |
|
||||
| `tsc-android` + `android/` | Android library + Gradle/Kotlin app (foreground services for voice and screen capture) | planned |
|
||||
|
||||
## Merging sources
|
||||
|
||||
|
||||
@@ -49,8 +49,9 @@ which uses a TS3-signed client version over the legacy UDP transport):
|
||||
| C→S | `setupstream` | `name type bitrate accessibility mode viewer_limit audio` (bot defaults: `type=3 bitrate=4608 accessibility=1 mode=1 viewer_limit=0 audio=1`) |
|
||||
| C→S | `respondjoinstreamrequest` | `id clid msg offer=<SDP> decision=1\|0` |
|
||||
| C→S | `streamsignaling` | `id clid json={"cmd":…,"args":{…}}` (answer, ICE candidates `candidate`/`sdpMid`/`sdpMlineIndex`, reconnect) |
|
||||
| C→S | `stopstream` | `id`? |
|
||||
| C→S | `removeclientfromstream` | `id clid`? |
|
||||
| C→S | `joinstreamrequest` | `id clid msg is_remove` (viewer; confirmed, see below) |
|
||||
| C→S | `stopstream` | `id reason` (confirmed) |
|
||||
| C→S | `removeclientfromstream` | `id clid reason` (confirmed) |
|
||||
| S→C | `notifystreamstarted`, `notifystreamstopped`, `notifystreaminfo` | |
|
||||
| S→C | `notifyjoinstreamrequest`, `notifyrespondjoinstreamrequest` | |
|
||||
| S→C | `notifystreamsignaling` | |
|
||||
@@ -101,6 +102,35 @@ the viewer disconnects. Found by testing candidate parameter names from the
|
||||
server binary against a live stream (`is_remove` matches the
|
||||
`JoinStreamRequestEvent.is_remove` protobuf field).
|
||||
|
||||
### End-to-end stream (confirmed, 6.0.0-beta13.1, 2026-09-25)
|
||||
|
||||
`crates/tsc-stream/tests/live_ts6.rs` runs a whole stream between two of our
|
||||
clients through the server, with str0m on both ends:
|
||||
|
||||
```
|
||||
streamer -> setupstream name=live\stest type=3 bitrate=4608 accessibility=1 mode=1 viewer_limit=0 audio=1
|
||||
streamer <- notifystreamstarted clid=<s> id=<uuid> ... return_code=... (viewer gets it without return_code)
|
||||
viewer -> joinstreamrequest id=<uuid> clid=<s> msg=... is_remove=0
|
||||
streamer <- notifyjoinstreamrequest clid=<v> id=<uuid> msg=... is_remove=0
|
||||
streamer -> respondjoinstreamrequest id=<uuid> clid=<v> msg offer=<SDP offer> decision=1
|
||||
viewer <- notifyrespondjoinstreamrequest id=<uuid> ... offer=<SDP, unchanged> decision=1
|
||||
viewer -> streamsignaling id=<uuid> clid=<s> json={"cmd":"answer","args":{"answer":<SDP>}}
|
||||
streamer <- notifystreamsignaling id=<uuid> clid=<v> json=<unchanged>
|
||||
ICE + DTLS directly between the peers; VP8 video and Opus audio flow
|
||||
streamer -> removeclientfromstream id=<uuid> clid=<v> reason=5
|
||||
viewer <- notifystreamclientleft id=<uuid> clid=<v> reason=5 (streamer: + return_code)
|
||||
streamer -> stopstream id=<uuid> reason=1
|
||||
viewer <- notifystreamstopped id=<uuid>
|
||||
```
|
||||
|
||||
- `stopstream id=<uuid>` alone and `stopstream id clid` fail with
|
||||
`ParameterMissing`; `stopstream id reason` works. `removeclientfromstream id clid`
|
||||
fails the same way; it needs `reason` too. Reasons are `StreamLeaveReason` values.
|
||||
- The server passes SDP and JSON through unchanged (escaped as usual).
|
||||
- Host candidates embedded in the SDP are enough on one machine; trickled
|
||||
candidates use `{"cmd":"iceCandidate","args":{"candidate","sdpMid","sdpMLineIndex"}}`
|
||||
(the parser also accepts `sdp`/`mid`/`mLine`).
|
||||
|
||||
### Schema embedded in the server (confirmed)
|
||||
|
||||
The server binary embeds the protobuf descriptors of the new binary protocol
|
||||
@@ -141,9 +171,12 @@ permissions") has been seen; no stream permission names are documented.
|
||||
|
||||
- [x] Viewer side: `joinstreamrequest id clid msg is_remove` (see above).
|
||||
- [x] Meaning of `setupstream` `type`, `accessibility` and `mode` values (enums above).
|
||||
- [ ] Parameters of `stopstream` (more than `id`) and `removeclientfromstream`.
|
||||
- [x] Parameters of `stopstream` and `removeclientfromstream` (`reason` is required).
|
||||
- [ ] Which permission gates `setupstream` (error 2568).
|
||||
- [ ] Contents of `notifystreaminfo` and `notifystreamstarted`.
|
||||
- [x] Contents of `notifystreamstarted` (see probe results).
|
||||
- [ ] Contents of `notifystreaminfo` (`requeststreaminfo`).
|
||||
- [ ] Interop with the official TS6 client (its offer/answer details, codecs it
|
||||
actually picks, whether it trickles candidates).
|
||||
- [ ] Whether stream audio can be sent without video.
|
||||
- [ ] The WebRTC/protobuf transport some TS6 clients use on UDP 9987
|
||||
(`client_protocol_format=proto`, reported in community reverse engineering).
|
||||
|
||||
@@ -218,4 +218,7 @@ done
|
||||
log "engine (tsc-core) against both servers"
|
||||
TSC_LIVE=1 cargo test --quiet -p tsc-core --test live 2>&1 | grep -E "test result|panicked|timed out" || fail "engine tests failed"
|
||||
|
||||
log "stream (tsc-stream) through the TeamSpeak 6 server"
|
||||
TSC_LIVE=1 cargo test --quiet -p tsc-stream --test live_ts6 2>&1 | grep -E "test result|panicked|timed out" || fail "stream test failed"
|
||||
|
||||
log "all smoke tests passed"
|
||||
Reference in new issue
Block a user