Author SHA1 Message Date
faumarayandClaude Fable 5.1 37f8fe9bc1 Say what the transfer commands did before f1df886: a notice and a hanging report, not a dropped connection
The review of the merge-and-minors round read ts/voice.rs: the Input::Cmd arm
sends a command's error as LinkEvent::Error and keeps the connection, so the
old anyhow::bail! never ended the TeamSpeak session. The 17.7 row said it did.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 12:57:30 +03:00
faumarayandClaude Sonnet 5.5 d5d85b3f3d Record the round after the review of slice 3 in the design of the session seam
17.7: the merge of main (ad20979), what it conflicted on and what it needed to
compile, the four minors of the review with their commits, and what ran on the
merged tree: fmt and clippy per commit, tests on both toolchains, the lib
suite ten times in a row, cargo doc, the acceptance of section 10 (including
the rustdoc JSON walk), the notices check, and the smoke script and the live
binaries before and after. The status line follows.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 11:43:48 +03:00
faumarayandClaude Sonnet 5.5 f1df88690b Fail a transfer the TeamSpeak link is given, not its connection
ts::voice::Voice::command answered LinkCmd::Download, Upload and CancelTransfer
with anyhow::bail!, which ends the whole TeamSpeak connection: chat, voice,
presence and the stream task with it. SessionLink copies the bytes of a
transfer itself and never sends them, but a command that does arrive is that
transfer's failure, not the connection's. Download and Upload answer their
report with TransferState::Failed and the connection goes on; CancelTransfer
has no report and nothing to cancel, so it is logged at debug.

A unit test gives an unconnected Voice the three commands: each returns Ok, the
two reports see Failed, nothing is pending.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 11:00:57 +03:00
faumarayandClaude Sonnet 5.5 76a884a779 Correct the paths and statements slice 3 left stale
- docs/session-seam.md 4.1: the TsConnector owns the myTeamSpeak account since
  a451f02; it is not registered "with the engine's watches".
- docs/session-seam.md 16.1: the live tests are src/ts/ts_session/live_tests.rs.
- docs/session-seam.md section 10: the acceptance rg is given as it runs from
  the repository root (--glob '!**/ts/**'); from crates/voelin-core/src the
  first glob is '!ts/**'.
- ts/voice.rs module documentation: the type that runs it is ts_link::TsLink
  (crate::TsLink is gone).
- link/tests.rs: ts/ts_session/driver.rs.
- voelin-store (IdentityOrigin::Imported, a one-word path) and
  docs/research/ui-review.md: voelin_core::ts::identity, ts/voice.rs.
- docs/audio.md: LinkCmd::Audio and LinkEvent::Audio are in link/mod.rs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 11:00:17 +03:00
faumarayandClaude Sonnet 5.5 f0d20cc02f Document QueryLogin.transport
The one public field of QueryLogin without a doc comment.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 10:58:50 +03:00
faumarayandClaude Sonnet 5.5 87926e9b59 Refuse a TeamSpeak identity that holds no JSON
link::connect::credential sent a TeamSpeak IdentityBlob with an empty json as
an empty Credential::Foreign blob, which is what the TeamSpeak connector reads
as "make an identity up" (identity: None). An identity that holds nothing is no
identity: it is refused with SessionError::Protocol, as the Voelin branch
refuses a key that cannot be read, before any connector is asked. The comment
of ts::identity::to_blob ("a blob with no JSON is refused when it is used")
holds on both paths now: the gateway's from_blob already refused it.

Two tests: connect_params refuses "" and white space and still sends none as
the empty blob; an engine on the fake host answers ConnectVoice with the reason
and the connector is never asked and makes no session.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 10:58:34 +03:00
faumarayandClaude Sonnet 5.5 e13d401b9c Merge main (ad20979) into phase4/session-seam
Main brings the merge of phase5/ui-vm: the toolkit-free crates/voelin-ui-vm
crate and the logic/bind split of crates/voelin-ui. Conflicts, and what each
resolution keeps:

- crates/voelin-ui/src/settings_pages.rs: main deleted it (it is
  settings_pages/{mod,bind}.rs and voelin-ui-vm's settings_pages/logic.rs
  now), this branch had changed its voelin_core::identity paths. Deleted; the
  paths are voelin_core::ts::identity:: in bind.rs and in logic.rs.
- crates/voelin-ui/src/identities.rs: the module comment names
  voelin_core::ts::identity::import_new (this branch) and settings_pages/
  (main).
- docs/architecture.md: the voelin-core row of this branch with the
  voelin-ui-vm and voelin-ui rows of main.

Not conflicts, but needed to compile: voelin-ui-vm named the in-tree
voelin-model by path, which this branch moved to the protocol repository
(workspace dependency), and imported voelin_core::identity::Found, which is
voelin_core::ts::identity::Found. Cargo.lock merged without a conflict and
resolves with --locked; THIRD_PARTY_NOTICES.md is up to date
(scripts/notices.sh --check).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 10:32:05 +03:00
faumarayandClaude Sonnet 5.5 6a08147f93 Record slice 3 in the design of the session seam
Section 17: what was done, commit by commit; where the code differs from the
text of section 10 (QueryLogin.allowlisted, the ServerLink trait moved rather
than made private, Backends::register_teamspeak, files::upload deleted, the
directory the acceptance rg runs from); the API changes that phase5/ui-vm-2
has to absorb; the acceptance list; what ran against the baseline (fmt,
clippy per commit, tests on both toolchains, cargo doc, notices, the smoke
script and the live tests before and after); the follow-ups. The status line,
4.1, 4.8, 9, 11.2 (H9's two edges into src/ts) and 16.1 follow.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 08:28:14 +03:00
faumarayandClaude Sonnet 5.5 d0092e467a Describe the session seam in the architecture document
"The server link" is "The session seam": the registry, SessionLink and the
vocabulary it shares with session.rs (crate-private now), what a session asks
for in VoiceOptions, the TeamSpeak module (voelin_core::ts), StreamPort, the
tests, and what is still TeamSpeak-shaped. The crate table row of voelin-core
follows.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:27:49 +03:00
faumarayandClaude Sonnet 5.5 f63d459865 Keep the crate's documentation free of links that do not resolve
cargo doc with warnings denied failed on efacb41 and on main alike, with eight
errors (six with the media features on): the cache's module documentation
linked to private items, and the crate documentation to modules and a type
that exist only with the media features. They are plain code spans now, so
that RUSTDOCFLAGS='-D warnings' cargo doc --no-deps -p voelin-core passes,
with and without --features media-desktop.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:24:37 +03:00
faumarayandClaude Sonnet 5.5 ca34f84610 Let a query login say that its address is on the server's allowlist
The engine's own query connections used the query crate's default line
options, which keep a client-side limit of nine commands in three seconds. The
live tests passed voelin_query::Connect with that limit off, because the
development servers allowlist their clients, and with the limit on the
channel relay of ts3_engine and ts6_engine did not connect within the two
seconds the test waits before it speaks. QueryLogin gets the one bit the
tests had: allowlisted, off for the application (which cannot know), on for
the tests, and the UI's login says false, as it always effectively did.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:23:46 +03:00
faumarayandClaude Sonnet 5.5 d70a3582f2 Take the transfers the engine does itself out of the TeamSpeak connection
voice.rs handled Download, Upload and CancelTransfer with a copying task per
transfer, a progress cadence, the picture limits and a cancel table; none of
it is reachable since SessionLink copies the bytes itself over the
connections OpenRead and OpenWrite open (the picture limits and the
negotiation deadline live there, tested in link/tests.rs). The connection
keeps the two connection jobs and refuses the three commands in words;
files::upload and its close wait go with it (SessionLink uses upload_to, and
the TCP test of the upload runs through that), and the test of the picture
download time moves to the cache, which owns the function.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:07:52 +03:00
faumarayandClaude Sonnet 5.5 1edc52ce74 Make the engine's link vocabulary private and the options neutral
VoiceOptions is a struct of its own, no longer an alias of the TeamSpeak
link's options: identity is an IdentityBlob and client_version a spec for
ts::versions::resolve, which rides the address as the link parameter
client_version and which the TeamSpeak connector resolves (a spec it refuses
fails the connect in words). SessionLink builds the connect parameters
(link/connect.rs: the bookmark's link, the hello, the credential of the
identity's kind, now also a Voelin key's signer) and session.rs holds it
directly: the ServerLink trait between them was redundant. The trait lives
on in the TeamSpeak module (ts/ts_link.rs, with the TeamSpeak-typed
ConnectOptions) for TsLink and the in-memory link of the tests.

ServerLink, TsLink, LinkCtx, LinkCmd, LinkEvent and Remote are crate-private,
Engine::start_with_link is gone, and the three tests that needed the inner
link (tests/link_fake.rs) are unit tests of link/ now. The rg over the crate
for tsclientlib, tsproto and voelin_query, outside ts/ and the three files
that use them privately (gateway.rs, query.rs, stream.rs), is empty. The UI
and voelinctl get compile fixes: the identity blob and the spec string.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:59:44 +03:00
faumarayandClaude Sonnet 5.5 be84874a09 Take the gateway's identity as a blob and the query login as the engine's own type
Command::ObserveGateway.identity is a Box<IdentityBlob> (a TeamSpeak
identity as the key store keeps it; voelin_core::ts::identity::to_blob and
from_blob convert) and gateway::connect takes the blob too; gateway.rs reads
it itself, and one it cannot read ends the observation with its reason
instead of reaching the gateway. Command::ObserveQuery.connect is a
QueryLogin (transport, address, user, secret, server port and id) that
query.rs turns into voelin_query::Connect with the query crate's own line
options, which is what the UI always passed. voelin_core re-exports
IdentityBlob; voelin-identity is a dependency of voelin-core now, so
Cargo.lock gains that edge (the crate was in the graph already, and no
third-party package is added: THIRD_PARTY_NOTICES.md is unchanged).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:29:50 +03:00
faumarayandClaude Sonnet 5.5 a451f027f3 Give the myTeamSpeak account to the TeamSpeak connector, not to the engine
Command::SetMytsIdentity and SetMytsData are gone (nothing sent them): the
account's proof and what servers are shown of it belong to TeamSpeak, and the
engine only forwarded two watch channels through every session to the link's
context. TsConnector is public now, with set_myts_identity and set_myts_data;
it owns the senders (shared by its clones through its TsLink) and each
connection holds them for as long as it runs, so a session outlives its
connector as it outlived the engine's loop. Backends::register_teamspeak
takes a connector whose clone the application keeps, and Backends::default
registers one of its own. LinkCtx, LocalCtx, SessionHandle and Session lose
the watches, and the test of the standalone context's senders is a test of
the account's: a connection keeps it open.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:17:16 +03:00
faumarayandClaude Sonnet 5.5 029b8464b7 Move the TeamSpeak implementation into src/ts
ts_link.rs, voice.rs, book.rs, ts_session/, versions.rs and identity.rs move
under crates/voelin-core/src/ts (git mv, so git log --follow keeps their
history). voelin_core::versions and voelin_core::identity are
voelin_core::ts::versions and voelin_core::ts::identity now; the UI and
voelinctl follow with the new paths. Nothing else changes: the module
declarations, the use paths and the path of Versions.csv are the only
edits to the moved files.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:08:10 +03:00
faumarayandClaude Sonnet 5.5 362e2b9da1 Assert the unique ids and the server's uid in the presence test
presence_follows_the_host_until_it_ends showed the clients' names and
channels but not what the engine keys contacts and private history by: the
unique id of each client (the base32 of a Voelin user's 32 bytes) and the
server's unique id in ServerDetails.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 05:58:27 +03:00
faumarayandClaude Sonnet 5.5 b92379d01b Name the replaced session and the refused stream in tests of their own
The tail of a_reconnect_finds_the_state_the_first_session_left (a connect
while connected replaces the session) and the end of
commands_reach_the_host_as_requests (a host without streams is not asked
for one) are tests of their own now, so that each name says what is
checked.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 05:56:28 +03:00
faumarayandClaude Sonnet 5.5 dd9140e1ea Check that the conformance suite is known before the cases that do not apply run
cases_that_do_not_apply_fail zips the suite's cases with EXPECTED, so a case
the protocol repository adds would have been left out without a word. It
calls the_suite_is_known first, as the conformance subset does.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 05:55:52 +03:00
faumarayandClaude Sonnet 5.5 efacb41894 Correct the record of a reconnect's replay and of the live module's prerequisite
Section 16 of the design said that after a reconnect to a v1 host the
display is right and only the store is wrong, because Dedup drops the copy
of the event. That holds only for the messages within 4 s of the newest one
seen: Dedup evicts what is older than that relative to the incoming
message, so a replayed older message is shown again as a live Event::Chat
and stored again. Corrected in 4.4, 16.1, 16.4 and F3 (16.5), with the two
ignored tests that pin the display and the store, and in P17 and H10: only
the CHAT-cursor resume cures both, and only within an epoch.

Also: the introduction of section 16 names the two production changes (F1,
F2), not three; the move-back test now sends two messages 10 s apart and
the record says what the single-message version did not prove; the live
module raises the anti-flood limits itself and the record says so and what
ran (a fresh stack before and after, in series and in parallel, and the
smoke script before and after on freshly reset stacks); the toolchains of
the review round, the nightly that replaced 2026-10-19, and the per-commit
checks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 04:54:16 +03:00
faumarayandClaude Sonnet 5.5 9283191e58 Raise the anti-flood limits of the development servers from the live module
On a freshly started stack the live module failed 8 tests of 12 with
ConnectFailedBanned: a server with its default anti-flood limits bans the
address that connects as often as these tests do, after three or four
connections. scripts/it-smoke.sh sets the limits when it prepares its admin
identity, so the module passed only after the smoke script had run.

The module now raises virtualserver_antiflood_points_needed_ip_block and
..._command_block itself before its first connection, once per server and
run, through the ServerQuery admin login that refused_moves uses, and clears
the bans of an earlier run with bandelall (banclear is not a command of
either server). The command of the module header works on a fresh stack.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 04:13:13 +03:00
faumarayandClaude Sonnet 5.5 81d1de86e1 Show in the tests that a reconnect's replay is shown again, and what the passing ones prove
a_reconnect_finds_the_state_the_first_session_left passed for a narrower
reason than its comment said: the one message seen before the disconnect is
the newest one, so Dedup (which holds the messages up to 4 s older than the
last one it was asked about) still held it and dropped the host's replay.
With two messages more than 4 s apart the replay of the older one reaches the
user as a live Event::Chat, and no test saw it: the ignored test of the
stored rows used the same one-message setup.

- The ignored replay test is now two, over one scenario: two messages 10 s
  apart are seen, the session ends, a third is said while we are away, a
  second session connects. One asserts that only "while away" is shown (it
  sees ["first", "while away"]), the other that the history has each message
  once (it sees every row twice). The comments of the passing reconnect test
  say what it proves: a message inside Dedup's window is not shown again.
- the_chat_of_a_channel_is_resubscribed_when_we_move_back passed without the
  `seen` check of SessionLink for the same reason (the message seen before is
  the newest one Dedup holds). It now sees two messages 10 s apart before it
  moves away and fails with the check disabled ("before" comes again).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 04:13:13 +03:00
faumarayandClaude Sonnet 5.5 2089f7ceba Record slice 2 in the design of the session seam
Section 16: what the tests on the fake host and the TeamSpeak sessions
cover, the verdict of every case of the conformance suite on both
development servers with the reason it was observed to fail or be skipped,
where the code differs from 9.2 and 9.3 (the CHAT re-subscription is a full
sync, a reconnect resumes nothing, the conformance and live tests are
in-crate), the three things the tests found (our own voice played back, a
session made outside an engine ending by itself, a v1 host's replay stored
twice after a reconnect, the last one open), the protocol and second-half
follow-ups, the deliberately broken translation, and what ran.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 02:29:40 +03:00
faumarayandClaude Sonnet 5.5 226933fcdc Run the link conformance subset and the session scenarios on both TeamSpeak servers
ts_session/live_tests.rs (VOELIN_LIVE=1, the development servers) holds the
TeamSpeak Session tests of docs/session-seam.md section 9.3, made through
TsConnector's plain Connector interface:

- the conformance suite of the protocol repository, every case listed with
  what a TeamSpeak session does with it: two pass (welcome_matches_features,
  close_ends_the_session), four are skipped for a feature the session lacks
  (chat.edit, chat chat.history, idempotency), and the rest do not apply;
  a case the suite gains fails until it is listed;
- what the suite cannot reach: an own-channel message answered and pushed to
  the other session and back, the PASSWORD and FULL refusals of a move, a
  poke between two sessions, voice RTP from one slot to the other session's
  media sink (marker, order, an empty payload at the end), and a channel file
  written with write_file and read back from an offset with read_file.

Two tests, ignored by default, run the cases that do not apply and watch each
fail; the reason in the table is what the case did when it was run.

scripts/it-smoke.sh runs the module before its engine stage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 02:02:39 +03:00
faumarayandClaude Sonnet 5.5 659798e5f9 Keep the account watches of a session made outside an engine open
A TeamSpeak session made through the plain Connector interface (the way the
conformance suite and any client of the seam that is no engine make one) got
a LocalCtx::standalone() whose only job is to hold the senders of the
myTeamSpeak watches. connect_link dropped that context when it returned, the
senders went with it, and the TeamSpeak link ends its connection with
"account source closed" when a watch has no sender: the session died by
itself a moment after it was handed out. The engine's own path was never
affected, its watches belong to the engine.

The context now moves into the driver task and lives as long as the session.

Found by running the link conformance suite against the development servers:
close_ends_the_session passed vacuously and the_backend_can_end_the_session
saw the session end with that text. The new test fails without this change
("the identity watch lost its sender").

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 02:02:07 +03:00
faumarayandClaude Sonnet 5.5 8d07502e1e Drop the media that comes back on our own slot
A session that loops our voice back (the fake host of the protocol
repository does, so that a test sees media move) made the engine hand our
own packets to the audio thread and show us as talking: the slot map holds
every participant of the server, ourselves included. The engine never plays
itself from the network (a sidetone is local), so on_media returns for the
packets of the slot the host gave us. TeamSpeak never sends a client its own
voice, so nothing changes for the servers the engine reaches today.

Found by the fake-host tests; the test failed before this change with
[1, 50] as the talkers heard (us, then alice).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 01:16:51 +03:00
faumarayandClaude Sonnet 5.5 82da64d8d3 Test the voice path and the conformance suite on the fake host
link/fake_tests.rs holds the tests that need what is private to the crate:

- our voice leaves as RTP on the slot the host gave us (sequence, marker on
  the first packet of a spurt, timestamps that advance by the previous
  packet's duration, an end of spurt that is an empty payload sent once, the
  SSRC that is the flow), read from FakeHandle::sent_media;
- the voice of other slots reaches the audio thread: the talker of the slot,
  a whisper sub-flow, stereo Opus as music, the end of a spurt, and what is
  no voice of a known slot (an unknown slot, probes, feedback) dropped;
- the link conformance suite of the protocol repository, 17 cases, run
  against the session Backends::connect hands over: all pass, none skipped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 01:16:23 +03:00
faumarayandClaude Sonnet 5.5 f9d3f86896 Test the engine on the protocol repository's fake host
tests/session_fake.rs runs the engine through Engine::start_with_backends
with a FakeConnector registered, so a session of the engine is a
voelin_proto::link::Session that no TeamSpeak code made. The host is a
FakeHost filled through put; FakeHandle plays the backend of one session.

The scenarios of link_fake.rs move over (presence until the host ends the
session, commands as v1 requests, a sent message and its echo, the dedup of
a message that comes twice, history across the session), and the ones the
v1 path needs are new: how a session ends and the text the user reads, what
a host refuses and the words it says it in, the chat of a channel
subscribed again when we move back (in full: there is no cursor), closed
scopes, a HostUpdate that changes what the engine asks for, offline messages
as Mail, files through read_file and write_file with a resumed upload, file
operations as FileEntry puts and deletes, the media of a session routed to
the talker of its slot, a reconnect that finds the state the first session
left, and a connect that fails.

link_fake.rs keeps the three tests that need the inner link: the stream
commands (they travel on a port a Session has no part in), the order in
which a reconnect shuts the streams and the old connection down, and a link
that keeps talking after its connection was replaced.

One test is ignored with its reason: a v1 host sends the window of a chat
scope again after a reconnect, and the engine stores the copy (the history
merges copies of different sources only). TeamSpeak never replays, so no
host the engine reaches today meets it; docs/session-seam.md will say so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 01:15:34 +03:00
faumarayandClaude Sonnet 5.5 bfc52e2688 Record the third review round in the design of the session seam
Section 15 lists the seven findings with their fix and test, what the fixes
leave as it was (the move shortcut and the window it keeps), and what ran:
format, clippy, tests and the workspace check on 1.94 and nightly, and the
smoke and live runs against fresh dev servers. The other sections say what
changed: the media and push channels have no order between them (4.2 step 9,
13), the second changed test (5.4), the move rule and the transfer deadline
(3.1), the nameless sender (5.2), the address rules (4.2) and the narrowed
features (4.7).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 23:21:07 +03:00
faumarayandClaude Sonnet 5.5 5df011f08c Count only the refusals that come after the host's update in the features test
The last wait of the test asked for file lists until one was refused locally and
took the first refusal on the bus. The asks made before the HostUpdate reached
SessionLink are refused too while the server's list stands, and their events can
still be unread on the bus, so the wait could end before the update had been
applied. It accepts a refusal of a request made after the update only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:45:38 +03:00
faumarayandClaude Sonnet 5.5 2bee828022 Refuse the bookmark addresses that a ts3server:// link would change
The engine hands the TeamSpeak side its bookmark as a ts3server:// link and
reads the options back from it. A link cannot say all an address can: a port
that is no u16 (host:99999) was dropped silently and the connection went to the
default port; a bare host with a '?' in it ended there and hid the channel
behind the next '?' that to_url writes; a '/' or '#' ended the host and a '%'
was decoded. The TeamSpeak library had refused every one of those when it
resolved the address.

connect_params returns a Result now. A bookmark whose port is not a number from
1 to 65535 (in host:port and [v6]:port), or whose host is empty, holds a '?',
'#', '/' or '%', white space or a control character, or has an unclosed '[',
fails the connect with a reason that shows the address without its query. The
other normalisations of the round trip (blanks cut, [v6] without a port read
as v6, an empty option is none, the model's rules for an address that is a
link) are listed in docs/session-seam.md.

Tests: the refused and the accepted addresses (the channel survives the round
trip of each accepted one), the empty options, and a connect with a bad port
that ends in Disconnected with the reason before any link is asked.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:30:03 +03:00
faumarayandClaude Sonnet 5.5 b8db1a85f0 Narrow the features of a session by the server's list
docs/session-seam.md 4.7 says features() is narrowed by Server.features, and
Features::narrowed exists for it, but SessionLink took Session::features() as
it was and a HostUpdate replaced the set wholesale. Against a host whose
server offers fewer features, Capabilities and the local Features::require
refusals were too generous.

SessionLink keeps the host's set and the set of the server (the host's,
narrowed by the Server entity's list; an empty list keeps all of them), and
recomputes the second when the SERVER scope changes or syncs and after a
HostUpdate. Capabilities, the local refusals and the presence fix-ups use it.

Test (over the protocol repository's fake host): a server that lists no files
leaves file transfer out of the capabilities and refuses a file list without
asking the host; an empty list brings it back; a HostUpdate that drops files
takes it away again. It fails on the code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:29:36 +03:00
faumarayandClaude Sonnet 5.5 6a2f00a636 Name a poke from a sender with no unique id who is not on the snapshot
Driver::sender made a synthetic user id for such a sender ("client:N") but put
no User entity into LIVE, so SessionLink::signal found no User and the nick of
the poke was empty. The earlier fix covered senders that have a unique id only.

The driver now puts a bare User with the name the link gave and no uid into
LIVE, keyed by the synthetic client id, before it pushes the signal (so it
shows in no presence, and the poke's from_uid stays none). A client id is given
again to whoever connects next, so the user is replaced when the same client
id comes back with another name; a sender with an empty name gets none.

Test: a poke from client 77 with no unique id is named, and named again with
the new name when the client id comes back as somebody else. It fails on the
code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:29:08 +03:00
faumarayandClaude Sonnet 5.5 b0b1c82ddc Leave the deadline of a transfer's negotiation to the caller
LinkSession gave the reply to an OpenRead or OpenWrite 30 seconds, for every
transfer. Only pictures had a deadline before the seam (IMAGE_NEGOTIATION,
which SessionLink still applies to them); a file the user asked for waited for
a slow server as long as it took. With the extra deadline such a transfer
failed with "timed out", and the inner job stayed in voice.rs until the server
opened it, found nobody to hand the connection to, and dropped it.

The driver waits without a deadline now. A caller that drops the call (the
picture's deadline, a cancel) is noticed through the closed reply channel, and
the driver's wait ends, dropping the receiver that the inner job holds.

Test (virtual time): a read and a write wait 120 seconds for the server and
then open; a read that is dropped closes the reply of the inner job. It fails
on the code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:28:32 +03:00
faumarayandClaude Sonnet 5.5 96dece42e6 Send a move to the link while another move of ours is on its way
Driver::join answered a JoinVoice with the own voice state and sent no Move
whenever the snapshot showed us in the requested channel. A move to another
channel that the link had not answered yet left the snapshot where it was, so
a second request back into the old channel was dropped without an error and
the user ended up in the channel of the first move. The baseline forwarded
every Move to the link (which swallows "already in that channel" itself).

A move into the channel the snapshots show is answered at once only while no
move of ours is pending; otherwise it goes to the link in order. The link says
nothing to a move into the channel it is in, so a refusal of the first move
now also answers the pending moves into the channel the snapshots show,
instead of leaving the second to its ten seconds.

Tests: a move made while another is on its way reaches the link and both are
answered by their snapshots (and a move into the channel we are in is still
answered without the link when none is pending); a move back after a refused
move is answered at once. Both fail on the code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:28:07 +03:00
faumarayandClaude Sonnet 5.5 e06ed43b07 Bind the count in the subscription wait so both rustfmt versions format it alike
Nightly rustfmt wanted `.count()` and `== 3` on separate lines in the wait for
the three subscriptions of a_session_that_ends_during_the_connect_syncs_says_why,
1.94 (which CI pins) did not. The count is a local now, and the comparison a
line of its own. Nightly rustfmt differs from the baseline's six diffs only
(history.rs, encoder.rs, discovery.rs, chat.rs, studio.rs, engine.rs) after it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:26:44 +03:00
faumarayandClaude Sonnet 5.5 6b2b792926 Do not let the fake-link presence test depend on the order of media and pushes
presence_follows_the_link_until_it_disconnects played a voice packet, a poke
and an error in one go and waited for Talking, the poke and the error in that
order. Talking comes from the media queue and the poke and the error from the
push channel, and the loop of SessionLink cannot order two channels: when the
push was polled first the engine reported Poke, Error, Talking, the wait for
Talking skipped the first two and the next wait timed out. It failed in 22 of
300 isolated runs (the baseline never did).

The test now plays the voice packet, waits for Talking, and only then plays the
poke and the error. The design records the change (it is a change of the order
of the steps, not of an assertion).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:26:28 +03:00
faumarayandClaude Sonnet 5.5 b5ea0c3e95 Send a scope that is bigger than the push channel in bigger chunks
A sync is sent whole or not at all, so that a scope is never left half sent;
that needs the channel to have room for every frame of it. A scope with more
frames than the channel holds when it is empty (more than 16 frames of 256
entities on the smallest channel) could never be sent and stayed lagged for
ever. The chunks of such a sync are now as big as the channel needs, so every
sync fits an empty channel. A test syncs a SERVER scope of 5,000 channels over
the smallest channel.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:53:26 +03:00
faumarayandClaude Sonnet 5.5 88f58ea468 Record the review round in the design of the session seam
Sections 3, 4.1 to 4.4 and 13 say what changed (notify, the talking hint, the
address text, the close reason of a connect, the chat scope limit and the SyncEnd
of a CHAT scope, the seat across tsclientlib's reconnect), the risk table has the
lagging consumer, and section 14 lists the eight findings with their fix and
test. Follow-ups P13 (a speaking hint for the own channel) and P14 (what a
backend that reconnects inside a session tells its consumer) are for the
protocol repository.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:34:17 +03:00
faumarayandClaude Sonnet 5.5 038f3841df Test the review's fixes through both adapters
Each test fails on the code before the two previous commits (checked against
2d71903 with these tests applied: eleven failures):

- the connection across TeamSpeak's own reconnect: the engine follows a new
  client id (OwnChannel, the chat of the channel, what we say, the voice slot,
  the flags), and stays the client it was while a ghost lingers;
- private messages from 24 peers all arrive;
- a talker the link hears but does not forward as Opus is shown as talking;
- notify refuses what has a stream of its own and runs the rest;
- a session that ends while the connect waits for the syncs says why (a fake
  host that answers the subscriptions and is killed with a reason);
- the text of an address nobody serves keeps the channel password out;
- a consumer that does not read the pushes does not stall the voice, and gets
  the scope again whole when it reads.

The rig can connect as a TeamSpeak 3 server, which is what makes the engine
follow its seat.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:34:17 +03:00
faumarayandClaude Sonnet 5.5 09a0ef3ad5 Make the engine side of the seam report every chat message, follow our seat and believe the host
The review found four defects in SessionLink and the link module, fixed here:

- A message of a CHAT scope's first full sync could be lost. The replica stages
  a full sync until its SyncEnd, so a message of a Change of the sync cannot be
  read when the Change is applied, and SyncBegin, Change and SyncEnd may come
  in different batches; but (channel, id) was marked as reported before the
  replica was asked for the message. A message is marked as reported only when
  it was shown now, and at the SyncEnd of a CHAT scope the messages of that
  channel not shown yet are (two deterministic unit tests, one with SyncEnd in
  a later batch and one for a message that comes before its scope).
- When the push channel ended during the connect syncs, the real close reason
  of the session was thrown away and the engine showed a silent disconnect. It
  now asks closed() (and closes a session that has not ended: a refusal with no
  words).
- The CHAT scopes were limited to 16 whatever the host said. The limit is now
  Welcome.limits.max_chat_subscriptions (0 or none: the v1.0 default of 16); the
  server chat and our channel come first, then the private conversations, the
  newest (highest id) first.
- The own participant was pinned to the one of the connect. Behind a TeamSpeak
  host the seat now follows our user: it stays while the participant is ours
  and moves to the participant that carries our user id when the seat is gone
  (tsclientlib's reconnect makes us another client) or no longer carries it (a
  ghost of the old connection); a seat whose user id changed by itself is
  followed. OwnChannel, the voice flags, the uplink slot and the chat scope of
  our channel follow.

A Signal{speaking} of the host is believed (TalkTracker::hint) until the host
says it is over: that is how a talker whose packets are no Opus is shown as
talking. The documentation of LinkEvent::Talking, OwnChannel and
Connected.own_client says what the adapter derives and what it does not.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:34:00 +03:00
faumarayandClaude Sonnet 5.5 4ddfdef04f Make the TeamSpeak session keep up with a lagging consumer, a reconnect and the contract
The task behind LinkSession (ts_session/driver.rs) is where the review found
five defects, all fixed here:

- It awaited pushes.send() on the bounded push channel, so a consumer that
  lagged stalled the voice media and the commands that share the task. It now
  never waits: a push that finds the channel full is dropped, its scope is
  marked as lagged and sent again whole (SyncBegin .. SyncEnd, all frames or
  none) once the channel has room, as ConnectParams.push_capacity documents; a
  signal has no scope and is dropped. The functions that only awaited the push
  are plain functions now.
- The own client id was the one of the connect for the whole connection, so
  after tsclientlib's own reconnect (a new client id, the same unique id) the
  own channel, the poke target, the own VoiceState, the author of our messages
  and the slot send_media checks were all the old client's. The task now follows
  the snapshots: it stays the client it was while that client is there, and
  else is the newest client of its unique id; the own client keeps the database
  id when an identity is there twice (entities::build), so the user stays the
  same; LinkSession.send_media reads the slot from a shared atomic.
- CHAT subscriptions were limited to 16 in process, so private messages from
  the 15th peer of a connection were never delivered. The limit is 65,536
  (Welcome.limits says so, and the total of subscriptions follows).
- notify accepted List, FileRead and FileWrite and ignored them. Only an op of
  the control stream goes without an answer now (a misplaced op is a Protocol
  error, as on FakeSession); our mute flags go to the link, and any other op is
  run as the request it is. A notify on a session that has closed is refused
  also while the task is still on its way out.
- The link's own Talking was dropped, so a talker whose packets TsLink does not
  forward as Opus (Speex, CELT) was no longer shown as talking. It goes on as a
  Signal{speaking} hint.

The assertion of the Welcome test on the limit follows. The engine side of the
reconnect, the limit and the hint is the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:33:17 +03:00
faumarayandClaude Sonnet 5.5 080d8873bb Keep the channel password out of the text of an address no connector serves
Backends::connect handed an address that no plain connector serves to
Connectors::connect, whose error names the whole address: "no connector for
ts3server://host?port=9987&channelpassword=...". The text is shown to the user
and may be logged, and a TeamSpeak link carries the channel password (and a
voelin:// link a host pin) in its query and fragment.

The registry now looks the connector up itself and cuts the address at ? and #
in the text (without_query, which the "not a TeamSpeak server address" error of
the TeamSpeak side uses too, so that one also loses a pin).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:32:19 +03:00
faumarayandClaude Fable 5.1 ad2097963e Merge phase5/ui-vm: the toolkit-free voelin-ui-vm crate (plan section 6 step 2)
CI / Linux checks (push) Failing after 1m7s
Shared view-model types (ImageSource, Rgb, list diffing), the view models,
the BBCode reader and the Twemoji archive, SessionView/Tab/Msg and the App
state moved out of the Slint crate into voelin-ui-vm; the Slint crate keeps
adapters and bindings (studio and settings split into logic and bind).
Opus gate accepted with five minors left as follow-ups (server_tint falls
back to black, ImageSource::size reads headers only, convert::image does
not check the RGBA length, docs/ui.md metric wording, field docs on the
mirrored bridge structs).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 02:16:48 +03:00
faumarayandClaude Sonnet 5.5 2d71903e8f Write two loops of the seam as newer clippy wants them
A nightly clippy (1.101) flags two places of the session seam that the pinned
1.94 does not: the sibling placement of ts_session/entities.rs is a while let
loop, and the generated channel tree of the presence round trip in book.rs
counts with its loop variable. Neither changes behaviour (the same random
stream, the same ids).

The remaining nightly findings are in code this branch does not touch:
audio.rs and media.rs of voelin-core (chunks_exact), voice.rs (a large Err
variant), voelin-audio, voelin-media and voelin-ui.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 02:13:19 +03:00
faumarayandClaude Sonnet 5.5 9bec557c81 Record the second smoke and live runs in the design
The first run of the adapter's smoke failed the stream directory scenario (the
fix is the previous commit); the second ran every per-server scenario of
scripts/it-smoke.sh on TeamSpeak 3 and 6 to the end, and the serial live tests
of voelin-core passed again (live 6, media_live 2, stream_live 3,
voice_features 3). The script's last stage fails as it does on the baseline
(ts6_banners, when the live tests run in parallel).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 01:48:13 +03:00
faumarayandClaude Sonnet 5.5 8c62030e5b Hold the stream task's reports until the engine has announced the connection
The first smoke run of the adapter failed its stream directory scenario (the
late viewer's WatchStream was refused with "not connected with voice"), and an
alternating probe of that scenario with the baseline binary and this one on the
TeamSpeak 6 dev server failed 3 of 6 for this branch and none of the baseline's
four runs the server's clone limit left alone.

The cause is an ordering the adapter lost. The TeamSpeak 6 stream task puts
Event::StreamsChanged on the engine's bus itself; behind a session the engine
hears of the connection only after the connect sequence (several requests
through the driver), while the stream task lists the server's streams as soon as
the server tells it, so a client that acts on the first list asked for a watch
before the engine knew it had voice.

The ts_session driver now holds the bus events of a link with streams that are
no answer to a request until the engine's first stream command (session.rs
sends one in its handling of Connected right after emitting the state), or for
three seconds. Three unit tests pin the hold, its end, and that a link without
streams is not held. The same probe passes 8 of 8; docs/session-seam.md section
13 records it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 01:41:14 +03:00
faumarayandClaude Sonnet 5.5 bc9ccbc85e Measure the voice path through both adapters; test the engine on a registered connector
- A unit test frames 5,000 Opus packets each way through SessionLink, the
  TeamSpeak session and the recording link and prints the cost per packet
  (about 7 microseconds to the host, 10 from it in a debug build; the test
  bounds each direction at 500 microseconds). docs/session-seam.md section 13
  records the figures, which were the one thing slice 1 had not measured.
- tests/session_backends.rs: the engine over voelin-proto's FakeConnector
  through Engine::start_with_backends (connect, server name and backend,
  channels, a move, disconnect), and the registry's error text for an address
  no connector serves.
- The error of a TeamSpeak connector given an address that is not a TeamSpeak
  one no longer prints the query, where a channel password rides.
- The note on the two library tests that need the name localhost to resolve to
  127.0.0.1 says so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 00:41:04 +03:00
faumarayandClaude Sonnet 5.5 1b7abdf4c7 Record slice 1 in the design; consume a host that is no TeamSpeak one
- docs/session-seam.md: the status line, and section 13 with how the code
  differs from the design, a follow-up for the protocol repository (P12), and
  what ran against the baseline.
- docs/architecture.md and the crate docs describe the engine on the Session.
- A departed client's talk state is dropped before the new snapshot replaces
  the table it is looked up in.
- The backend of a host that names none is its product and version.
- A unit test drives the engine over the protocol repository's FakeSession
  through the registry: connect, presence, a move, chat in the channel,
  disconnect.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 22:25:56 +03:00
faumarayandClaude Sonnet 5.5 c473ab216e Run the engine on voelin_proto::link::Session
The engine's voice source is now a voelin_proto::link::Session obtained from a
registry of connectors (docs/session-seam.md, slice 1):

- link::Backends keeps the plain connectors of voelin_proto::link::Connectors
  and the in-process ones that also hand the engine a port for TeamSpeak 6
  streams; the scheme of the address picks the connector, an address without
  one is a TeamSpeak bookmark.
- link::SessionLink is the engine's ServerLink. session.rs is unchanged and
  still speaks LinkCmd and LinkEvent; SessionLink runs the connect sequence
  (List the server, subscribe HOME, SERVER and LIVE, take the seat), keeps a
  voelin_model::replica::Replica, projects it into the client's older model
  (link/project.rs, the fix-ups F1 to F10), frames voice as RTP and derives
  who talks from the media (link/media.rs), and turns every command into the
  Session call of its row. Transfers copy through read_file and write_file.
- ts_session makes a TeamSpeak connection a Session: LinkSession over any
  ServerLink translates the link's commands, events and presence snapshots to
  v1 entities, pushes, answers and RTP; TsConnector makes them for
  ts3server:// and teamspeak:// addresses with TsLink inside, and
  LinkConnector for the link of Engine::start_with_link.
- voice.rs opens the transfer connection itself for the new OpenRead and
  OpenWrite commands; files::download and upload are generic over the stream.
- Engine::start_with_backends is new; start_with and start_with_link go
  through the registry.

tests/link_fake.rs runs through both adapters; its fixtures are normalised as
the design says (an order chain, database ids, talking from media, the server
named, channel chat for the channel we are in), and the request id the link
sees is the session's own. New unit tests cover every row of the mapping with a
recording link, the TeamSpeak session on its own, media framing both ways, the
talk tracker, the close table, the error texts, the backend and capability
tables, the connect parameters, and the presence round trip on book fixtures
and generated presences.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 22:13:07 +03:00
faumarayandClaude Sonnet 5.5 fb8e6b63dd Take voelin-model from VoelinProtocol and add voelin-proto
voelin-identity, voelin-proto and voelin-model now come from one revision of
the protocol repository (main c8e0e5a: the session seam voelin_proto::link
with its account types, and the replica in voelin-model). The client's own
crates/voelin-model is removed: the protocol's crate is a superset, identical
in presence, server, chat and percent, and differs in badges.rs, link.rs and
tree.rs only by a doc comment and two equivalent expressions, and adds the
perms and replica modules. Every crate that used it takes
voelin-model.workspace = true. voelin-core depends on voelin-proto (and, in
its dev-dependencies, on the test-util fakes), which the engine will consume
in the next commits.

Manifests, the lock file and docs only: no source change. THIRD_PARTY_NOTICES.md
is unchanged (scripts/notices.sh --check: up to date).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 21:26:06 +03:00
faumarayandClaude Opus 5.5 38473b761d Design the engine on voelin_proto::link::Session (docs/session-seam.md)
The first half of plan step 7: every LinkCmd, LinkEvent and StreamCmd
variant mapped to the Session API and back, with the decision for what v1
cannot carry yet (streams on a local port, TeamSpeak-only connect options
on the ts3server:// link, presence fix-ups F1-F10 through Foreign);
SessionLink over a Backends registry on the engine side, LinkSession over
TsLink on the TeamSpeak side; connect, close, error texts, Features and
LinkStats; RTP framing of voice against voelin-audio's packets; credentials
with the account left as a hook; files through read_file and write_file;
the FakeLink tests through the adapter, then on FakeSession and FakeHost,
and which conformance cases the TeamSpeak session can run; three slices
with acceptance, and the follow-ups for the protocol repository and for
the move to VoelinGateWay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:47:14 +03:00
faumarayandClaude Sonnet 5.5 5d66be43d4 Document the public functions, constants and types of voelin-ui-vm that had no docs
The items moved from a private module of voelin-ui, where they needed none;
as public API of the new crate they get a line each. The fields of the bridge
structs, which mirror bridge.slint field by field (module docs), and a few
self-describing fields and variants are left as they are.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 20:40:51 +03:00
faumarayandClaude Sonnet 5.5 668c1a8038 Give the bridge struct counts as they are in docs/ui.md
The text said 49 (the plan's figure); bridge.rs has 51 and studio_bridge.rs
10, and MytsBadge and MytsForm stay in Slint.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 20:37:49 +03:00
faumarayandClaude Sonnet 5.5 0447e6bc92 Say in the notices that the Twemoji archive lives in voelin-ui-vm
The asset list in about-assets.md (and the copy appended to
THIRD_PARTY_NOTICES.md) put all bundled assets in crates/voelin-ui; the
archive moved with the emoji reader. Cargo.lock only gained the own crate,
so no third-party entry changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 20:34:18 +03:00
faumarayandClaude Sonnet 5.5 2b113479ec Point the Slint files' header comments at voelin-ui-vm
bridge.slint and studio-bridge.slint still named src/vm/ and src/studio.rs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 19:55:19 +03:00
faumarayandClaude Sonnet 5.5 a4aa58f7be Count the sample chat's ids with zip instead of a loop counter
Newer clippy (nightly) reports explicit_counter_loop for the sample
messages' id in dev.rs, which failed `cargo clippy -D warnings` on nightly
for voelin-ui. Same ids, 1 upwards.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 19:46:50 +03:00
faumarayandClaude Sonnet 5.5 767a9dad46 Document the two UI crates, the adapter boundary and the controllers still to split
docs/ui.md: the structure of voelin-ui-vm and voelin-ui, a "Two crates"
section (values, lists, conversion, state, logic/bind) and the written list
of the controllers that still interleave logic with Bridge writes, with
their .set_ counts, for the next round; the pointers to the moved files
(Twemoji archive, BBCode reader, settings pages, studio) are corrected.
docs/architecture.md: the crate table has voelin-ui-vm. README.md and
CHANGELOG.md name the new crate. Module comments that pointed at studio.rs
and vm/ point at studio/ and the crate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 16:06:29 +03:00
faumarayandClaude Sonnet 5.5 ce0e6e1f62 Split the Stream Studio: logic into voelin-ui-vm, the windows and the engine in bind.rs
studio.rs (62 Bridge writes) is split like the settings pages. What the
studio decides lives in voelin_ui_vm::studio::logic:

- StudioData, the state apart from the running parts (settings, scenes,
  status, statistics, destination, stream, pickers, overlays), with the
  bitrate and layers a stream starts with, the hidden-tick counter, the
  preview size, the destination choice, the stream settings form and the
  header/bottom-bar status (status_view, with the front end's side passed
  in as a StatusContext), the overlays the switches ask for;
- where the stream goes (destinations, their names and rows, the channel
  tab of the stream chat), the stream settings panel's edits, the output,
  the layer, source, picker and mixer controls (source_action,
  source_change, camera/screen/audio pickers, main_source_changes), the
  studio settings dialog, event and ending texts;
- the studio's own settings type and key (StudioUi, STUDIO_UI), the demo
  studio's sample scenes, viewers, stream and chat message.

voelin-ui keeps studio/mod.rs (StudioState: the models, the running
studio, the windows, the mixer handles, plus StudioData) and studio/bind.rs
(the engine tasks, the preview, the encoder, the two windows' StudioBridge
writes, the camera and screen listing, the chat and stream commands). The
demo settings return their problems instead of logging them. SessionView
and Tab methods that need no Default list type no longer ask for one.
28 new tests cover the logic.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 16:01:12 +03:00
faumarayandClaude Sonnet 5.5 03f4a92161 Split the settings pages: logic into voelin-ui-vm, the Bridge writes stay in bind.rs
settings_pages.rs had 52 Bridge writes interleaved with what the pages
show and change. The decisions now live in
voelin_ui_vm::settings_pages::logic and work on the settings service, the
AppState and the plain bridge rows:

- the forms read from the settings (video, streaming, notifications,
  privacy, advanced), the layer and audio-source rows and the filtered list
  of all settings;
- the settings written from the forms (apply_video, apply_streaming,
  layer, audio source, SRTP profile, notification, privacy and advanced
  edits), each returning the messages for the status line instead of
  writing them;
- the Integrations rows (gateways, configuration keys, permission rules,
  encoders and decoders with their status texts) and the Profiles rows
  (identities, bookmark pickers, what an import found, the account form);
- the pages' own state (PagesState, Improving), the layer, preset and
  codec helpers, allowed_index/of and origin_label, with the tests that
  went with them and tests for each of the above.

voelin-ui keeps settings_pages/{mod,bind}.rs: Pages (PagesState plus the
camera preview and the audio-app watcher), the Bridge and model writes, and
what a change sets going (camera, engine, identity store, threads). A
message the logic returns is logged and shown as before; the one visible
difference is that the "A layer needs a size" hint is logged with it.
serde_json becomes a regular dependency of voelin-ui-vm (the JSON typed into
the Advanced list); the lock file is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 15:31:53 +03:00
faumarayandClaude Fable 5.1 59fec5b19f Merge phase4/store-hygiene: identity store follow-ups and cargo-deny advisories
CI / Linux checks (push) Failing after 58s
A sign-out finishes when a row's binding columns cannot be read; deleted
keys are overwritten (secure_delete) and the log is truncated once per
sign-out with a short wait; the device key refuses a synced binding; the
unbind step keeps non-text data byte for byte; rustls and yoke-derive
updated, wasapi ignored until 2026-12-20. Two Opus gates accepted; the
last left two minors (wording of where deleted bytes may stay; a test
that counts the checkpoint) as follow-ups.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-20 15:18:06 +03:00
faumarayandClaude Sonnet 5.5 ac4cee0a8f Move SessionView, Tab, Msg and the App data fields into voelin-ui-vm::state
The sessions and their chat tabs, the downloads, pins and linked pictures,
and the data the screens share (the servers, the settings, the dialogs'
targets, the share and watch bookkeeping) no longer live in the Slint
crate. `SessionView<L>` and `Tab<L>` are generic over the list type of a
tab's chat lines: the Slint app plugs in `Rows<ChatLine>`
(`app::ChatRows`), a GPUI view can use a plain `Vec`. `App` keeps one
`AppState` in `state` and the Slint models; every `self.sessions`,
`self.current`, `self.bookmarks`, ... becomes `self.state.<field>`.

server_icon and server_icon_for stay with the session: `ImageRef` is
toolkit-free now, so they need no adapter. Tests for the tab and session
logic (private chat focus, tab removal, read markers, the divider) are
new, since that logic could not be tested without the Slint crate before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 15:01:24 +03:00
faumarayandClaude Sonnet 5.5 670ed9f29b Keep the stored bytes when a sign-out unbinds a row whose data is not text
KeyStore::get reads a data column that is a BLOB, or TEXT of bytes that are no
UTF-8, as text with the odd bytes replaced. The sign-out's unbind step puts that
text back with the binding removed; REBIND (data = ?3) matches nothing for such
a row, so put fell through to the full write: the lossy string replaced the
original bytes (invalid UTF-8 became U+FFFD, a BLOB became TEXT), and for a
TeamSpeak row the replaced text is no identity, so check_teamspeak refused it
and the sign-out could never finish for that row.

- put() now tries a second statement when REBIND changed nothing:
  rebind_stored_bytes reads the stored data raw and, if it reads (lossy_text) as
  exactly the blob's JSON, updates only the four binding columns by (kind, uid)
  (REBIND_BYTES) and returns without check_teamspeak, so the original bytes are
  kept and the TeamSpeak case unsticks. Any other JSON is a new identity for the
  uid, checked and stored as before.
- The doc sentences at the top of keystore.rs (what a binding-only put and a
  non-text data column mean) and docs/architecture.md are narrowed to what holds:
  the bytes are kept for the text get returned, any other text replaces them.

Tests: the gate's probe (a bound voelin row with data x'7b2276223aff317d', two
future-kind rows, one a BLOB and one TEXT of no UTF-8, and two TeamSpeak BLOB
rows, one of a good identity and one of garbage): sign_out(Auto) and
sign_out(Forget) are Ok and every data value is byte-identical afterwards; a put
of what get read changes the binding and keeps the bytes; a put of other data is
checked and replaces them. The three tests fail on the previous code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 14:35:46 +03:00
faumarayandClaude Sonnet 5.5 0ac4095143 Bound the checkpoint after a removed key to a short wait, once per sign-out
Store::truncate_wal ran PRAGMA wal_checkpoint(TRUNCATE) with the connection's
busy timeout of five seconds. A checkpoint that truncates holds the writer lock
of the log while it waits for readers, so a reader that kept a snapshot made
every removed row cost the whole timeout with the store's mutex held, and other
writers failed with "database is locked" meanwhile. KeyStore::sign_out removes
up to four rows (the synced copies, the device key, the record) and ran the
checkpoint after each: 20 s and failing writers in the gate's probe.

- truncate_wal now sets a busy timeout of 150 ms (CHECKPOINT_WAIT) around the
  pragma and restores the timeout the connection had (read back with PRAGMA
  busy_timeout, so a value set by a caller survives) whatever the checkpoint
  returned. A blocked checkpoint still leaves the delete standing and warns.
- SqliteKeyStore overrides sign_out: the trait's own steps run on a private
  SignOutPass whose remove deletes the row and notes it, and the sign-out
  truncates the log once after its last step (also when a step failed, the
  removals before it have happened). KeyStore::remove on its own still
  truncates after the row it removed.
- The three sentences that said the bytes "stay in the log until the next
  checkpoint" (keystore.rs, Store::truncate_wal, docs/architecture.md) are
  corrected: they go when a later checkpoint truncates the log, later writes
  overwrite those frames, or the last connection closes and the log is deleted.

Tests: with a raw connection holding a read snapshot, a sign-out with four
removals returns in about 170 ms (it took 20 s) while a writer on another
connection with a one-second busy timeout writes throughout without an error
(it got "database is locked" nineteen times), and the next removal after the
reader is gone truncates the log again; a unit test shows a blocked
truncate_wal returns in under a second, leaves the log, and restores a
non-default busy timeout, and that the same call truncates once the reader is
gone. Both tests fail on the previous code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 10:21:49 +03:00
faumarayandClaude Sonnet 5.5 ce7ec3afb7 Move the view models into voelin-ui-vm; the Slint models take plain rows
vm/{avatar,tree,servers,streams,home,chat,social,studio} and the UI
settings (settings.rs: keys, UiSettings, LastVoice, ClientPlaybackMap,
the audio form) move into voelin-ui-vm with their tests (102 there now;
the 86 view-model tests of voelin-ui all survive, the old list::sync test
became the list::diff tests). They produce the plain bridge structs, with
Rgb for colours and ImageRef for pictures:

- a file picture is ImageSource::File { path, stamp }: the engine writes
  a picture that arrives again into the same file, so the length and
  write time are part of the reference and a changed file redraws its
  row; size() reads the header once per stamp (no toolkit decoder);
- pictures held in memory (chat previews) are ImageSource::Memory;
- the line cache of the chat no longer keeps Slint models alive for
  pointer equality: plain lines compare by value, so an unchanged
  message makes the same line with or without the cache.

voelin-ui keeps every model as bind::rows::Rows<T>: the plain rows last
shown plus the VecModel, synced with list::diff, converting only the rows
that changed (bind/convert has the From impls). The controllers hand the
view-model rows to Rows::sync and convert forms at the bridge
(`.into()`); crate::vm is now `voelin_ui_vm as vm`, so paths stay.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 10:20:55 +03:00
faumarayandClaude Sonnet 5.5 8e6838a00f Move the BBCode reader and the Twemoji archive into voelin-ui-vm
Both are pure (no Slint): vm/bbcode.rs and emoji.rs with their tests and
the packed archive (assets/twemoji.bin, with its license note; the
packing script writes it there). voelin-ui keeps the paths
crate::vm::bbcode and crate::emoji as re-exports until the callers move.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 09:15:44 +03:00
faumarayandClaude Sonnet 5.5 4dc8272c64 Add voelin-ui-vm: toolkit-free view-model types and the Slint adapter
New crate voelin-ui-vm with no UI toolkit in its tree: ImageRef
(Arc<ImageSource>: File, Rgba, Svg, Memory, None, with size()), Rgb for
colours, list::diff(old, new) -> Changes (updates, removals and
insertions by index) and the bridge structs as plain Clone + PartialEq
values (the 51 of bridge.slint without the account's two, and the 10 of
studio-bridge.slint). Strings are Arc<str>, lists Vec.

voelin-ui keeps the temporary seam: From impls between every bridge
struct and its Slint twin (bind/convert), and bind/rows.rs, which applies
Changes to a VecModel and converts only the rows that changed. The
viewer's quality list is the first model on it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 08:53:13 +03:00
faumarayandClaude Sonnet 5.5 2e026a043c Update rustls and yoke-derive for cargo deny, ignore wasapi until 0.25
cargo deny check failed on the advisories of the base lock:

- rustls 0.23.45 (RUSTSEC-2026-0346 to 0349: Debug output of client session
  values, buffered data after ECH rejection, unbounded brotli certificate
  decompression, ServerHello downgrade): cargo update -p rustls --precise
  0.23.46, which the advisories name as the fix.
- yoke-derive 0.8.3 was yanked: cargo update -p yoke-derive --precise 0.8.4.
- wasapi 0.24.0 (RUSTSEC-2026-0332, unsound WaveFormat::parse): the fix is
  wasapi 0.25.0, a breaking release of a Windows-only dependency of
  voelin-media, which the Linux CI can neither build nor test, so it is not a
  semver update. voelin-media never calls WaveFormat::parse (it only builds
  formats with WaveFormat::new). deny.toml ignores the advisory with that
  reason and a date: remove by 2026-12-20, by upgrading wasapi on a Windows
  machine. cargo-deny cannot enforce the date; the comment and the reason say it.

Cargo.lock changes only those two packages (cargo's re-resolution also moved
tempfile to getrandom 0.3.4; that is put back to 0.4.3 by hand so the diff is
the advisories' and nothing else; cargo metadata --locked accepts it).
THIRD_PARTY_NOTICES.md is regenerated (scripts/notices.sh, cargo-about 0.9.2)
for the two version numbers.

cargo deny --locked --workspace check: advisories, bans, licenses and sources
ok.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 08:46:58 +03:00
faumarayandClaude Sonnet 5.5 3c59f24608 Refuse to store the device key as a synced copy
KeyStore::sign_out deletes every identity bound with synced = true in its
first step, before it reads the account record that says which Voelin key is
the device key and whether it predates the account. A device key stored with
synced = true was therefore deleted even where the record says to keep it.
Nothing in this crate stored such a key, but the store accepted it.

SqliteKeyStore::put now refuses, with an error that names the key and the
record and says why, a voelin blob with synced = true while an account record
names its uid as the device key, and also while an account record cannot be
read (it may name the key, and the sign-out would delete it on that guess).
The state is also reached from the other side, so a put of an account record
whose device key is already stored as a synced copy is refused as well. A
binding with synced = false is accepted: a sign-out unbinds it and then follows
the record. The check runs before the binding-only fast path, so a put of the
key's own data cannot rebind it as synced.

Documented in keystore.rs and docs/architecture.md. Tests cover the refusal
for records that keep and that delete the key (the error text, the row left
untouched, the sign-out still following the record), another key that may be
synced, no record or a record naming another key, a record put naming a synced
copy, and unreadable records; the three refusal tests fail without the check.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 08:31:36 +03:00
faumarayandClaude Sonnet 5.5 248955b85c Overwrite a deleted key and truncate the log after it
SQLite's secure_delete was off: a deleted row stayed in the free space of its
page, and the frame of the write-ahead log that held that page kept the key
until the log was reset. Every connection (Store::init) now sets
secure_delete = ON next to foreign_keys, and Store::delete_identity and
KeyStore::remove (how a sign-out deletes the device key, the synced copies and
the account record) run PRAGMA wal_checkpoint(TRUNCATE) after a row was
deleted, so the page with the overwritten row is copied into client.db and the
log is empty.

The truncate is best effort: the delete has happened and a sign-out must still
finish, so a checkpoint that another connection blocks, or that fails, only
logs a warning that the bytes stay in the log until the next checkpoint.
Keys deleted before this change stay in the free pages until a VACUUM; the
architecture notes say so.

Tests read client.db and client.db-wal as bytes: the PKCS#8 text of a Voelin
device key (sign-out with Auto, and with Forget), a synced TeamSpeak copy's key,
a TeamSpeak identity deleted by Store::delete_identity and a key removed
through KeyStore::remove are present before and in neither file after, another
key is still stored and the log is empty; and secure_delete reads 1 on every
connection. Each raw-file test fails with either measure taken out.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 08:27:56 +03:00
faumarayandClaude Sonnet 5.5 4944a0694b Let a sign-out finish when a row's binding columns cannot be read
SqliteKeyStore::list() failed on the first row whose binding columns were
damaged outside this crate (synced = 2 on the account record, say), and
KeyStore::sign_out starts with list() through bound_to(): it never reached the
record, so it could never finish, and DeviceKeyChoice::Forget did not delete
the key it was given either. get() failed the same way where sign_out reads
the record and the device key.

A row whose binding columns cannot be read (refused by
AccountBinding::from_columns, or a value of the wrong type) is now listed and
read as unbound, with a tracing warning that names the row and the reason and
quotes no content. Unbound is the reading that never deletes on a guess: such
a row is not deleted as a synced copy, and a put of it writes four good
columns. A data column that is not text is read as text with the odd bytes
replaced, so a record that cannot be read is deleted by the trait's sign_out
instead of its read failing; a row whose kind or uid is not text cannot be
addressed and the list leaves it out with a warning. list() now fails only
when the database does.

Tests: the gate's probe (UPDATE identities SET synced = 2 WHERE kind =
'account', then sign_out with Auto and with Forget on a store with
bound_existing_key true and false), more damage to the record row, the device
key row and a synced copy, and the unreadable data and kind/uid cases; the
test that asserted the old precise errors of get() and list() now asserts the
unbound reading. The six new tests fail on the previous keystore.rs.

voelin-store gets the tracing dependency (already in the lock); Cargo.lock
changes, THIRD_PARTY_NOTICES.md is unchanged by it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 08:23:55 +03:00
faumarayandClaude Fable 5.1 7c6d149f78 Merge phase4/identity-store: voelin-identity key store on SQLite (Phase 4 step 2)
CI / Linux checks (push) Failing after 40s
voelin-identity from VoelinProtocol as a git dependency pinned by rev;
the identity migrations as schema versions 6 and 7 (kind column, account
binding columns); voelin_identity::KeyStore on the identities table with
bindings and the account sign-out rules; notices regenerated; the sibling
checkout recipe in docs/building.md. Opus gate accepted with three minors
(damaged binding columns block sign-out, secure_delete off, one commit red
on the notices job) left as follow-ups. Building now needs read access to
the private VoelinProtocol repository (docs/building.md, docs/ci.md).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-20 08:11:14 +03:00
faumarayandClaude Sonnet 5.5 4ab019fcb8 Document the key store's error text, the rebind put and the notices step
architecture.md: a refused TeamSpeak blob says only that it is refused, never
its JSON (a private key), and a put that changes only a row's binding does not
read the JSON again, so a damaged row cannot keep a sign-out from unbinding
it. building.md: moving the protocol pin commits Cargo.lock together with the
notices scripts/notices.sh regenerates; the CI notices job fails on a stale
THIRD_PARTY_NOTICES.md, which is what 015c938 did.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:21:45 +03:00
faumarayandClaude Sonnet 5.5 71edc7cc2f Unbind a bound TeamSpeak row without reading its JSON again
KeyStore::sign_out unbinds a device-only secret by get() and put() of the
same blob with the binding cleared. put() ran check_teamspeak on the data
first, so a bound row whose JSON had been damaged outside this crate made the
put fail on every call: the account record was never reached, and with
DeviceKeyChoice::Forget the order of the sign-out kept the named key from
being deleted by the retry loop the module doc promised was unnecessary.

put() now first tries a statement that rewrites only the four binding columns
of the row of the same (kind, uid) whose data equals the blob's, and returns
if it changed a row. Anything else, a new row or other data, goes through the
check and the upsert as before: damage is not replaced by more damage, a
stranger's key still cannot take over a uid, and another kind's put of a held
uid is still refused. Nothing but the binding of the row is written, so the
name, origin, default flag and creation time stay as they were.

Tests: sign_out (Auto, and Forget with and without bound_existing_key)
completes on a damaged bound row, deletes the record, unbinds the row and
leaves its data as it was; the put cases above; each fails on the previous
commit. The scratch directories of the test file are unique per call now, as
two tests that pass the same name run side by side.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:21:10 +03:00
faumarayandClaude Sonnet 5.5 f3345bccf2 Do not quote a TeamSpeak key in the error of a refused put
SqliteKeyStore::put checked a TeamSpeak blob by parsing its JSON as a
tsproto::Identity and forwarded serde's error. tsproto's key visitor answers
a key it cannot decode with invalid_value(Unexpected::Str(key)), so the
message read `invalid value: string "<the key text>", expected a P256 private
ecc key`: the private key reached Display and Debug of the KeyStoreError, and
so any log line that reports it.

check_teamspeak now drops the serde error and returns a Backend error of
fixed text (Refused::NotATeamSpeakIdentity). The test puts a blob with a
malformed key string, first checks that serde does quote it (so the case
proves something), and asserts that neither Display, Debug nor pretty Debug
of the error or of any error in its source chain contains the string.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:20:41 +03:00
faumarayandClaude Sonnet 5.5 143bc945f7 Keep the per-developer .cargo out of the Docker build context
docs/building.md tells developers to put a [patch] to a sibling
VoelinProtocol checkout in .cargo/config.toml. It is git-ignored but was not
in .dockerignore, so it was sent to the daemon with every docker build and
could redirect the dependency to a path that does not exist in the image.
Only the root .cargo is excluded: third_party/dimpl/.cargo is committed and
stays.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:19:11 +03:00
faumarayandClaude Sonnet 5.5 b68aeb6829 Regenerate the third-party notices for the protocol dependency
015c938 changed Cargo.lock without regenerating THIRD_PARTY_NOTICES.md, so
the third-party notices job (scripts/notices.sh --check) failed on this
branch. voelin-identity brings x509-cert 0.3 and der_derive 0.8, both MIT
OR Apache-2.0: two more crates under the MIT License row of the summary,
and two names on existing "Used by" lines. Regenerated with cargo-about
0.9.2, the version the script requires. The protocol crates themselves are
publish = false and left out by about.toml, like the client's own.

015c938 on its own is still red on that job: history is not rewritten, and
this commit is the fix that follows it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:18:58 +03:00
faumarayandClaude Sonnet 5.5 87f4a574e6 Document the identity store in architecture.md and the changelog
A new Identities section says what the identities table holds now (the kinds,
the binding, the two schema versions and whose SQL they are), what Store and
SqliteKeyStore each do with it, what the TeamSpeak level and the sign-out
mean on this table, and that the engine and the UI do not use the key store
yet. The voelin-store row of the workspace table names the new content, and
the changelog notes the migration and the new access requirement for the
private protocol repository.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 05:52:00 +03:00
faumarayandClaude Sonnet 5.5 526e59d5ca Test the sign-out of the account on the SQLite store
KeyStore::sign_out is voelin-identity's, generic over the trait, so the
store uses it as it is and these tests run it on the SQLite table, each case
of the protocol's section 13.6 as its own test:

- the account record and the synced copies are removed and the unsynced bound
  identities are left unbound, byte for byte;
- the device key is kept, unbound and byte for byte (the stored blob is
  equal, the key signs the same bytes), when the record says
  bound_existing_key, and deleted when it does not;
- DeviceKeyChoice::Forget(device uid) deletes the key it names in both
  cases and no other, and a uid that is not stored deletes nothing;
- a record without the flag keeps the key;
- an unreadable record (unknown version, damaged JSON, an empty object) is
  deleted before the error is reported; with Forget the named key is deleted
  even then; a second call completes without bringing the key back;
- a sign-out that stopped half way can be run again;
- the result is durable in the file, and the kept key's row has no account.

The five hand-made mutants of the protocol's own acceptance (Auto always
deleting, Forget keeping, a missing flag reading false, the unreadable record
left behind, Forget deleting only after the record was read) were applied to
a copy of voelin-identity through the documented [patch] recipe, and each is
caught by these tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 05:51:30 +03:00
faumarayandClaude Sonnet 5.5 2898281d35 Implement voelin-identity's KeyStore on the SQLite identities table
SqliteKeyStore is the identities table as a KeyStore: every kind (TeamSpeak,
a Voelin key, the account record, an unknown kind that passes through) with
the account binding of the columns that ADD_ACCOUNT_COLUMNS added. It owns a
Store behind a mutex, because a KeyStore is Sync and a connection is not;
with_store runs the TeamSpeak methods on the same connection. The trait's
provided methods (bound_to, account_record, put_account_record, sign_out)
are used as they are.

- put is one upsert; a replaced row keeps its name, origin, default flag and
  creation time, and a blob without a binding unbinds the row. The uid is
  UNIQUE across kinds, so a uid another kind holds is a backend error that
  replaces nothing; get and remove are addressed by kind and uid.
- The TeamSpeak level stays computed from the key and counter, as before; the
  level of a blob that is put is not stored. A TeamSpeak row whose JSON was
  damaged outside this crate lists and reads with level 0.
- A TeamSpeak blob is stored only if its JSON is a tsproto identity and its
  key has the uid the blob names. Without the first one bad row breaks the
  list of TeamSpeak identities; without the second a blob could replace, by
  its uid, the key of a different identity.

Tests copy the exercise() cases of voelin-identity's tests/storage.rs into
the client (with the two deviations of a SQLite store, marked), round-trip
bound and synced entries through the table and a reopen with their raw
columns, and load a client.db migrated from schema versions 5 and 6 through
the key store: kind teamspeak, no binding, JSON byte for byte, origin and
default flag kept.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 05:48:51 +03:00
faumarayandClaude Sonnet 5.5 0137d03d5b Run the identity migrations of voelin-identity as schema versions 6 and 7
ADD_KIND_COLUMN and then ADD_ACCOUNT_COLUMNS are the next two entries of the
user_version list, in the order the protocol's Phase 2 tasks 7 and 28 give.
Every identity that exists stays what it was: kind teamspeak, unbound, its
JSON untouched, its origin and default flag kept, and the level still
computed from the key.

The TeamSpeak methods of Store (identities, identity, update, rename, delete,
set_default) now act on rows of kind teamspeak only, so that a Voelin key or
the account record in the same table can never be listed as a tsproto
identity (listing would fail on its JSON) or renamed, changed or deleted by
the old API. Their signatures are unchanged.

Tests build a client.db at the current schema (version 5) and at version 6
from the migration list itself, open it, and check both steps: the fixture
row (the real tsproto serialization, its uid and level checked against
tsproto), a second generated identity, the raw columns, the old API, and a
reopen that runs nothing twice. A test pins the SQL of both migrations
against the protocol's strings so that a newer protocol revision cannot
change a shipped version.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 05:43:52 +03:00
faumarayandClaude Sonnet 5.5 015c938212 Depend on voelin-identity from the private VoelinProtocol repository
voelin-store will keep Voelin identities and the signed-in account next to
the TeamSpeak ones (Phase 4 step 2, protocol Phase 2 tasks 7 and 28), through
the identity blobs and the KeyStore trait of voelin-identity.

The dependency is a workspace git dependency on the SSH URL that the
protocol's docs/development.md names, pinned by commit (64808cc, the head of
its main when task 28 was accepted), so that a per-developer
.cargo/config.toml [patch] can redirect it to a sibling checkout. The recipe
is in docs/building.md; .cargo/ is ignored so it is never committed.
deny.toml allows that one git source. CI and the Docker builds need read
access to the private repository (a deploy key or a token); docs/ci.md and
docs/building.md say so.

Cargo.lock gains voelin-identity, voelin-proto, x509-cert 0.3 and
der_derive 0.8.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 05:41:52 +03:00
faumarayandClaude Fable 5.1 cb595a0621 claude: cap effort at xhigh for every role
CI / Linux checks (push) Failing after 36m48s
The user asked for xhigh as the maximum effort. The designer and the
Opus reviewer drop from max to xhigh, and settings.json sets
maxEffortLevel so nothing in this repository exceeds it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-19 22:10:09 +03:00
faumarayandClaude Sonnet 5.5 ff054008c3 Settle the small leftovers of the earlier reviews
CI / Linux checks (push) Failing after 20m23s
- jitter.rs: short_packet_fuzz takes payloads of 0..=100 bytes (was under
  12) and 3000 iterations (was 500).
- ui-review.md: the whisper row pointed at voelin-audio/src/encode.rs:90;
  the C2S-only packet is built by out_audio in voelin-core/src/voice.rs.
- mixer.rs: the module doc's first paragraph is reflowed, and
  Mixer::set_priority names its parameter talkers, not clients.
- stream.rs: api_types_convert_at_the_boundary asserts the remaining
  variants: every ViewerState, StreamKind (both ways) and LeaveReason
  (alone and inside EndReason::Removed).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 18:09:21 +03:00
faumarayandClaude Sonnet 5.5 cfd9cba2dd Document what is still TeamSpeak's in the seam and the real event order
link.rs and architecture.md now list every part of the ServerLink seam that
still has TeamSpeak types or shape: ConnectOptions.identity and
client_version, the account proof in LinkCtx, the u16 client ids, the
Presence snapshots, and the stream vocabulary of voelin-stream (PeerConfig,
MediaFrame, VideoFormat, VideoCodec, FrameSource). StreamAudioEnded joins the
event list.

Disconnected is no longer promised to be the last event: the stream task is a
task of its own that winds down after the connection, so OwnStream(Ended) and
StreamAudioEnded may follow it. The docs say TsLink ends the stream task as
the connection's loop ends (usually before Disconnected, not always) and that
the session does not depend on the order: it ends our stream and the watched
audio itself on Disconnected and ignores what the link says after it. The
reconnect order (StreamCmd::Shutdown before Disconnect) is documented too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 18:06:54 +03:00
faumarayandClaude Sonnet 5.5 e0ac95ee79 Pin the order of a reconnect in the FakeLink tests
The session ends the streams of a connection it replaces by sending
StreamCmd::Shutdown through that connection and only then Disconnect; a link
that stops reading commands at Disconnect (TsLink) relies on it. The new test
connects with streams, takes the directory, connects again and asserts the old
connection is given Shutdown before Disconnect. Swapping the two sends in
Session::command makes it fail.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 18:04:34 +03:00
faumarayandClaude Sonnet 5.5 a5125b3998 End the connection's streams as the loop ends, not after the shutdown
The ConnectionStreams guard was dropped only after shutdown_connection, which
can wait up to three seconds. The loop no longer reads commands once it has
broken, so a StreamCmd::Shutdown the session sent in that window never
reached the stream task; the task ran on until the guard dropped. Drop the
guard right after the loop. The stream task's shutdown needs nothing of the
connection (it reports to the session's channels), so nothing relied on the
late drop.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 18:04:34 +03:00
faumarayandClaude Sonnet 5.5 ac4464db7b Format the voelinctl stream watcher with rustfmt 1.94
The stream-types commit shortened a let-chain in tools/voelinctl/src/engine.rs
that rustfmt 1.94 (the CI toolchain) lays out differently from nightly.
`cargo fmt --check` over scripts/own-crates.sh now passes on 1.94.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 18:02:30 +03:00
faumarayandClaude Sonnet 5.5 6c1898bf5a Put the voice source behind a ServerLink
The session no longer spawns the TeamSpeak connection itself. link.rs adds
ServerLink (spawn(options, ctx, cmds, events)) with LinkCmd and LinkEvent,
VoiceCmd and VoiceEvent moved and renamed, plus ConnectOptions (VoiceOptions
stays as its name for the app), LinkCtx and Remote. TsLink (ts_link.rs) is
the TeamSpeak implementation and the engine's default; Engine::start_with_link
takes another.

The stream task moves inside the connection: voice.rs spawns it when the
server has streams, feeds it the server's notifications and the clients'
channels, and sends its requests. The session reaches it only through
LinkCmd::Stream(StreamCmd) and hears of our own stream (OwnStream) and the
audio of watched streams (StreamAudio) as link events, so the link holds no
handle on the audio thread. stream.rs keeps its tests, adapted to the split
of StreamInput into StreamCmd and the link-private input.

tests/link_fake.rs drives the session with an in-memory link: connect,
presence, commands, a message sent and echoed, a message that comes twice,
history, and a replaced connection, without a TeamSpeak crate. The
architecture doc describes ServerLink and the planned move of TsLink to
VoelinGateWay and the QUIC link of VoelinProtocol.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 15:54:08 +03:00
faumarayandClaude Sonnet 5.5 da372dfe10 Give the stream API core-owned types
Command and Event no longer carry voelin-stream's types. voelin-core owns
StreamInfo, ViewerInfo, StreamSetup, StreamKind, ViewerState, EndReason and
LeaveReason (stream_types.rs) with u16 client ids, a viewer's SRTP profile
as its name and its codec as voelin_media::Codec; stream.rs converts at the
boundary. Command::SetSrtpProfiles takes profile names, which the stream
task parses.

EncodedFrame, LayerSpec, LayerId and LayerSet move into voelin-media
(stream::EncodedFrame, layer); voelin-stream depends on it and re-exports
them, so the engine, the stream sessions and voelinctl share one type. The
crate is now a plain dependency of voelin-core (feature media keeps the
module and WHIP), and its str0m feature is gone with str0m always there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 15:01:24 +03:00
faumarayandClaude Sonnet 5.5 b0f95a384f Take ServerFlavor out of the engine API
Event::ServerInfo carried voelin_model::ServerFlavor, a TeamSpeak notion. It
now carries backend: BackendInfo { product, version } (plain strings, with
label() for a sentence) next to the capabilities. The voice source decides
the flavor from the version string (voice.rs backend_of) and puts the
backend and capabilities in VoiceEvent::Connected; session.rs forwards them
and no longer classifies anything.

The UI reads backend.product for a server's chip (ServerItem.flavor becomes
product, as does the session view's field) and backend.label() for the
"Connected to ..." status line; the sample data builds its own backend and
the TeamSpeak 6 capabilities, pinned against the flavor's by a test.
voelinctl's engine mode prints the label. ServerFlavor stays in voelin-model
for the gateway and the voice source.

Shown text is unchanged. New tests: the voice source's backend for TS3, TS6
and an unrecognised version, BackendInfo::label, the status line, the sample
servers' backends, and the server item's product.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 13:59:20 +03:00
faumarayandClaude Sonnet 5.5 df7be67d4c Move voice packet types into voelin-audio
voelin-audio no longer depends on tsclientlib or tsproto-packets. Its
boundary is now plain types in packet.rs: TalkerId, VoiceCodec, VoicePacket
(talker, seq, codec, whisper, payload) and EncodedVoice (codec, payload; an
empty payload ends the transmission). The jitter buffer moves from
tsclientlib::audio into jitter.rs and reads VoicePacket fields; the encoder
returns EncodedVoice and the mixer is keyed by TalkerId.

In voelin-core, voice.rs is the only place that wraps EncodedVoice into a
TeamSpeak audio packet and reads one into a VoicePacket (codecs other than
Opus are dropped there, where the jitter buffer rejected them before);
audio.rs and session.rs work on the new types. voelinctl converts at its
own edge. Behaviour is unchanged: the one-hour drift simulation gives the
same latencies as before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 13:06:46 +03:00
168 changed files with 33291 additions and 8814 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
name: mao-designer
description: Produces designs and acceptance criteria for a task, and handles escalations from mao-implementer after 3 failed attempts. Use before delegating non-trivial work and whenever an implementation is stuck.
model: opus
effort: max
effort: xhigh
---
You are **mao-designer**, the design and escalation role of the Voelin
+1 -1
View File
@@ -2,7 +2,7 @@
name: mao-opus-reviewer
description: Final, fresh and independent review of substantive code changes for correctness, architecture and unresolved risks. Reports concrete defects; does not fix code. Use after the sonnet review, in a new agent, never in the design agent's conversation.
model: opus
effort: max
effort: xhigh
tools: Read, Grep, Glob, Bash
---
+2 -1
View File
@@ -1,5 +1,6 @@
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"model": "fable",
"effortLevel": "xhigh"
"effortLevel": "xhigh",
"maxEffortLevel": "xhigh"
}
+4
View File
@@ -2,6 +2,10 @@
# the sources only. Builds keep target/ in cache mounts, never in the context.
.git
.claude
# The per-developer .cargo/config.toml (docs/building.md, a [patch] to a sibling
# VoelinProtocol checkout): never part of a build. Only the root one; the
# committed third_party/dimpl/.cargo stays.
.cargo
target
dist
fuzz/target
+1
View File
@@ -1,3 +1,4 @@
/target/
/dev/.state/
/dist/
/.cargo/
+18
View File
@@ -69,6 +69,21 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Changed
- The view models, the app's state and the decisions of the settings pages and
of the Stream Studio moved out of `voelin-ui` into a new crate,
`voelin-ui-vm`, which depends on no UI toolkit (a second front end can use
it); `voelin-ui` converts its plain rows into Slint's and keeps the window,
the Bridge writes and the engine's tasks. The chat formatting reader and the
Twemoji archive moved with them. Nothing changes on screen. See
docs/ui.md, "Two crates".
- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin
key, the signed-in account) with the account each belongs to, as a
`voelin-identity` key store, in two database migrations. Existing
databases migrate on first start and every identity stays what it was (kind
TeamSpeak, no account, same key, name, origin and default); nothing changes
on screen yet. The build now fetches `voelin-identity` from the private
VoelinProtocol repository, so a fresh checkout needs read access to it
(see docs/building.md).
- Selecting a server observes it through its gateway at once; the Observe
button is gone. The server dialog asks only for the address, password,
name and nickname: the gateway is found from the address.
@@ -180,6 +195,9 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Fixed
- A deleted identity key no longer stays in the database file: SQLite overwrites
what it deletes, and the log is truncated after a key is deleted (an identity
you delete, a key a sign-out deletes).
- Hover help in the Stream Studio (a source's error, the status details)
shows each time and closes when the pointer leaves; it showed only once,
and stayed open until a click.
+2 -2
View File
@@ -30,10 +30,10 @@ review, help) and does not delegate it again or spawn further orchestration.
| Agent | Model / effort | Job |
|---|---|---|
| main session | (settings) | **Orchestrator**: decomposes work, delegates, tracks progress and attempt counts, resolves escalations, reports results. Delegates implementation, investigation, testing and review rather than doing them inline. |
| `mao-designer` | opus / max | Designs, acceptance criteria, escalation handling |
| `mao-designer` | opus / xhigh | Designs, acceptance criteria, escalation handling |
| `mao-implementer` | sonnet / xhigh | Implements, runs checks, self-reviews; escalates after 3 failed attempts |
| `mao-sonnet-reviewer` | sonnet / xhigh | Fresh, independent implementation review |
| `mao-opus-reviewer` | opus / max | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
| `mao-opus-reviewer` | opus / xhigh | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
| `mao-helper` | haiku | Focused file searches, summaries, routine git operations within the user's authorization |
### Before delegating
Generated
+85 -11
View File
@@ -1996,7 +1996,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid 0.9.6",
"der_derive",
"der_derive 0.7.3",
"flagset",
"pem-rfc7468 0.7.0",
"zeroize",
@@ -2009,6 +2009,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"
dependencies = [
"const-oid 0.10.2",
"der_derive 0.8.0",
"flagset",
"pem-rfc7468 1.0.0",
"zeroize",
]
@@ -2038,6 +2040,17 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "der_derive"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "deranged"
version = "0.5.8"
@@ -2134,7 +2147,7 @@ dependencies = [
"spki 0.7.3",
"subtle",
"time",
"x509-cert",
"x509-cert 0.2.5",
]
[[package]]
@@ -7136,9 +7149,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.45"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"aws-lc-rs",
"once_cell",
@@ -9449,7 +9462,6 @@ dependencies = [
"tokio",
"tracing",
"tracing-subscriber",
"tsclientlib",
"voelin-core",
"voelin-media",
"voelin-model",
@@ -9474,8 +9486,6 @@ dependencies = [
"sonora-simd",
"thiserror 2.0.21",
"tracing",
"tsclientlib",
"tsproto-packets",
]
[[package]]
@@ -9508,10 +9518,12 @@ dependencies = [
"tsproto-types",
"voelin-audio",
"voelin-gateway-proto",
"voelin-identity",
"voelin-media",
"voelin-model",
"voelin-observer",
"voelin-platform",
"voelin-proto",
"voelin-query",
"voelin-store",
"voelin-stream",
@@ -9563,6 +9575,23 @@ dependencies = [
"voelin-model",
]
[[package]]
name = "voelin-identity"
version = "0.2.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650"
dependencies = [
"aws-lc-rs",
"base64 0.23.1",
"prost",
"rcgen",
"serde",
"serde_json",
"thiserror 2.0.21",
"voelin-proto",
"x509-cert 0.3.0",
"zeroize",
]
[[package]]
name = "voelin-media"
version = "0.1.0"
@@ -9608,9 +9637,11 @@ dependencies = [
[[package]]
name = "voelin-model"
version = "0.1.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650"
dependencies = [
"prost",
"serde",
"serde_json",
"voelin-proto",
]
[[package]]
@@ -9642,6 +9673,17 @@ dependencies = [
"zbus",
]
[[package]]
name = "voelin-proto"
version = "0.2.0"
source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650"
dependencies = [
"bytes",
"prost",
"thiserror 2.0.21",
"tokio",
]
[[package]]
name = "voelin-query"
version = "0.1.0"
@@ -9665,7 +9707,9 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"tracing",
"tsclientlib",
"voelin-identity",
]
[[package]]
@@ -9685,6 +9729,7 @@ dependencies = [
"tracing-subscriber",
"tsclientlib",
"tsproto-packets",
"voelin-media",
]
[[package]]
@@ -9695,7 +9740,6 @@ dependencies = [
"chrono",
"dirs",
"image",
"miniz_oxide 0.8.9",
"png",
"serde",
"serde_json",
@@ -9713,6 +9757,25 @@ dependencies = [
"voelin-platform",
"voelin-query",
"voelin-store",
"voelin-ui-vm",
]
[[package]]
name = "voelin-ui-vm"
version = "0.0.1-alpha"
dependencies = [
"chrono",
"image",
"miniz_oxide 0.8.9",
"png",
"serde",
"serde_json",
"unicode-segmentation",
"voelin-audio",
"voelin-core",
"voelin-gateway-proto",
"voelin-model",
"voelin-store",
]
[[package]]
@@ -10852,6 +10915,17 @@ dependencies = [
"spki 0.7.3",
]
[[package]]
name = "x509-cert"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b"
dependencies = [
"const-oid 0.10.2",
"der 0.8.2",
"spki 0.8.0",
]
[[package]]
name = "x509-parser"
version = "0.18.1"
@@ -10968,9 +11042,9 @@ dependencies = [
[[package]]
name = "yoke-derive"
version = "0.8.3"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
dependencies = [
"proc-macro2",
"quote",
+15 -2
View File
@@ -16,13 +16,13 @@ members = [
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-media",
"crates/voelin-model",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
"crates/voelin-store",
"crates/voelin-stream",
"crates/voelin-ui",
"crates/voelin-ui-vm",
"tools/voelinctl",
]
default-members = [
@@ -36,13 +36,13 @@ default-members = [
"crates/voelin-core",
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-model",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
"crates/voelin-store",
"crates/voelin-stream",
"crates/voelin-ui",
"crates/voelin-ui-vm",
"tools/voelinctl",
]
@@ -53,6 +53,19 @@ license = "MIT OR Apache-2.0"
repository = "https://github.com/Faumaray/Voelin"
publish = false
[workspace.dependencies]
# The protocol repository is private (VoelinProtocol). This is the SSH URL its
# docs/development.md names, so that a per-developer .cargo/config.toml [patch]
# can point it at a sibling checkout (docs/building.md, "Working with a sibling
# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release:
# the three crates below are at one revision (main c8e0e5a: the account-bound
# KeyStore of Phase 2 task 28, the account types of the session seam).
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
# The backend-neutral session seam (`voelin_proto::link`) and the v1 messages.
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
# The UI-facing domain model and the client's replica of v1 entities.
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
[workspace.lints.rust]
# deny, not forbid: generated code (Slint) needs a local allow.
unsafe_code = "deny"
+4 -1
View File
@@ -28,7 +28,7 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
- `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream
messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes;
see [UPSTREAM.md](crates/proto/UPSTREAM.md))
- `crates/voelin-model`: server flavor detection (TS3 / TS6) and capabilities
- `voelin-model` (from VoelinProtocol, a git dependency): domain model, server flavor detection (TS3 / TS6) and capabilities
- `crates/voelin-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices
- `crates/voelin-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets
- `crates/voelin-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive)
@@ -45,6 +45,9 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
(in the window and as a global hotkey), audio settings with a level meter, per-client volume, and on
TeamSpeak 6 streams: watch in a viewer, share the screen with sound. Desktop and phone layouts
from one design system, dark and light themes, text size, emoji ([docs/ui.md](docs/ui.md))
- `crates/voelin-ui-vm`: the view models and the app's state behind the UI, with no UI toolkit: engine state
as plain rows and forms, chat formatting, the Twemoji archive, and what the settings pages and the
Stream Studio decide; `voelin-ui` puts them on Slint windows ([docs/ui.md](docs/ui.md))
- `crates/voelin-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
+7 -6
View File
@@ -175,7 +175,7 @@ the crate's authors are listed as its copyright holders.
| License | Crates |
|---|---|
| MIT License | 658 |
| MIT License | 660 |
| Apache License 2.0 | 31 |
| Unicode License v3 | 26 |
| BSD 3-Clause "New" or "Revised" License | 22 |
@@ -4150,7 +4150,7 @@ DEALINGS IN THE SOFTWARE.
````
Used by: hyper-rustls 0.27.10, rustls-native-certs 0.8.4, rustls 0.23.45
Used by: hyper-rustls 0.27.10, rustls-native-certs 0.8.4, rustls 0.23.46
````text
Copyright (c) 2016 Joseph Birr-Pixton <jpixton@gmail.com>
@@ -6994,7 +6994,7 @@ DEALINGS IN THE SOFTWARE.
````
Used by: cpufeatures 0.2.17
Used by: cpufeatures 0.2.17, der_derive 0.8.0
````text
Copyright (c) 2020-2025 The RustCrypto Project Developers
@@ -7246,7 +7246,7 @@ DEALINGS IN THE SOFTWARE.
````
Used by: pem-rfc7468 1.0.0, pkcs1 0.8.0-rc.4
Used by: pem-rfc7468 1.0.0, pkcs1 0.8.0-rc.4, x509-cert 0.3.0
````text
Copyright (c) 2021-2025 The RustCrypto Project Developers
@@ -11796,7 +11796,7 @@ authorization of the copyright holder.
````
Used by: fixed_decimal 0.7.2, icu_collections 2.3.0, icu_decimal 2.3.0, icu_decimal_data 2.3.0, icu_locale_core 2.3.0, icu_locale_fallback 2.3.0, icu_locale_fallback_data 2.3.0, icu_normalizer 2.3.0, icu_normalizer_data 2.3.0, icu_properties 2.3.0, icu_properties_data 2.3.0, icu_provider 2.3.1, icu_segmenter 2.3.0, icu_segmenter_data 2.3.0, litemap 0.8.3, potential_utf 0.1.6, tinystr 0.8.4, writeable 0.6.4, yoke-derive 0.8.3, yoke 0.8.3, zerofrom-derive 0.1.8, zerofrom 0.1.8, zerotrie 0.2.5, zerovec-derive 0.11.6, zerovec 0.11.8
Used by: fixed_decimal 0.7.2, icu_collections 2.3.0, icu_decimal 2.3.0, icu_decimal_data 2.3.0, icu_locale_core 2.3.0, icu_locale_fallback 2.3.0, icu_locale_fallback_data 2.3.0, icu_normalizer 2.3.0, icu_normalizer_data 2.3.0, icu_properties 2.3.0, icu_properties_data 2.3.0, icu_provider 2.3.1, icu_segmenter 2.3.0, icu_segmenter_data 2.3.0, litemap 0.8.3, potential_utf 0.1.6, tinystr 0.8.4, writeable 0.6.4, yoke-derive 0.8.4, yoke 0.8.3, zerofrom-derive 0.1.8, zerofrom 0.1.8, zerotrie 0.2.5, zerovec-derive 0.11.6, zerovec 0.11.8
````text
UNICODE LICENSE V3
@@ -11991,7 +11991,8 @@ bzip2/libbzip2 version 1.1.0 of 6 September 2010
<!-- From about-assets.md, appended by scripts/notices.sh. -->
The user interface bundles these assets (in crates/voelin-ui):
The user interface bundles these assets (in crates/voelin-ui, the Twemoji
archive in crates/voelin-ui-vm):
- Inter (the UI font), Copyright (c) 2016 The Inter Project Authors, under
the SIL Open Font License 1.1 (OFL-1.1; text below).
+2 -1
View File
@@ -3,7 +3,8 @@
<!-- From about-assets.md, appended by scripts/notices.sh. -->
The user interface bundles these assets (in crates/voelin-ui):
The user interface bundles these assets (in crates/voelin-ui, the Twemoji
archive in crates/voelin-ui-vm):
- Inter (the UI font), Copyright (c) 2016 The Inter Project Authors, under
the SIL Open Font License 1.1 (OFL-1.1; text below).
+1 -5
View File
@@ -19,7 +19,7 @@ tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "
tracing = "0.1.44"
voelin-core = { path = "../voelin-core" }
# Channels and people for the voice notification.
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
[target.'cfg(target_os = "android")'.dependencies]
anyhow = "1.0.104"
@@ -32,9 +32,5 @@ voelin-platform = { path = "../voelin-platform", default-features = false }
voelin-store = { path = "../voelin-store" }
voelin-ui = { path = "../voelin-ui" }
[dev-dependencies]
# Client ids of stream viewers in the tests.
tsclientlib = { path = "../proto/tsclientlib" }
[lints]
workspace = true
+3 -3
View File
@@ -194,7 +194,7 @@ fn connected(viewers: &[ViewerInfo]) -> usize {
mod tests {
use voelin_core::SessionState;
use voelin_core::stream::EndReason;
use voelin_model::{Capabilities, ChannelInfo, ClientInfo, ServerFlavor};
use voelin_model::{Capabilities, ChannelInfo, ClientInfo};
use super::*;
@@ -244,7 +244,7 @@ mod tests {
let info = Event::ServerInfo {
session: 1,
name: "Home".into(),
flavor: ServerFlavor::Unknown(String::new()),
backend: voelin_core::BackendInfo::default(),
capabilities: Capabilities::default(),
};
assert_eq!(fg.update_at(&info, 6).voice, notice("Connecting…", "Home", false, 0));
@@ -316,7 +316,7 @@ mod tests {
};
assert_eq!(fg.screen(), screen("Live in Chill Zone", "a server").flatten());
let viewer = |client, state| ViewerInfo {
client: tsclientlib::ClientId(client),
client,
state,
message: String::new(),
layer: None,
+1 -3
View File
@@ -1,7 +1,7 @@
[package]
name = "voelin-audio"
version = "0.1.0"
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices."
description = "Voice pipeline: Opus encoding, framing, resampling, jitter buffer/mixer and audio devices, independent of the voice transport."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
@@ -25,8 +25,6 @@ sonora-agc2 = "0.2"
sonora-simd = "0.2"
thiserror = "2.0.21"
tracing = "0.1.44"
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
[dev-dependencies]
serde_json = "1"
+43 -55
View File
@@ -1,45 +1,15 @@
//! Opus encoding into TeamSpeak voice packets.
//! Opus encoding of 20 ms frames into [`EncodedVoice`].
use opus2::{Application, Bitrate, Channels, Encoder};
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
use crate::pcm::{FRAME_SAMPLES, SAMPLE_RATE};
use crate::packet::{EncodedVoice, VoiceCodec};
use crate::pcm::SAMPLE_RATE;
use crate::{Error, Result};
/// Largest possible Opus packet.
const MAX_PACKET: usize = 1275;
/// The two Opus codecs TeamSpeak channels use.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VoiceCodec {
/// Mono, tuned for speech (`CodecType::OpusVoice`).
Voice,
/// Stereo, tuned for music (`CodecType::OpusMusic`).
Music,
}
impl VoiceCodec {
pub fn channels(self) -> usize {
match self {
VoiceCodec::Voice => 1,
VoiceCodec::Music => 2,
}
}
pub fn codec_type(self) -> CodecType {
match self {
VoiceCodec::Voice => CodecType::OpusVoice,
VoiceCodec::Music => CodecType::OpusMusic,
}
}
/// Samples (all channels) in one 20 ms frame.
pub fn frame_len(self) -> usize {
FRAME_SAMPLES * self.channels()
}
}
/// Encodes 20 ms frames of 48 kHz audio into voice packets.
/// Encodes 20 ms frames of 48 kHz audio into Opus packets.
pub struct VoiceEncoder {
encoder: Encoder,
codec: VoiceCodec,
@@ -53,7 +23,7 @@ impl VoiceEncoder {
VoiceCodec::Music => (Channels::Stereo, Application::Audio),
};
let mut encoder = Encoder::new(SAMPLE_RATE, channels, application)?;
// Survive some packet loss: TeamSpeak voice is plain UDP.
// Survive some packet loss: voice travels over unreliable datagrams.
encoder.set_inband_fec(true)?;
encoder.set_packet_loss_perc(5)?;
Ok(Self { encoder, codec, out: vec![0; MAX_PACKET] })
@@ -82,26 +52,25 @@ impl VoiceEncoder {
Ok(&self.out[..len])
}
/// Encode one frame into a packet ready for `Connection::send_audio`.
/// The connection assigns the packet id.
pub fn encode(&mut self, frame: &[f32]) -> Result<OutPacket> {
let codec = self.codec.codec_type();
let data = self.encode_to_bytes(frame)?;
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec, data }))
/// Encode one frame for the transport to send. The transport assigns the
/// packet number.
pub fn encode(&mut self, frame: &[f32]) -> Result<EncodedVoice> {
let codec = self.codec;
let payload = self.encode_to_bytes(frame)?.to_vec();
Ok(EncodedVoice { codec, payload })
}
/// The empty packet that tells listeners the transmission ended.
pub fn end_of_stream(&self) -> OutPacket {
OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &[] })
pub fn end_of_stream(&self) -> EncodedVoice {
EncodedVoice { codec: self.codec, payload: Vec::new() }
}
}
#[cfg(test)]
mod tests {
use tsproto_packets::packets::{Direction, InAudioBuf};
use super::*;
use crate::pcm;
use crate::packet::{TalkerId, VoicePacket};
use crate::pcm::{self, FRAME_SAMPLES};
/// Encode a tone, feed the packets through the mixer (jitter buffer +
/// decoder), and check the tone comes out.
@@ -112,15 +81,16 @@ mod tests {
let tone = pcm::sine(1000.0, 1.0, 0.5);
let mut decoded = Vec::new();
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
let data = encoder.encode_to_bytes(frame).unwrap().to_vec();
let packet = OutAudio::new(&AudioData::S2C {
id: i as u16,
codec: CodecType::OpusVoice,
from: 7,
data: &data,
});
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
mixer.handle_packet(tsclientlib::ClientId(7), packet).unwrap();
let sent = encoder.encode(frame).unwrap();
assert_eq!(sent.codec, VoiceCodec::Voice);
let packet = VoicePacket {
talker: TalkerId(7),
seq: i as u16,
codec: sent.codec,
whisper: false,
payload: sent.payload,
};
mixer.handle_packet(packet).unwrap();
let mut out = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut out);
decoded.extend(pcm::to_mono(&out, 2));
@@ -131,6 +101,24 @@ mod tests {
assert!(ratio > 0.8, "tone ratio {ratio}");
}
#[test]
fn end_of_stream_has_no_payload() {
let encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
let end = encoder.end_of_stream();
assert_eq!(end, EncodedVoice { codec: VoiceCodec::Music, payload: vec![] });
assert!(end.is_end());
}
#[test]
fn encoded_frames_carry_codec_and_audio() {
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
let a = voice.encode(&[0.1; FRAME_SAMPLES]).unwrap();
let b = music.encode(&[0.1; FRAME_SAMPLES * 2]).unwrap();
assert_eq!((a.codec, b.codec), (VoiceCodec::Voice, VoiceCodec::Music));
assert!(!a.is_end() && !b.is_end());
}
#[test]
fn rejects_wrong_frame_size() {
let mut encoder = VoiceEncoder::new(VoiceCodec::Music).unwrap();
+879
View File
@@ -0,0 +1,879 @@
//! Handle receiving audio.
//!
//! Moved here from the vendored `tsclientlib::audio` and made independent of the
//! transport: it reads [`VoicePacket`]s, whatever carried them.
//!
//! The [`AudioHandler`] collects all incoming audio packets and queues them per
//! talker. It decodes the audio, handles out-of-order packets and missing
//! packets. It automatically adjusts the queue length based on the jitter of
//! incoming packets.
use std::cmp::Reverse;
use std::collections::{HashMap, VecDeque};
use std::convert::TryInto;
use opus2::{Channels, Decoder, packet};
use thiserror::Error;
use tracing::{Span, debug, info_span, trace, warn};
use crate::packet::{TalkerId, VoicePacket};
const SAMPLE_RATE: u32 = 48_000;
const CHANNELS: Channels = Channels::Stereo;
const CHANNEL_NUM: usize = 2;
/// If this amount of packets is lost consecutively, we assume the stream stopped.
const MAX_PACKET_LOSSES: usize = 3;
/// Store the buffer sizes for the last `LAST_BUFFER_SIZE_COUNT` packets.
const LAST_BUFFER_SIZE_COUNT: u8 = 255;
/// The amount of samples to maximally buffer. Equivalent to 0.5 s.
const MAX_BUFFER_SIZE: usize = 48_000 / 2;
/// Maximum number of packets in the queue.
const MAX_BUFFER_PACKETS: usize = 50;
/// Buffer for maximal 0.5 s without playing anything.
const MAX_BUFFER_TIME: usize = 48_000 / 2;
/// Duplicate or remove every `step` sample when speeding-up.
const SPEED_CHANGE_STEPS: usize = 100;
/// The usual amount of samples in a frame.
///
/// Use 48 kHz, 20 ms frames (50 per second) and mono data (1 channel).
/// This means 1920 samples and 7.5 kiB.
const USUAL_FRAME_SIZE: usize = 48000 / 50;
type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
#[error("Failed to create opus decoder: {0}")]
CreateDecoder(#[source] opus2::Error),
#[error("Opus decode failed: {error} (packet: {packet:?})")]
Decode {
#[source]
error: opus2::Error,
packet: Option<Vec<u8>>,
},
#[error("Get duplicate packet id {0}")]
Duplicate(u16),
#[error("Failed to get packet samples: {0}")]
GetPacketSample(#[source] opus2::Error),
#[error("Audio queue is full, dropping")]
QueueFull,
#[error("Audio packet is too late, dropping (wanted {wanted}, got {got})")]
TooLate { wanted: u16, got: u16 },
#[error("Packet has too many samples")]
TooManySamples,
}
#[derive(Clone, Debug)]
struct SlidingWindowMinimum<T: Copy + Default + Ord> {
/// How long a value stays in the sliding window.
size: u8,
/// This is a sliding window minimum, it contains
/// `(insertion time, value)`.
///
/// When we insert a value, we can remove all bigger sample counts,
/// thus the queue always stays sorted with the minimum at the front
/// and the maximum at the back (latest entry).
///
/// Provides amortized O(1) minimum.
/// Source: https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html#sliding-window-minimum-algorithm
queue: VecDeque<(u8, T)>,
/// The current insertion time.
cur_time: u8,
}
#[derive(Debug)]
struct QueuePacket {
packet: VoicePacket,
samples: usize,
id: u16,
}
/// A queue for audio packets for one audio stream.
pub struct AudioQueue {
span: Span,
decoder: Decoder,
pub volume: f32,
/// The id of the next packet that should be decoded.
///
/// Used to check for packet loss.
next_id: u16,
/// If the last packet was a whisper packet.
whispering: bool,
packet_buffer: VecDeque<QueuePacket>,
/// Amount of samples in the `packet_buffer`.
packet_buffer_samples: usize,
/// Temporary buffer that contains the samples of one decoded packet.
decoded_buffer: Vec<f32>,
/// The number of samples in `decoded_buffer` that have been returned.
decoded_pos: usize,
/// The number of samples in the last packet.
last_packet_samples: usize,
/// The last `packet_loss_num` packet decodes were a loss.
packet_loss_num: usize,
/// The amount of samples to buffer until this queue is ready to play.
buffering_samples: usize,
/// The amount of packets in the buffer when a packet was decoded.
///
/// Uses the amount of samples in the `packet_buffer` / `USUAL_PACKET_SAMPLES`.
/// Used to expand or reduce the buffer.
last_buffer_size_min: SlidingWindowMinimum<u8>,
last_buffer_size_max: SlidingWindowMinimum<Reverse<u8>>,
/// Buffered for this duration.
buffered_for_samples: usize,
}
/// Handles incoming audio, has one [`AudioQueue`] per talker.
#[derive(Default)]
pub struct AudioHandler {
queues: HashMap<TalkerId, AudioQueue>,
/// Buffer this amount of samples for new queues before starting to play.
///
/// Updated when a new queue gets added.
avg_buffer_samples: usize,
}
impl<T: Copy + Default + Ord> SlidingWindowMinimum<T> {
fn new(size: u8) -> Self {
Self { size, queue: Default::default(), cur_time: 0 }
}
fn push(&mut self, value: T) {
while self.queue.back().map(|(_, s)| *s >= value).unwrap_or_default() {
self.queue.pop_back();
}
let i = self.cur_time;
self.queue.push_back((i, value));
while self
.queue
.front()
.map(|(i, _)| self.cur_time.wrapping_sub(*i) >= self.size)
.unwrap_or_default()
{
self.queue.pop_front();
}
self.cur_time = self.cur_time.wrapping_add(1);
}
fn get_min(&self) -> T {
self.queue.front().map(|(_, s)| *s).unwrap_or_default()
}
}
impl AudioQueue {
fn new(packet: VoicePacket) -> Result<Self> {
let last_packet_samples =
packet::get_nb_samples(&packet.payload, SAMPLE_RATE).map_err(Error::GetPacketSample)?;
if last_packet_samples > MAX_BUFFER_SIZE {
return Err(Error::TooManySamples);
}
let last_packet_samples = last_packet_samples * CHANNEL_NUM;
let whispering = packet.whisper;
let decoder = Decoder::new(SAMPLE_RATE, CHANNELS).map_err(Error::CreateDecoder)?;
let mut res = Self {
span: Span::current(),
decoder,
volume: 1.0,
next_id: packet.seq,
whispering,
packet_buffer: Default::default(),
packet_buffer_samples: 0,
decoded_buffer: Default::default(),
decoded_pos: 0,
last_packet_samples,
packet_loss_num: 0,
buffering_samples: 0,
last_buffer_size_min: SlidingWindowMinimum::new(LAST_BUFFER_SIZE_COUNT),
last_buffer_size_max: SlidingWindowMinimum::<Reverse<u8>>::new(LAST_BUFFER_SIZE_COUNT),
buffered_for_samples: 0,
};
res.add_buffer_size(0);
res.add_packet(packet)?;
Ok(res)
}
pub fn get_decoder(&self) -> &Decoder {
&self.decoder
}
pub fn is_whispering(&self) -> bool {
self.whispering
}
/// Size is in samples.
fn add_buffer_size(&mut self, size: usize) {
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
self.last_buffer_size_min.push(size);
self.last_buffer_size_max.push(Reverse(size));
} else {
warn!(parent: &self.span, size, "Failed to put amount of packets into an u8");
}
}
/// The approximate deviation of the buffer size.
fn get_deviation(&self) -> u8 {
let min = self.last_buffer_size_min.get_min();
let max = self.last_buffer_size_max.get_min();
max.0 - min
}
fn add_packet(&mut self, packet: VoicePacket) -> Result<()> {
let _span = self.span.enter();
if self.packet_buffer.len() >= MAX_BUFFER_PACKETS {
return Err(Error::QueueFull);
}
let samples;
if packet.is_end() {
// End of stream
samples = 0;
} else {
samples = packet::get_nb_samples(&packet.payload, SAMPLE_RATE)
.map_err(Error::GetPacketSample)?;
if samples > MAX_BUFFER_SIZE {
return Err(Error::TooManySamples);
}
}
let id = packet.seq;
let packet = QueuePacket { packet, samples, id };
if id.wrapping_sub(self.next_id) > MAX_BUFFER_PACKETS as u16 {
return Err(Error::TooLate { wanted: self.next_id, got: id });
}
// Put into first spot where the id is smaller
let i = self.packet_buffer.len()
- self
.packet_buffer
.iter()
.enumerate()
.rev()
.take_while(|(_, p)| p.id.wrapping_sub(id) <= MAX_BUFFER_PACKETS as u16)
.count();
// Check for duplicate packet
if let Some(p) = self.packet_buffer.get(i)
&& p.id == packet.id
{
return Err(Error::Duplicate(p.id));
}
trace!("Insert packet {} at {}", id, i);
let last_id = self.packet_buffer.back().map(|p| p.id.wrapping_add(1)).unwrap_or(id);
if last_id <= id {
self.buffering_samples = self.buffering_samples.saturating_sub(samples);
// Reduce buffering counter by lost packets if there are some
self.buffering_samples = self
.buffering_samples
.saturating_sub(usize::from(id - last_id) * self.last_packet_samples);
}
self.packet_buffer_samples += packet.samples;
self.packet_buffer.insert(i, packet);
Ok(())
}
fn decode_packet(&mut self, packet: Option<&QueuePacket>, fec: bool) -> Result<()> {
let _span = self.span.clone().entered();
trace!(has_packet = packet.is_some(), fec, "Decoding packet");
let packet_data;
let len;
if let Some(p) = packet {
packet_data = &p.packet.payload[..];
len = p.samples;
self.whispering = p.packet.whisper;
} else {
// An empty slice signals packet loss to the decoder
packet_data = &[];
len = self.last_packet_samples;
}
self.packet_loss_num += 1;
let orig_buffer_len = self.decoded_buffer.len();
self.decoded_buffer.resize(orig_buffer_len + len * CHANNEL_NUM, 0.0);
let len = self
.decoder
.decode_float(packet_data, &mut self.decoded_buffer[orig_buffer_len..], fec)
.map_err(|e| Error::Decode {
error: e,
packet: packet.map(|p| p.packet.payload.clone()),
})?;
self.last_packet_samples = len;
self.decoded_buffer.truncate(orig_buffer_len + len * CHANNEL_NUM);
// Update packet_loss_num
if packet.is_some() && !fec {
self.packet_loss_num = 0;
}
// Update last_buffer_size
let mut count = self.packet_buffer_samples;
if let Some(last) = self.packet_buffer.back() {
// Lost packets
trace!(
last.id,
next_id = self.next_id,
first_id = self.packet_buffer.front().unwrap().id,
buffer_len = self.packet_buffer.len(),
"Ids"
);
count += (usize::from(last.id.wrapping_sub(self.next_id)) + 1
- self.packet_buffer.len())
* self.last_packet_samples;
}
self.add_buffer_size(count);
Ok(())
}
/// Decode data and return the requested length of buffered data.
///
/// Returns `true` in the second return value when the stream ended,
/// `false` when it continues normally.
pub fn get_next_data(&mut self, len: usize) -> Result<(&[f32], bool)> {
let _span = self.span.clone().entered();
if self.buffering_samples > 0 {
if self.buffered_for_samples >= MAX_BUFFER_TIME {
self.buffering_samples = 0;
self.buffered_for_samples = 0;
trace!(
buffered_for_samples = self.buffered_for_samples,
buffering_samples = self.buffering_samples,
"Buffered for too long"
);
} else {
self.buffered_for_samples += len;
trace!(
buffered_for_samples = self.buffered_for_samples,
buffering_samples = self.buffering_samples,
"Buffering"
);
return Ok((&[], false));
}
}
// Need to refill buffer
self.decoded_buffer.drain(..self.decoded_pos);
while self.decoded_buffer.len() < len {
trace!(decoded_buffer = self.decoded_buffer.len(), len, "get_next_data");
// Decode a packet
if let Some(packet) = self.packet_buffer.pop_front() {
if packet.packet.is_end() {
// End of stream
return Ok((&self.decoded_buffer, true));
}
self.packet_buffer_samples -= packet.samples;
let cur_id = self.next_id;
self.next_id = self.next_id.wrapping_add(1);
if packet.id != cur_id {
debug_assert!(
packet.id.wrapping_sub(cur_id) < MAX_BUFFER_PACKETS as u16,
"Invalid packet queue state: {} < {}",
packet.id,
cur_id
);
// Packet loss
debug!(need = cur_id, have = packet.id, "Audio packet loss");
if packet.id == self.next_id {
// Can use forward-error-correction
self.decode_packet(Some(&packet), true)?;
} else {
self.decode_packet(None, false)?;
}
self.packet_buffer_samples += packet.samples;
self.packet_buffer.push_front(packet);
} else {
self.decode_packet(Some(&packet), false)?;
}
} else {
debug!("No packets in queue");
// Packet loss or end of stream
self.decode_packet(None, false)?;
}
if self.last_packet_samples == 0 {
break;
}
// Check if we should speed-up playback
let min = self.last_buffer_size_min.get_min();
let dev = self.get_deviation();
if min > (MAX_BUFFER_SIZE / USUAL_FRAME_SIZE) as u8 {
debug!(min, "Truncating buffer");
// Throw out all but min samples
let mut keep_samples = 0;
let keep = self
.packet_buffer
.iter()
.rev()
.take_while(|p| {
keep_samples += p.samples;
keep_samples < usize::from(min) + USUAL_FRAME_SIZE
})
.count();
let len = self.packet_buffer.len() - keep;
self.packet_buffer.drain(..len);
self.packet_buffer_samples = self.packet_buffer.iter().map(|p| p.samples).sum();
if let Some(p) = self.packet_buffer.front() {
self.next_id = p.id;
}
} else if min > dev {
// Speed-up
debug!(
min,
cur_packet_count = self.packet_buffer.len(),
last_packet_samples = self.last_packet_samples,
dev,
"Speed-up buffer"
);
let start = self.decoded_buffer.len() - self.last_packet_samples * CHANNEL_NUM;
for i in 0..(self.last_packet_samples / SPEED_CHANGE_STEPS) {
let i = start + i * (SPEED_CHANGE_STEPS - 1) * CHANNEL_NUM;
self.decoded_buffer.drain(i..(i + CHANNEL_NUM));
}
}
}
self.decoded_pos = len;
Ok((&self.decoded_buffer[..len], false))
}
}
impl AudioHandler {
pub fn new() -> Self {
Default::default()
}
/// Delete all queues
pub fn reset(&mut self) {
self.queues.clear();
}
pub fn get_queues(&self) -> &HashMap<TalkerId, AudioQueue> {
&self.queues
}
pub fn get_mut_queues(&mut self) -> &mut HashMap<TalkerId, AudioQueue> {
&mut self.queues
}
/// `buf` is not cleared before filling it.
///
/// Returns the clients that are not talking anymore.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
self.fill_buffer_with_proc(buf, |_, _| {})
}
/// `buf` is not cleared before filling it.
///
/// Same as [`Self::fill_buffer`] but before merging a queue into the output buffer, a preprocessor
/// function is called. The queue volume is applied after calling the preprocessor.
///
/// Returns the clients that are not talking anymore.
pub fn fill_buffer_with_proc<F: FnMut(&TalkerId, &[f32])>(
&mut self,
buf: &mut [f32],
mut handle: F,
) -> Vec<TalkerId> {
trace!(len = buf.len(), "Filling audio buffer");
let mut to_remove = Vec::new();
for (id, queue) in self.queues.iter_mut() {
if queue.packet_loss_num >= MAX_PACKET_LOSSES {
debug!(packet_loss_num = queue.packet_loss_num, "Removing talker");
to_remove.push(*id);
continue;
}
let vol = queue.volume;
match queue.get_next_data(buf.len()) {
Err(error) => {
warn!(%error, "Failed to decode audio packet");
}
Ok((r, is_end)) => {
handle(id, r);
for i in 0..r.len() {
buf[i] += r[i] * vol;
}
if is_end {
to_remove.push(*id);
}
}
}
}
for id in &to_remove {
self.queues.remove(id);
}
to_remove
}
/// Add a packet to the queue of its talker.
///
/// If a new talker started talking, returns its id.
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>> {
let id = packet.talker;
let empty = packet.is_end();
if let Some(queue) = self.queues.get_mut(&id) {
queue.add_packet(packet)?;
Ok(None)
} else {
if empty {
return Ok(None);
}
let _span = info_span!("audio queue", client = ?id);
trace!("Adding talker");
let mut queue = AudioQueue::new(packet)?;
if !self.queues.is_empty() {
// Update avg_buffer_samples
let total: usize = self
.queues
.values()
.map(|q| usize::from(q.last_buffer_size_min.get_min()))
.sum();
self.avg_buffer_samples = USUAL_FRAME_SIZE + total / self.queues.len();
}
queue.buffering_samples = self.avg_buffer_samples;
self.queues.insert(id, queue);
Ok(Some(id))
}
}
}
#[cfg(test)]
mod test {
use opus2::Encoder;
use super::*;
use crate::packet::VoiceCodec;
type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
const ID: TalkerId = TalkerId(0);
fn packet(seq: u16, payload: &[u8]) -> VoicePacket {
VoicePacket {
talker: ID,
seq,
codec: VoiceCodec::Music,
whisper: false,
payload: payload.to_vec(),
}
}
enum SimulateAction {
CreateEncoder,
/// Create packet with id.
///
/// The `bool` is `false` if packet handling should fail.
ReceivePacket(u16, bool),
ReceiveRaw(u16, Vec<u8>),
/// Fetch audio of this sample count and expect a certain packet id.
FillBuffer(usize, Option<u16>),
/// Custom check
Check(Box<dyn FnOnce(&AudioHandler)>),
}
fn simulate(actions: Vec<SimulateAction>) -> TestResult {
let mut encoder = None;
let mut opus_output = [0; 1275]; // Max size for an opus packet
let mut handler = AudioHandler::new();
for a in actions {
println!("\nCurrent state");
for q in &handler.queues {
print!("Queue {:?}:", q.0);
for p in &q.1.packet_buffer {
print!(" {:?},", p);
}
println!();
}
match a {
SimulateAction::CreateEncoder => {
encoder = Some(Encoder::new(
48_000,
opus2::Channels::Mono,
opus2::Application::Voip,
)?);
}
SimulateAction::ReceivePacket(i, success) => {
let e = encoder.as_mut().unwrap();
let data = vec![i as f32; USUAL_FRAME_SIZE];
let len = e.encode_float(&data, &mut opus_output[..])?;
if handler.handle_packet(packet(i, &opus_output[..len])).is_ok() != success {
return Err(format!(
"handle_packet returned {:?} but expected {:?}",
!success, success
)
.into());
}
}
SimulateAction::ReceiveRaw(i, data) => {
let _ = handler.handle_packet(packet(i, &data));
}
SimulateAction::FillBuffer(size, expect) => {
let mut buf = vec![0.0; size * 2]; // Stereo
let cur_packet_id =
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
handler.fill_buffer(&mut buf);
let next_packet_id =
handler.queues.get(&ID).and_then(|q| q.packet_buffer.front()).map(|p| p.id);
if expect.is_some() {
assert_eq!(expect, cur_packet_id);
assert_ne!(cur_packet_id, next_packet_id);
}
}
SimulateAction::Check(f) => {
f(&handler);
}
}
}
Ok(())
}
#[test]
fn sliding_window_minimum() {
let data = &[
(5, 5),
(6, 5),
(3, 3),
(4, 3),
(6, 3),
(5, 3),
(6, 3),
(6, 4),
(6, 5),
(6, 5),
(6, 6),
(7, 6),
(5, 5),
];
let mut window = SlidingWindowMinimum::new(5);
assert_eq!(window.get_min(), 0);
for (i, (val, min)) in data.iter().enumerate() {
println!("{:?}", window);
window.push(*val);
assert_eq!(window.get_min(), *min, "Failed in iteration {} ({:?})", i, window);
}
}
#[test]
fn sliding_window_minimum_full() {
let mut window = SlidingWindowMinimum::new(255);
window.push(1);
assert_eq!(window.get_min(), 1);
for _ in 0..254 {
window.push(2);
}
assert_eq!(window.get_min(), 1);
window.push(2);
assert_eq!(window.get_min(), 2);
}
#[test]
fn packets_wrapping() {
let mut handler = AudioHandler::new();
let mut buf = vec![0.0; 48_000 / 100 * 2];
for i in 0..100 {
let seq = 65_500u16.wrapping_add(i);
handler.handle_packet(packet(seq, &[0, 0, 0, 0, 0, 0, 0])).unwrap();
if i > 5 {
handler.fill_buffer(&mut buf);
}
}
}
/// Short and malformed packets of any content are errors, never panics.
#[test]
fn short_packet_fuzz() {
let mut handler = AudioHandler::new();
let mut buf = vec![0.0; 48_000 / 100 * 2];
let mut state = 0x2545_f491_4f6c_dd1du64;
let mut next = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
for _ in 0..3_000 {
// Payloads of 0..=100 bytes: empty, a lone TOC byte, and frames of any shape.
let len = (next() % 101) as usize;
let payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
let _ = handler.handle_packet(packet(30, &payload));
handler.fill_buffer(&mut buf);
handler.fill_buffer(&mut buf);
}
}
#[test]
fn packets_wrapping2() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 0..100 {
let i = 65_500u16.wrapping_add(i);
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn silence() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for _ in 0..100 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
simulate(a)
}
#[test]
fn reversed() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 0..5 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
a.push(SimulateAction::ReceivePacket(4, false));
a.push(SimulateAction::ReceivePacket(3, false));
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn duplicate() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
a.push(SimulateAction::ReceivePacket(0, true));
a.push(SimulateAction::ReceivePacket(0, false));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(0)));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
simulate(a)
}
#[test]
fn big_whole() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 27120..27124 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
a.push(SimulateAction::ReceiveRaw(27124, vec![2]));
for _ in 0..10 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
for i in 27339..27349 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn end_packet() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
for i in 0..10 {
a.push(SimulateAction::ReceivePacket(i, true));
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, Some(i)));
}
a.push(SimulateAction::ReceiveRaw(10, vec![]));
for _ in 0..4 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn packet_loss() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
a.push(SimulateAction::ReceivePacket(50, true));
a.push(SimulateAction::ReceivePacket(53, true));
for _ in 0..8 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
#[test]
fn packet_wrapping_loss() -> TestResult {
let mut a = vec![SimulateAction::CreateEncoder];
a.push(SimulateAction::ReceivePacket(65534, true));
a.push(SimulateAction::ReceivePacket(0, true));
for _ in 0..7 {
a.push(SimulateAction::FillBuffer(USUAL_FRAME_SIZE, None));
}
a.push(SimulateAction::Check(Box::new(|h| assert!(h.queues.is_empty()))));
simulate(a)
}
/// The talker is the key of the queues, and a new one is reported once.
#[test]
fn talkers_have_their_own_queues() -> TestResult {
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
let mut out = [0; 1275];
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
let from = |talker: u16, seq: u16| VoicePacket {
talker: TalkerId(talker),
seq,
codec: VoiceCodec::Voice,
whisper: false,
payload: out[..len].to_vec(),
};
let mut handler = AudioHandler::new();
assert_eq!(handler.handle_packet(from(7, 100))?, Some(TalkerId(7)));
assert_eq!(handler.handle_packet(from(7, 101))?, None);
assert_eq!(handler.handle_packet(from(9, 5))?, Some(TalkerId(9)));
let mut talkers: Vec<_> = handler.get_queues().keys().map(|t| t.0).collect();
talkers.sort_unstable();
assert_eq!(talkers, [7, 9]);
// A talker that only says goodbye never gets a queue.
let end = VoicePacket { payload: vec![], ..from(11, 0) };
assert_eq!(handler.handle_packet(end)?, None);
assert_eq!(handler.get_queues().len(), 2);
Ok(())
}
/// A queue knows whether the last packet it played was a whisper.
#[test]
fn whisper_flag_follows_the_packets() -> TestResult {
let mut encoder = Encoder::new(48_000, opus2::Channels::Mono, opus2::Application::Voip)?;
let mut out = [0; 1275];
let len = encoder.encode_float(&vec![0.1; USUAL_FRAME_SIZE], &mut out)?;
let packet = |seq: u16, whisper: bool| VoicePacket {
talker: ID,
seq,
codec: VoiceCodec::Voice,
whisper,
payload: out[..len].to_vec(),
};
let mut handler = AudioHandler::new();
handler.handle_packet(packet(0, true))?;
assert!(handler.get_queues()[&ID].is_whispering());
handler.handle_packet(packet(1, false))?;
// One packet is played per call.
let mut buf = [0.0; USUAL_FRAME_SIZE * 2];
handler.fill_buffer(&mut buf);
handler.fill_buffer(&mut buf);
assert!(!handler.get_queues()[&ID].is_whispering());
Ok(())
}
}
+11 -5
View File
@@ -1,14 +1,17 @@
//! Voice pipeline building blocks.
//!
//! - [`pcm`]: sample-rate constants, tone generation and detection helpers
//! - [`encode`]: Opus encoding of 20 ms frames into TeamSpeak voice packets
//! - [`packet`]: the voice packet types the pipeline takes and produces
//! ([`VoicePacket`], [`EncodedVoice`]), independent of the transport
//! - [`encode`]: Opus encoding of 20 ms frames into [`EncodedVoice`]
//! - [`framer`]: slice an arbitrary sample stream into codec frames
//! - [`resample`]: sample-rate conversion to the 48 kHz the codec uses
//! - [`wav`]: WAV file input/output
//! - [`process`]: echo cancellation, noise suppression and gain control
//! - [`vad`]: voice activity detection
//! - [`mixer`]: per-client jitter buffer, decoder, volume and mixing (on the
//! vendored `tsclientlib::audio::AudioHandler`)
//! - [`jitter`]: the per-talker jitter buffer and Opus decoder
//! - [`mixer`]: per-talker volume, mute and priority dimming over the jitter
//! buffer, mixing to stereo
//! - [`settings`]: all user audio settings in one serde struct
//! - [`tap`]: the processed microphone for other consumers (the stream
//! mixer), free while nobody listens
@@ -17,7 +20,9 @@
pub mod encode;
pub mod framer;
pub mod jitter;
pub mod mixer;
pub mod packet;
pub mod pcm;
pub mod process;
pub mod resample;
@@ -29,12 +34,13 @@ pub mod wav;
#[cfg(feature = "device")]
pub mod device;
pub use encode::{VoiceCodec, VoiceEncoder};
pub use encode::VoiceEncoder;
pub use framer::Framer;
pub use jitter::AudioHandler;
pub use mixer::Mixer;
pub use packet::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
pub use process::{ProcessingSettings, Processor};
pub use settings::AudioSettings;
pub use tsclientlib::audio::AudioHandler;
pub use vad::{Vad, VadSettings};
#[derive(Debug, thiserror::Error)]
+62 -67
View File
@@ -1,9 +1,9 @@
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
//! volume and mute per client, and everyone else dimmed while a priority
//! Incoming voice: per-talker jitter buffer, decoder and mixer, with a
//! volume and mute per talker, and everyone else dimmed while a priority
//! speaker talks.
//!
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
//! sender it keeps a queue of Opus packets and adapts its length:
//! The jitter buffer is [`AudioHandler`]. Per sender it keeps a queue of Opus
//! packets and adapts its length:
//!
//! - a new talker starts after a pre-buffer derived from the queue lengths of
//! the other talkers (none for the first one);
@@ -21,13 +21,11 @@
use std::collections::{HashMap, HashSet};
use tsclientlib::ClientId;
use tsclientlib::audio::{AudioHandler, Error as QueueError};
use tsproto_packets::packets::InAudioBuf;
use crate::jitter::{AudioHandler, Error as QueueError};
use crate::packet::{TalkerId, VoicePacket};
use crate::pcm::FRAME_SAMPLES;
/// Loudest per-client volume: +12 dB.
/// Loudest per-talker volume: +12 dB.
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
/// Most a priority speaker dims the others (dB).
const MAX_DIMM_DB: f32 = -60.0;
@@ -35,14 +33,14 @@ const MAX_DIMM_DB: f32 = -60.0;
/// samples (5 frames, 100 ms) instead of jumping.
const DIMM_RAMP_SAMPLES: usize = 5 * FRAME_SAMPLES;
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
/// Jitter buffer, decoder and mixer for incoming voice, keyed by talker.
/// Output is interleaved stereo at 48 kHz.
pub struct Mixer {
handler: AudioHandler<ClientId>,
volumes: HashMap<ClientId, f32>,
muted: HashSet<ClientId>,
handler: AudioHandler,
volumes: HashMap<TalkerId, f32>,
muted: HashSet<TalkerId>,
/// While one of them talks, everyone else is dimmed.
priority: HashSet<ClientId>,
priority: HashSet<TalkerId>,
/// Linear gain of the others while a priority speaker talks (1: none).
dimm: f32,
/// How far the dimming has faded in (0..=1).
@@ -70,21 +68,17 @@ impl Mixer {
Self::default()
}
/// Queue a voice packet from `id`. Returns `Some(id)` when this client
/// just started talking. Late, duplicate and malformed packets are
/// errors; on UDP they are expected and can be ignored.
pub fn handle_packet(
&mut self,
id: ClientId,
packet: InAudioBuf,
) -> Result<Option<ClientId>, QueueError> {
self.handler.handle_packet(id, packet)
/// Queue a voice packet for its talker. Returns `Some(talker)` when this
/// talker just started talking. Late, duplicate and malformed packets are
/// errors; on datagrams they are expected and can be ignored.
pub fn handle_packet(&mut self, packet: VoicePacket) -> Result<Option<TalkerId>, QueueError> {
self.handler.handle_packet(packet)
}
/// Add the next `buf.len() / 2` stereo frames of all talkers to `buf`
/// (not cleared first), each scaled by its volume, and dimmed while a
/// priority speaker talks. Returns the clients that stopped talking.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
/// priority speaker talks. Returns the talkers that stopped talking.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<TalkerId> {
let queues = self.handler.get_mut_queues();
// A priority speaker with a queue (talking or buffering) dims all
// other queues, streams too, unless we muted it.
@@ -141,9 +135,9 @@ impl Mixer {
stopped
}
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
/// Kept when the client stops and starts talking again.
pub fn set_volume(&mut self, id: ClientId, volume: f32) {
/// Linear gain for one talker, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
/// Kept when the talker stops and starts talking again.
pub fn set_volume(&mut self, id: TalkerId, volume: f32) {
let volume = if volume.is_finite() { volume.clamp(0.0, MAX_CLIENT_VOLUME) } else { 1.0 };
if volume == 1.0 {
self.volumes.remove(&id);
@@ -153,15 +147,15 @@ impl Mixer {
}
/// Like [`set_volume`](Self::set_volume), in dB (0 dB = unchanged).
pub fn set_volume_db(&mut self, id: ClientId, db: f32) {
pub fn set_volume_db(&mut self, id: TalkerId, db: f32) {
self.set_volume(id, 10f32.powf(db / 20.0));
}
pub fn volume(&self, id: ClientId) -> f32 {
pub fn volume(&self, id: TalkerId) -> f32 {
self.volumes.get(&id).copied().unwrap_or(1.0)
}
pub fn set_muted(&mut self, id: ClientId, muted: bool) {
pub fn set_muted(&mut self, id: TalkerId, muted: bool) {
if muted {
self.muted.insert(id);
} else {
@@ -169,30 +163,30 @@ impl Mixer {
}
}
pub fn is_muted(&self, id: ClientId) -> bool {
pub fn is_muted(&self, id: TalkerId) -> bool {
self.muted.contains(&id)
}
/// The priority speakers, and how much everyone else is dimmed while
/// one of them talks: dB, clamped to -60..=0 (NaN: not at all).
/// Replaces the previous set; [`forget`](Self::forget) leaves it alone,
/// the caller sends a new set when the clients change.
pub fn set_priority(&mut self, clients: impl IntoIterator<Item = ClientId>, dimm_db: f32) {
self.priority = clients.into_iter().collect();
/// the caller sends a new set when the talkers change.
pub fn set_priority(&mut self, talkers: impl IntoIterator<Item = TalkerId>, dimm_db: f32) {
self.priority = talkers.into_iter().collect();
let db = if dimm_db.is_nan() { 0.0 } else { dimm_db.clamp(MAX_DIMM_DB, 0.0) };
self.dimm = 10f32.powf(db / 20.0);
}
/// Forget volume and mute of a client (e.g. it left the server; client
/// ids are reused).
pub fn forget(&mut self, id: ClientId) {
/// Forget volume and mute of a talker (e.g. it left the server; ids may
/// be reused).
pub fn forget(&mut self, id: TalkerId) {
self.volumes.remove(&id);
self.muted.remove(&id);
self.handler.get_mut_queues().remove(&id);
}
/// Clients with a queue, i.e. currently talking or buffering.
pub fn talkers(&self) -> impl Iterator<Item = ClientId> + '_ {
/// Talkers with a queue, i.e. currently talking or buffering.
pub fn talkers(&self) -> impl Iterator<Item = TalkerId> + '_ {
self.handler.get_queues().keys().copied()
}
@@ -202,7 +196,7 @@ impl Mixer {
}
/// The underlying jitter buffer.
pub fn handler(&self) -> &AudioHandler<ClientId> {
pub fn handler(&self) -> &AudioHandler {
&self.handler
}
}
@@ -221,23 +215,26 @@ impl std::fmt::Debug for Mixer {
#[cfg(test)]
mod tests {
use tsproto_packets::packets::{AudioData, CodecType, Direction, OutAudio};
use super::*;
use crate::VoiceEncoder;
use crate::encode::VoiceCodec;
use crate::packet::VoiceCodec;
use crate::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
fn packet(from: u16, id: u16, data: &[u8]) -> InAudioBuf {
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap()
fn packet(from: u16, seq: u16, data: &[u8]) -> VoicePacket {
VoicePacket {
talker: TalkerId(from),
seq,
codec: VoiceCodec::Voice,
whisper: false,
payload: data.to_vec(),
}
}
/// Two clients send tones at the same level; after setting volumes the
/// mix carries each at its own gain, and a muted one not at all.
#[test]
fn volume_per_client() {
let (a, b) = (ClientId(3), ClientId(4));
let (a, b) = (TalkerId(3), TalkerId(4));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_b = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone_a = pcm::sine(500.0, 2.0, 0.2);
@@ -251,11 +248,11 @@ mod tests {
let frames = tone_a.chunks_exact(FRAME_SAMPLES).zip(tone_b.chunks_exact(FRAME_SAMPLES));
for (i, (fa, fb)) in frames.enumerate() {
let id = i as u16;
let started = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let started = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
if i == 0 {
assert_eq!(started.unwrap(), Some(a));
}
mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap())).unwrap();
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
@@ -274,8 +271,8 @@ mod tests {
let id = 100 + i;
let fa = &tone_a[..FRAME_SAMPLES];
let fb = &tone_b[..FRAME_SAMPLES];
let _ = mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let _ = mixer.handle_packet(b, packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
let _ = mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(fa).unwrap()));
let _ = mixer.handle_packet(packet(4, id, enc_b.encode_to_bytes(fb).unwrap()));
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
@@ -289,7 +286,7 @@ mod tests {
/// in and out, but not itself, and not while we muted it.
#[test]
fn priority_speaker_dims_others() {
let (a, p) = (ClientId(3), ClientId(5));
let (a, p) = (TalkerId(3), TalkerId(5));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone_a = pcm::sine(500.0, 4.0, 0.2);
@@ -308,14 +305,12 @@ mod tests {
let mut out = Vec::new();
for _ in 0..frames {
let fa = frame(&tone_a, id_a);
mixer
.handle_packet(a, packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap()))
.unwrap();
mixer.handle_packet(packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap())).unwrap();
id_a += 1;
if with_p {
let fp = frame(&tone_p, id_p);
let data = enc_p.encode_to_bytes(&fp).unwrap();
mixer.handle_packet(p, packet(5, id_p, data)).unwrap();
mixer.handle_packet(packet(5, id_p, data)).unwrap();
id_p += 1;
}
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
@@ -359,7 +354,7 @@ mod tests {
/// frame: the other talker's level (per period of its tone) never jumps.
#[test]
fn priority_dimming_ramps_per_sample() {
let (a, p) = (ClientId(3), ClientId(5));
let p = TalkerId(5);
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone = pcm::sine(500.0, 2.0, 0.2);
@@ -371,10 +366,10 @@ mod tests {
// p talks from frame 30 to 59.
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
let id = i as u16;
mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
mixer.handle_packet(packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
if let Some(j) = i.checked_sub(30).filter(|j| *j < 30) {
let data = enc_p.encode_to_bytes(frame).unwrap();
mixer.handle_packet(p, packet(5, j as u16, data)).unwrap();
mixer.handle_packet(packet(5, j as u16, data)).unwrap();
}
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
@@ -400,17 +395,17 @@ mod tests {
fn priority_dimm_bounds() {
let mut mixer = Mixer::new();
assert_eq!(mixer.dimm, 1.0);
mixer.set_priority([ClientId(1)], -18.0);
mixer.set_priority([TalkerId(1)], -18.0);
assert!((mixer.dimm - 0.1259).abs() < 1e-3);
mixer.set_priority([ClientId(1)], 6.0);
mixer.set_priority([TalkerId(1)], 6.0);
assert_eq!(mixer.dimm, 1.0);
mixer.set_priority([ClientId(1)], f32::NEG_INFINITY);
mixer.set_priority([TalkerId(1)], f32::NEG_INFINITY);
assert!((mixer.dimm - 0.001).abs() < 1e-6);
mixer.set_priority([ClientId(1)], f32::NAN);
mixer.set_priority([TalkerId(1)], f32::NAN);
assert_eq!(mixer.dimm, 1.0);
// Forgetting a client keeps the set: the caller replaces it.
mixer.forget(ClientId(1));
assert!(mixer.priority.contains(&ClientId(1)));
mixer.forget(TalkerId(1));
assert!(mixer.priority.contains(&TalkerId(1)));
mixer.set_priority([], -18.0);
assert!(mixer.priority.is_empty());
}
@@ -418,7 +413,7 @@ mod tests {
#[test]
fn volume_bounds_and_forget() {
let mut mixer = Mixer::new();
let id = ClientId(9);
let id = TalkerId(9);
mixer.set_volume(id, 100.0);
assert_eq!(mixer.volume(id), MAX_CLIENT_VOLUME);
mixer.set_volume(id, -1.0);
+101
View File
@@ -0,0 +1,101 @@
//! Voice packets as the audio pipeline sees them, whatever transport carries
//! them (the TeamSpeak connection today, a Voelin server later).
//!
//! The transport adapter turns what it receives into a [`VoicePacket`] and
//! what [`VoiceEncoder`](crate::VoiceEncoder) produces ([`EncodedVoice`])
//! into its own wire format; nothing in this crate knows either format.
use crate::pcm::FRAME_SAMPLES;
/// Who is talking: a sender id, unique among the talkers of one voice
/// connection. A transport maps its own client ids onto it (TeamSpeak's
/// 16-bit client id is used as is).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TalkerId(pub u16);
/// The two Opus flavours voice is sent in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VoiceCodec {
/// Mono, tuned for speech.
Voice,
/// Stereo, tuned for music.
Music,
}
impl VoiceCodec {
pub fn channels(self) -> usize {
match self {
VoiceCodec::Voice => 1,
VoiceCodec::Music => 2,
}
}
/// Samples (all channels) in one 20 ms frame.
pub fn frame_len(self) -> usize {
FRAME_SAMPLES * self.channels()
}
}
/// A voice packet received from a talker.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VoicePacket {
pub talker: TalkerId,
/// Packet number of this talker, counting up by one per 20 ms frame and
/// wrapping at 65536; the jitter buffer orders by it and finds gaps.
pub seq: u16,
pub codec: VoiceCodec,
/// Sent to us as a whisper instead of to the whole channel.
pub whisper: bool,
/// One Opus packet. An empty one ends the talk (a single byte counts as
/// empty too: some servers send one).
pub payload: Vec<u8>,
}
impl VoicePacket {
/// Whether this packet only ends the talk and carries no audio.
pub fn is_end(&self) -> bool {
self.payload.len() <= 1
}
}
/// One encoded frame to send. The transport assigns the packet number.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncodedVoice {
pub codec: VoiceCodec,
/// One Opus packet; empty: the transmission ended.
pub payload: Vec<u8>,
}
impl EncodedVoice {
/// Whether this only tells listeners the transmission ended.
pub fn is_end(&self) -> bool {
self.payload.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codec_frames() {
assert_eq!(VoiceCodec::Voice.frame_len(), FRAME_SAMPLES);
assert_eq!(VoiceCodec::Music.frame_len(), FRAME_SAMPLES * 2);
}
#[test]
fn end_of_talk() {
let voice = |payload: &[u8]| VoicePacket {
talker: TalkerId(1),
seq: 0,
codec: VoiceCodec::Voice,
whisper: false,
payload: payload.to_vec(),
};
assert!(voice(&[]).is_end());
assert!(voice(&[2]).is_end());
assert!(!voice(&[2, 3]).is_end());
assert!(EncodedVoice { codec: VoiceCodec::Voice, payload: vec![] }.is_end());
assert!(!EncodedVoice { codec: VoiceCodec::Voice, payload: vec![0] }.is_end());
}
}
+10 -12
View File
@@ -7,10 +7,8 @@
//! loss. Every 30 s it sends a loud marker frame instead of the quiet one;
//! the latency is the time from generating a marker to it leaving the mixer.
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
use voelin_audio::pcm::{FRAME_SAMPLES, SAMPLE_RATE, energy, sine, white_noise};
use voelin_audio::{Mixer, VoiceCodec, VoiceEncoder};
use voelin_audio::{Mixer, TalkerId, VoiceCodec, VoiceEncoder, VoicePacket};
/// The receiver pulls 10 ms at a time, like a playback loop.
const PULL: usize = SAMPLE_RATE as usize / 100;
@@ -38,7 +36,7 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
let mut rng = Rng(ppm.to_bits());
let mut mixer = Mixer::new();
let client = ClientId(5);
let talker = TalkerId(5);
let total = (hours * 3600.0 * SAMPLE_RATE as f64) as u64;
// Sender frame n is made at n * 20 ms of the sender's clock.
let frame_time = |n: u64| n as f64 * FRAME_SAMPLES as f64 / (1.0 + ppm * 1e-6);
@@ -68,15 +66,15 @@ fn simulate(ppm: f64, hours: f64) -> Vec<f64> {
let arrived = in_flight.partition_point(|&(t, _)| t <= now as f64);
for (_, n) in in_flight.drain(..arrived) {
let data = if n % MARKER_EVERY == MARKER_EVERY / 2 { &marker } else { &quiet };
let packet = OutAudio::new(&AudioData::S2C {
id: n as u16,
codec: CodecType::OpusVoice,
from: 5,
data,
});
let packet = InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap();
let packet = VoicePacket {
talker,
seq: n as u16,
codec: VoiceCodec::Voice,
whisper: false,
payload: data.clone(),
};
// Late packets are dropped by the jitter buffer, as on a real network.
let _ = mixer.handle_packet(client, packet);
let _ = mixer.handle_packet(packet);
}
out.fill(0.0);
+17 -6
View File
@@ -14,8 +14,9 @@ default = ["audio-device"]
audio-device = ["voelin-audio/device"]
# The `media` module: capture and video codecs for streams, with whatever
# voelin-media backends are enabled (e.g. MediaCodec and a registered capture
# source on Android).
media = ["dep:voelin-media"]
# source on Android), and the studio's WHIP output. The crate itself is always
# there: the stream types in the API (`EncodedFrame`, `LayerSpec`) are its.
media = ["voelin-media/whip"]
# `media` with voelin-media's desktop backends: libvpx, dav1d, OpenH264 and
# FFmpeg loaded at runtime, X11 and PipeWire on Linux. Not for Android
# (libvpx does not cross-compile there).
@@ -24,6 +25,8 @@ media-desktop = ["media", "voelin-media/default"]
[dependencies]
anyhow = "1"
base64 = "0.22"
# The RTP packets of the session seam (`voelin_proto::link::MediaPacket`).
bytes = "1"
dirs = "6"
futures = "0.3"
# Finding a server's gateway in DNS (the voice resolver's version).
@@ -49,11 +52,17 @@ toml = "1.1.6"
tracing = "0.1"
voelin-audio = { path = "../voelin-audio", default-features = false }
voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] }
voelin-media = { path = "../voelin-media", default-features = false, features = ["str0m", "whip"], optional = true }
voelin-model = { path = "../voelin-model" }
# `IdentityBlob`, the identity of the API (a TeamSpeak identity as the key store
# keeps it, or a Voelin key).
voelin-identity = { workspace = true }
voelin-media = { path = "../voelin-media", default-features = false }
voelin-model = { workspace = true }
voelin-observer = { path = "../voelin-observer" }
# Paths only (the cache directory).
voelin-platform = { path = "../voelin-platform", default-features = false }
# The backend-neutral session seam the engine consumes (`voelin_proto::link`)
# and the v1 messages it speaks.
voelin-proto = { workspace = true }
voelin-query = { path = "../voelin-query" }
voelin-store = { path = "../voelin-store" }
voelin-stream = { path = "../voelin-stream" }
@@ -64,13 +73,15 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
tsproto-types = { path = "../proto/tsproto-types" }
[dev-dependencies]
# An HTTP/2 connection in a test (both already in the tree through h2).
bytes = "1"
# An HTTP/2 connection in a test (already in the tree through h2).
http = "1"
# Already in the app's graph (reqwest); for one_rustls_crypto_provider.
rustls = { version = "0.23", default-features = false }
# `process`: the browser interop test drives Chromium through Node.js.
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
# The fakes of the session seam (`FakeHost`, `FakeSession`, the conformance
# suite).
voelin-proto = { workspace = true, features = ["test-util"] }
[lints]
workspace = true
+46 -49
View File
@@ -16,16 +16,18 @@ use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tracing::{debug, warn};
use tsclientlib::ClientId;
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio, OutPacket};
use voelin_audio::pcm::{self, FRAME_SAMPLES};
use voelin_audio::settings::TransmitMode;
use voelin_audio::tap;
use voelin_audio::vad::SILENCE_DB;
use voelin_audio::{AudioSettings, Framer, Mixer, Processor, Vad, VoiceCodec, VoiceEncoder};
use voelin_audio::{
AudioSettings, EncodedVoice, Framer, Mixer, Processor, TalkerId, Vad, VoiceCodec, VoiceEncoder,
VoicePacket,
};
pub(crate) enum AudioIn {
Packet(InAudioBuf),
/// Voice of a talker, from the voice connection.
Packet(VoicePacket),
Transmit(bool),
InputMuted(bool),
OutputMuted(bool),
@@ -33,19 +35,19 @@ pub(crate) enum AudioIn {
Settings(Box<AudioSettings>),
/// Playback volume of one client, linear (1 = unchanged, up to 4).
ClientVolume {
client: ClientId,
client: TalkerId,
volume: f32,
},
ClientMuted {
client: ClientId,
client: TalkerId,
muted: bool,
},
/// The client left; client ids are reused, so forget its volume.
ClientLeft(ClientId),
ClientLeft(TalkerId),
/// The priority speakers: while one talks, everyone else (streams too)
/// is dimmed by `dimm_db` (the server's setting, e.g. -18).
PrioritySpeakers {
clients: Vec<ClientId>,
clients: Vec<TalkerId>,
dimm_db: f32,
},
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
@@ -111,10 +113,10 @@ pub(crate) const LEVEL_INTERVAL: Duration = Duration::from_millis(100);
/// Samples of one 20 ms Opus frame at 48 kHz: the unit of stream packet ids.
const OPUS_FRAME: u64 = 960;
/// Start the audio thread. Encoded packets go to `outgoing`; problems (e.g.
/// Start the audio thread. Encoded voice goes to `outgoing`; problems (e.g.
/// no device) and the microphone level are reported through `events`.
pub(crate) fn spawn(
outgoing: mpsc::UnboundedSender<OutPacket>,
outgoing: mpsc::UnboundedSender<EncodedVoice>,
events: mpsc::UnboundedSender<AudioEvent>,
settings: AudioSettings,
) -> AudioHandle {
@@ -126,9 +128,9 @@ pub(crate) fn spawn(
AudioHandle { tx }
}
/// Audio of a watched stream in the mixer, under a made-up client id.
/// Audio of a watched stream in the mixer, under a made-up talker id.
struct StreamAudio {
client: ClientId,
client: TalkerId,
/// RTP time and packet id of the last packet.
last: Option<(u64, u64)>,
}
@@ -190,11 +192,7 @@ impl Pipeline {
fn handle(&mut self, msg: AudioIn) {
match msg {
AudioIn::Packet(packet) => {
let from = match packet.data().data() {
AudioData::S2C { from, .. } | AudioData::S2CWhisper { from, .. } => *from,
_ => return,
};
if let Err(error) = self.mixer.handle_packet(ClientId(from), packet) {
if let Err(error) = self.mixer.handle_packet(packet) {
debug!(%error, "dropped voice packet");
}
}
@@ -241,8 +239,8 @@ impl Pipeline {
let client = match self.streams.get(&stream) {
Some(s) => s.client,
None => {
let used: Vec<ClientId> = self.streams.values().map(|s| s.client).collect();
let Some(client) = (0..=u16::MAX).rev().map(ClientId).find(|c| !used.contains(c))
let used: Vec<TalkerId> = self.streams.values().map(|s| s.client).collect();
let Some(client) = (0..=u16::MAX).rev().map(TalkerId).find(|c| !used.contains(c))
else {
return;
};
@@ -263,19 +261,15 @@ impl Pipeline {
}
};
entry.last = Some((time, id));
let packet = OutAudio::new(&AudioData::S2C {
id: id as u16,
codec: CodecType::OpusMusic,
from: client.0,
data,
});
match InAudioBuf::try_new(Direction::S2C, packet.into_vec()) {
Ok(packet) => {
if let Err(error) = self.mixer.handle_packet(client, packet) {
debug!(%error, "dropped stream audio packet");
}
}
Err(error) => debug!(?error, "stream audio packet"),
let packet = VoicePacket {
talker: client,
seq: id as u16,
codec: VoiceCodec::Music,
whisper: false,
payload: data.to_vec(),
};
if let Err(error) = self.mixer.handle_packet(packet) {
debug!(%error, "dropped stream audio packet");
}
}
@@ -286,7 +280,7 @@ impl Pipeline {
/// Microphone audio in (mono, 48 kHz, any length); voice packets out.
/// `delay_ms` is the playback-to-capture delay hint for the echo canceller.
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(OutPacket)) {
fn capture(&mut self, samples: &[f32], delay_ms: u32, send: &mut impl FnMut(EncodedVoice)) {
self.processor.set_delay_ms(delay_ms);
self.processed.clear();
self.processor.capture(samples, &mut self.processed);
@@ -308,7 +302,7 @@ impl Pipeline {
}
}
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(OutPacket)) {
fn transmit(&mut self, frame: Vec<f32>, send: &mut impl FnMut(EncodedVoice)) {
// Always analysed, so the detector's state is current when needed.
let voice = self.vad.process(&frame);
let level = self.vad.level_db().max(SILENCE_DB);
@@ -369,7 +363,7 @@ fn sanitize(mut settings: AudioSettings) -> AudioSettings {
fn run(
rx: std_mpsc::Receiver<AudioIn>,
outgoing: mpsc::UnboundedSender<OutPacket>,
outgoing: mpsc::UnboundedSender<EncodedVoice>,
events: mpsc::UnboundedSender<AudioEvent>,
settings: AudioSettings,
) {
@@ -445,11 +439,10 @@ fn run(
#[cfg(feature = "audio-device")]
mod devices {
use tracing::debug;
use tsproto_packets::packets::OutPacket;
use voelin_audio::AudioSettings;
use voelin_audio::device::{Capture, DeviceEvent, Managed, Playback};
use voelin_audio::pcm::{self, FRAME_SAMPLES, SAMPLE_RATE};
use voelin_audio::resample::Linear;
use voelin_audio::{AudioSettings, EncodedVoice};
use super::{DEVICE_LATENCY_MS, PLAYBACK_CAPACITY_MS, Pipeline};
@@ -509,7 +502,7 @@ mod devices {
pub fn step(
&mut self,
pipeline: &mut Pipeline,
send: &mut impl FnMut(OutPacket),
send: &mut impl FnMut(EncodedVoice),
error: &impl Fn(String),
) -> bool {
if let Some(event) = self.playback.poll() {
@@ -575,16 +568,20 @@ mod tests {
/// end-of-stream packets).
fn capture(p: &mut Pipeline, samples: &[f32]) -> (usize, usize) {
let (mut voice, mut end) = (0, 0);
p.capture(samples, 0, &mut |packet: OutPacket| {
// Header of 3 bytes (id + codec) for C2S audio.
if packet.content().len() > 3 { voice += 1 } else { end += 1 }
p.capture(samples, 0, &mut |packet: EncodedVoice| {
if packet.is_end() { end += 1 } else { voice += 1 }
});
(voice, end)
}
fn incoming(from: u16, id: u16, data: &[u8]) -> AudioIn {
let packet = OutAudio::new(&AudioData::S2C { id, codec: CodecType::OpusVoice, from, data });
AudioIn::Packet(InAudioBuf::try_new(Direction::S2C, packet.into_vec()).unwrap())
fn incoming(from: u16, seq: u16, data: &[u8]) -> AudioIn {
AudioIn::Packet(VoicePacket {
talker: TalkerId(from),
seq,
codec: VoiceCodec::Voice,
whisper: false,
payload: data.to_vec(),
})
}
#[test]
@@ -667,14 +664,14 @@ mod tests {
energy(&out[out.len() / 2..])
};
let full = play(&mut p, 1);
p.handle(AudioIn::ClientVolume { client: ClientId(2), volume: 0.5 });
p.handle(AudioIn::ClientVolume { client: TalkerId(2), volume: 0.5 });
let half = play(&mut p, 2);
let ratio_db = 10.0 * (half / full).log10();
assert!((ratio_db + 6.0).abs() < 1.0, "volume 0.5 gave {ratio_db} dB");
p.handle(AudioIn::ClientMuted { client: ClientId(3), muted: true });
p.handle(AudioIn::ClientMuted { client: TalkerId(3), muted: true });
assert!(play(&mut p, 3) < 1e-8);
p.handle(AudioIn::ClientLeft(ClientId(3)));
assert!(!p.mixer.is_muted(ClientId(3)));
p.handle(AudioIn::ClientLeft(TalkerId(3)));
assert!(!p.mixer.is_muted(TalkerId(3)));
}
/// While a priority speaker talks, another talker and a watched stream
@@ -682,7 +679,7 @@ mod tests {
#[test]
fn priority_speaker() {
let mut p = pipeline(TransmitMode::PushToTalk);
p.handle(AudioIn::PrioritySpeakers { clients: vec![ClientId(2)], dimm_db: -12.0 });
p.handle(AudioIn::PrioritySpeakers { clients: vec![TalkerId(2)], dimm_db: -12.0 });
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut priority = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
+25 -5
View File
@@ -4,21 +4,21 @@
//! id (the CRC32 of the image, as TeamSpeak assigns them), so a lookup is a
//! map access, and the same image seen on several servers or under
//! several clients is one file. Pictures from the web (banners,
//! [`crate::web`]) are named by the MD5 hash of their address. Keys are
//! `web`) are named by the MD5 hash of their address. Keys are
//! relative paths (`avatars/<md5>`, `icons/<id>`, `pictures/<md5>`).
//!
//! The cache is bounded by `cache.max_mb` (read on every insert; 0: no
//! limit): the least recently used files go first. Use times survive
//! restarts as the files' modification times.
//!
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
//! Downloads are deduplicated: `Cache::fetch` tells the first asker to
//! download (into a temporary path), later askers wait for the same
//! download ([`Cache::finish`] answers them all).
//! download (`Cache::finish` answers them all).
//!
//! A picture from the web keeps its host's validators (`ETag`,
//! `Last-Modified`) next to it, in `validators/pictures/<md5>`: asked for
//! again, it is downloaded only if it changed ([`Cache::validators`],
//! [`Arrived::Unchanged`]).
//! again, it is downloaded only if it changed (`Cache::validators`,
//! `Arrived::Unchanged`).
use std::collections::{BTreeMap, HashMap};
use std::fmt;
@@ -184,6 +184,17 @@ pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
/// does not hold a download slot.
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
/// How long a picture of `size` bytes may take to arrive: a minute, plus
/// its size at [`MIN_PICTURE_RATE`], so large banners arrive on slow
/// links while a stalled transfer still ends.
pub(crate) fn image_download_time(size: u64) -> std::time::Duration {
std::time::Duration::from_secs(60 + size / MIN_PICTURE_RATE)
}
/// How long the server may take to start an image transfer (a busy server
/// answers the requests of a large channel tree in turn).
pub(crate) const IMAGE_NEGOTIATION: std::time::Duration = std::time::Duration::from_secs(30);
/// The cache key of a picture on the web: only `http` and `https`
/// addresses (blanks around one are not part of it).
pub(crate) fn picture_key(url: &str) -> Option<String> {
@@ -489,6 +500,15 @@ mod tests {
use super::*;
#[test]
fn large_pictures_get_time_to_arrive() {
let secs = std::time::Duration::from_secs;
assert_eq!(image_download_time(0), secs(60));
assert_eq!(image_download_time(100 << 10), secs(72));
// The largest picture, at the slowest rate allowed.
assert_eq!(image_download_time(MAX_PICTURE_BYTES), secs(60 + 16384));
}
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"voelin-cache-{tag}-{}-{:?}",
+29 -21
View File
@@ -32,13 +32,13 @@
//! never downloaded). [`crate::Command::SetAvatar`] uploads our own.
use std::fmt;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde::Serialize;
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWrite, AsyncWriteExt};
/// Picked by the caller; the answer carries it back.
pub type RequestId = u64;
@@ -106,11 +106,11 @@ impl TransferState {
}
/// Reports a transfer's states.
pub(crate) type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
pub type Report = Arc<dyn Fn(TransferState) + Send + Sync>;
/// Where a running download writes.
#[derive(Clone, Debug)]
pub(crate) enum Sink {
pub enum Sink {
/// Write `part` (appending with `append`), then rename it to `dest`.
File {
part: PathBuf,
@@ -168,9 +168,10 @@ impl Progress<'_> {
const CHUNK: usize = 64 * 1024;
/// Receive a file: `size` bytes in total, `offset` of them already in the
/// sink. Reports `Started`, `Progress` and the final state.
pub(crate) async fn download(
mut stream: TcpStream,
/// sink; `stream` carries the rest. Reports `Started`, `Progress` and the
/// final state.
pub(crate) async fn download<R: AsyncRead + Unpin>(
mut stream: R,
size: u64,
offset: u64,
sink: Sink,
@@ -185,8 +186,8 @@ pub(crate) async fn download(
});
}
async fn receive(
stream: &mut TcpStream,
async fn receive<R: AsyncRead + Unpin>(
stream: &mut R,
size: u64,
offset: u64,
sink: &Sink,
@@ -253,26 +254,34 @@ async fn receive(
}
}
/// Send `file` from `offset` (`size` bytes in total). Reports `Started`,
/// `Progress` and the final state.
pub(crate) async fn upload(
mut stream: TcpStream,
/// Send `file` from `offset` (`size` bytes in total) into `writer`, then end
/// it and wait for `stored`, which resolves once the server has the file.
/// Reports `Started`, `Progress` and the final state.
pub(crate) async fn upload_to<W, F>(
mut writer: W,
stored: F,
file: PathBuf,
size: u64,
offset: u64,
progress_every: Duration,
report: Report,
) {
) where
W: AsyncWrite + Unpin,
F: Future<Output = Result<(), String>>,
{
report(TransferState::Started { size, offset });
let result = send(&mut stream, &file, size, offset, progress_every, &report).await;
let result = match send(&mut writer, &file, size, offset, progress_every, &report).await {
Ok(()) => stored.await,
Err(e) => Err(e),
};
report(match result {
Ok(()) => TransferState::Done { size, path: Some(file), data: None },
Err(e) => TransferState::Failed(e),
});
}
async fn send(
stream: &mut TcpStream,
async fn send<W: AsyncWrite + Unpin>(
stream: &mut W,
path: &Path,
size: u64,
offset: u64,
@@ -300,8 +309,6 @@ async fn send(
}
stream.flush().await.map_err(|e| e.to_string())?;
stream.shutdown().await.map_err(|e| e.to_string())?;
// The server closes the connection once it has everything.
let _ = tokio::time::timeout(Duration::from_secs(30), stream.read(&mut buf[..1])).await;
Ok(())
}
@@ -421,7 +428,7 @@ fn percent_decode(text: &str) -> Option<String> {
mod tests {
use std::sync::Mutex;
use tokio::net::TcpListener;
use tokio::net::{TcpListener, TcpStream};
use super::*;
@@ -562,7 +569,8 @@ mod tests {
});
let (report, states) = recorder();
let stream = TcpStream::connect(addr).await.unwrap();
upload(stream, file.clone(), 10, 4, Duration::ZERO, report).await;
let (_, write) = tokio::io::split(stream);
upload_to(write, async { Ok(()) }, file.clone(), 10, 4, Duration::ZERO, report).await;
assert_eq!(server.await.unwrap(), b"456789");
assert!(matches!(states.lock().unwrap().last(), Some(TransferState::Done { .. })));
assert_eq!(md5_file(&file).unwrap(), "781e5e245d69b566979b86e28d23f2c7");
+44 -19
View File
@@ -61,6 +61,7 @@ use voelin_gateway_proto::{
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
StreamSpec, TopicInfo, UserRef,
};
use voelin_identity::IdentityBlob;
use voelin_model::{ChannelId, ChatTarget, Presence};
use voelin_store::WriteOutcome;
@@ -91,13 +92,23 @@ pub(crate) enum GatewayEvent {
Disconnected(Option<String>),
}
/// The TeamSpeak identity of a blob, or why a gateway cannot be logged in to
/// with it.
fn login_identity(blob: &IdentityBlob) -> Result<tsclientlib::Identity, String> {
crate::ts::identity::from_blob(blob).map_err(|e| e.to_string())
}
/// Connect to a gateway (`ws://…/v1` or `wss://…/v1`) and log in with a
/// TeamSpeak identity.
/// TeamSpeak identity (a blob of kind `teamspeak`, see
/// [`crate::ts::identity::to_blob`]; one that is none is refused as
/// [`ErrorCode::AuthFailed`], the way the gateway would).
pub async fn connect(
url: &str,
identity: &tsclientlib::Identity,
identity: &IdentityBlob,
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
connect_watched(url, identity, &Progress::default()).await
let identity = login_identity(identity)
.map_err(|message| ClientError::Gateway { code: ErrorCode::AuthFailed, message })?;
connect_watched(url, &identity, &Progress::default()).await
}
/// [`connect`], telling `progress` each step (for the log).
@@ -114,10 +125,19 @@ async fn connect_watched(
/// logs in.
pub(crate) async fn run(
mut urls: Vec<String>,
identity: tsclientlib::Identity,
identity: IdentityBlob,
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
events: mpsc::UnboundedSender<GatewayEvent>,
) {
// An identity that cannot be read will not be tomorrow: like a refused login.
let identity = match login_identity(&identity) {
Ok(identity) => identity,
Err(reason) => {
debug!(%reason, "gateway: the identity cannot be read");
let _ = events.send(GatewayEvent::Disconnected(Some(reason)));
return;
}
};
// A gateway that is away (down, restarting, a network change, a proxy
// in front of it that fails) or cannot log us in yet (it does not know
// the identity before voice connected once, its server is restarting)
@@ -274,20 +294,24 @@ pub(crate) struct Observed {
}
impl Observed {
pub(crate) fn new(urls: &[String], identity: &tsclientlib::Identity) -> Self {
Self {
urls: urls.to_vec(),
key: identity.key().to_pub().to_ts(),
counter: identity.counter(),
nudged: None,
pub(crate) fn new(urls: &[String], identity: &IdentityBlob) -> Self {
let (key, counter) = Self::of(identity);
Self { urls: urls.to_vec(), key, counter, nudged: None }
}
/// The public key and the counter of an identity: an identity that cannot be
/// read has neither (and so is the same as any other that cannot).
fn of(identity: &IdentityBlob) -> (String, u64) {
match login_identity(identity) {
Ok(identity) => (identity.key().to_pub().to_ts(), identity.counter()),
Err(_) => (String::new(), 0),
}
}
/// Whether this is what is observed with.
pub(crate) fn same(&self, urls: &[String], identity: &tsclientlib::Identity) -> bool {
self.urls == urls
&& self.counter == identity.counter()
&& self.key == identity.key().to_pub().to_ts()
pub(crate) fn same(&self, urls: &[String], identity: &IdentityBlob) -> bool {
let (key, counter) = Self::of(identity);
self.urls == urls && self.counter == counter && self.key == key
}
/// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice
@@ -1182,15 +1206,16 @@ mod tests {
#[test]
fn the_same_observation_is_nudged_at_most_every_5_s() {
let blob = crate::ts::identity::to_blob;
let identity = tsclientlib::Identity::create();
let urls = vec!["ws://gw.example.test:7788/v1".to_owned()];
let mut observed = Observed::new(&urls, &identity);
assert!(observed.same(&urls, &identity));
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &identity));
assert!(!observed.same(&urls, &tsclientlib::Identity::create()));
let mut observed = Observed::new(&urls, &blob(&identity));
assert!(observed.same(&urls, &blob(&identity)));
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &blob(&identity)));
assert!(!observed.same(&urls, &blob(&tsclientlib::Identity::create())));
// Its security level raised: logged in with the new counter.
let raised = tsclientlib::Identity::new(identity.key().clone(), identity.counter() + 1);
assert!(!observed.same(&urls, &raised));
assert!(!observed.same(&urls, &blob(&raised)));
let now = Instant::now();
assert!(observed.nudge_at(now));
assert!(!observed.nudge_at(now + Duration::from_secs(4)));
+88 -62
View File
@@ -3,7 +3,10 @@
//! The UI talks to an [`Engine`] with [`Command`]s and receives [`Event`]s.
//! Each server the user works with is a session with up to three sources:
//!
//! - **voice**: a normal client connection (visible, can talk)
//! - **voice**: a normal client connection (visible, can talk): a
//! `voelin_proto::link::Session` that the connector of the server's address
//! makes ([`Backends`], and [`ts::TsConnector`] for TeamSpeak servers; see
//! [`link`])
//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat)
//! - **query**: the user's own ServerQuery credentials (same, without a gateway)
//!
@@ -16,9 +19,9 @@
//! [`Engine::subscribe_frames`] for the frames of watched streams. The audio
//! of watched streams plays through the session's speakers by itself
//! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video
//! are in [`media`] (feature `media`), and the Stream Studio (scenes of
//! are in `media` (feature `media`), and the Stream Studio (scenes of
//! sources composited into one stream, recording, a replay buffer, WHIP) in
//! [`studio`].
//! `studio`.
//!
//! Settings are a [`settings::Settings`] service: typed keys, runtime
//! values stored in the client database ahead of command line, config file
@@ -45,14 +48,13 @@
//! volume) are engine-wide ([`contacts`]).
mod audio;
mod book;
pub mod cache;
pub mod contacts;
pub mod discover;
pub mod files;
pub mod gateway;
pub mod history;
pub mod identity;
pub mod link;
#[cfg(feature = "media")]
pub mod media;
pub mod offline;
@@ -61,22 +63,21 @@ mod route;
mod session;
pub mod settings;
pub mod stream;
mod stream_types;
#[cfg(feature = "media")]
pub mod studio;
pub mod versions;
mod voice;
pub mod ts;
mod web;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc, watch};
use tokio::sync::{broadcast, mpsc};
pub use voelin_audio::settings::TransmitMode;
pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
use voelin_model::{
Capabilities, ChannelId, ChatMessage, ChatTarget, FileRef, GroupInfo, Presence, ServerDetails,
ServerFlavor,
};
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
@@ -88,14 +89,14 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta
pub use gateway::{GatewayRequest, GatewayUpdate};
use history::SharedHistory;
pub use history::{History, HistoryMessage, HistorySource};
pub use link::{Backends, VoiceOptions};
pub use offline::{OfflineMessage, OfflineMessageInfo};
pub use query::{QueryLogin, QueryTransport};
pub use route::{ChatRoute, Dedup, route_chat};
use settings::{SettingChange, Settings, SharedSettings};
use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
use voelin_stream::{
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
};
pub use voice::VoiceOptions;
pub use voelin_identity::IdentityBlob;
/// Banners are downloaded and shown by the same rule.
pub use web::is_svg;
/// Pictures from the web go through the desktop's proxy (set at startup).
@@ -110,13 +111,6 @@ pub const POKE_MESSAGE_MAX: usize = 100;
/// What the UI asks for.
#[derive(Clone, Debug)]
pub enum Command {
/// Main account proof for every current and future voice connection.
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
/// What voice servers are shown of the main account (its avatar and
/// badges with their certificates, its User Tag; TeamSpeak 6): sent to
/// every connection that presents the account's myTS ID, once connected
/// and when it changes; cleared on a sign-out.
SetMytsData(Option<Arc<tsclientlib::MytsData>>),
ConnectVoice {
session: SessionId,
options: Box<VoiceOptions>,
@@ -132,12 +126,15 @@ pub enum Command {
ObserveGateway {
session: SessionId,
urls: Vec<String>,
identity: Box<tsclientlib::Identity>,
/// The TeamSpeak identity to log in with ([`ts::identity::to_blob`]).
/// One that is none, or cannot be read, ends the observation with
/// its reason.
identity: Box<IdentityBlob>,
},
/// Invisible presence and relay chat with own ServerQuery credentials.
ObserveQuery {
session: SessionId,
connect: Box<voelin_query::Connect>,
connect: Box<QueryLogin>,
},
StopObserving {
session: SessionId,
@@ -248,11 +245,13 @@ pub enum Command {
session: SessionId,
layers: Vec<LayerSpec>,
},
/// SRTP protection profiles for stream connections, in order of
/// preference (a user setting; empty: the default,
/// `SrtpProfile::DEFAULT_ORDER`). Applies to connections made from now
/// on, in all sessions and those started later.
SetSrtpProfiles(Vec<SrtpProfile>),
/// SRTP protection profiles for stream connections by name (RFC 5764 and
/// RFC 7714: `AEAD_AES_128_GCM`, `AES128_CM_SHA1_80`, ...; names the stream
/// transport does not know are left out), in order of preference (the
/// `stream.srtp_profiles` setting). Empty: the transport's default order.
/// Applies to connections made from now on, in all sessions and those
/// started later.
SetSrtpProfiles(Vec<String>),
/// Watch a stream from [`Event::StreamsChanged`]. Frames arrive through
/// [`Engine::subscribe_frames`].
WatchStream {
@@ -270,7 +269,7 @@ pub enum Command {
},
/// The video of a watched stream arrives, but none of it decodes: watch
/// it in another codec the streamer offered, if there is one (a new
/// connection without this one). [`media::Viewer`] sends it.
/// connection without this one). `media::Viewer` sends it.
StreamUndecodable {
session: SessionId,
stream_id: String,
@@ -507,6 +506,30 @@ pub enum JoinFailure {
Other(String),
}
/// The software on the other end of a session, as its link names it. It is
/// for people to read; nothing branches on it (what the server can do is
/// [`Capabilities`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BackendInfo {
/// What it is called ("TeamSpeak 6"); empty when it was not recognised.
pub product: String,
/// Its version as the product shows it ("6.0.0-beta13.1"); what the
/// server said, as it is, when `product` is empty.
pub version: String,
}
impl BackendInfo {
/// For a sentence: the product and the version, whichever there are
/// ("TeamSpeak 6 6.0.0-beta13.1", "TeamSpeak 3", "custom 9").
pub fn label(&self) -> String {
match (self.product.is_empty(), self.version.is_empty()) {
(false, false) => format!("{} {}", self.product, self.version),
(false, true) => self.product.clone(),
(true, _) => self.version.clone(),
}
}
}
/// What the engine reports.
#[derive(Clone, Debug)]
pub enum Event {
@@ -514,10 +537,12 @@ pub enum Event {
session: SessionId,
state: SessionState,
},
/// The server answered: its name, the software it runs and what that
/// software can do (the UI hides what it cannot).
ServerInfo {
session: SessionId,
name: String,
flavor: ServerFlavor,
backend: BackendInfo,
capabilities: Capabilities,
},
/// Full presence of the session (the UI rebuilds its view from it).
@@ -760,8 +785,18 @@ impl Engine {
}
/// Start the engine on the current tokio runtime with `settings` and
/// chat `history`.
/// chat `history`, connecting voice with the engine's own connectors
/// ([`Backends::default`]: TeamSpeak 3 and 6).
pub fn start_with(settings: Settings, history: History) -> Self {
Self::start_with_backends(settings, history, Backends::default())
}
/// Start the engine on the current tokio runtime with `settings` and
/// chat `history`, connecting voice with the connectors in `backends`:
/// the one for the scheme of a session's address makes its
/// `voelin_proto::link::Session`.
pub fn start_with_backends(settings: Settings, history: History, backends: Backends) -> Self {
let link = Arc::new(link::SessionLink::new(backends));
let (commands, rx) = mpsc::unbounded_channel();
let (events, _) = broadcast::channel(4096);
// About a minute of one watched stream.
@@ -773,7 +808,7 @@ impl Engine {
history,
cache: SharedCache::new(Cache::new(Cache::default_dir())),
};
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone()));
tokio::spawn(run(rx, events.clone(), frames.clone(), shared.clone(), link));
Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), shared }
}
@@ -857,19 +892,18 @@ async fn run(
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
engine: Shared,
link: Arc<link::SessionLink>,
) {
let Shared { settings: shared, history, cache, contacts } = engine.clone();
// Before any command: a contact set meanwhile would be lost.
contacts.load().await;
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let (myts_identity, _) = watch::channel(None);
let (myts_data, _) = watch::channel(None);
let mut current = shared.current();
// Pruning: at start, then hourly (and when the setting changes).
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
let mut changes = current.subscribe();
let mut settings = AudioSettings::default();
let mut srtp_profiles: Option<Vec<SrtpProfile>> = None;
let mut srtp_profiles: Option<Vec<String>> = None;
let mut mic_test: Option<AudioHandle> = None;
loop {
let input = tokio::select! {
@@ -908,29 +942,6 @@ async fn run(
},
};
let id = match command {
Command::SetMytsIdentity(identity) => {
// Still no account is no change: every notification restarts
// handshakes and sends `updatemytsid` on every connection. Any
// account is (each connection's proof is signed anew).
myts_identity.send_if_modified(|current| {
if current.is_none() && identity.is_none() {
return false;
}
*current = identity;
true
});
continue;
}
Command::SetMytsData(data) => {
myts_data.send_if_modified(|current| {
if *current == data {
return false;
}
*current = data;
true
});
continue;
}
Command::SetAudioSettings(new) => {
settings = (*new).clone();
for s in sessions.values() {
@@ -1006,8 +1017,7 @@ async fn run(
frames.clone(),
settings.clone(),
engine.clone(),
myts_identity.subscribe(),
myts_data.subscribe(),
link.clone(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
@@ -1086,9 +1096,7 @@ fn command_session(command: &Command) -> SessionId {
| Command::DeleteOfflineMessage { session, .. }
| Command::SetOfflineMessageRead { session, .. }
| Command::CloseSession { session } => *session,
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::SetAudioSettings(_)
Command::SetAudioSettings(_)
| Command::SetSrtpProfiles(_)
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
@@ -1111,3 +1119,21 @@ fn command_session(command: &Command) -> SessionId {
fn one_rustls_crypto_provider() {
let _ = rustls::ClientConfig::builder();
}
#[cfg(test)]
mod tests {
use super::BackendInfo;
#[test]
fn a_backend_reads_as_its_product_and_version() {
let backend = |product: &str, version: &str| BackendInfo {
product: product.into(),
version: version.into(),
};
assert_eq!(backend("TeamSpeak 6", "6.0.0-beta13.1").label(), "TeamSpeak 6 6.0.0-beta13.1");
assert_eq!(backend("TeamSpeak 3", "").label(), "TeamSpeak 3");
// Not recognised: the version string alone, or nothing.
assert_eq!(backend("", "custom 9").label(), "custom 9");
assert_eq!(BackendInfo::default().label(), "");
}
}
+261
View File
@@ -0,0 +1,261 @@
//! The registry of the engine's connectors, by address scheme.
//!
//! A session's voice source is a `voelin_proto::link::Session`
//! (`docs/session-seam.md` section 4.1). Which backend makes it is the
//! scheme of the address: [`Backends`] holds the plain connectors of
//! `voelin_proto::link::Connectors` (the Voelin protocol's QUIC connector
//! later, `FakeConnector` in tests) and the in-process connectors, which
//! also hand the engine what a `Session` has no room for yet (the TeamSpeak 6
//! stream task, [`StreamPort`]).
use std::sync::Arc;
use tokio::sync::mpsc;
use voelin_proto::link::{
AccountAgent, BoxFuture, ConnectParams, Connected, Connector, Connectors, HostIdentity,
HostTrust, SessionError,
};
use voelin_stream::PeerConfig;
use super::LinkCtx;
use crate::stream::{OwnStreamEvent, StreamCmd};
use crate::ts::TsConnector;
/// The scheme of the TeamSpeak servers a bookmark names without one.
pub(crate) const TEAMSPEAK_SCHEME: &str = "ts3server";
/// What comes back from the stream task of a connection that has one.
#[derive(Debug)]
pub(crate) enum StreamEvent {
/// Our own stream's life, for the gateway directory.
OwnStream(OwnStreamEvent),
/// An Opus frame of a watched stream, for the audio thread.
Audio { stream: String, time: u64, data: Arc<[u8]> },
/// A watched stream ended.
AudioEnded(String),
}
/// The in-process channel of TeamSpeak 6 streams past the `Session` trait
/// (`docs/session-seam.md` section 6.4): TeamSpeak 6 streams are peer to peer
/// and not v1 entities yet, so the commands go to the connection's stream
/// task and its events come back here.
pub(crate) struct StreamPort {
send: Box<dyn Fn(StreamCmd) + Send + Sync>,
/// What the stream task reports.
pub(crate) events: mpsc::UnboundedReceiver<StreamEvent>,
}
impl StreamPort {
/// A port whose commands go to `send`.
pub(crate) fn new(
send: impl Fn(StreamCmd) + Send + Sync + 'static,
events: mpsc::UnboundedReceiver<StreamEvent>,
) -> Self {
Self { send: Box::new(send), events }
}
/// Give the stream task a command.
pub(crate) fn send(&self, cmd: StreamCmd) {
(self.send)(cmd);
}
}
/// What an in-process backend needs besides the connect parameters.
#[derive(Clone)]
pub(crate) struct LocalCtx {
/// The session's side of the engine: its id, event bus, frames and
/// settings.
pub(crate) link: LinkCtx,
/// Open the audio devices (the stream task plays what streams carry).
pub(crate) audio: bool,
/// Network settings for stream peer connections.
pub(crate) stream_peer: PeerConfig,
}
impl LocalCtx {
pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self {
Self { link, audio, stream_peer }
}
/// A context for a connection made outside an engine (a test or a tool
/// that calls a connector itself): a session of its own that nobody
/// listens to.
pub(crate) fn standalone() -> Self {
let (events, _) = tokio::sync::broadcast::channel(16);
let (frames, _) = tokio::sync::broadcast::channel(16);
let link = LinkCtx {
session: 0,
events,
frames,
settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()),
};
Self { link, audio: false, stream_peer: PeerConfig::default() }
}
}
/// A connection an in-process connector made.
pub(crate) struct LocalConnected {
pub(crate) connected: Connected,
/// The stream task's port, for a backend that runs one.
pub(crate) streams: Option<StreamPort>,
}
/// A connector that runs in this process and can use the engine's context
/// ([`LocalCtx`]); its sessions may come with a [`StreamPort`].
pub(crate) trait LocalConnector: Connector {
/// Whether this connector serves addresses of `scheme`. By default, the
/// schemes it names.
fn accepts(&self, scheme: &str) -> bool {
self.schemes().contains(&scheme)
}
/// Connect with the engine's context.
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>>;
}
/// The connectors of an engine, found by the scheme of an address.
///
/// A scheme served by an in-process connector goes to it, one served by a
/// plain connector ([`Backends::register`]) to that. An address without a
/// scheme is a TeamSpeak bookmark and is taken for a `ts3server` one.
#[derive(Clone)]
pub struct Backends {
connectors: Connectors,
locals: Vec<Arc<dyn LocalConnector>>,
account: Option<Arc<dyn AccountAgent>>,
/// The connections' trust in hosts that are neither valid nor pinned.
trust: Option<Arc<dyn HostTrust>>,
}
impl Default for Backends {
/// The engine's connectors: TeamSpeak 3 and 6 (`ts3server://` and
/// `teamspeak://`, and an address without a scheme).
fn default() -> Self {
let mut backends = Self::empty();
backends.register_teamspeak(TsConnector::new());
backends
}
}
impl Backends {
/// No connector at all. ([`Backends::default`] has the TeamSpeak one.)
pub fn empty() -> Self {
Self { connectors: Connectors::default(), locals: Vec::new(), account: None, trust: None }
}
/// Register a connector for the schemes it names.
pub fn register(&mut self, connector: Arc<dyn Connector>) {
self.connectors.register(connector);
}
pub(crate) fn register_local(&mut self, connector: Arc<dyn LocalConnector>) {
self.locals.push(connector);
}
/// Register the TeamSpeak connector for the schemes it names
/// (`ts3server`, `teamspeak`, and addresses without a scheme).
/// [`Backends::default`] registers one of its own; register yours to keep a
/// clone of it, whose [`TsConnector::set_myts_identity`] and
/// [`TsConnector::set_myts_data`] set the main myTeamSpeak account for every
/// connection it makes.
pub fn register_teamspeak(&mut self, connector: TsConnector) {
self.register_local(Arc::new(connector));
}
/// The device's Voelin account, for the connectors that use it (the QUIC
/// connector's certificate, the TeamSpeak connector's myTS ID proof).
/// None is the default: nothing uses an account yet.
pub fn set_account(&mut self, agent: Option<Arc<dyn AccountAgent>>) {
self.account = agent;
}
/// The account agent, if one was set ([`Backends::set_account`]).
pub fn account(&self) -> Option<Arc<dyn AccountAgent>> {
self.account.clone()
}
/// Decide about hosts that are neither valid nor pinned. The default
/// refuses them: there is no trust dialog yet, and TeamSpeak has no host
/// key.
pub fn set_trust(&mut self, trust: Option<Arc<dyn HostTrust>>) {
self.trust = trust;
}
pub(crate) fn trust(&self) -> Arc<dyn HostTrust> {
self.trust.clone().unwrap_or_else(|| Arc::new(RefuseUnknownHosts))
}
/// The scheme of an address, lowercase; a TeamSpeak bookmark's when there
/// is none.
pub(crate) fn scheme(address: &str) -> String {
match address.split_once("://") {
Some((scheme, _)) => scheme.to_ascii_lowercase(),
None => TEAMSPEAK_SCHEME.to_owned(),
}
}
/// Open a session to `params.address` with the connector of its scheme.
pub(crate) fn connect(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
let scheme = Self::scheme(&params.address);
if let Some(local) = self.locals.iter().find(|c| c.accepts(&scheme)) {
return local.connect_local(params, ctx);
}
// Not `Connectors::connect`, which names the whole address when none serves it:
// the text is shown, and a TeamSpeak link carries a channel password.
let Some(connector) = self.connectors.for_address(&params.address) else {
let shown = without_query(&params.address).to_owned();
return Box::pin(async move {
Err(SessionError::Protocol(format!("no connector for {shown}")))
});
};
let connect = connector.connect(params);
Box::pin(async move {
let connected = connect.await?;
Ok(LocalConnected { connected, streams: None })
})
}
}
/// An address as it may be shown or logged: without its query and fragment,
/// where a link keeps a channel password or a host pin.
pub(crate) fn without_query(address: &str) -> &str {
address.split(['?', '#']).next().unwrap_or_default()
}
/// Refuses every host that asks to be trusted.
struct RefuseUnknownHosts;
impl HostTrust for RefuseUnknownHosts {
fn confirm(&self, _host: HostIdentity) -> BoxFuture<bool> {
Box::pin(async { false })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_bookmark_without_a_scheme_is_a_teamspeak_server() {
assert_eq!(Backends::scheme("ts.example.com:9987"), "ts3server");
assert_eq!(Backends::scheme("[::1]:9987"), "ts3server");
assert_eq!(Backends::scheme("TS3Server://ts.example.com"), "ts3server");
assert_eq!(Backends::scheme("teamspeak://x"), "teamspeak");
assert_eq!(Backends::scheme("voelin://host/i/code"), "voelin");
}
#[test]
fn an_address_is_shown_without_its_secrets() {
assert_eq!(without_query("ts3server://h?port=1&channelpassword=hunter2"), "ts3server://h");
assert_eq!(without_query("voelin://h/i/code#h=abcd"), "voelin://h/i/code");
assert_eq!(without_query("host:9987"), "host:9987");
}
}
+261
View File
@@ -0,0 +1,261 @@
//! What a session hands the connector of an address: the `ConnectParams` of
//! a [`VoiceOptions`] (`docs/session-seam.md` section 4.2).
//!
//! The options are the engine's own, and a connector reads them back: the
//! address is the link of the bookmark (a `ts3server://` link for a
//! bookmark that names a TeamSpeak server by `host[:port]`), the nickname,
//! the server password and the privilege key are in the hello, the identity
//! is the credential. What v1 has no field for yet (the channel to join and
//! its password, the client version a TeamSpeak server is shown) rides in
//! the address, as parameters of the link.
use std::sync::Arc;
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bytes::Bytes;
use voelin_identity::{IdentityBlob, KIND_TEAMSPEAK};
use voelin_model::Link;
use voelin_proto::link::{ConnectParams, Credential, IssuerTrust, MediaSink, SessionError};
use voelin_proto::v1;
use super::{Backends, VoiceOptions, without_query};
/// The link parameter that carries the client version to impersonate: the
/// user's spec (`VoiceOptions::client_version`), in unpadded URL-safe base64.
/// The connector for TeamSpeak resolves it; other connectors never read it.
pub(crate) const VERSION_PARAM: &str = "client_version";
/// The connect parameters of a connection, from the options the session was
/// asked to connect with.
///
/// The address is the link of the bookmark (the channel and its password
/// ride in it, and so does the client version to claim, until v1 has fields
/// for them), the server password is `Hello.password` and the privilege key
/// `Hello.invite_code`. The identity goes as the credential of its kind; no
/// account is used yet.
///
/// An address a link cannot carry is refused here ([`bookmark`]), and so is
/// an identity that is of no kind a connector can use.
pub(crate) fn connect_params(
options: &VoiceOptions,
media: Arc<dyn MediaSink>,
backends: &Backends,
) -> Result<ConnectParams, SessionError> {
let hello = v1::Hello {
version: 1,
client: Some(v1::ClientInfo {
name: "Voelin".into(),
version: voelin_platform::crash::app_version().to_owned(),
platform: std::env::consts::OS.into(),
kind: v1::ClientKind::User as i32,
}),
nickname: options.nickname.clone(),
password: options.server_password.clone().unwrap_or_default(),
invite_code: options.token.clone().unwrap_or_default(),
..Default::default()
};
Ok(ConnectParams {
address: address_link(options)?,
credential: credential(options.identity.as_ref())?,
linked: Vec::new(),
account: backends.account(),
issuer_trust: IssuerTrust::Unknown,
hello,
host_pin: None,
trust: backends.trust(),
media,
push_capacity: 1024,
timeout: Duration::from_secs(35),
})
}
/// The credential of an identity (`docs/session-seam.md` section 7). A
/// TeamSpeak identity goes as the JSON the key store keeps, and none at all as
/// an empty one, for which the TeamSpeak connector makes an identity up (the
/// protocol's convention for "generate one", follow-up P11); a Voelin key
/// signs. A TeamSpeak identity that holds no JSON is refused: sent as it is,
/// it would be that same empty blob and be taken for the request to make one
/// up, which only the absence of an identity may be.
fn credential(identity: Option<&IdentityBlob>) -> Result<Credential, SessionError> {
let Some(blob) = identity else {
return Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: Bytes::new() });
};
if blob.is_teamspeak() {
if blob.json.trim().is_empty() {
return Err(SessionError::Protocol(
"the TeamSpeak identity cannot be read: it is empty".into(),
));
}
let json = Bytes::copy_from_slice(blob.json.as_bytes());
Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: json })
} else if blob.is_voelin() {
let key = blob.voelin_key().map_err(|e| {
SessionError::Protocol(format!("the Voelin identity cannot be read: {e}"))
})?;
Ok(Credential::Voelin(Arc::new(key)))
} else {
Err(SessionError::Protocol(format!(
"an identity of kind {:?} cannot be used to connect",
blob.kind
)))
}
}
/// The `ts3server://` link of the options' address, with the channel to join
/// and the client version to claim.
fn address_link(options: &VoiceOptions) -> Result<String, SessionError> {
let mut link = match Link::parse(&options.address) {
Some(Link::Server(link)) => link,
// Not a TeamSpeak link, or none: a bookmark's `host[:port]`.
_ if !options.address.contains("://") => bookmark(&options.address)?,
// Some other scheme: as given, for the connector of that scheme.
_ => return Ok(options.address.clone()),
};
link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel);
link.channel_password =
options.channel_password.clone().filter(|p| !p.is_empty()).or(link.channel_password);
let mut url = link.to_url();
if let Some(spec) = &options.client_version {
url.push(if url.contains('?') { '&' } else { '?' });
url.push_str(VERSION_PARAM);
url.push('=');
url.push_str(&URL_SAFE_NO_PAD.encode(spec));
}
Ok(url)
}
/// The link to a bookmark's `host[:port]`.
///
/// A link cannot say everything an address can: it drops a port that is no
/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins
/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a
/// `%` (so that a `?` in the host would hide the channel behind the next
/// one). The TeamSpeak library refuses such an address when it resolves it;
/// so does this, in words, instead of connecting to something else.
fn bookmark(address: &str) -> Result<voelin_model::ServerLink, SessionError> {
let address = address.trim();
// Without the query: a link keeps secrets in it.
let shown = without_query(address);
let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}"));
if address.is_empty()
|| address
.chars()
.any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control())
{
return Err(not_an_address());
}
// The text after the port's colon: `[v6]:port`, or `host:port` with the one
// colon (more colons are an IPv6 address without a port).
let port = if let Some(rest) = address.strip_prefix('[') {
let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?;
(!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after))
} else {
address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port)
};
if let Some(port) = port
&& !port.parse::<u16>().is_ok_and(|port| port != 0)
{
return Err(SessionError::Protocol(format!(
"the port in {shown} is not a number from 1 to 65535"
)));
}
Ok(voelin_model::ServerLink::new(address))
}
#[cfg(test)]
mod tests {
use super::*;
use voelin_identity::IdentityKey;
fn params(options: &VoiceOptions) -> Result<ConnectParams, SessionError> {
let (media, _rx) = voelin_proto::test_util::media_channel();
connect_params(options, media, &Backends::empty())
}
/// The identity of the options is the credential of its kind: a TeamSpeak
/// identity as the JSON the key store keeps, none as the empty blob a
/// connector makes an identity up for, a Voelin key as its signer.
#[test]
fn an_identity_is_the_credential_of_its_kind() {
let mut options = VoiceOptions::new("ts.example.com", "nick");
let none = params(&options).unwrap();
assert!(matches!(
&none.credential,
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
));
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, r#"{"key":"k"}"#));
let sent = params(&options).unwrap();
assert!(matches!(
&sent.credential,
Credential::Foreign { kind: "teamspeak", blob } if &blob[..] == br#"{"key":"k"}"#
));
let key = IdentityKey::generate().unwrap();
options.identity = Some(IdentityBlob::voelin(&key).unwrap());
let Credential::Voelin(signer) = params(&options).unwrap().credential else {
panic!("a Voelin credential")
};
assert_eq!(signer.public_key(), key.public_key());
assert_eq!(signer.sign(b"hello"), key.sign(b"hello"));
// A Voelin blob whose key cannot be read, and a kind that connects to
// nothing: refused in words, without the JSON.
options.identity = Some(IdentityBlob::new("voelin", "x", 0, "hunter2"));
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
assert!(
text.starts_with("the Voelin identity cannot be read") && !text.contains("hunter2")
);
options.identity = Some(IdentityBlob::new("account", "x", 0, "hunter2"));
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
assert_eq!(text, "an identity of kind \"account\" cannot be used to connect");
}
/// A TeamSpeak identity with no JSON is no identity. The empty blob is
/// what asks the TeamSpeak connector to make one up (`identity: None`), so
/// it is refused here instead of being sent as that request.
#[test]
fn a_teamspeak_identity_without_json_is_refused() {
let mut options = VoiceOptions::new("ts.example.com", "nick");
for json in ["", " \n\t"] {
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json));
let Err(SessionError::Protocol(text)) = params(&options) else {
panic!("a refusal for {json:?}")
};
assert_eq!(text, "the TeamSpeak identity cannot be read: it is empty");
}
// No identity at all is the request to make one up, as before.
options.identity = None;
assert!(matches!(
params(&options).unwrap().credential,
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
));
}
/// The client version spec rides the link as it was typed, whatever it
/// holds, and only for an address that is a TeamSpeak bookmark or link.
#[test]
fn the_client_version_spec_rides_the_link_unchanged() {
let spec = |address: &str, spec: &str| {
let mut options = VoiceOptions::new(address, "nick");
options.client_version = Some(spec.into());
params(&options).unwrap().address
};
let address = spec("ts.example.com:9988", "windows@3.6.2 [Build: 1]&x=#");
let (_, query) = address.split_once('?').unwrap();
let text = query
.split('&')
.find_map(|pair| pair.strip_prefix("client_version="))
.expect("the parameter");
let decoded = URL_SAFE_NO_PAD.decode(text).unwrap();
assert_eq!(decoded, b"windows@3.6.2 [Build: 1]&x=#");
// Another scheme is left as it is: its connector has no use for a TeamSpeak
// client's version.
assert_eq!(spec("voelin://host/i/code", "generic"), "voelin://host/i/code");
// No spec, no parameter.
let options = VoiceOptions::new("ts.example.com", "nick");
assert!(!params(&options).unwrap().address.contains(VERSION_PARAM));
}
}
@@ -0,0 +1,363 @@
//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each
//! connection the test asks for to the test, which plays the server by
//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session
//! gives. These are the tests that need the inner link itself:
//!
//! - the stream commands, which travel on the in-process port of the link
//! and which a `voelin_proto::link::Session` has no part in until the
//! stream task moves (`docs/session-seam.md` sections 6.4 and 9.2);
//! - the order in which a reconnect shuts the streams and the old connection
//! down, which is the order of the one queue `LinkSession` keeps;
//! - a link that keeps talking after the engine replaced its connection,
//! which a closed `FakeSession` cannot do on purpose.
//!
//! (They were integration tests while the inner link was public; it is the
//! TeamSpeak module's now, and so are these.)
//!
//! Presence, chat, the dedup of a message that comes twice, history, transfers
//! and the rest of what the engine does with a session are tested on the
//! protocol repository's fake host in `tests/session_fake.rs`. Nothing here
//! needs a TeamSpeak server or a TeamSpeak type.
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::{broadcast, mpsc};
use super::{Backends, LinkCmd, LinkCtx, LinkEvent};
use crate::settings::Settings;
use crate::stream::{StreamCmd, StreamSetup};
use crate::ts::ts_session::LinkConnector;
use crate::ts::{ConnectOptions, ServerLink};
use crate::{
BackendInfo, Command, Engine, Event, History, SessionId, SessionState, VoiceOptions, VoiceState,
};
use voelin_model::{
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
ServerDetails,
};
/// A connection the session asked the link for.
struct Conn {
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
}
impl Conn {
/// Play `script`, the server's side, in order.
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
for event in script {
self.events.send(event).expect("the session listens");
}
}
/// The next command the session gave.
async fn cmd(&mut self) -> LinkCmd {
tokio::time::timeout(Duration::from_secs(10), self.cmds.recv())
.await
.expect("a command in time")
.expect("the session keeps the connection")
}
}
/// Hands every connection to the test.
struct FakeLink {
conns: mpsc::UnboundedSender<Conn>,
}
impl FakeLink {
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
let (conns, rx) = mpsc::unbounded_channel();
(Self { conns }, rx)
}
}
impl ServerLink for FakeLink {
fn spawn(
&self,
_options: ConnectOptions,
_ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
let _ = self.conns.send(Conn { cmds, events });
}
}
const SESSION: SessionId = 1;
const SERVER_UID: &str = "fake-server=";
const ME: u16 = 7;
const ME_UID: &str = "me=";
const LOBBY: ChannelId = 1;
const GAMES: ChannelId = 2;
struct Harness {
engine: Engine,
events: broadcast::Receiver<Event>,
conns: mpsc::UnboundedReceiver<Conn>,
}
impl Harness {
fn start() -> Self {
let (link, conns) = FakeLink::new();
let mut backends = Backends::empty();
backends.register_local(Arc::new(LinkConnector::any(Arc::new(link))));
let engine =
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
let events = engine.subscribe();
Self { engine, events, conns }
}
/// Ask for a voice connection and take it from the link.
async fn connect(&mut self) -> Conn {
let options = VoiceOptions::new("fake.test:9987", "tester");
self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
tokio::time::timeout(Duration::from_secs(10), self.conns.recv())
.await
.expect("the session spawns the link")
.expect("the link lives")
}
/// The next event `f` picks, skipping the others.
async fn next<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
if let Some(t) = f(self.events.recv().await.expect("engine events")) {
return t;
}
}
})
.await
.expect("event in time")
}
/// The next state of the session that `ok` accepts.
async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState {
self.next(|e| match e {
Event::State { state, .. } if ok(&state) => Some(state),
_ => None,
})
.await
}
/// The next live chat message.
async fn chat(&mut self) -> ChatMessage {
self.next(|e| match e {
Event::Chat { message, .. } => Some(message),
_ => None,
})
.await
}
}
fn now_ms() -> i64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64
}
fn capabilities(streams: bool) -> Capabilities {
Capabilities { streams, file_transfer: true, ..Default::default() }
}
fn backend() -> BackendInfo {
BackendInfo { product: "Fake".into(), version: "1.2".into() }
}
fn connected(streams: bool) -> LinkEvent {
LinkEvent::Connected {
name: "Fake Server".into(),
backend: backend(),
capabilities: capabilities(streams),
own_client: ME,
server_uid: SERVER_UID.into(),
own_uid: Some(ME_UID.into()),
}
}
/// A client as a TeamSpeak link reports one: with its database id, and not
/// talking (who talks comes from the media, which the session derives).
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
ClientInfo {
id,
uid: Some(format!("{nickname}=")),
nickname: nickname.into(),
channel,
talking: Some(false),
database_id: Some(1_000 + u64::from(id)),
..Default::default()
}
}
/// Two channels, three clients; we are in the second channel. The shape is
/// what a TeamSpeak link reports: sibling channels form an order chain, the
/// server is named and has its unique id.
fn presence() -> Presence {
let channel =
|id, name: &str, order| ChannelInfo { id, name: name.into(), order, ..Default::default() };
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
presence.server = ServerDetails {
name: "Fake Server".into(),
uid: Some(SERVER_UID.into()),
version: backend().version,
..Default::default()
};
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby", 0));
presence.channels.insert(GAMES, channel(GAMES, "Games", LOBBY));
let me = ClientInfo { uid: Some(ME_UID.into()), ..client(ME, "tester", GAMES) };
for c in [me, client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
presence.clients.insert(c.id, c);
}
presence
}
fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
ChatMessage {
target: ChatTarget::Channel(GAMES),
author_name: author.into(),
author_uid: Some(format!("{author}=")),
author_id: None,
text: text.into(),
ts_ms,
via_relay: false,
blocked: false,
}
}
/// Stream commands reach a link that has streams in its capabilities, and
/// end with the connection; a link without them is spared. (The rest of what
/// the user asks for is checked on the fake host in `session_fake.rs`.)
#[tokio::test(flavor = "multi_thread")]
async fn stream_commands_reach_a_link_with_streams() {
let mut h = Harness::start();
let mut conn = h.connect().await;
conn.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
// No streams in the capabilities: the session refuses them itself.
let engine = h.engine.clone();
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
let error = h
.next(|e| match e {
Event::Error { message, .. } => Some(message),
_ => None,
})
.await;
assert!(error.contains("streams"), "{error}");
assert!(conn.cmds.try_recv().is_err(), "nothing reached the link");
// A link with streams: stream commands go to it, and end with the connection.
let mut with_streams = {
let link_engine = h.engine.clone();
link_engine.send(Command::ConnectVoice {
session: SESSION,
options: Box::new(VoiceOptions::new("fake.test:9987", "tester")),
});
h.conns.recv().await.expect("the second connection")
};
// The replaced connection is told to go.
assert!(matches!(conn.cmd().await, LinkCmd::Disconnect));
with_streams.play([connected(true)]);
h.next(|e| match e {
Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()),
_ => None,
})
.await;
// A connection with streams is given the (empty) stream directory first.
let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else {
panic!("the stream directory")
};
assert!(directory.is_empty());
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else {
panic!("a stream start")
};
assert_eq!((setup.name.as_str(), auto_accept), ("screen", true));
engine.send(Command::StopStream { session: SESSION });
assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop)));
engine.send(Command::DisconnectVoice { session: SESSION });
assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect));
}
/// A reconnect ends the streams of the connection it replaces through that
/// connection, before the connection itself: the old link is given
/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its
/// connection on `Disconnect` (the TeamSpeak one stops reading commands
/// there) relies on this order for the streams to hear of their end.
#[tokio::test(flavor = "multi_thread")]
async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() {
let mut h = Harness::start();
let mut old = h.connect().await;
old.play([
connected(true),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else {
panic!("the stream directory")
};
assert!(directory.is_empty());
// Connecting again replaces the connection.
let _new = h.connect().await;
let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else {
panic!("the streams end first")
};
assert_eq!(reason, "voice reconnecting");
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
}
/// Events of a connection the session replaced do not reach it.
#[tokio::test(flavor = "multi_thread")]
async fn a_replaced_connection_is_ignored() {
let mut h = Harness::start();
let mut old = h.connect().await;
old.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let new = h.connect().await;
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
// The old connection winds down, and says more than it should.
let mut stale = presence();
stale.clients.insert(10, client(10, "ghost", LOBBY));
old.play([
LinkEvent::Presence(Box::new(stale)),
LinkEvent::Chat(message("ghost", "boo", now_ms())),
LinkEvent::Disconnected(None),
]);
let mut fresh = presence();
fresh.clients.remove(&9);
// A link that says we are in the lobby shows us in the lobby.
fresh.clients.get_mut(&ME).expect("we are on the server").channel = LOBBY;
new.play([
connected(false),
LinkEvent::Presence(Box::new(fresh.clone())),
LinkEvent::OwnChannel(LOBBY),
]);
// Only the new connection's presence is shown (nobody else has 2 clients).
let shown = h
.next(|e| match e {
Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => {
Some(presence)
}
_ => None,
})
.await;
assert_eq!(*shown, fresh);
let state = h.state(|s| s.own_channel == Some(LOBBY)).await;
assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count");
// Channel chat reaches the channel we are in (the lobby, now).
new.play([LinkEvent::Chat(ChatMessage {
target: ChatTarget::Channel(LOBBY),
..message("alice", "hello", now_ms())
})]);
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
}
+322
View File
@@ -0,0 +1,322 @@
//! The engine's side of the seam against the protocol repository's fake host
//! (`docs/session-seam.md` sections 9.2 and 16): the voice path through a
//! `SessionLink` that talks to a `FakeSession`, and the link conformance
//! suite run against the session the engine's registry hands over.
//!
//! The tests that need only the engine's public API are in
//! `tests/session_fake.rs`; these need what is private to the crate: the
//! `LinkCmd`/`LinkEvent` vocabulary between `session.rs` and `SessionLink`,
//! the registry's `connect` and the context of a connector called outside an
//! engine.
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaClass, MediaPacket, voice_sub};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
use voelin_proto::test_util::{
FAKE_HOST_UID, FakeConnector, FakeHandle, connect_params, eventually,
};
use voelin_proto::v1::{self, entity::Kind};
use super::*;
const WAIT: Duration = Duration::from_secs(10);
/// An Opus frame of 20 ms, mono (TOC `0xf8`), and the same as stereo (`0xfc`).
const MONO: [u8; 3] = [0xf8, 0xff, 0xfe];
const STEREO: [u8; 3] = [0xfc, 0xff, 0xfe];
const ALICE: u32 = 50;
const ALICE_SLOT: u32 = 90;
const BOB: u32 = 51;
const BOB_SLOT: u32 = 91;
fn put(connector: &FakeConnector, kind: Kind) {
connector.host().put(v1::Entity { kind: Some(kind) }).expect("the fake host stores it");
}
/// A host with one server, a lobby, and alice and bob talking in it.
fn host() -> FakeConnector {
let connector = FakeConnector::new();
put(
&connector,
Kind::Server(v1::Server {
id: 1,
name: "Fake Host".into(),
uid: "fake-host".into(),
default_channel_id: 10,
..Default::default()
}),
);
put(
&connector,
Kind::Channel(v1::Channel {
id: 10,
server_id: 1,
kind: v1::ChannelKind::Voice as i32,
name: "Lobby".into(),
..Default::default()
}),
);
for (user, participant, slot, name) in
[(2, ALICE, ALICE_SLOT, "alice"), (3, BOB, BOB_SLOT, "bob")]
{
put(
&connector,
Kind::User(v1::User {
id: user,
uid: vec![user as u8; 32].into(),
uid_kind: v1::IdKind::Voelin as i32,
name: name.into(),
..Default::default()
}),
);
put(
&connector,
Kind::Voice(v1::VoiceState {
server_id: 1,
participant_id: participant,
user_id: user,
channel_id: 10,
slot,
nick: name.into(),
..Default::default()
}),
);
}
connector
}
/// A `SessionLink` over a fake host, driven the way `session.rs` drives it.
struct HostRig {
handle: FakeHandle,
cmds: mpsc::UnboundedSender<LinkCmd>,
events: mpsc::UnboundedReceiver<LinkEvent>,
/// Our participant and voice slot, as the host gave them.
own_client: u16,
own_slot: u32,
/// The clients the link told started talking, in order.
talking: Vec<u16>,
}
/// The next event `f` picks from `events`, skipping the others.
async fn event_of<T>(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
mut f: impl FnMut(LinkEvent) -> Option<T>,
) -> T {
tokio::time::timeout(WAIT, async {
loop {
if let Some(t) = f(events.recv().await.expect("the link lives")) {
return t;
}
}
})
.await
.expect("an event in time")
}
impl HostRig {
async fn connect() -> Self {
let connector = host();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let link = SessionLink::new(backends);
let (cmds, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
let ctx = LocalCtx::standalone().link;
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
let own_client = event_of(&mut events, |e| match e {
LinkEvent::Connected { own_client, .. } => Some(own_client),
_ => None,
})
.await;
event_of(&mut events, |e| matches!(e, LinkEvent::OwnChannel(10)).then_some(())).await;
let own_slot = connector
.host()
.entities(&v1::Scope { kind: v1::ScopeKind::Live as i32, id: 1 })
.into_iter()
.find_map(|e| match e.kind? {
Kind::Voice(v) if v.participant_id == u32::from(own_client) => Some(v.slot),
_ => None,
})
.expect("the host seated us in voice");
let handle = connector.last_session().expect("the connector made a session");
Self { handle, cmds, events, own_client, own_slot, talking: Vec::new() }
}
/// The next voice packet the audio thread would get; who started to talk on
/// the way is kept in `talking`.
async fn audio(&mut self) -> VoicePacket {
let talking = &mut self.talking;
event_of(&mut self.events, |e| match e {
LinkEvent::Talking { client, talking: true } => {
talking.push(client);
None
}
LinkEvent::Audio(packet) => Some(packet),
_ => None,
})
.await
}
fn give(&self, cmd: LinkCmd) {
self.cmds.send(cmd).expect("the link listens");
}
}
/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it.
fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket {
let flow = FlowId::new(slot, sub);
let mut out = bytes::BytesMut::new();
RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960)
.write(flow, &mut out)
.expect("a header");
out.extend_from_slice(payload);
MediaPacket { flow, rtp: out.freeze() }
}
fn voice(payload: &[u8]) -> EncodedVoice {
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
}
/// Our voice leaves as RTP on the slot the host gave us: the sequence counts
/// every packet, the timestamp advances by the duration of the previous one,
/// the marker is on the first packet of a spurt, the end of a spurt is an
/// empty payload sent once, and the SSRC is the flow (protocol section 6).
#[tokio::test(flavor = "multi_thread")]
async fn our_voice_is_rtp_on_the_slot_the_host_gave_us() {
let rig = HostRig::connect().await;
// The fake host loops accepted media back; this test looks at what left.
rig.handle.set_loopback(false);
for n in 1..=3 {
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, n])));
}
rig.give(LinkCmd::Audio(voice(&[])));
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, 9])));
let handle = rig.handle.clone();
eventually(WAIT, "the five packets", || handle.sent_media().len() == 5).await;
let flow = FlowId::new(rig.own_slot, voice_sub::CHANNEL);
let sent = rig.handle.sent_media();
let seen: Vec<_> = sent
.iter()
.map(|(class, packet)| {
let view = RtpView::parse(&packet.rtp).expect("RTP");
assert_eq!(*class, MediaClass::Voice);
assert_eq!(packet.flow, flow);
assert_eq!((view.payload_type(), view.ssrc()), (PT_OPUS, flow.0));
(view.sequence(), view.marker(), view.timestamp(), view.payload().to_vec())
})
.collect();
let ticks = OPUS_20_MS_TICKS;
assert_eq!(
seen,
[
(0, true, 0, vec![0xf8, 0xff, 0xfe, 1]),
(1, false, ticks, vec![0xf8, 0xff, 0xfe, 2]),
(2, false, 2 * ticks, vec![0xf8, 0xff, 0xfe, 3]),
// The end of the spurt: no payload, no marker, once.
(3, false, 3 * ticks, vec![]),
// The next spurt marks its first packet again.
(4, true, 3 * ticks, vec![0xf8, 0xff, 0xfe, 9]),
]
);
}
/// The RTP of other slots becomes the packets of the audio thread: the talker
/// is the participant of the slot, a whisper sub-flow is a whisper, a stereo
/// Opus frame is music, an empty payload ends the spurt; what is no voice of a
/// slot the host told about is dropped.
#[tokio::test(flavor = "multi_thread")]
async fn the_voice_of_other_slots_reaches_the_audio_thread() {
let mut rig = HostRig::connect().await;
let handle = rig.handle.clone();
// A slot nobody has, a probe and feedback: nothing. Then alice, mono.
handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &MONO));
handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) });
handle.inject_media(MediaPacket {
flow: FlowId::FEEDBACK,
rtp: bytes::Bytes::from_static(&[1, 2]),
});
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 5, &MONO));
let packet = rig.audio().await;
assert_eq!(
(packet.talker.0, packet.seq, packet.codec, packet.whisper, packet.payload.as_slice()),
(ALICE as u16, 5, VoiceCodec::Voice, false, MONO.as_slice())
);
// Bob whispers (sub-flow 1) in stereo: music, a whisper.
handle.inject_media(voice_packet(BOB_SLOT, 1, 6, &STEREO));
let packet = rig.audio().await;
assert_eq!(
(packet.talker.0, packet.seq, packet.codec, packet.whisper),
(BOB as u16, 6, VoiceCodec::Music, true)
);
// Alice stops: an empty payload.
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 7, &[]));
let packet = rig.audio().await;
assert_eq!((packet.talker.0, packet.seq, packet.payload.len()), (ALICE as u16, 7, 0));
// Who talks comes from the same packets: alice started, then bob, once each
// (the slot nobody has started nobody).
assert_eq!(rig.talking, [ALICE as u16, BOB as u16]);
}
/// A host whose session loops our own voice back (the fake one does, so that
/// the conformance suite can see media move) does not make the engine play us
/// our own voice or show us as talking: the engine never plays itself.
#[tokio::test(flavor = "multi_thread")]
async fn our_own_voice_coming_back_is_not_played_back() {
let mut rig = HostRig::connect().await;
// The fake host loops accepted media back into the sink (the default).
rig.give(LinkCmd::Audio(voice(&MONO)));
let handle = rig.handle.clone();
eventually(WAIT, "the packet to leave", || handle.sent_media().len() == 1).await;
// A packet of alice behind it: when this one is out, ours has been through.
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &MONO));
let own = rig.own_client;
let mut heard = Vec::new();
while heard.last().is_none_or(|talker| *talker != ALICE as u16) {
heard.push(rig.audio().await.talker.0);
}
assert!(!heard.contains(&own), "the engine played our own voice back: {heard:?}");
}
/// The link conformance suite of the protocol repository against the session
/// the engine's registry hands over: the registry adds nothing to a plain
/// connector's session (`Backends::connect` returns it untouched), so the 17
/// cases pass as they do in the protocol repository, none skipped.
#[tokio::test(flavor = "multi_thread")]
async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
async fn through_the_registry() -> Fixture {
let connector = FakeConnector::new();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let (params, media) = connect_params("fake://conformance");
let local = backends
.connect(params, LocalCtx::standalone())
.await
.unwrap_or_else(|e| panic!("the registry connects: {e}"));
assert_eq!(local.connected.host_uid, FAKE_HOST_UID, "the connector's own answer");
assert!(local.streams.is_none(), "a plain connector has no stream port");
let backend = connector.last_session().expect("the connector made a session");
// The session is the connector's own, so a request id means the same to both.
Fixture {
shared_request_ids: true,
..Fixture::new(local.connected.session, local.connected.pushes, media, backend)
}
}
let report = conformance::run(&through_the_registry).await;
assert_eq!(report.cases.len(), conformance::CASES.len());
assert_eq!(report.cases.len(), 17, "the suite of c8e0e5a has 17 cases");
assert!(
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
"{:?}",
report.cases
);
}
+310
View File
@@ -0,0 +1,310 @@
//! Voice across the seam, engine side (`docs/session-seam.md` section 6.1):
//! our encoded frames as RTP on our voice slot, the RTP of other slots as
//! the audio thread's packets, and who is talking from the media.
//!
//! `voelin-audio`'s [`EncodedVoice`] and [`VoicePacket`] stay what the audio
//! thread speaks; this is the framing in the v1 media codec
//! (`voelin_proto::media`, protocol section 6).
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};
use bytes::BytesMut;
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
use voelin_proto::media::opus::{self, Toc};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
/// A talker is silent after this long without a packet.
pub(crate) const TALK_SILENCE: Duration = Duration::from_millis(400);
/// Our voice as RTP: the sequence number counts every packet from 0, the
/// timestamp starts at 0 and advances by the duration of the previous
/// packet, the marker is set on the first packet of a spurt, and the end of a
/// spurt is a packet with an empty payload, sent once.
#[derive(Default)]
pub(crate) struct Uplink {
sequence: u16,
timestamp: u32,
/// The ticks the last voice packet spans.
ticks: u32,
in_spurt: bool,
}
impl Uplink {
/// `voice` as the RTP packet of our voice slot.
pub(crate) fn frame(&mut self, slot: u32, voice: &EncodedVoice) -> Option<MediaPacket> {
let flow = FlowId::new(slot, voice_sub::CHANNEL);
// The previous packet's duration has passed.
self.timestamp = self.timestamp.wrapping_add(self.ticks);
let end = voice.is_end();
let mut header = RtpHeader::new(PT_OPUS, self.sequence, self.timestamp);
header.marker = !end && !self.in_spurt;
self.ticks =
if end { 0 } else { opus::packet_ticks(&voice.payload).unwrap_or(OPUS_20_MS_TICKS) };
self.in_spurt = !end;
self.sequence = self.sequence.wrapping_add(1);
let mut out = BytesMut::with_capacity(header.encoded_len() + voice.payload.len());
header.write(flow, &mut out).ok()?;
out.extend_from_slice(&voice.payload);
Some(MediaPacket { flow, rtp: out.freeze() })
}
}
/// A voice packet of some slot, taken from its RTP.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Incoming {
pub(crate) slot: u32,
/// Sent on a whisper sub-flow (1 to 6).
pub(crate) whisper: bool,
pub(crate) sequence: u16,
pub(crate) codec: VoiceCodec,
/// Empty: the spurt ends.
pub(crate) payload: Vec<u8>,
}
impl Incoming {
/// Parse a media packet. `None` for what is not the voice of a slot:
/// feedback, probes, a flow that is no media, a packet that is no RTP.
pub(crate) fn parse(packet: &MediaPacket) -> Option<Incoming> {
if !packet.flow.is_media() {
return None;
}
let view = RtpView::parse(&packet.rtp).ok()?;
let payload = view.payload();
// Stereo Opus is music; the jitter buffer decodes both the same way.
let codec = match Toc::parse(payload) {
Ok(toc) if toc.stereo() => VoiceCodec::Music,
_ => VoiceCodec::Voice,
};
Some(Incoming {
slot: packet.flow.slot(),
whisper: (voice_sub::FIRST_TALK_TARGET..=voice_sub::LAST_TALK_TARGET)
.contains(&packet.flow.sub()),
sequence: view.sequence(),
codec,
payload: payload.to_vec(),
})
}
/// The packet for the audio thread, from `talker`.
pub(crate) fn voice(self, talker: u16) -> VoicePacket {
VoicePacket {
talker: TalkerId(talker),
seq: self.sequence,
codec: self.codec,
whisper: self.whisper,
payload: self.payload,
}
}
}
/// Who is talking: derived from the media (protocol section 6.4). A talker
/// starts with its first packet and stops after [`TALK_SILENCE`] without one.
///
/// A host can also say that someone talks whose voice it does not carry as
/// media (a `Speaking` signal; TeamSpeak's Speex and CELT talkers are such):
/// that is a hint, which holds until the host says it is over.
#[derive(Default)]
pub(crate) struct TalkTracker {
last: HashMap<u16, Instant>,
hinted: HashSet<u16>,
}
impl TalkTracker {
/// A packet of `client` arrived; whether this starts its talking.
pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool {
let was = self.is_talking(client);
self.last.insert(client, now);
!was
}
/// The host says `client` talks or has stopped; whether this changes
/// whether it is talking.
pub(crate) fn hint(&mut self, client: u16, talking: bool) -> bool {
let was = self.is_talking(client);
if talking {
self.hinted.insert(client);
} else {
self.hinted.remove(&client);
}
was != self.is_talking(client)
}
/// Forget the hints about clients `present` does not hold any more: a
/// client that left cannot say it stopped.
pub(crate) fn retain_hints(&mut self, present: impl Fn(u16) -> bool) {
self.hinted.retain(|client| present(*client));
}
/// The talkers that have been silent long enough, no longer talking.
pub(crate) fn expire(&mut self, now: Instant) -> Vec<u16> {
let mut silent: Vec<u16> = self
.last
.iter()
.filter(|(_, last)| now.saturating_duration_since(**last) >= TALK_SILENCE)
.map(|(client, _)| *client)
.collect();
silent.sort_unstable();
for client in &silent {
self.last.remove(client);
}
silent.retain(|client| !self.hinted.contains(client));
silent
}
pub(crate) fn is_talking(&self, client: u16) -> bool {
self.last.contains_key(&client) || self.hinted.contains(&client)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// 20 ms of CELT, mono, one frame.
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
fn voice(payload: &[u8]) -> EncodedVoice {
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
}
fn view(packet: &MediaPacket) -> RtpView<'_> {
RtpView::parse(&packet.rtp).unwrap()
}
#[test]
fn our_voice_is_sequenced_stamped_and_marked() {
let mut up = Uplink::default();
let first = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
let second = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
assert_eq!((first.flow.slot(), first.flow.sub()), (8, 0));
let (a, b) = (view(&first), view(&second));
assert_eq!((a.sequence(), a.timestamp(), a.marker()), (0, 0, true));
assert_eq!((b.sequence(), b.timestamp(), b.marker()), (1, OPUS_20_MS_TICKS, false));
assert_eq!((a.ssrc(), a.payload_type()), (first.flow.0, PT_OPUS));
assert_eq!(a.payload(), OPUS_20_MS);
}
#[test]
fn the_end_is_one_empty_packet_and_the_next_spurt_has_a_marker() {
let mut up = Uplink::default();
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
let end = up.frame(8, &voice(&[])).unwrap();
assert!(view(&end).payload().is_empty() && !view(&end).marker());
assert_eq!(view(&end).sequence(), 1);
let next = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
assert!(view(&next).marker());
assert_eq!(view(&next).sequence(), 2);
}
#[test]
fn the_sequence_wraps() {
let mut up = Uplink { sequence: u16::MAX, ..Default::default() };
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
let wrapped = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
assert_eq!(view(&wrapped).sequence(), 0);
}
#[test]
fn received_voice_is_split_into_slot_sub_flow_sequence_and_codec() {
let flow = FlowId::new(9, 0);
let mut header = RtpHeader::new(PT_OPUS, 513, 0);
header.marker = true;
let mut rtp = BytesMut::new();
header.write(flow, &mut rtp).unwrap();
rtp.extend_from_slice(&OPUS_20_MS);
let packet = MediaPacket { flow, rtp: rtp.freeze() };
let got = Incoming::parse(&packet).unwrap();
assert_eq!(
got,
Incoming {
slot: 9,
whisper: false,
sequence: 513,
codec: VoiceCodec::Voice,
payload: OPUS_20_MS.to_vec()
}
);
let voice = got.voice(8);
assert_eq!((voice.talker, voice.seq, voice.whisper), (TalkerId(8), 513, false));
}
#[test]
fn whispers_stereo_ends_and_what_is_no_voice() {
let packet = |flow: FlowId, payload: &[u8]| {
let mut rtp = BytesMut::new();
RtpHeader::new(PT_OPUS, 1, 0).write(flow, &mut rtp).unwrap();
rtp.extend_from_slice(payload);
MediaPacket { flow, rtp: rtp.freeze() }
};
assert!(Incoming::parse(&packet(FlowId::new(9, 3), &OPUS_20_MS)).unwrap().whisper);
assert!(!Incoming::parse(&packet(FlowId::new(9, 7), &OPUS_20_MS)).unwrap().whisper);
let stereo = [OPUS_20_MS[0] | 0x04, 1, 2];
assert_eq!(
Incoming::parse(&packet(FlowId::new(9, 0), &stereo)).unwrap().codec,
VoiceCodec::Music
);
let end = Incoming::parse(&packet(FlowId::new(9, 0), &[])).unwrap();
assert!(end.payload.is_empty() && end.voice(8).is_end());
// Feedback and probes are no voice.
assert!(
Incoming::parse(&MediaPacket { flow: FlowId::FEEDBACK, rtp: Default::default() })
.is_none()
);
assert!(
Incoming::parse(&MediaPacket { flow: FlowId::PROBE, rtp: Default::default() })
.is_none()
);
assert!(
Incoming::parse(&MediaPacket { flow: FlowId::new(9, 0), rtp: vec![1, 2].into() })
.is_none()
);
}
#[test]
fn a_talker_starts_with_a_packet_and_stops_400_ms_after_its_last() {
let mut talk = TalkTracker::default();
let t0 = Instant::now();
assert!(talk.heard(8, t0));
assert!(!talk.heard(8, t0 + Duration::from_millis(100)), "already talking");
assert!(talk.heard(9, t0 + Duration::from_millis(150)));
assert!(talk.is_talking(8));
// 399 ms after 8's last packet: still talking.
assert!(talk.expire(t0 + Duration::from_millis(499)).is_empty());
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [8]);
assert!(!talk.is_talking(8) && talk.is_talking(9));
assert_eq!(talk.expire(t0 + Duration::from_millis(551)), [9]);
// A packet after the silence starts it again.
assert!(talk.heard(8, t0 + Duration::from_secs(2)));
}
#[test]
fn a_host_that_says_someone_talks_is_believed_until_it_says_otherwise() {
let mut talk = TalkTracker::default();
let t0 = Instant::now();
// A talker whose voice is no media: on, and no silence ends it.
assert!(talk.hint(8, true));
assert!(!talk.hint(8, true), "already talking");
assert!(talk.is_talking(8));
assert!(talk.expire(t0 + Duration::from_secs(60)).is_empty());
assert!(talk.hint(8, false));
assert!(!talk.is_talking(8));
// A talker with media that the host also names: the media ends it, when
// the host has said it is over (in either order).
assert!(talk.heard(9, t0));
assert!(!talk.hint(9, true), "heard already");
assert!(talk.expire(t0 + Duration::from_millis(500)).is_empty(), "the host still says so");
assert!(talk.is_talking(9));
assert!(talk.hint(9, false));
assert!(!talk.is_talking(9));
assert!(talk.heard(10, t0));
assert!(!talk.hint(10, false), "the media goes on");
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [10]);
// A hint about somebody who is gone is forgotten.
assert!(talk.hint(11, true));
talk.retain_hints(|client| client != 11);
assert!(!talk.is_talking(11));
}
}
+322
View File
@@ -0,0 +1,322 @@
//! The engine's seam to the server its voice source talks to.
//!
//! A session merges up to three sources (voice, gateway, query). The *voice*
//! source is the connection that is visible on the server, can talk and
//! carries chat, files, pokes, offline messages and streams. The engine holds
//! it as a `voelin_proto::link::Session`, the backend-neutral interface of the
//! protocol repository, and knows nothing else of the server software behind
//! it: which backend makes the `Session` is the scheme of the address, and
//! [`Backends`] is the registry of connectors by scheme
//! ([`Backends::default`] has the TeamSpeak one,
//! [`crate::ts::TsConnector`]; a Voelin host's QUIC connector will be
//! another). [`VoiceOptions`] says what to connect to and as whom.
//!
//! Inside the crate `session.rs` merges and routes, and an adapter below it
//! turns what it asks into `Session` calls and what the `Session` pushes into
//! what it hears (`link/session_link.rs`, with `project.rs` and `media.rs`);
//! `docs/session-seam.md` describes the mapping row by row.
mod backends;
mod connect;
#[cfg(test)]
mod fake_link_tests;
#[cfg(test)]
mod fake_tests;
pub(crate) mod media;
pub(crate) mod project;
mod session_link;
#[cfg(test)]
mod tests;
pub use backends::Backends;
pub(crate) use backends::{
LocalConnected, LocalConnector, LocalCtx, StreamEvent, StreamPort, without_query,
};
pub(crate) use connect::{VERSION_PARAM, connect_params};
pub(crate) use session_link::SessionLink;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::{broadcast, oneshot};
use voelin_audio::{EncodedVoice, VoicePacket};
use voelin_identity::IdentityBlob;
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
use voelin_stream::PeerConfig;
use crate::files::{Report, RequestId, Sink, TransferId};
use crate::settings::SharedSettings;
use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame};
use crate::{BackendInfo, Event, SessionId};
/// What a voice connection needs to know: the server, who to be, where to
/// join ([`Command::ConnectVoice`](crate::Command::ConnectVoice)).
///
/// Nothing in it belongs to one kind of server: what a connector needs of it
/// that is its own (a TeamSpeak identity, the client version to claim) is in
/// the `identity` blob and the `client_version` spec, which the connector of
/// the address reads.
#[derive(Clone, Debug)]
pub struct VoiceOptions {
/// The server: `host[:port]` of a TeamSpeak bookmark, or an address with a
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
/// that picks the connector ([`Backends`]).
pub address: String,
pub nickname: String,
/// The identity to connect with: a TeamSpeak identity
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
/// for a Voelin host. None lets the connector make one up (a TeamSpeak
/// connection generates an identity, which a server then knows as a new
/// client).
pub identity: Option<IdentityBlob>,
/// The client version a TeamSpeak server is shown, as a spec for
/// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
/// none ends the connect with the reason. Other backends ignore it.
pub client_version: Option<String>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections (TeamSpeak 6).
pub stream_peer: PeerConfig,
}
impl VoiceOptions {
/// Options for `address` and `nickname`; everything else is left to the
/// connector.
pub fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
Self {
address: address.into(),
nickname: nickname.into(),
identity: None,
client_version: None,
server_password: None,
channel: None,
channel_password: None,
token: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
/// What the engine gives a link besides the options: where the connection
/// answers the requests the session need not see, and what it shares with
/// the session's other parts.
#[derive(Clone)]
pub(crate) struct LinkCtx {
pub(crate) session: SessionId,
pub(crate) events: broadcast::Sender<Event>,
/// The frames of watched streams (kept off the event bus).
pub(crate) frames: broadcast::Sender<StreamFrame>,
pub(crate) settings: SharedSettings,
}
impl LinkCtx {
/// The session this connection belongs to.
pub(crate) fn session(&self) -> SessionId {
self.session
}
/// Tell the engine's event bus something (a request's answer, a
/// transfer's progress).
pub(crate) fn emit(&self, event: Event) {
let _ = self.events.send(event);
}
pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) {
self.emit(Event::RequestDone { session: self.session, request, result });
}
}
/// A file on the server: channel, its password, path.
#[derive(Clone, Debug)]
pub(crate) struct Remote {
pub channel: ChannelId,
pub password: Option<String>,
pub path: String,
}
/// A boxed stream of bytes to read: the body of a file the server sends.
pub(crate) type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
/// A connection that can be read and written: a file transfer connection.
pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {}
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
/// A boxed [`Duplex`].
pub(crate) type BoxDuplex = Pin<Box<dyn Duplex>>;
/// What the session asks of a connection.
pub(crate) enum LinkCmd {
SendChat(ChatTarget, String),
Move(ChannelId, Option<String>),
SetInputMuted(bool),
SetOutputMuted(bool),
/// An encoded voice frame from the audio thread.
Audio(EncodedVoice),
/// A stream command; the link answers on the event bus. Only sent while
/// the connection's capabilities include streams.
Stream(StreamCmd),
Poke {
client: u16,
message: String,
},
ListFiles {
request: RequestId,
dir: Remote,
},
/// Download `file`; `transfer` if the user can cancel it.
Download {
transfer: Option<TransferId>,
file: Remote,
sink: Sink,
report: Report,
},
Upload {
transfer: Option<TransferId>,
file: Remote,
from: PathBuf,
overwrite: bool,
resume: bool,
report: Report,
},
CancelTransfer(TransferId),
/// Open a file of the server for reading, from `offset`: the transfer
/// connection itself, and the file's size in all, once the server has
/// agreed (the text of the failure otherwise). The engine copies the
/// bytes, reports the progress and cancels by dropping the connection, so
/// this does not use [`LinkCmd::Download`]'s sink and report.
OpenRead {
file: Remote,
offset: u64,
reply: oneshot::Sender<Result<(u64, BoxRead), String>>,
},
/// Open a file of the server for writing: the transfer connection and the
/// position the server wants the bytes from (the size it already has, if
/// `resume`). The engine writes the bytes and ends the connection.
OpenWrite {
file: Remote,
/// The file's size in all.
size: u64,
overwrite: bool,
resume: bool,
reply: oneshot::Sender<Result<(u64, BoxDuplex), String>>,
},
DeleteFiles {
/// `None`: best effort, nobody waits for the answer.
request: Option<RequestId>,
channel: ChannelId,
password: Option<String>,
paths: Vec<String>,
},
RenameFile {
request: RequestId,
from: Remote,
to: Remote,
},
CreateDirectory {
request: RequestId,
dir: Remote,
},
/// Announce our avatar's hash (empty: no avatar).
SetAvatarHash {
request: Option<RequestId>,
hash: String,
},
OfflineList {
request: RequestId,
},
OfflineGet {
request: RequestId,
id: u32,
},
OfflineAdd {
request: RequestId,
to_uid: String,
subject: String,
text: String,
},
OfflineDelete {
request: RequestId,
id: u32,
},
OfflineFlag {
request: RequestId,
id: u32,
read: bool,
},
Disconnect,
}
/// What a connection tells the session.
pub(crate) enum LinkEvent {
Connected {
name: String,
/// The server software, and what it can do (the connection knows
/// both from the server's version).
backend: BackendInfo,
capabilities: Capabilities,
/// Our client id when the link connected. TeamSpeak's own reconnect gives
/// a new one, which is not announced; the engine follows it in the
/// snapshots by our unique id.
own_client: u16,
/// The server's unique id.
server_uid: String,
/// Our unique id as the server knows it.
own_uid: Option<String>,
},
/// The server's channels and clients as they are now.
Presence(Box<Presence>),
/// The channel we are in, after every [`LinkEvent::Presence`]. The engine
/// derives it itself, from our own voice state in the snapshots of the
/// `Session` it talks to, and so follows us when TeamSpeak's reconnect makes
/// us another client. What an in-process link such as `TsLink` says here only
/// tells the TeamSpeak `Session` made of it that a move has arrived.
OwnChannel(ChannelId),
Chat(ChatMessage),
Poke {
from: u16,
from_uid: Option<String>,
from_name: String,
message: String,
},
/// Incoming voice for the audio thread.
Audio(VoicePacket),
/// Who is talking (on, and off again when it stopped). The engine derives
/// it from the media of its `Session` (protocol section 6.4). What an
/// in-process link such as `TsLink` says here reaches the engine as a
/// speaking hint next to the media: that is what shows the talkers whose
/// packets the link does not forward as Opus (Speex, CELT).
Talking {
client: u16,
talking: bool,
},
/// Our own stream's life, for the gateway directory.
OwnStream(OwnStreamEvent),
/// An Opus frame (48 kHz) of a watched stream, for the audio thread
/// ([`VoiceOptions::audio`]); `time` is its RTP time on the 48 kHz
/// clock.
StreamAudio {
stream: String,
time: u64,
data: Arc<[u8]>,
},
/// A watched stream ended: its audio leaves the mixer.
StreamAudioEnded(String),
/// A command failed (the connection stays).
Error(String),
/// The connection ended; the reason if it was not asked for. Sent once;
/// the stream task's closing reports may still follow (see the module
/// documentation).
Disconnected(Option<String>),
}
+214
View File
@@ -0,0 +1,214 @@
//! The engine's view of a session's replica, in the client's older model
//! (`docs/session-seam.md` section 5.3).
//!
//! The UI and `session.rs` still speak `Presence`, `ChannelInfo`,
//! `ClientInfo`, `ServerDetails` and `ChatMessage`. [`presence`] and
//! [`chat_message`] project the replica into them with
//! `voelin_model::replica::convert`, and fix up where that says less than the
//! older model does (F1 to F10 of the design). The fix-ups apply the
//! TeamSpeak gateway's id rules of protocol section 11.1, so the UI keeps the
//! ids it has; they go when the UI reads the replica.
use std::collections::BTreeMap;
use voelin_model::replica::{Replica, convert};
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
use voelin_proto::link::Features;
use voelin_proto::v1::{self, ChannelKind, MessageFlag, RoleScope};
use super::media::TalkTracker;
use crate::ts::ts_session::entities::user_uid;
use crate::ts::ts_session::ids::{self, FOREIGN_SYSTEM};
/// What the projection needs to know besides the replica.
pub(crate) struct View<'a> {
pub(crate) replica: &'a Replica,
/// The server of the session.
pub(crate) server: u64,
/// The backend is TeamSpeak (`Welcome.host.backend.product`): its id rules
/// (channel groups) are undone.
pub(crate) teamspeak: bool,
/// The version the host said (`Welcome.host.backend.version`).
pub(crate) version: &'a str,
pub(crate) features: &'a Features,
/// Whether the connection has streams (a port, not just the feature).
pub(crate) streams: bool,
pub(crate) talking: &'a TalkTracker,
}
/// What a `Foreign` of TeamSpeak holds under `key`.
fn foreign_value(
foreign: Option<&v1::Foreign>,
kind: &str,
key: &str,
) -> Option<serde_json::Value> {
let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?;
serde_json::from_slice::<serde_json::Value>(&foreign.json).ok()?.get(key).cloned()
}
/// The server's unique id as the client keys its history and aliases by it:
/// the host's without the `ts:` of protocol section 11.2 (F3).
pub(crate) fn server_key(uid: &str) -> String {
uid.strip_prefix("ts:").unwrap_or(uid).to_owned()
}
/// The client's older model of the server (what `LinkEvent::Presence` holds).
pub(crate) fn presence(view: &View<'_>) -> Presence {
let replica = view.replica;
let server = view.server;
// F1: only what the older model calls channels.
let channels: Vec<&v1::Channel> = replica
.channels(server)
.filter(|channel| {
!matches!(
ChannelKind::try_from(channel.kind),
Ok(ChannelKind::ServerChat
| ChannelKind::Dm
| ChannelKind::GroupDm
| ChannelKind::Thread)
)
})
.collect();
let by_id: BTreeMap<u64, &v1::Channel> = channels.iter().map(|c| (c.id, *c)).collect();
let channel_infos = convert::channel_infos(&channels)
.into_iter()
.map(|mut info| {
// F7: a limit of 0 is a limit, not "unlimited".
let zero = by_id
.get(&info.id)
.and_then(|c| foreign_value(c.foreign.as_ref(), "channel", "max_clients"));
if zero.and_then(|v| v.as_i64()) == Some(0) {
info.max_clients = Some(0);
}
(info.id, info)
})
.collect();
let clients = replica
.voice_states(server)
.filter_map(|voice| {
let user = replica.user(voice.user_id);
let member = replica.member(server, voice.user_id);
let mut client =
convert::client_info(voice, user, member, replica.presence_of(voice.user_id))?;
// F10: a unique id that is no base64 rides in `Foreign`.
client.uid = user.and_then(user_uid);
// F2: the client's channel group is TeamSpeak's own number.
if view.teamspeak {
client.channel_group = client.channel_group.map(ids::channel_group);
}
// F6: the client's icon.
client.icon = foreign_value(member.and_then(|m| m.foreign.as_ref()), "client", "icon")
.and_then(|v| v.as_u64())
.and_then(|v| u32::try_from(v).ok())
.unwrap_or(0);
// F8: who is talking comes from the media.
client.talking = view.features.has("voice").then(|| view.talking.is_talking(client.id));
// F9: the stream flag only where there are streams.
if !view.streams {
client.streaming = None;
}
Some((client.id, client))
})
.collect();
let mut server_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
let mut channel_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
for role in replica.roles(server) {
let mut info = convert::group_info(role);
if role.scope == RoleScope::Channel as i32 {
if view.teamspeak {
info.id = ids::channel_group(info.id);
}
channel_groups.insert(info.id, info);
} else {
server_groups.insert(info.id, info);
}
}
let details = replica.server(server).map(|stub| server_details(view, stub)).unwrap_or_default();
Presence {
server_name: details.name.clone(),
channels: channel_infos,
clients,
server: details,
server_groups,
channel_groups,
}
}
/// `convert::server_details` with F2 to F5.
fn server_details(view: &View<'_>, server: &v1::Server) -> ServerDetails {
let mut details = convert::server_details(server);
// F3: the unique id as the client keys it.
details.uid = details.uid.as_deref().map(server_key);
let foreign = server.foreign.as_ref();
// F4: the version the server sent, else the one the host reports.
details.version = foreign_value(foreign, "server", "version")
.and_then(|v| v.as_str().map(str::to_owned))
.filter(|v| !v.is_empty())
.unwrap_or_else(|| view.version.to_owned());
// F5: the server's platform.
details.platform = foreign_value(foreign, "server", "platform")
.and_then(|v| v.as_str().map(str::to_owned))
.unwrap_or_default();
// F2: the default channel group is TeamSpeak's own number.
if view.teamspeak {
details.default_channel_group = details.default_channel_group.map(ids::channel_group);
}
details
}
/// Where the older model files the messages of a channel (the replica's
/// `chat_target`, with the unique id of F10).
fn chat_target(replica: &Replica, channel: u64) -> ChatTarget {
let Some(info) = replica.channel(channel) else { return ChatTarget::Channel(channel) };
match ChannelKind::try_from(info.kind) {
Ok(ChannelKind::ServerChat) => ChatTarget::Server,
Ok(ChannelKind::Dm | ChannelKind::GroupDm) => {
let own = replica.own_user();
info.recipients
.iter()
.copied()
.find(|id| *id != own)
.and_then(|id| replica.user(id))
.and_then(user_uid)
.map_or(ChatTarget::Channel(channel), ChatTarget::Private)
}
_ => ChatTarget::Channel(channel),
}
}
/// A message of the replica as the older model has it.
pub(crate) fn chat_message(replica: &Replica, channel: u64, id: u64) -> Option<ChatMessage> {
let message = replica.message(channel, id)?;
let author = replica.user(message.author_id);
let name = Some(message.author_name.as_str())
.filter(|name| !name.is_empty())
.or_else(|| author.map(|u| u.name.as_str()).filter(|name| !name.is_empty()))
.unwrap_or_default();
Some(ChatMessage {
target: chat_target(replica, channel),
author_name: name.to_owned(),
author_uid: author.and_then(user_uid),
author_id: (message.author_participant != 0)
.then(|| u16::try_from(message.author_participant).ok())
.flatten(),
text: message.text.clone(),
ts_ms: message.ts_ms,
via_relay: message.flags & MessageFlag::Relayed as u32 != 0,
blocked: false,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_ts_prefix_of_a_server_uid_goes() {
assert_eq!(server_key("ts:abc="), "abc=");
assert_eq!(server_key("abc="), "abc=");
assert_eq!(server_key(""), "");
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+5 -11
View File
@@ -56,16 +56,16 @@ use voelin_media::mix::{
};
pub use voelin_media::mix::{Level, SourceState};
use voelin_media::scale::Pyramid;
use voelin_media::stream::EncodedFrame;
use voelin_media::studio::Studio;
use voelin_media::studio::output::{Packet, Track};
use voelin_media::{
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, H264Profile,
VideoEncoder, VideoFrame,
LayerId, LayerSet, LayerSpec, VideoEncoder, VideoFrame,
};
pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference};
use voelin_stream::{
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
MediaTime, PeerConfig, VideoCodec, VideoFormat,
FrameSource, Frequency, MediaFrame, MediaKind, MediaTime, PeerConfig, VideoCodec, VideoFormat,
};
use crate::settings::{AudioSourceKindSetting, AudioSourceSetting};
@@ -127,13 +127,7 @@ fn spawn(name: &str, f: impl FnOnce() + Send + 'static) -> Result<JoinHandle<()>
/// The `voelin_media` codec of a negotiated video codec.
pub fn media_codec(codec: VideoCodec) -> Codec {
match codec {
VideoCodec::Vp8 => Codec::Vp8,
VideoCodec::Vp9 => Codec::Vp9,
VideoCodec::H264 => Codec::H264,
VideoCodec::Av1 => Codec::Av1,
VideoCodec::H265 => Codec::H265,
}
crate::stream::media_codec(codec)
}
/// The H.264 profile an encoder of `format` makes (Constrained High for
@@ -2686,7 +2680,7 @@ pub struct DecodeStats {
pub bytes: u64,
/// Pictures decoded per second and video received in bit/s, over the
/// time since the previous [`VideoPipeline::stats`] (at least
/// [`RATE_WINDOW`]; the watch screen asks once a second).
/// `RATE_WINDOW`; the watch screen asks once a second).
pub fps: u32,
pub bitrate: u64,
}
+141 -1
View File
@@ -1,11 +1,94 @@
//! The query source: own ServerQuery credentials, in-process observer and relays.
use std::fmt;
use tokio::sync::{broadcast, mpsc};
use voelin_model::{ChatMessage, ChatTarget, Presence};
use voelin_observer::{
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
};
/// How a ServerQuery connection talks to the server.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueryTransport {
/// The raw text protocol (TeamSpeak 3; port 10011).
Raw,
/// SSH.
Ssh,
/// The HTTP query (TeamSpeak 6; a WebQuery API key is the secret).
Http,
}
/// The user's own ServerQuery credentials for a server
/// ([`Command::ObserveQuery`](crate::Command::ObserveQuery)): what the
/// engine logs in with to observe a server invisibly and to relay its
/// channels' chat. The connection's own tuning (flood protection, timeouts)
/// is the engine's.
#[derive(Clone, PartialEq, Eq)]
pub struct QueryLogin {
/// The protocol of the query interface at `address`.
pub transport: QueryTransport,
/// `host:port` of the query interface.
pub address: String,
/// The login name (raw and SSH; ignored for HTTP).
pub user: String,
/// The password (raw and SSH) or API key (HTTP, optional for guest access).
pub secret: Option<String>,
/// Select the virtual server by its voice port...
pub server_port: Option<u16>,
/// ...or by id (the first server when neither is given).
pub server_id: Option<u32>,
/// This machine's address is on the server's query allowlist, which the
/// server's flood protection skips: the engine then sends its commands
/// without the limit it keeps for a server that has not said so (a command
/// the server refuses as a flood slows the connection down all the same).
/// The application usually cannot know, and says `false`; the development
/// servers of the tests allowlist their clients.
pub allowlisted: bool,
}
impl fmt::Debug for QueryLogin {
// The secret is kept out of logs.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("QueryLogin")
.field("transport", &self.transport)
.field("address", &self.address)
.field("user", &self.user)
.field("secret", &self.secret.as_ref().map(|_| "[secret]"))
.field("server_port", &self.server_port)
.field("server_id", &self.server_id)
.field("allowlisted", &self.allowlisted)
.finish()
}
}
impl QueryLogin {
/// The connection the observer and the relays open.
fn connect(&self) -> voelin_query::Connect {
voelin_query::Connect {
transport: match self.transport {
QueryTransport::Raw => voelin_query::Transport::Raw,
QueryTransport::Ssh => voelin_query::Transport::Ssh,
QueryTransport::Http => voelin_query::Transport::Http,
},
addr: self.address.clone(),
user: self.user.clone(),
secret: self.secret.clone(),
server_port: self.server_port,
server_id: self.server_id,
line: voelin_query::LineOptions {
// Off the client-side limit only where the server skips it.
rate_limit: if self.allowlisted {
None
} else {
voelin_query::LineOptions::default().rate_limit
},
..Default::default()
},
}
}
}
pub(crate) enum QueryCmd {
OpenChat(ChatTarget),
CloseChat(ChatTarget),
@@ -21,10 +104,11 @@ pub(crate) enum QueryEvent {
}
pub(crate) async fn run(
connect: voelin_query::Connect,
login: QueryLogin,
mut commands: mpsc::UnboundedReceiver<QueryCmd>,
events: mpsc::UnboundedSender<QueryEvent>,
) {
let connect = login.connect();
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
let relays = RelayPool::new(RelayConfig::new(connect));
let mut observed = observer.subscribe();
@@ -88,3 +172,59 @@ pub(crate) async fn run(
relays.close_all().await;
let _ = events.send(QueryEvent::Disconnected);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_login_is_the_connection_the_query_crate_opens() {
let login = QueryLogin {
transport: QueryTransport::Ssh,
address: "ts.example.com:10022".into(),
user: "serveradmin".into(),
secret: Some("hunter2".into()),
server_port: Some(9987),
server_id: Some(3),
allowlisted: false,
};
let connect = login.connect();
assert_eq!(connect.transport, voelin_query::Transport::Ssh);
assert_eq!(
(connect.addr.as_str(), connect.user.as_str(), connect.secret.as_deref()),
("ts.example.com:10022", "serveradmin", Some("hunter2"))
);
assert_eq!((connect.server_port, connect.server_id), (Some(9987), Some(3)));
for (ours, theirs) in [
(QueryTransport::Raw, voelin_query::Transport::Raw),
(QueryTransport::Http, voelin_query::Transport::Http),
] {
let connect = QueryLogin { transport: ours, ..login.clone() }.connect();
assert_eq!(connect.transport, theirs);
}
// The line options are the query crate's defaults, as the UI always
// gave them, unless the server allowlists the client.
let line = voelin_query::LineOptions::default();
assert!(line.rate_limit.is_some());
assert_eq!(connect.line.rate_limit, line.rate_limit);
assert_eq!(connect.line.timeout, line.timeout);
let allowlisted = QueryLogin { allowlisted: true, ..login.clone() }.connect();
assert_eq!(allowlisted.line.rate_limit, None);
assert_eq!(allowlisted.line.timeout, line.timeout);
}
#[test]
fn the_secret_stays_out_of_the_debug_text() {
let login = QueryLogin {
transport: QueryTransport::Raw,
address: "h:1".into(),
user: "u".into(),
secret: Some("hunter2".into()),
server_port: None,
server_id: None,
allowlisted: false,
};
let text = format!("{login:?}");
assert!(!text.contains("hunter2") && text.contains("[secret]"), "{text}");
}
}
+146 -185
View File
@@ -16,11 +16,9 @@ use tokio::time::Instant;
use tokio::sync::{broadcast, mpsc, watch};
use tracing::{debug, info, warn};
use tsclientlib::ClientId;
use voelin_audio::AudioSettings;
use voelin_audio::{AudioSettings, EncodedVoice, TalkerId};
use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature};
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails, badges};
use voelin_stream::ClientState;
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
use crate::cache::{self, Fetch, FetchError, RetryHint, SharedCache, Waiter};
@@ -31,6 +29,7 @@ use crate::gateway::{
Push, ReactionPush,
};
use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory};
use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, SessionLink};
use crate::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
use crate::settings::{
@@ -38,10 +37,9 @@ use crate::settings::{
PRIVACY_PRIVATE_MESSAGES, SharedSettings,
};
use crate::stream::{
LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo,
StreamInput, StreamKind, kind_name, parse_kind,
LayerSpec, OwnStreamEvent, StreamCmd, StreamFrame, StreamInfo, StreamKind, kind_name,
parse_kind, parse_srtp_profiles,
};
use crate::voice::{self, Remote, VoiceCmd, VoiceEvent, VoiceLink};
use crate::web;
use crate::{Command, Event, ObserveState, SessionId, SessionState, Shared, Source, VoiceState};
@@ -86,14 +84,10 @@ impl SessionHandle {
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
link: Arc<SessionLink>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(
Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data)
.run(rx),
);
tokio::spawn(Session::new(id, events, frames, audio_settings, shared, link).run(rx));
Self { tx }
}
@@ -105,13 +99,11 @@ impl SessionHandle {
/// Events from sources, tagged with the generation of the source so events
/// of a replaced source are ignored.
enum SourceEvent {
Voice(u64, VoiceEvent),
Voice(u64, LinkEvent),
Gateway(u64, GatewayEvent),
Query(u64, QueryEvent),
AudioOut(u64, tsproto_packets::packets::OutPacket),
AudioOut(u64, EncodedVoice),
Audio(u64, AudioEvent),
/// Our own stream (from the stream task of that voice connection).
OwnStream(u64, OwnStreamEvent),
/// The gateway's stream directory after subscribing.
Directory(u64, Result<Vec<StreamEntry>, ClientError>),
/// The server's unique id the database remembers for an address.
@@ -290,13 +282,13 @@ struct OwnStream {
}
struct Session {
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
/// Starts the voice connections.
link: Arc<SessionLink>,
id: SessionId,
events: broadcast::Sender<Event>,
state: SessionState,
generation: u64,
voice: Option<(u64, mpsc::UnboundedSender<VoiceCmd>)>,
voice: Option<(u64, mpsc::UnboundedSender<LinkCmd>)>,
voice_address: String,
voice_presence: Option<Presence>,
nickname: String,
@@ -318,18 +310,15 @@ struct Session {
/// Other names of this server (`voice:<address>`, `gateway:<url>`),
/// remembered with its unique id once a source tells it.
aliases: Vec<String>,
/// Streams of the voice connection (TeamSpeak 6 only).
streams: Option<StreamHandle>,
stream_peer: PeerConfig,
/// The voice connection carries streams (its capabilities say so; the
/// connection runs their task, `LinkCmd::Stream` reaches it).
streams: bool,
/// Simulcast layers of our stream, for the stream task.
stream_layers: Vec<LayerSpec>,
/// The SRTP profile setting (`Command::SetSrtpProfiles`), over the voice
/// options' `stream_peer`.
srtp_profiles: Option<Vec<SrtpProfile>>,
srtp_profiles: Option<Vec<String>>,
frames: broadcast::Sender<StreamFrame>,
/// Channel and `client_is_streaming` of the voice presence, as last told
/// to the streams.
streaming_clients: BTreeMap<u16, ClientState>,
/// The gateway's stream directory, by id.
directory: BTreeMap<String, StreamEntry>,
own_stream: Option<OwnStream>,
@@ -386,15 +375,13 @@ impl Session {
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
link: Arc<SessionLink>,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
let Shared { settings, history, cache, contacts } = shared;
let contacts_rx = Some(contacts.watch());
Self {
myts_identity,
myts_data,
link,
cache,
contacts,
contacts_rx,
@@ -434,12 +421,10 @@ impl Session {
history,
own_uid: None,
aliases: Vec::new(),
streams: None,
stream_peer: PeerConfig::default(),
streams: false,
stream_layers: Vec::new(),
srtp_profiles: None,
frames,
streaming_clients: BTreeMap::new(),
directory: BTreeMap::new(),
own_stream: None,
open_chats: HashSet::new(),
@@ -509,17 +494,19 @@ impl Session {
fn command(&mut self, cmd: Command) {
match cmd {
Command::ConnectVoice { options, .. } => {
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(VoiceCmd::Disconnect);
}
// The streams end first: their shutdown goes through the
// connection that is replaced.
self.stop_streams("voice reconnecting");
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(LinkCmd::Disconnect);
}
let mut options = *options;
let generation = self.next_generation();
self.voice_address = options.address.clone();
self.details = None;
self.nickname = options.nickname.clone();
self.stream_peer = options.stream_peer.clone();
if let Some(profiles) = &self.srtp_profiles {
self.stream_peer.srtp_profiles = profiles.clone();
options.stream_peer.srtp_profiles = parse_srtp_profiles(profiles);
}
self.known_server(format!("voice:{}", options.address));
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
@@ -532,14 +519,13 @@ impl Session {
self.forward(out_rx, move |p| SourceEvent::AudioOut(generation, p));
self.forward(audio_rx, move |e| SourceEvent::Audio(generation, e));
}
let link = VoiceLink {
myts_identity: self.myts_identity.clone(),
myts_data: self.myts_data.clone(),
let ctx = LinkCtx {
session: self.id,
events: self.events.clone(),
frames: self.frames.clone(),
settings: self.settings.clone(),
};
tokio::spawn(voice::run(*options, link, cmd_rx, ev_tx));
self.link.spawn(options, ctx, cmd_rx, ev_tx);
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
self.forget_images();
self.voice = Some((generation, cmd_tx));
@@ -548,7 +534,7 @@ impl Session {
}
Command::DisconnectVoice { .. } => {
if let Some((_, tx)) = &self.voice {
let _ = tx.send(VoiceCmd::Disconnect);
let _ = tx.send(LinkCmd::Disconnect);
}
}
Command::ObserveGateway { urls, identity, .. } => {
@@ -590,7 +576,10 @@ impl Session {
// source, the history is kept under the query address.
if self.state.server_uid.is_none() {
let port = connect.server_port.map(|p| format!("/{p}")).unwrap_or_default();
self.learn_server_uid(format!("query:{}{port}", connect.addr), Source::Query);
self.learn_server_uid(
format!("query:{}{port}", connect.address),
Source::Query,
);
self.open_histories();
}
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
@@ -626,7 +615,7 @@ impl Session {
self.store_own(&target, &text, &route);
}
match route {
ChatRoute::Voice => self.voice_cmd(VoiceCmd::SendChat(target, text)),
ChatRoute::Voice => self.voice_cmd(LinkCmd::SendChat(target, text)),
ChatRoute::Gateway => {
if let Some((_, tx)) = &self.gateway {
let _ = tx.send(GatewayCmd::SendChat(target, text));
@@ -657,11 +646,11 @@ impl Session {
},
Command::Gateway { request, .. } => self.gateway_request(request),
Command::MoveToChannel { channel, password, .. } => {
self.voice_cmd(VoiceCmd::Move(channel, password));
self.voice_cmd(LinkCmd::Move(channel, password));
}
Command::SetInputMuted { muted, .. } => {
self.state.input_muted = muted;
self.voice_cmd(VoiceCmd::SetInputMuted(muted));
self.voice_cmd(LinkCmd::SetInputMuted(muted));
if let Some(a) = &self.audio {
a.send(AudioIn::InputMuted(muted));
}
@@ -669,7 +658,7 @@ impl Session {
}
Command::SetOutputMuted { muted, .. } => {
self.state.output_muted = muted;
self.voice_cmd(VoiceCmd::SetOutputMuted(muted));
self.voice_cmd(LinkCmd::SetOutputMuted(muted));
if let Some(a) = &self.audio {
a.send(AudioIn::OutputMuted(muted));
}
@@ -692,12 +681,12 @@ impl Session {
// again after connecting.
Command::SetClientVolume { client, volume, .. } => {
if let Some(a) = &self.audio {
a.send(AudioIn::ClientVolume { client: ClientId(client), volume });
a.send(AudioIn::ClientVolume { client: TalkerId(client), volume });
}
}
Command::SetClientMuted { client, muted, .. } => {
if let Some(a) = &self.audio {
a.send(AudioIn::ClientMuted { client: ClientId(client), muted });
a.send(AudioIn::ClientMuted { client: TalkerId(client), muted });
}
}
Command::SetStreamVolume { stream_id, volume, .. } => {
@@ -706,50 +695,43 @@ impl Session {
}
}
Command::StartStream { setup, auto_accept, .. } => {
self.stream_input(StreamInput::Start { setup, auto_accept });
self.stream_input(StreamCmd::Start { setup, auto_accept });
}
Command::StopStream { .. } => self.stream_input(StreamInput::Stop),
Command::StopStream { .. } => self.stream_input(StreamCmd::Stop),
Command::AcceptViewer { viewer, accept, .. } => {
self.stream_input(StreamInput::Respond { viewer, accept });
self.stream_input(StreamCmd::Respond { viewer, accept });
}
Command::KickViewer { viewer, .. } => self.stream_input(StreamInput::Kick { viewer }),
Command::KickViewer { viewer, .. } => self.stream_input(StreamCmd::Kick { viewer }),
Command::SendStreamFrame { frame, .. } => {
// Frames without a stream are dropped silently.
if let Some(s) = &self.streams {
s.send(StreamInput::Frame(frame));
}
self.stream_cmd(StreamCmd::Frame(frame));
}
Command::WatchStream { stream_id, .. } => {
self.stream_input(StreamInput::Watch { stream_id });
self.stream_input(StreamCmd::Watch { stream_id });
}
Command::LeaveStream { stream_id, .. } => {
self.stream_input(StreamInput::Leave { stream_id });
self.stream_input(StreamCmd::Leave { stream_id });
}
Command::RequestStreamKeyframe { stream_id, .. } => {
self.stream_input(StreamInput::RequestKeyframe { stream_id });
self.stream_input(StreamCmd::RequestKeyframe { stream_id });
}
Command::StreamUndecodable { stream_id, .. } => {
self.stream_input(StreamInput::Undecodable { stream_id });
self.stream_input(StreamCmd::Undecodable { stream_id });
}
Command::SetWatchLayer { stream_id, layer, .. } => {
self.stream_input(StreamInput::WatchLayer { stream_id, layer });
self.stream_input(StreamCmd::WatchLayer { stream_id, layer });
}
// Kept for streams started later, also without a connection.
Command::SetStreamLayers { layers, .. } => {
self.stream_layers = layers.clone();
if let Some(s) = &self.streams {
s.send(StreamInput::Layers(layers));
}
self.stream_cmd(StreamCmd::Layers(layers));
}
Command::SetSrtpProfiles(profiles) => {
self.stream_peer.srtp_profiles = profiles.clone();
self.srtp_profiles = Some(profiles.clone());
if let Some(s) = &self.streams {
s.send(StreamInput::SrtpProfiles(profiles));
}
self.stream_cmd(StreamCmd::SrtpProfiles(profiles));
}
Command::Poke { client, message, .. } => {
self.voice_cmd(VoiceCmd::Poke { client, message });
self.voice_cmd(LinkCmd::Poke { client, message });
}
Command::ListFiles { request, channel, password, path, .. } => {
if self.voice.is_none() {
@@ -759,7 +741,7 @@ impl Session {
return;
}
let dir = Remote { channel, password, path };
self.voice_cmd(VoiceCmd::ListFiles { request, dir });
self.voice_cmd(LinkCmd::ListFiles { request, dir });
}
Command::DownloadFile { transfer, channel, password, path, to, .. } => {
self.download(transfer, Remote { channel, password, path }, &to);
@@ -797,34 +779,27 @@ impl Session {
let report = self.transfer_report(transfer);
let file = Remote { channel, password, path };
let transfer = Some(transfer);
self.voice_cmd(VoiceCmd::Upload {
transfer,
file,
from,
overwrite,
resume,
report,
});
self.voice_cmd(LinkCmd::Upload { transfer, file, from, overwrite, resume, report });
}
Command::CancelTransfer { transfer, .. } => {
self.voice_cmd(VoiceCmd::CancelTransfer(transfer));
self.voice_cmd(LinkCmd::CancelTransfer(transfer));
}
Command::DeleteFiles { request, channel, password, paths, .. } => {
let request = Some(request);
self.voice_request(
request,
VoiceCmd::DeleteFiles { request, channel, password, paths },
LinkCmd::DeleteFiles { request, channel, password, paths },
);
}
Command::RenameFile { request, channel, password, from, to, to_channel, .. } => {
let (to_channel, to_password) = to_channel.unwrap_or((channel, password.clone()));
let from = Remote { channel, password, path: from };
let to = Remote { channel: to_channel, password: to_password, path: to };
self.voice_request(Some(request), VoiceCmd::RenameFile { request, from, to });
self.voice_request(Some(request), LinkCmd::RenameFile { request, from, to });
}
Command::CreateDirectory { request, channel, password, path, .. } => {
let dir = Remote { channel, password, path };
self.voice_request(Some(request), VoiceCmd::CreateDirectory { request, dir });
self.voice_request(Some(request), LinkCmd::CreateDirectory { request, dir });
}
Command::SetAvatar { request, image, .. } => self.set_avatar(request, image),
Command::FetchAvatar { client_uid, .. } => {
@@ -856,7 +831,7 @@ impl Session {
self.emit(Event::OfflineMessages { session: self.id, request, result });
return;
}
self.voice_cmd(VoiceCmd::OfflineList { request });
self.voice_cmd(LinkCmd::OfflineList { request });
}
Command::GetOfflineMessage { request, id, .. } => {
if self.voice.is_none() {
@@ -864,22 +839,20 @@ impl Session {
self.emit(Event::OfflineMessage { session: self.id, request, result });
return;
}
self.voice_cmd(VoiceCmd::OfflineGet { request, id });
self.voice_cmd(LinkCmd::OfflineGet { request, id });
}
Command::SendOfflineMessage { request, to_uid, subject, text, .. } => {
let cmd = VoiceCmd::OfflineAdd { request, to_uid, subject, text };
let cmd = LinkCmd::OfflineAdd { request, to_uid, subject, text };
self.voice_request(Some(request), cmd);
}
Command::DeleteOfflineMessage { request, id, .. } => {
self.voice_request(Some(request), VoiceCmd::OfflineDelete { request, id });
self.voice_request(Some(request), LinkCmd::OfflineDelete { request, id });
}
Command::SetOfflineMessageRead { request, id, read, .. } => {
self.voice_request(Some(request), VoiceCmd::OfflineFlag { request, id, read });
self.voice_request(Some(request), LinkCmd::OfflineFlag { request, id, read });
}
// Engine-wide.
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::CloseSession { .. }
Command::CloseSession { .. }
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
| Command::ResetSetting { .. }
@@ -894,7 +867,7 @@ impl Session {
// Files, avatars, icons
/// A request to the voice connection; without one it fails at once.
fn voice_request(&self, request: Option<RequestId>, cmd: VoiceCmd) {
fn voice_request(&self, request: Option<RequestId>, cmd: LinkCmd) {
match (&self.voice, request) {
(Some(_), _) => self.voice_cmd(cmd),
(None, Some(request)) => self.emit(Event::RequestDone {
@@ -925,7 +898,7 @@ impl Session {
}
let report = self.transfer_report(transfer);
let sink = Sink::from_target(to);
self.voice_cmd(VoiceCmd::Download { transfer: Some(transfer), file, sink, report });
self.voice_cmd(LinkCmd::Download { transfer: Some(transfer), file, sink, report });
}
/// Upload our avatar and announce its hash, or remove it.
@@ -938,7 +911,7 @@ impl Session {
let Some(image) = image else {
// The file too (best effort), then no hash.
if let Some(path) = self.own_uid.as_deref().and_then(files::avatar_path) {
let cmd = VoiceCmd::DeleteFiles {
let cmd = LinkCmd::DeleteFiles {
request: None,
channel: 0,
password: None,
@@ -947,7 +920,7 @@ impl Session {
self.voice_cmd(cmd);
}
let hash = String::new();
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash });
return;
};
let (sources, cache, settings) =
@@ -983,7 +956,7 @@ impl Session {
let _ = sources.send(SourceEvent::AvatarUploaded(generation, request, result));
});
let file = Remote { channel: 0, password: None, path: "/avatar".into() };
let upload = VoiceCmd::Upload {
let upload = LinkCmd::Upload {
transfer: None,
file,
from: image,
@@ -1403,7 +1376,7 @@ impl Session {
let sink = Sink::File { part: temp.clone(), dest: temp, append: false };
let file = Remote { channel, password: None, path };
let failed = report.clone();
if voice.send(VoiceCmd::Download { transfer: None, file, sink, report }).is_err() {
if voice.send(LinkCmd::Download { transfer: None, file, sink, report }).is_err() {
failed(TransferState::Failed(NO_VOICE.into()));
}
}
@@ -1436,24 +1409,22 @@ impl Session {
if let Some(a) = &self.audio {
for (client, (volume, muted)) in &wanted {
if self.contact_audio.get(client) != Some(&(*volume, *muted)) {
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: *volume });
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: *muted });
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: *volume });
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: *muted });
}
}
// No contact setting any more: back to normal.
for client in self.contact_audio.keys().filter(|c| !wanted.contains_key(c)) {
if p.clients.contains_key(client) {
a.send(AudioIn::ClientVolume { client: ClientId(*client), volume: 1.0 });
a.send(AudioIn::ClientMuted { client: ClientId(*client), muted: false });
a.send(AudioIn::ClientVolume { client: TalkerId(*client), volume: 1.0 });
a.send(AudioIn::ClientMuted { client: TalkerId(*client), muted: false });
}
}
self.contact_audio = wanted;
}
if friends != self.stream_friends {
self.stream_friends = friends.clone();
if let Some(s) = &self.streams {
s.send(StreamInput::Friends(friends));
}
self.stream_cmd(StreamCmd::Friends(friends));
}
}
@@ -1464,7 +1435,7 @@ impl Session {
let clients = p.clients.values().filter(|c| c.priority_speaker).map(|c| c.id).collect();
let wanted = (clients, p.server.priority_speaker_dimm_db);
if wanted != self.priority_audio {
let clients = wanted.0.iter().map(|c| ClientId(*c)).collect();
let clients = wanted.0.iter().map(|c| TalkerId(*c)).collect();
a.send(AudioIn::PrioritySpeakers { clients, dimm_db: wanted.1 as f32 });
self.priority_audio = wanted;
}
@@ -1502,26 +1473,36 @@ impl Session {
allows(self.settings.current().get(key), uid.map(|u| self.contacts.relation(u)))
}
fn stream_input(&self, input: StreamInput) {
match &self.streams {
Some(s) => s.send(input),
None if self.state.voice == VoiceState::Connected => {
self.error("streams need a TeamSpeak 6 server");
}
None => self.error("not connected with voice"),
/// A stream command of the user: an error where the connection has no
/// streams.
fn stream_input(&self, cmd: StreamCmd) {
if self.streams {
self.stream_cmd(cmd);
} else if self.state.voice == VoiceState::Connected {
self.error("streams need a TeamSpeak 6 server");
} else {
self.error("not connected with voice");
}
}
/// A command for the streams of the voice connection; dropped where it
/// has none.
fn stream_cmd(&self, cmd: StreamCmd) {
if let (true, Some((_, tx))) = (self.streams, &self.voice) {
let _ = tx.send(LinkCmd::Stream(cmd));
}
}
fn stop_streams(&mut self, reason: &str) {
if let Some(s) = self.streams.take() {
s.send(StreamInput::Shutdown(reason.into()));
if self.streams {
self.stream_cmd(StreamCmd::Shutdown(reason.into()));
self.streams = false;
}
self.streaming_clients.clear();
// The stream task's report comes from a replaced source.
self.own_stream_ended();
}
fn voice_cmd(&self, cmd: VoiceCmd) {
fn voice_cmd(&self, cmd: LinkCmd) {
match &self.voice {
Some((_, tx)) => {
let _ = tx.send(cmd);
@@ -1710,14 +1691,16 @@ impl Session {
/// The registered streams of the directory, for the stream task.
fn feed_directory(&self) {
let Some(streams) = &self.streams else { return };
if !self.streams {
return;
}
let entries = self
.directory
.values()
.filter_map(|e| {
Some(StreamInfo {
id: e.stream_id.clone()?,
streamer: ClientId(e.client_id?),
streamer: e.client_id?,
name: e.title.clone(),
kind: parse_kind(&e.kind),
// Not in the directory; the stream's offer tells.
@@ -1729,7 +1712,7 @@ impl Session {
})
})
.collect();
streams.send(StreamInput::Directory(entries));
self.stream_cmd(StreamCmd::Directory(entries));
}
fn register_own_stream(&mut self) {
@@ -1834,7 +1817,7 @@ impl Session {
}
self.stop_streams("session closed");
if let Some((_, tx)) = self.voice.take() {
let _ = tx.send(VoiceCmd::Disconnect);
let _ = tx.send(LinkCmd::Disconnect);
}
self.audio = None;
self.stop_observing();
@@ -1858,7 +1841,7 @@ impl Session {
SourceEvent::Query(g, e) if self.is_current(Source::Query, g) => self.query_event(e),
SourceEvent::AudioOut(g, packet) if self.is_current(Source::Voice, g) => {
if let Some((_, tx)) = &self.voice {
let _ = tx.send(VoiceCmd::Audio(packet));
let _ = tx.send(LinkCmd::Audio(packet));
}
}
SourceEvent::Audio(g, event) if self.is_current(Source::Voice, g) => match event {
@@ -1867,9 +1850,6 @@ impl Session {
self.emit(Event::InputLevel { session: Some(self.id), level_db: db, sending })
}
},
SourceEvent::OwnStream(g, e) if self.is_current(Source::Voice, g) => {
self.own_stream_event(e)
}
SourceEvent::Directory(g, result) if self.is_current(Source::Gateway, g) => {
match result {
Ok(streams) => {
@@ -1895,7 +1875,7 @@ impl Session {
}
SourceEvent::AvatarUploaded(g, request, result) => match result {
Ok(hash) if self.is_current(Source::Voice, g) => {
self.voice_cmd(VoiceCmd::SetAvatarHash { request: Some(request), hash });
self.voice_cmd(LinkCmd::SetAvatarHash { request: Some(request), hash });
}
Ok(_) => self.emit(Event::RequestDone {
session: self.id,
@@ -1923,9 +1903,16 @@ impl Session {
}
}
fn voice_event(&mut self, e: VoiceEvent) {
fn voice_event(&mut self, e: LinkEvent) {
match e {
VoiceEvent::Connected { name, flavor, own_client, server_uid, own_uid } => {
LinkEvent::Connected {
name,
backend,
capabilities,
own_client,
server_uid,
own_uid,
} => {
self.state.voice = VoiceState::Connected;
self.state.own_client = Some(own_client);
if own_uid.is_some() {
@@ -1940,50 +1927,26 @@ impl Session {
{
let _ = tx.send(GatewayCmd::RetryNow);
}
let capabilities = flavor.capabilities();
if capabilities.streams
&& let Some((generation, voice)) = &self.voice
{
let generation = *generation;
let (own_tx, own_rx) = mpsc::unbounded_channel();
self.forward(own_rx, move |e| SourceEvent::OwnStream(generation, e));
let streams = StreamHandle::spawn(
self.id,
own_client,
self.stream_peer.clone(),
voice.clone(),
self.events.clone(),
self.frames.clone(),
self.audio.clone(),
self.settings.clone(),
own_tx,
);
if capabilities.streams {
self.streams = true;
if !self.stream_layers.is_empty() {
streams.send(StreamInput::Layers(self.stream_layers.clone()));
self.stream_cmd(StreamCmd::Layers(self.stream_layers.clone()));
}
// The setting may have changed since the connection was asked for.
if let Some(profiles) = self.srtp_profiles.clone() {
self.stream_cmd(StreamCmd::SrtpProfiles(profiles));
}
self.streams = Some(streams);
self.feed_directory();
}
self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities });
self.emit(Event::ServerInfo { session: self.id, name, backend, capabilities });
self.reopen_relayed_chats();
self.open_histories();
}
VoiceEvent::Presence(p) => {
LinkEvent::Presence(p) => {
// Client ids are reused: forget the volumes of those who left.
if let (Some(a), Some(old)) = (&self.audio, &self.voice_presence) {
for id in old.clients.keys().filter(|id| !p.clients.contains_key(id)) {
a.send(AudioIn::ClientLeft(ClientId(*id)));
}
}
if let Some(s) = &self.streams {
let clients: BTreeMap<_, _> = p
.clients
.values()
.map(|c| (c.id, ClientState { channel: c.channel, streaming: c.streaming }))
.collect();
if clients != self.streaming_clients {
self.streaming_clients = clients.clone();
s.send(StreamInput::Clients(clients));
a.send(AudioIn::ClientLeft(TalkerId(*id)));
}
}
self.report_details(&p);
@@ -1993,7 +1956,7 @@ impl Session {
self.voice_presence = Some(*p);
self.publish_presence();
}
VoiceEvent::Poke { from, from_uid, from_name, message } => {
LinkEvent::Poke { from, from_uid, from_name, message } => {
let blocked = self.contacts.is_blocked(from_uid.as_deref());
if blocked && self.block_mode() == BlockMode::Hide {
debug!(?from_uid, "poke of a blocked contact hidden");
@@ -2006,35 +1969,37 @@ impl Session {
let session = self.id;
self.emit(Event::Poke { session, from, from_uid, from_name, message, blocked });
}
VoiceEvent::Error(message) => self.error(message),
VoiceEvent::Stream(n) => {
if let Some(s) = &self.streams {
s.send(StreamInput::Notification(n));
LinkEvent::Error(message) => self.error(message),
LinkEvent::OwnStream(e) => self.own_stream_event(e),
LinkEvent::StreamAudio { stream, time, data } => {
if let Some(a) = &self.audio {
a.send(AudioIn::StreamAudio { stream, time, data });
}
}
VoiceEvent::StreamRequestFailed(request, error) => {
if let Some(s) = &self.streams {
s.send(StreamInput::RequestFailed(request, error));
LinkEvent::StreamAudioEnded(stream) => {
if let Some(a) = &self.audio {
a.send(AudioIn::StreamEnded(stream));
}
}
VoiceEvent::OwnChannel(cid) => {
LinkEvent::OwnChannel(cid) => {
if self.state.own_channel != Some(cid) {
self.state.own_channel = Some(cid);
self.emit_state();
}
}
VoiceEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
VoiceEvent::Audio(packet) => {
LinkEvent::Chat(msg) => self.chat(msg, MessageSource::Voice, None),
LinkEvent::Audio(packet) => {
if let Some(a) = &self.audio {
a.send(AudioIn::Packet(packet));
}
}
VoiceEvent::Talking { client, talking } => {
LinkEvent::Talking { client, talking } => {
self.emit(Event::Talking { session: self.id, client, talking });
}
VoiceEvent::Disconnected(reason) => {
self.stop_streams("voice disconnected");
LinkEvent::Disconnected(reason) => {
// The connection ended its streams itself.
self.voice = None;
self.stop_streams("voice disconnected");
self.voice_presence = None;
self.audio = None;
self.forget_images();
@@ -2288,18 +2253,13 @@ mod banner_tests {
cache: SharedCache::new(Cache::new(dir)),
contacts: Contacts::new(events.clone(), history),
};
// No myTeamSpeak account; its source stays open, as the engine's does
// (a closed one ends voice connections).
let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
let session = Session::new(
1,
events,
frames,
AudioSettings::default(),
shared,
myts_identity,
myts_data,
Arc::new(SessionLink::new(crate::Backends::empty())),
);
(session, receiver)
}
@@ -2386,7 +2346,7 @@ mod banner_tests {
Err("temporarily unavailable".into()),
);
session.retry_images(session.image_retries[&request].due.unwrap());
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
commands.try_recv().unwrap()
else {
panic!("expected an image download");
@@ -2433,7 +2393,7 @@ mod banner_tests {
session.state.server_uid = Some("server-a".into());
session.fetch_pictures(&presence);
assert!(session.pictures.contains(url));
let VoiceCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
let LinkCmd::Download { file, sink: Sink::File { part, .. }, report, .. } =
commands.try_recv().unwrap()
else {
panic!("expected a file download");
@@ -2975,9 +2935,10 @@ mod banner_tests {
let (mut session, _events) = session("gateway-wake");
let (tx, mut rx) = mpsc::unbounded_channel();
session.gateway = Some((session.next_generation(), tx));
let connected = || VoiceEvent::Connected {
let connected = || LinkEvent::Connected {
name: "test".into(),
flavor: voelin_model::ServerFlavor::Unknown(String::new()),
backend: crate::BackendInfo::default(),
capabilities: voelin_model::Capabilities::default(),
own_client: 1,
server_uid: "server=".into(),
own_uid: None,
+2 -2
View File
@@ -50,8 +50,8 @@ use serde_json::{Value, json};
use tokio::sync::{broadcast, watch};
use tracing::{debug, warn};
use voelin_audio::AudioSettings;
use voelin_media::{LayerId, LayerSpec};
use voelin_store::Store;
use voelin_stream::{LayerId, LayerSpec};
/// A value of any key, typed (`Arc<T>` of the key's `T`).
type Stored = Arc<dyn Any + Send + Sync>;
@@ -1135,7 +1135,7 @@ pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
);
/// Import identities from the official TeamSpeak clients when the app
/// starts ([`crate::identity::import_new`]; their files are only read).
/// starts ([`crate::ts::identity::import_new`]; their files are only read).
pub static IDENTITY_IMPORT: Key<bool> = Key::new(
"identity.import_from_teamspeak",
Kind::Bool,
File diff suppressed because it is too large. Load diff
+155
View File
@@ -0,0 +1,155 @@
//! The stream types of the engine's API, owned by the core: what the UI is
//! told about streams ([`StreamInfo`], [`ViewerInfo`], why a stream
//! [ended](EndReason)) and what it asks for ([`StreamSetup`]).
//!
//! They carry plain fields only: client ids are `u16`, an SRTP profile is its
//! name, a video codec is `voelin_media`'s. What a server link speaks (the
//! TeamSpeak 6 stream crate today) is converted to and from them at the
//! boundary in [`crate::stream`], so the UI does not depend on the link's
//! types. The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`,
//! `LayerId`) are `voelin-media`'s.
use voelin_media::{Codec, LayerId};
/// What a stream shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StreamKind {
Camera,
Screen,
Window,
/// A kind this client does not know, by its number on the server.
Other(u8),
}
impl StreamKind {
/// From the number servers use: 2 camera, 3 screen, 4 window.
pub fn from_u8(v: u8) -> Self {
match v {
2 => Self::Camera,
3 => Self::Screen,
4 => Self::Window,
v => Self::Other(v),
}
}
/// [`from_u8`](Self::from_u8) back.
pub fn to_u8(self) -> u8 {
match self {
Self::Camera => 2,
Self::Screen => 3,
Self::Window => 4,
Self::Other(v) => v,
}
}
}
/// What we announce when we start a stream ([`crate::Command::StartStream`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamSetup {
pub name: String,
pub kind: StreamKind,
/// The stream's video bitrate in kbit/s (the single layer's without
/// simulcast). TeamSpeak 6 servers keep it in 16 bits, so it is
/// announced as at most 65535; the stream sends its real rate whatever
/// the announcement says.
pub bitrate: u32,
/// `accessibility`: the official client sends 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 on the server ([`crate::Event::StreamsChanged`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamInfo {
pub id: String,
/// The client id of the streamer.
pub streamer: u16,
pub name: String,
pub kind: StreamKind,
pub bitrate: u32,
pub viewer_limit: u32,
pub audio: bool,
/// How many watch it; `None` where nothing told (e.g. a gateway's
/// directory entry).
pub viewers: Option<u32>,
}
/// A viewer of our stream, as we see it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ViewerState {
/// Asked to watch, waiting for our decision.
Requested,
/// Offer sent; waiting for the answer and the connection.
Connecting,
Connected,
}
/// A viewer of our stream ([`crate::Event::StreamViewers`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ViewerInfo {
/// The client id of the viewer.
pub client: u16,
pub state: ViewerState,
/// The message of the join request.
pub message: String,
/// The simulcast layer the viewer receives (it moves at a keyframe of the
/// new layer); `None` before we offered, and with RID simulcast (all
/// layers).
pub layer: Option<LayerId>,
/// The latest bandwidth estimate of the connection (bit/s).
pub estimate: Option<u64>,
/// The SRTP profile of the connection by its name (as in RFC 5764 and
/// WebRTC statistics, e.g. `AEAD_AES_128_GCM`), once the key exchange is
/// done.
pub srtp_profile: Option<String>,
/// The video codec the viewer's answer chose (it gets video in that
/// codec).
pub codec: Option<Codec>,
}
/// Why a viewer left a stream.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LeaveReason {
None,
Left,
Denied,
Failed,
Kicked,
Banned,
/// A reason this client does not know, by its number on the server.
Other(u8),
}
/// Why a stream ended for us ([`crate::StreamState::Ended`],
/// [`crate::WatchState::Ended`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EndReason {
/// We stopped streaming or watching.
Local,
/// The streamer denied our join request.
Denied,
/// The stream was stopped (or its streamer disconnected).
Stopped,
/// The streamer or the server ended our viewing session.
Removed(Option<LeaveReason>),
/// A command failed or no connection could be established.
Failed(String),
}
@@ -331,4 +331,301 @@ mod tests {
let p = presence_from_book(&book, None, |_| false);
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
}
// ---- across the session seam ---------------------------------------------
/// A presence made into the entities the TeamSpeak session writes
/// (`ts_session::entities`), pushed the way a host syncs them, and
/// projected back by the engine (`link::project`): what the UI is shown
/// of what a TeamSpeak link reported (`docs/session-seam.md` section 5.1).
fn through_the_seam(presence: &Presence, ts6: bool, own: Option<u16>) -> Presence {
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
use voelin_proto::link::Features;
use voelin_proto::v1::{self, push::Body};
use crate::link::media::TalkTracker;
use crate::link::project::{View, presence as project};
use crate::ts::ts_session::entities::build;
let built = build(presence, ts6, own);
let mut replica = Replica::new(SCHEMA_GENERATION);
for (scope, layer) in [(ScopeId::Server(1), &built.server), (ScopeId::Live(1), &built.live)]
{
replica.subscribe(scope);
let pushes = [
Body::SyncBegin(v1::SyncBegin {
scope: Some(scope.to_proto()),
mode: v1::SyncMode::Full as i32,
epoch: 1,
}),
Body::Change(v1::Change {
scope: Some(scope.to_proto()),
rev: 1,
put: layer.values().cloned().collect(),
del: Vec::new(),
}),
Body::SyncEnd(v1::SyncEnd {
scope: Some(scope.to_proto()),
cursor: Some(v1::Cursor { epoch: 1, rev: 1 }),
gap: false,
}),
];
for body in pushes {
replica.apply_push(&v1::Push { body: Some(body) });
}
}
let features = Features::new(["voice"]);
let talking = TalkTracker::default();
project(&View {
replica: &replica,
server: 1,
teamspeak: true,
version: "",
features: &features,
streams: ts6,
talking: &talking,
})
}
/// A TeamSpeak 6 server and some clients with what the book holds of them.
fn ts6_presence() -> Presence {
let mut book = ts6_book();
let list = format!(
"channellist {}|{}|{}",
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
channel(
12,
1,
"Raid",
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
),
channel(20, 12, "Last", "channel_banner_gfx_url channel_banner_mode=0"),
);
book.handle_command(&message(&list)).unwrap();
let enter = |clid: u16, channel: u64, groups: &str, away: &str, avatar: &str| {
format!(
"notifycliententerview reasonid=0 ctid={channel} clid={clid} \
client_database_id={} client_nickname=c{clid} client_type=0 cfid=0 \
client_unique_identifier=u{clid}= client_flag_avatar=abcdef \
client_description=about\\sme client_icon_id=777 client_input_muted=1 \
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
client_output_hardware=1 client_meta_data client_is_recording=1 \
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
client_servergroups={groups} client_away={} client_away_message={away} \
client_talk_power=75 client_talk_request=0 client_talk_request_msg \
client_is_talker=1 client_is_priority_speaker=1 client_unread_messages=0 \
client_nickname_phonetic client_needed_serverquery_view_power=75 \
client_is_channel_commander=1 client_country=RU client_badges \
client_myteamspeak_id=m{clid} client_integrations{avatar}",
100 + u64::from(clid),
u8::from(!away.is_empty()),
)
};
for text in [
enter(5, 1, "8", "", r" client_myteamspeak_avatar=2,https:\/\/a.example\/on.png"),
enter(6, 12, "8,9", "gone\\sfishing", ""),
enter(7, 12, "", "", " client_myteamspeak_avatar"),
] {
book.handle_command(&message(&text)).unwrap();
}
presence_from_book(&book, Some("ibhejBRSRRI7v+fSsUzpQ33JGK6rf5xKOLelpWUr0sE="), |_| false)
}
#[test]
fn a_book_is_what_the_ui_is_shown_across_the_seam() {
let p = ts6_presence();
assert_eq!(p.clients.len(), 3, "the fixture has clients");
assert!(p.clients.values().any(|c| c.away.is_some()), "one is away");
// A TeamSpeak 6 client the book has no streaming flag of (it was not
// sent) is not streaming: v1 has no "unknown" for it.
let mut expected = p.clone();
for client in expected.clients.values_mut() {
client.streaming = Some(client.streaming.unwrap_or(false));
}
assert_eq!(through_the_seam(&p, true, Some(5)), expected);
// The same server as a TeamSpeak 3 one has no streams to tell of.
let mut ts3 = p.clone();
for client in ts3.clients.values_mut() {
client.streaming = None;
}
assert_eq!(through_the_seam(&ts3, false, Some(5)), ts3);
}
/// A deterministic stream of numbers for the generated presences.
struct Numbers(u64);
impl Numbers {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
fn flag(&mut self) -> bool {
self.below(2) == 0
}
fn text(&mut self, prefix: &str) -> String {
format!("{prefix}{}", self.below(1000))
}
}
/// A presence of the shape a TeamSpeak link reports: sibling channels in an
/// order chain, every client with a database id, unique ids that are base64
/// (TeamSpeak 3 and 6) or login names, groups of both kinds.
fn generated(seed: u64, ts6: bool) -> Presence {
use base64::Engine as _;
use voelin_model::{
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
HostMessageMode,
};
let mut n = Numbers(seed | 1);
let mut p = Presence::default();
let name = n.text("Server ");
p.server_name = name.clone();
p.server = voelin_model::ServerDetails {
name,
uid: Some(n.text("uid")),
welcome_message: n.text("welcome "),
host_message: n.text("host "),
host_message_mode: [
HostMessageMode::None,
HostMessageMode::Log,
HostMessageMode::Modal,
][n.below(3) as usize],
banner_url: if n.flag() { n.text("https://b/") } else { String::new() },
banner_gfx_url: if n.flag() { n.text("https://g/") } else { String::new() },
banner_gfx_interval_s: n.below(100),
banner_mode: [BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect]
[n.below(3) as usize],
host_button_tooltip: if n.flag() { n.text("tip ") } else { String::new() },
host_button_url: String::new(),
host_button_gfx_url: String::new(),
icon: n.below(5) as u32 * 1000,
platform: "Linux".into(),
version: n.text("6.0."),
max_clients: n.below(500) as u16,
priority_speaker_dimm_db: -(n.below(30) as i32),
default_server_group: Some(1 + n.below(9)),
default_channel_group: Some(1 + n.below(9)),
};
// Groups.
for id in 1..=(2 + n.below(4)) {
let group = |id: u64, n: &mut Numbers| GroupInfo {
id,
name: n.text("group "),
icon: n.below(3) as u32 * 100,
sort_id: n.below(1000) as i32 - 500,
naming_mode: [
GroupNamingMode::None,
GroupNamingMode::Before,
GroupNamingMode::After,
][n.below(3) as usize],
group_type: [GroupType::Regular, GroupType::Template, GroupType::Query]
[n.below(3) as usize],
};
p.server_groups.insert(id, group(id, &mut n));
p.channel_groups.insert(id, group(id, &mut n));
}
// Channels: a tree whose siblings follow each other.
let mut parents = vec![0u64];
for id in 1..=(3 + n.below(8)) {
let parent = parents[n.below(parents.len() as u64) as usize];
let order = p
.channels
.values()
.filter(|c| c.parent == parent)
.map(|c| c.id)
.next_back()
.unwrap_or(0);
parents.push(id);
p.channels.insert(
id,
ChannelInfo {
id,
parent,
order,
name: n.text("channel "),
topic: n.flag().then(|| n.text("topic ")),
has_password: n.flag(),
max_clients: match n.below(3) {
0 => None,
1 => Some(0),
_ => Some(1 + n.below(50) as i32),
},
needed_subscribe_power: n.below(3) as i32 * 10,
needed_talk_power: n.below(3) as i32 * 25,
is_default: id == 1,
icon: n.below(3) as u32 * 500,
banner_gfx_url: n.flag().then(|| n.text("https://c/")),
banner_mode: [
BannerMode::NoAdjust,
BannerMode::IgnoreAspect,
BannerMode::KeepAspect,
][n.below(3) as usize],
},
);
}
// Clients.
let channels: Vec<u64> = p.channels.keys().copied().collect();
for id in 1..=(1 + n.below(12)) {
let id = id as u16;
let uid = match n.below(4) {
0 => None,
1 => Some(n.text("login")),
_ => {
let bytes: Vec<u8> =
(0..if ts6 { 32 } else { 20 }).map(|_| n.below(256) as u8).collect();
Some(base64::engine::general_purpose::STANDARD.encode(bytes))
}
};
let channel = channels[n.below(channels.len() as u64) as usize];
p.clients.insert(
id,
ClientInfo {
id,
uid,
nickname: n.text("nick "),
channel,
is_query: n.below(5) == 0,
away: n.flag().then(|| if n.flag() { n.text("away ") } else { String::new() }),
input_muted: n.flag(),
output_muted: n.flag(),
talking: Some(false),
streaming: ts6.then(|| n.flag()),
server_groups: (0..n.below(3)).map(|_| 1 + n.below(9)).collect(),
country: n.flag().then(|| "DE".into()),
avatar: n.flag().then(|| n.text("hash")),
myts_avatar: n.flag().then(|| n.text("https://a/")),
description: n.flag().then(|| n.text("about ")),
talk_power: n.below(100) as i32,
talker: n.flag(),
channel_group: n.flag().then(|| 1 + n.below(9)),
badges: (0..n.below(3)).map(|_| n.text("badge")).collect(),
icon: n.below(3) as u32 * 111,
recording: n.flag(),
priority_speaker: n.flag(),
channel_commander: n.flag(),
database_id: Some(1_000 + u64::from(id)),
},
);
}
p
}
#[test]
fn generated_presences_survive_the_seam() {
for seed in 1..=200u64 {
for ts6 in [false, true] {
let p = generated(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15), ts6);
let own = p.clients.keys().next().copied();
assert_eq!(through_the_seam(&p, ts6, own), p, "seed {seed}, ts6 {ts6}");
}
}
}
}
@@ -32,6 +32,7 @@ use std::{fs, str};
use rusqlite::{Connection, OpenFlags, OptionalExtension};
use tsclientlib::Identity;
use voelin_gateway_proto::UniqueIds;
use voelin_identity::IdentityBlob;
use voelin_store::{IdentityOrigin, Store};
/// Name given to an identity whose source kept none.
@@ -55,6 +56,9 @@ pub enum IdentityError {
NoIdentity { path: String },
#[error("client database: {0}")]
Store(String),
/// An [`IdentityBlob`] that is no TeamSpeak identity ([`from_blob`]).
#[error("{0}")]
Blob(String),
}
impl IdentityError {
@@ -230,6 +234,43 @@ pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result<LaunchImport, Iden
Ok(report)
}
/// A TeamSpeak identity as the API takes it
/// ([`VoiceOptions::identity`](crate::VoiceOptions::identity),
/// [`Command::ObserveGateway`](crate::Command::ObserveGateway)) and the key
/// store keeps it: kind `teamspeak`, the unique id TeamSpeak 3 servers know it
/// by (also how [`voelin_store`] keys it), its security level, and the JSON
/// the store writes.
pub fn to_blob(identity: &Identity) -> IdentityBlob {
// An identity is a key and two counters: writing it cannot fail. (A blob with
// no JSON is refused when it is used, in words.)
let json = serde_json::to_string(identity).unwrap_or_default();
IdentityBlob::teamspeak(identity.key().to_pub().get_uid(), identity.level(), json)
}
/// The TeamSpeak identity of a blob (the reverse of [`to_blob`]).
pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
if !blob.is_teamspeak() {
return Err(IdentityError::Blob(format!(
"the identity is of kind {:?}, not a TeamSpeak one",
blob.kind
)));
}
serde_json::from_str(&blob.json).map_err(|e| {
// Where the JSON is wrong, not what it says: it holds a private key.
let what = match e.classify() {
serde_json::error::Category::Syntax => "malformed",
serde_json::error::Category::Eof => "cut short",
serde_json::error::Category::Data => "not an identity",
serde_json::error::Category::Io => "unreadable",
};
IdentityError::Blob(format!(
"the TeamSpeak identity cannot be read: {what} at line {}, column {}",
e.line(),
e.column()
))
})
}
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
/// and every other tool reads.
pub fn export(nickname: &str, identity: &Identity) -> String {
@@ -548,6 +589,32 @@ mod tests {
Identity::create()
}
/// The blob of an identity is how the key store keeps it, and reads back as
/// the same identity; what is no TeamSpeak identity is refused without
/// quoting its JSON.
#[test]
fn an_identity_goes_through_its_blob() {
let identity = synthetic();
let blob = to_blob(&identity);
assert!(blob.is_teamspeak());
assert_eq!(blob.uid, identity.key().to_pub().get_uid());
assert_eq!(blob.level, identity.level());
assert_eq!(blob.json, serde_json::to_string(&identity).unwrap());
let back = from_blob(&blob).unwrap();
assert_eq!(serde_json::to_value(&back).unwrap(), serde_json::to_value(&identity).unwrap());
// Another kind.
let other = IdentityBlob::new("voelin", "x", 0, blob.json.clone());
let error = from_blob(&other).unwrap_err().to_string();
assert!(error.contains("\"voelin\""), "{error}");
// Not an identity: the text says where, and nothing of what it holds.
for json in ["", "{", r#"{"key":"hunter2-key","counter":"hunter2"}"#, "[1]"] {
let error = from_blob(&IdentityBlob::teamspeak("x", 0, json)).unwrap_err().to_string();
assert!(error.starts_with("the TeamSpeak identity cannot be read"), "{error}");
assert!(!error.contains("hunter2"), "{error}");
}
}
#[test]
fn improve_level_keeps_the_key() {
let identity = synthetic();
+30
View File
@@ -0,0 +1,30 @@
//! The TeamSpeak implementation of the session seam.
//!
//! Everything of the engine that is TeamSpeak's lives here, so that it can
//! leave this crate for the TeamSpeak gateway (`voelin-gateway-ts` of
//! VoelinGateWay) as one piece (`docs/session-seam.md`, H9):
//!
//! - `ts_link.rs` and `voice.rs` are the connection of `tsclientlib`
//! (chat, voice, files, pokes, offline messages, the stream task's
//! requests) with `book.rs`, its presence from the library's book;
//! - `ts_session/` makes a `voelin_proto::link::Session` of such a connection
//! ([`TsConnector`] is the `Connector` the engine registers for
//! `ts3server://` and `teamspeak://`);
//! - [`versions`] and [`identity`] are what a TeamSpeak client has to know
//! about itself: the signed compatibility versions it can claim, and the
//! identities (reading, importing from the official clients, the security
//! level).
//!
//! The TeamSpeak crates' types (`tsclientlib::Identity`, `Version`, ...) are
//! named in the public items of this module and nowhere else of the crate's
//! API.
mod book;
pub mod identity;
mod ts_link;
pub(crate) mod ts_session;
pub mod versions;
mod voice;
pub(crate) use ts_link::{ConnectOptions, ServerLink, TsLink};
pub use ts_session::TsConnector;
+256
View File
@@ -0,0 +1,256 @@
//! The inner link of the TeamSpeak side: [`ServerLink`], the trait that
//! [`TsLink`] implements, and the [`ConnectOptions`] it connects with.
//!
//! The engine does not know this vocabulary: it talks to a
//! `voelin_proto::link::Session`. The `ts_session` module makes a `Session`
//! of a [`ServerLink`] (`LinkSession`), and the engine's tests give it a link
//! of their own, an in-memory one. [`TsLink`] connects as a normal TeamSpeak 3
//! or 6 client with `tsclientlib` and
//! runs the connection ([`super::voice`]) with everything that rides on it:
//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the
//! stream task. Which product the server is (and what it can do) is decided
//! there, from the version it sends, and reported in
//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected).
//!
//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`,
//! `identity.rs`) is TeamSpeak's and leaves this crate together with it:
//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts`
//! of VoelinGateWay.
use std::sync::Arc;
use tokio::sync::{mpsc, watch};
use voelin_stream::PeerConfig;
use super::voice;
use crate::link::{LinkCmd, LinkCtx, LinkEvent};
/// Starts the connection of a link: the contract of `crate::link` for the
/// vocabulary ([`LinkCmd`] in, [`LinkEvent`] out) holds for what a link does
/// with them, and the module documentation of `link/session_link.rs` states
/// it.
///
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
/// one connection.
pub(crate) trait ServerLink: Send + Sync + 'static {
/// Connect to the server `options` names and run the connection on its
/// own task: take commands from `cmds`, report through `events`, and end
/// the connection with [`LinkEvent::Disconnected`]. Does not block.
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
);
}
/// What a TeamSpeak connection needs to know: the server, who to be, where
/// to join. The reverse of what the engine's `ConnectParams` carry
/// (`ts_session::inner_options`).
#[derive(Clone, Debug)]
pub(crate) struct ConnectOptions {
pub address: String,
pub nickname: String,
/// The identity to connect with; none generates one.
pub identity: Option<tsclientlib::Identity>,
/// Signed compatibility version; `None` selects the native platform's tuple.
pub client_version: Option<tsclientlib::Version>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections.
pub stream_peer: PeerConfig,
}
impl ConnectOptions {
/// Options for `address` and `nickname`, the rest as a test leaves it.
#[cfg(test)]
pub(crate) fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
Self {
address: address.into(),
nickname: nickname.into(),
identity: None,
client_version: None,
server_password: None,
channel: None,
channel_password: None,
token: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
/// The main myTeamSpeak account of an application, as its connections show
/// it to the servers: the proof of the myTS ID, and what servers are shown
/// of it (its avatar and badges with their certificates, its User Tag).
///
/// The senders live here, one pair for every connection of a [`TsLink`]; each
/// connection watches the pair through [`Watches`], presents the account it
/// finds when it connects, and follows the changes.
pub(crate) struct Account {
identity: watch::Sender<Option<Arc<tsproto::myts::Identity>>>,
data: watch::Sender<Option<Arc<tsclientlib::MytsData>>>,
}
impl Default for Account {
/// No account is signed in.
fn default() -> Self {
Self { identity: watch::Sender::new(None), data: watch::Sender::new(None) }
}
}
impl Account {
/// The account proof for every current and future connection. Still no
/// account is no change: every notification restarts the handshakes and
/// sends `updatemytsid` on every connection. Any account is (each
/// connection's proof is signed anew).
pub(crate) fn set_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
self.identity.send_if_modified(|current| {
if current.is_none() && identity.is_none() {
return false;
}
*current = identity;
true
});
}
/// What the servers are shown of the account: sent to every connection
/// that presents the account's myTS ID, once connected and when it
/// changes; cleared on a sign-out. The same data is no change.
pub(crate) fn set_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
self.data.send_if_modified(|current| {
if *current == data {
return false;
}
*current = data;
true
});
}
/// What one connection watches. It keeps the senders alive for as long as
/// it runs: a connection ends with "account source closed" when its
/// watches have lost them, so the account outlives the connector that
/// made the connection.
pub(crate) fn watches(self: &Arc<Self>) -> Watches {
Watches {
identity: self.identity.subscribe(),
data: self.data.subscribe(),
_keep: Some(self.clone()),
}
}
}
/// The account a connection presents and follows ([`Account::watches`]).
pub(crate) struct Watches {
pub(super) identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
pub(super) data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
_keep: Option<Arc<Account>>,
}
impl Watches {
/// Watches of senders that someone else keeps (a test's).
#[cfg(test)]
pub(super) fn of(
identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
) -> Self {
Self { identity, data, _keep: None }
}
}
/// Connects to TeamSpeak 3 and 6 servers. The link of [`TsConnector`](super::TsConnector).
#[derive(Clone, Default)]
pub(crate) struct TsLink {
account: Arc<Account>,
}
impl TsLink {
/// A link that presents no account until it is given one.
pub(crate) fn new() -> Self {
Self::default()
}
/// The account the link's connections present.
pub(crate) fn account(&self) -> &Arc<Account> {
&self.account
}
}
impl ServerLink for TsLink {
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
tokio::spawn(voice::run(options, ctx, self.account.watches(), cmds, events));
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A myTS ID's proof (the standard Ed25519 base point as the public key).
fn identity() -> Arc<tsproto::myts::Identity> {
let mut private = [0; 32];
private[0] = 1;
let mut public = [0x66; 32];
public[0] = 0x58;
Arc::new(
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(),
)
}
/// An account sets what it holds only when it changes: every notification
/// of a watch restarts the handshake of a connection.
#[test]
fn a_watch_hears_of_a_change_and_not_of_the_same_account_again() {
let account = Arc::new(Account::default());
let mut watches = account.watches();
// No account, still none: nothing.
account.set_identity(None);
account.set_data(None);
assert!(!watches.identity.has_changed().unwrap());
assert!(!watches.data.has_changed().unwrap());
let proof = identity();
account.set_identity(Some(proof.clone()));
assert!(watches.identity.borrow_and_update().is_some());
// An account again is a change (each connection signs its proof anew), the
// same data is none.
account.set_identity(Some(proof));
assert!(watches.identity.has_changed().unwrap());
watches.identity.borrow_and_update();
let data = Arc::new(tsclientlib::MytsData::default());
account.set_data(Some(data.clone()));
assert!(watches.data.has_changed().unwrap());
watches.data.borrow_and_update();
account.set_data(Some(Arc::new(tsclientlib::MytsData::default())));
assert!(!watches.data.has_changed().unwrap(), "equal data is no change");
// A sign-out is a change.
account.set_identity(None);
assert!(watches.identity.has_changed().unwrap());
assert!(watches.identity.borrow_and_update().is_none());
}
/// A connection outlives the connector that made it (a session handed out
/// by a connector that was dropped): its watches keep their senders.
#[test]
fn a_connection_keeps_the_account_open_when_its_link_is_gone() {
let link = TsLink::new();
let watches = link.account().watches();
drop(link);
assert!(watches.identity.has_changed().is_ok(), "the identity watch lost its sender");
assert!(watches.data.has_changed().is_ok(), "the data watch lost its sender");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,537 @@
//! The TeamSpeak connection's presence as v1 entities (protocol section
//! 11.1, "Ids and entities"): the client's older model on one side, the
//! protocol's `Server`, `Channel`, `Role`, `User`, `Member`, `Presence` and
//! `VoiceState` on the other.
//!
//! [`build`] is the translation the TeamSpeak `Session` makes of every
//! snapshot its link reports; the engine's projection (`link/project.rs`)
//! is its reverse, and `docs/session-seam.md` section 5.1 states the rule
//! both keep: projecting what was built gives back the snapshot (up to the
//! normalisations of section 5.4). What v1 has no field for rides in
//! [`Foreign`](v1::Foreign) under [`FOREIGN_SYSTEM`].
use std::collections::{BTreeMap, HashMap, HashSet};
use serde_json::json;
use voelin_model::replica::Key;
use voelin_model::{
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
HostMessageMode, Presence, ServerDetails,
};
use voelin_proto::v1::{self, Entity, entity::Kind};
use super::ids::{self, FOREIGN_SYSTEM, SERVER_CHAT, SERVER_ID};
/// Entities by key, as a scope holds them.
pub(crate) type Layer = BTreeMap<Key, Entity>;
/// The entities one snapshot stands for, by scope.
#[derive(Debug, Default)]
pub(crate) struct Built {
/// SERVER (1): the server, its channels and its roles.
pub server: Layer,
/// LIVE (1): who is online and where.
pub live: Layer,
/// The own user, for HOME, when the snapshot holds our client.
pub own_user: Option<v1::User>,
/// Clients by unique id: their user id and participant id.
pub by_uid: HashMap<String, (u64, u32)>,
}
/// The `Foreign` of something v1 has no field for.
pub(crate) fn foreign(kind: &str, json: &serde_json::Value) -> v1::Foreign {
v1::Foreign {
system: FOREIGN_SYSTEM.into(),
kind: kind.into(),
json: serde_json::to_vec(json).unwrap_or_default().into(),
}
}
fn entity(kind: Kind) -> Entity {
Entity { kind: Some(kind) }
}
/// A picture known by its id (an icon CRC).
fn icon(id: u32) -> Option<v1::Image> {
(id != 0).then(|| v1::Image { hash: id.to_string(), ..Default::default() })
}
fn banner_mode(mode: BannerMode) -> v1::BannerMode {
match mode {
BannerMode::NoAdjust => v1::BannerMode::NoAdjust,
BannerMode::IgnoreAspect => v1::BannerMode::IgnoreAspect,
BannerMode::KeepAspect => v1::BannerMode::KeepAspect,
}
}
fn host_message_mode(mode: HostMessageMode) -> v1::HostMessageMode {
match mode {
HostMessageMode::None => v1::HostMessageMode::None,
HostMessageMode::Log => v1::HostMessageMode::Log,
HostMessageMode::Modal => v1::HostMessageMode::Modal,
HostMessageMode::ModalQuit => v1::HostMessageMode::ModalQuit,
}
}
/// The `Server` entity of a connection.
pub(crate) fn server(details: &ServerDetails, name: &str, default_channel: u64) -> v1::Server {
let gfx =
|url: &str| (!url.is_empty()).then(|| v1::Image { url: url.into(), ..Default::default() });
let banner = (!details.banner_url.is_empty()
|| !details.banner_gfx_url.is_empty()
|| details.banner_gfx_interval_s != 0
|| details.banner_mode != BannerMode::NoAdjust)
.then(|| v1::Banner {
image: gfx(&details.banner_gfx_url),
link: details.banner_url.clone(),
reload_s: u32::try_from(details.banner_gfx_interval_s).unwrap_or(u32::MAX),
mode: banner_mode(details.banner_mode) as i32,
});
let host_button = (!details.host_button_tooltip.is_empty()
|| !details.host_button_url.is_empty()
|| !details.host_button_gfx_url.is_empty())
.then(|| v1::HostButton {
tooltip: details.host_button_tooltip.clone(),
url: details.host_button_url.clone(),
icon: gfx(&details.host_button_gfx_url),
});
v1::Server {
id: SERVER_ID,
name: name.to_owned(),
icon: icon(details.icon),
banner,
host_button,
welcome: details.welcome_message.clone(),
host_message: details.host_message.clone(),
host_message_mode: host_message_mode(details.host_message_mode) as i32,
default_channel_id: default_channel,
default_role_id: details.default_server_group.unwrap_or(0),
default_channel_role_id: details.default_channel_group.map_or(0, ids::channel_role),
priority_dim_db: details.priority_speaker_dimm_db,
max_members: u32::from(details.max_clients),
uid: details.uid.as_deref().map(|uid| format!("ts:{uid}")).unwrap_or_default(),
foreign: Some(foreign(
"server",
&json!({ "platform": details.platform, "version": details.version }),
)),
..Default::default()
}
}
/// The server group or channel group `info` as a role.
fn role(info: &GroupInfo, channel: bool) -> v1::Role {
v1::Role {
id: if channel { ids::channel_role(info.id) } else { info.id },
server_id: SERVER_ID,
name: info.name.clone(),
icon: icon(info.icon),
position: info.sort_id.saturating_neg(),
scope: if channel { v1::RoleScope::Channel } else { v1::RoleScope::Server } as i32,
name_mode: match info.naming_mode {
GroupNamingMode::None => v1::NameMode::None,
GroupNamingMode::Before => v1::NameMode::Before,
GroupNamingMode::After => v1::NameMode::After,
} as i32,
kind: match info.group_type {
GroupType::Template => v1::RoleKind::Template,
GroupType::Regular => v1::RoleKind::Regular,
GroupType::Query => v1::RoleKind::Query,
} as i32,
..Default::default()
}
}
/// The sibling chain of each parent as positions: `order` names the sibling
/// above, so the chain is followed from 0; siblings that no chain reaches
/// (a snapshot with broken orders) follow by id.
fn positions(channels: &BTreeMap<ChannelId, ChannelInfo>) -> HashMap<ChannelId, i64> {
let mut by_parent: BTreeMap<ChannelId, Vec<&ChannelInfo>> = BTreeMap::new();
for channel in channels.values() {
by_parent.entry(channel.parent).or_default().push(channel);
}
let mut positions = HashMap::new();
for siblings in by_parent.values() {
let mut placed: HashSet<ChannelId> = HashSet::new();
let mut next = 0;
let mut above = 0;
// The sibling whose `order` is the one placed last (lowest id first, so
// that two claiming the same place do not depend on map order).
while let Some(channel) = siblings
.iter()
.filter(|c| c.order == above && !placed.contains(&c.id))
.min_by_key(|c| c.id)
{
positions.insert(channel.id, next * 1024);
placed.insert(channel.id);
above = channel.id;
next += 1;
}
for channel in siblings.iter().filter(|c| !placed.contains(&c.id)) {
positions.insert(channel.id, next * 1024);
next += 1;
}
}
positions
}
fn channel(info: &ChannelInfo, position: i64) -> v1::Channel {
let mut needed = HashMap::new();
if info.needed_talk_power != 0 {
needed.insert(v1::Power::Talk as u32, info.needed_talk_power);
}
if info.needed_subscribe_power != 0 {
needed.insert(v1::Power::Subscribe as u32, info.needed_subscribe_power);
}
let banner =
(info.banner_gfx_url.is_some() || info.banner_mode != BannerMode::NoAdjust).then(|| {
v1::Banner {
image: info
.banner_gfx_url
.as_ref()
.map(|url| v1::Image { url: url.clone(), ..Default::default() }),
mode: banner_mode(info.banner_mode) as i32,
..Default::default()
}
});
v1::Channel {
id: info.id,
server_id: SERVER_ID,
parent_id: info.parent,
kind: v1::ChannelKind::Voice as i32,
name: info.name.clone(),
topic: info.topic.clone().unwrap_or_default(),
position,
has_password: info.has_password,
// A limit of 0 cannot be said with `max_members` (0 is unlimited).
max_members: info.max_clients.map_or(0, |n| u32::try_from(n).unwrap_or(0)),
needed,
icon: icon(info.icon),
banner,
is_default: info.is_default,
foreign: (info.max_clients == Some(0))
.then(|| foreign("channel", &json!({ "max_clients": 0 }))),
..Default::default()
}
}
/// The user a client is. `Foreign` carries a unique id that is no base64.
fn user(client: &ClientInfo, id: u64, ts6: bool) -> v1::User {
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
let bytes = uid.and_then(ids::uid_bytes);
let avatar = (client.avatar.is_some() || client.myts_avatar.is_some()).then(|| v1::Image {
hash: client.avatar.clone().unwrap_or_default(),
url: client.myts_avatar.clone().unwrap_or_default(),
..Default::default()
});
v1::User {
id,
uid: bytes.clone().unwrap_or_default().into(),
uid_kind: if ts6 { v1::IdKind::Ts6 } else { v1::IdKind::Ts3 } as i32,
name: client.nickname.clone(),
avatar,
badges: client.badges.clone(),
country: client.country.clone().unwrap_or_default(),
foreign: uid.filter(|_| bytes.is_none()).map(|uid| foreign("user", &json!({ "uid": uid }))),
..Default::default()
}
}
/// A user who is on no snapshot (the sender of a message or a poke): its
/// unique id and name only. `None` for a unique id with no content.
pub(crate) fn bare_user(uid: &str, name: &str, ts6: bool) -> v1::User {
user(
&ClientInfo { uid: Some(uid.to_owned()), nickname: name.to_owned(), ..Default::default() },
ids::synthetic_user(uid),
ts6,
)
}
/// A user who is on no snapshot and has no unique id (the sender of a poke
/// or a message that the link names by its client id only): `id` and name.
pub(crate) fn client_user(id: u64, name: &str, ts6: bool) -> v1::User {
user(&ClientInfo { nickname: name.to_owned(), ..Default::default() }, id, ts6)
}
/// Everything the snapshot `presence` says, as entities of the scopes of
/// server 1. `ts6`: the server is TeamSpeak 6 (the kind of its unique ids).
pub(crate) fn build(presence: &Presence, ts6: bool, own_client: Option<u16>) -> Built {
let mut built = Built::default();
let name =
if presence.server.name.is_empty() { &presence.server_name } else { &presence.server.name };
let default_channel =
presence.channels.values().find(|c| c.is_default).map_or(0, |channel| channel.id);
let put = |layer: &mut Layer, kind: Kind| {
let entity = entity(kind);
if let Some(key) = Key::of(&entity) {
layer.insert(key, entity);
}
};
put(&mut built.server, Kind::Server(server(&presence.server, name, default_channel)));
put(
&mut built.server,
Kind::Channel(v1::Channel {
id: SERVER_CHAT,
server_id: SERVER_ID,
kind: v1::ChannelKind::ServerChat as i32,
name: "Server chat".into(),
..Default::default()
}),
);
let positions = positions(&presence.channels);
for info in presence.channels.values() {
let position = positions.get(&info.id).copied().unwrap_or_default();
put(&mut built.server, Kind::Channel(channel(info, position)));
}
for info in presence.server_groups.values() {
put(&mut built.server, Kind::Role(role(info, false)));
}
for info in presence.channel_groups.values() {
put(&mut built.server, Kind::Role(role(info, true)));
}
// The own client first, then by client id.
let mut clients: Vec<&ClientInfo> = presence.clients.values().collect();
clients.sort_by_key(|client| (Some(client.id) != own_client, client.id));
let mut used: HashSet<u64> = HashSet::new();
for client in clients {
// The same identity twice on a server has one database id: the own
// client keeps it (it must stay the user we are, also while a ghost of
// our old connection lingers), else the lower client id; the other is a
// user of its own.
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
let mut id = client.database_id.unwrap_or_else(|| {
ids::synthetic_user(&uid.map_or_else(|| format!("client:{}", client.id), str::to_owned))
});
if !used.insert(id) {
id = ids::synthetic_user(&format!("client:{}", client.id));
used.insert(id);
}
let participant = u32::from(client.id);
if let Some(uid) = uid {
built.by_uid.entry(uid.to_owned()).or_insert((id, participant));
}
let user = user(client, id, ts6);
if Some(client.id) == own_client {
built.own_user = Some(user.clone());
}
put(&mut built.live, Kind::User(user));
put(
&mut built.live,
Kind::Member(v1::Member {
server_id: SERVER_ID,
user_id: id,
roles: client.server_groups.clone(),
channel_roles: client
.channel_group
.map(|group| (client.channel, ids::channel_role(group)))
.into_iter()
.collect(),
description: client.description.clone().unwrap_or_default(),
foreign: (client.icon != 0)
.then(|| foreign("client", &json!({ "icon": client.icon }))),
..Default::default()
}),
);
put(
&mut built.live,
Kind::Presence(v1::Presence {
user_id: id,
status: if client.away.is_some() { v1::Status::Idle } else { v1::Status::Online }
as i32,
text: client.away.clone().unwrap_or_default(),
..Default::default()
}),
);
put(
&mut built.live,
Kind::Voice(v1::VoiceState {
server_id: SERVER_ID,
participant_id: participant,
user_id: id,
channel_id: client.channel,
slot: slot(client.id),
nick: client.nickname.clone(),
kind: if client.is_query {
v1::ParticipantKind::Query
} else {
v1::ParticipantKind::User
} as i32,
self_mute: client.input_muted,
self_deaf: client.output_muted,
priority_speaker: client.priority_speaker,
channel_commander: client.channel_commander,
talker: client.talker,
talk_power: client.talk_power,
recording: client.recording,
streaming: client.streaming.unwrap_or(false),
..Default::default()
}),
);
}
built
}
/// The unique id of a user as the client's older model writes it: base64 for
/// a TeamSpeak id, or the text kept in `Foreign` when it was no base64 (a
/// ServerQuery client's login name). `None` for a user without one.
pub(crate) fn user_uid(user: &v1::User) -> Option<String> {
let kept = user
.foreign
.as_ref()
.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == "user")
.and_then(|f| serde_json::from_slice::<serde_json::Value>(&f.json).ok())
.and_then(|json| json.get("uid")?.as_str().map(str::to_owned));
kept.or_else(|| voelin_model::replica::convert::uid_text(user))
}
/// The media slot of a client: its id plus one (slot 0 is not a media source).
pub(crate) fn slot(client: u16) -> u32 {
u32::from(client) + 1
}
/// The key of an entity, as a `Change` deletes it: the key fields only.
pub(crate) fn key_only(entity: &Entity) -> Entity {
let kind = match entity.kind.as_ref() {
Some(Kind::Server(s)) => Kind::Server(v1::Server { id: s.id, ..Default::default() }),
Some(Kind::Channel(c)) => Kind::Channel(v1::Channel { id: c.id, ..Default::default() }),
Some(Kind::Role(r)) => {
Kind::Role(v1::Role { server_id: r.server_id, id: r.id, ..Default::default() })
}
Some(Kind::Member(m)) => Kind::Member(v1::Member {
server_id: m.server_id,
user_id: m.user_id,
..Default::default()
}),
Some(Kind::User(u)) => Kind::User(v1::User { id: u.id, ..Default::default() }),
Some(Kind::Presence(p)) => {
Kind::Presence(v1::Presence { user_id: p.user_id, ..Default::default() })
}
Some(Kind::Voice(v)) => Kind::Voice(v1::VoiceState {
server_id: v.server_id,
participant_id: v.participant_id,
..Default::default()
}),
Some(Kind::Message(m)) => {
Kind::Message(v1::Message { channel_id: m.channel_id, id: m.id, ..Default::default() })
}
Some(Kind::Mail(m)) => Kind::Mail(v1::Mail { id: m.id, ..Default::default() }),
_ => return entity.clone(),
};
Entity { kind: Some(kind) }
}
/// What changed from `old` to `new`: the entities to put (new or different)
/// and the keys to delete.
pub(crate) fn diff(old: &Layer, new: &Layer) -> (Vec<Entity>, Vec<Entity>) {
let put = new.iter().filter(|(key, entity)| old.get(*key) != Some(*entity));
let del = old.iter().filter(|(key, _)| !new.contains_key(*key));
(put.map(|(_, e)| e.clone()).collect(), del.map(|(_, e)| key_only(e)).collect())
}
#[cfg(test)]
mod tests {
use super::*;
fn channel_info(id: u64, parent: u64, order: u64) -> ChannelInfo {
ChannelInfo { id, parent, order, name: format!("c{id}"), ..Default::default() }
}
#[test]
fn the_order_chain_becomes_positions() {
// 3 first, then 1, then 2 under the same parent; 5 alone under 3.
let channels: BTreeMap<_, _> = [
channel_info(1, 0, 3),
channel_info(2, 0, 1),
channel_info(3, 0, 0),
channel_info(5, 3, 0),
]
.into_iter()
.map(|c| (c.id, c))
.collect();
let positions = positions(&channels);
assert!(positions[&3] < positions[&1] && positions[&1] < positions[&2]);
assert_eq!(positions[&5], 0);
}
#[test]
fn siblings_a_chain_does_not_reach_follow_by_id() {
// Both claim the first place, and 4 follows nobody.
let channels: BTreeMap<_, _> =
[channel_info(1, 0, 0), channel_info(2, 0, 0), channel_info(4, 0, 77)]
.into_iter()
.map(|c| (c.id, c))
.collect();
let positions = positions(&channels);
assert_eq!((positions[&1], positions[&2], positions[&4]), (0, 1024, 2048));
}
#[test]
fn the_same_identity_twice_keeps_both_clients() {
let client = |id, db| ClientInfo {
id,
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
nickname: format!("n{id}"),
database_id: Some(db),
..Default::default()
};
let mut presence = Presence::default();
for c in [client(3, 77), client(4, 77)] {
presence.clients.insert(c.id, c);
}
let built = build(&presence, false, None);
let voices = built.live.keys().filter(|k| matches!(k, Key::Voice { .. })).count();
let users = built.live.keys().filter(|k| matches!(k, Key::User { .. })).count();
assert_eq!((voices, users), (2, 2));
}
/// The own client is the user whose database id the identity has, also when a
/// ghost of the old connection (the lower client id) lingers.
#[test]
fn the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice() {
let client = |id| ClientInfo {
id,
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
nickname: format!("n{id}"),
database_id: Some(77),
..Default::default()
};
let mut presence = Presence::default();
for c in [client(3), client(4)] {
presence.clients.insert(c.id, c);
}
let user_of = |built: &Built, client: u32| {
let key = Key::Voice { server_id: SERVER_ID, participant_id: client };
let Some(Entity { kind: Some(Kind::Voice(voice)) }) = built.live.get(&key) else {
panic!("no voice state")
};
voice.user_id
};
// Nobody is us: the lower client id keeps it.
let built = build(&presence, false, None);
assert_eq!(user_of(&built, 3), 77);
assert_ne!(user_of(&built, 4), 77);
// The later client is us: it keeps it, and the ghost has the made-up id.
let built = build(&presence, false, Some(4));
assert_eq!(user_of(&built, 4), 77);
assert_ne!(user_of(&built, 3), 77);
assert_eq!(built.own_user.map(|u| u.id), Some(77));
assert_eq!(built.by_uid["uXDkxSZbv0IoA0z/toW3guGpUbI="], (77, 4));
}
#[test]
fn a_change_deletes_by_key_and_puts_what_differs() {
let mut presence = Presence::default();
presence.channels.insert(1, channel_info(1, 0, 0));
let before = build(&presence, false, None);
presence.channels.insert(2, channel_info(2, 0, 1));
presence.channels.get_mut(&1).unwrap().name = "renamed".into();
let after = build(&presence, false, None);
let (put, del) = diff(&before.server, &after.server);
assert_eq!(put.len(), 2, "the renamed channel and the new one");
assert!(del.is_empty());
let (put, del) = diff(&after.server, &before.server);
assert_eq!(put.len(), 1, "channel 1 is back to its old name");
assert_eq!(del.len(), 1);
let Some(Kind::Channel(gone)) = &del[0].kind else { panic!("a channel") };
assert_eq!((gone.id, gone.name.as_str()), (2, ""));
}
}
+115
View File
@@ -0,0 +1,115 @@
//! Ids and unique ids as the TeamSpeak gateway writes them (protocol
//! section 11.1, "Ids"): TeamSpeak's numbers as they are, and a few
//! synthetic ones with bit 63 set.
//!
//! Both sides of the seam use these rules: the TeamSpeak `Session`
//! ([`super::LinkSession`]) writes entities with them, and the engine's
//! projection (`link/project.rs`) undoes the few that the client's older
//! model has no room for.
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
/// The only server of a TeamSpeak connection (its virtual server).
pub(crate) const SERVER_ID: u64 = 1;
/// Marks the ids the gateway makes up: the server chat, direct-message
/// channels and users it knows by their unique id only.
pub(crate) const SYNTHETIC: u64 = 1 << 63;
/// The channel of the server chat, in the SERVER scope.
pub(crate) const SERVER_CHAT: u64 = SYNTHETIC;
/// Set on the id of a channel group, so that a role id does not mean a server
/// group and a channel group at once.
pub(crate) const CHANNEL_ROLE: u64 = 1 << 62;
/// The `Foreign.system` of what the protocol has no field for.
pub(crate) const FOREIGN_SYSTEM: &str = "teamspeak";
/// The role id of a channel group.
pub(crate) fn channel_role(group: u64) -> u64 {
group | CHANNEL_ROLE
}
/// The channel group a role id stands for (the reverse of [`channel_role`]).
pub(crate) fn channel_group(role: u64) -> u64 {
role & !CHANNEL_ROLE
}
/// FNV-1a, 64 bits.
fn fnv1a(bytes: &[u8]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
/// A synthetic id for something known by a name only: bit 63 set and the
/// hash of `name` in the low 63 bits (1 if they come out 0, so it is never
/// [`SERVER_CHAT`]).
fn synthetic(name: &str) -> u64 {
let low = fnv1a(name.as_bytes()) & !SYNTHETIC;
SYNTHETIC | low.max(1)
}
/// The direct-message channel with the client of this unique id.
pub(crate) fn dm_channel(uid: &str) -> u64 {
synthetic(uid)
}
/// The user id of a client that has no database id (or that the snapshot
/// does not hold): by unique id, else by whatever names it.
pub(crate) fn synthetic_user(uid: &str) -> u64 {
synthetic(uid)
}
/// The bytes of a unique id, when it is canonical base64 (what TeamSpeak
/// writes): decoding and encoding again gives the same text. A ServerQuery
/// client's login name, or anything else, is not, and goes into
/// [`Foreign`](voelin_proto::v1::Foreign) instead.
pub(crate) fn uid_bytes(uid: &str) -> Option<Vec<u8>> {
let bytes = STANDARD.decode(uid).ok()?;
(STANDARD.encode(&bytes) == uid && !bytes.is_empty()).then_some(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn channel_groups_keep_their_number_below_the_flag() {
assert_eq!(channel_role(8), 8 | (1 << 62));
assert_eq!(channel_group(channel_role(8)), 8);
assert_eq!(channel_group(channel_role(0)), 0);
}
#[test]
fn synthetic_ids_have_bit_63_and_are_never_the_server_chat() {
for name in ["", "alice=", "client:7", "a-very-long-name-that-hashes-to-something"] {
let id = dm_channel(name);
assert_ne!(id & SYNTHETIC, 0, "{name}");
assert_ne!(id, SERVER_CHAT, "{name}");
}
assert_eq!(dm_channel("alice="), dm_channel("alice="));
assert_ne!(dm_channel("alice="), dm_channel("bob="));
}
#[test]
fn only_canonical_base64_is_a_unique_id() {
// A TeamSpeak 3 unique id (SHA-1) and a TeamSpeak 6 one (SHA-256).
assert_eq!(uid_bytes("uXDkxSZbv0IoA0z/toW3guGpUbI=").map(|b| b.len()), Some(20));
assert_eq!(
uid_bytes("xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M=").map(|b| b.len()),
Some(32)
);
// A ServerQuery login name, a fixture's name, the empty string.
for not in ["serveradmin", "alice=", "me=", "", "Af4"] {
assert_eq!(uid_bytes(not), None, "{not:?}");
}
// Non-canonical trailing bits decode but do not round trip.
assert_eq!(uid_bytes("Af5="), None);
}
}
@@ -0,0 +1,862 @@
//! The TeamSpeak `Session` against the development servers
//! (`dev/docker-compose.yml`; `docs/session-seam.md` sections 9.3 and 16).
//! Runs only with `VOELIN_LIVE=1`:
//!
//! ```text
//! VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1
//! ```
//!
//! Two kinds of test, each on TeamSpeak 3 and on TeamSpeak 6:
//!
//! - the link conformance suite of the protocol repository, the cases that
//! apply to a TeamSpeak session, with the verdict of every case asserted
//! and the reason of every case that cannot pass or cannot run in
//! [`EXPECTED`];
//! - what the suite cannot reach, as a session of its own does it: a message
//! in the own channel answered, then pushed to the other session and back to
//! ours, the refusals of a move, a poke between two sessions, voice RTP from
//! one session's slot to the other's media sink, and a channel file written
//! and read back from an offset.
//!
//! The sessions are made by [`TsConnector`] through the plain `Connector`
//! interface, as a client of the seam outside an engine would make them.
//!
//! The servers ban an address that connects as often as these tests do
//! (`ConnectFailedBanned` after three or four connections) unless their
//! anti-flood limits are raised first. `scripts/it-smoke.sh` raises them when it
//! prepares its admin identity; this module raises them itself, once per server
//! and run, through the ServerQuery admin login that `refused_moves` uses
//! ([`raise_flood_limits`]), so that the command above works on a freshly
//! started stack. It needs that login (the development servers of
//! `dev/docker-compose.yml` have it) and does not lower the limits again.
use std::collections::BTreeMap;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::mpsc;
use voelin_proto::link::{Connector, FlowId, MediaClass, MediaPacket, voice_sub};
use voelin_proto::media::payload::PT_OPUS;
use voelin_proto::media::{RtpHeader, RtpView};
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
use voelin_proto::test_util::{FakeConnector, MediaReceiver, media_channel};
use voelin_proto::v1::request::Op;
use voelin_proto::v1::{self, entity::Kind};
use super::*;
use crate::link::{Backends, VoiceOptions, connect_params};
fn live() -> bool {
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
}
/// How long a test waits for the server.
const WAIT: Duration = Duration::from_secs(20);
async fn within<T>(what: &str, future: impl Future<Output = T>) -> T {
match tokio::time::timeout(WAIT, future).await {
Ok(value) => value,
Err(_) => panic!("timed out after {WAIT:?} waiting for {what}"),
}
}
/// A development server: where to connect, and how to ask it as the admin.
#[derive(Clone, Copy)]
struct Dev {
name: &'static str,
voice: &'static str,
ssh: bool,
query: &'static str,
}
const TS3: Dev = Dev { name: "ts3", voice: "127.0.0.1:9987", ssh: false, query: "127.0.0.1:10011" };
const TS6: Dev = Dev { name: "ts6", voice: "127.0.0.1:9988", ssh: true, query: "127.0.0.1:10022" };
impl Dev {
fn query(&self) -> voelin_query::Connect {
voelin_query::Connect {
transport: if self.ssh {
voelin_query::Transport::Ssh
} else {
voelin_query::Transport::Raw
},
addr: self.query.into(),
user: "serveradmin".into(),
secret: Some("voelin-dev-admin".into()),
server_port: Some(9987),
server_id: None,
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
}
}
/// A nickname no other client of this run has.
fn nick(&self, role: &str) -> String {
static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let n = COUNT.fetch_add(1, Ordering::Relaxed);
format!("{role}-{}-{n}", std::process::id() % 10_000)
}
}
/// Raise the anti-flood limits of a development server, once per run, and
/// lift the bans an earlier run left behind. The tests connect many times in
/// a few seconds from one address, which a server with its default limits
/// bans (`ConnectFailedBanned`); `scripts/it-smoke.sh` sets the same two
/// values in `admin_args`. Done through the ServerQuery login of the admin,
/// which the tests that create channels and keys use as well.
async fn raise_flood_limits(dev: &Dev) {
use tokio::sync::OnceCell;
use voelin_query::{Command as Query, QueryClient};
static TS3_READY: OnceCell<()> = OnceCell::const_new();
static TS6_READY: OnceCell<()> = OnceCell::const_new();
let ready = if dev.ssh { &TS6_READY } else { &TS3_READY };
ready
.get_or_init(|| async {
let (admin, _) = within("the query login", QueryClient::connect(&dev.query()))
.await
.unwrap_or_else(|e| panic!("the query login of {}: {e}", dev.name));
for key in [
"virtualserver_antiflood_points_needed_ip_block",
"virtualserver_antiflood_points_needed_command_block",
] {
let edit = Query::new("serveredit").arg(key, 100_000);
within("the anti-flood limits", admin.send(&edit))
.await
.unwrap_or_else(|e| panic!("{} refused {key}: {e}", dev.name));
}
// A ban of an earlier run outlives the change of the limit.
within("the ban list", admin.send(&Query::new("bandelall")))
.await
.unwrap_or_else(|e| panic!("{} did not lift its bans: {e}", dev.name));
})
.await;
}
/// A TeamSpeak session as a client of the seam sees it: made by the
/// connector, with its push channel and media sink.
async fn session(
dev: &Dev,
options: &VoiceOptions,
) -> (Arc<dyn Session>, mpsc::Receiver<v1::Push>, MediaReceiver) {
raise_flood_limits(dev).await;
let (sink, media) = media_channel();
let params = connect_params(options, sink, &Backends::empty()).expect("connect parameters");
let connected =
within(&format!("a connection to {}", dev.name), TsConnector::new().connect(params))
.await
.unwrap_or_else(|e| panic!("{} did not connect: {e}", dev.name));
(connected.session, connected.pushes, media)
}
/// A client of the TeamSpeak session that has done what an engine does after
/// it connects (`docs/session-seam.md` 4.2, without the replica): the server
/// listed, HOME, SERVER and LIVE subscribed and synced, a seat in voice.
struct Client {
session: Arc<dyn Session>,
pushes: mpsc::Receiver<v1::Push>,
media: MediaReceiver,
server: u64,
default_channel: u64,
/// Our seat in voice (participant, slot, channel).
seat: v1::VoiceState,
/// The voice states of the server, as the pushes told them.
voices: BTreeMap<u32, v1::VoiceState>,
}
fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope {
v1::Scope { kind: kind as i32, id }
}
impl Client {
async fn connect(dev: &Dev, nick: &str) -> Self {
Self::connect_with(dev, VoiceOptions::new(dev.voice, nick)).await
}
async fn connect_with(dev: &Dev, options: VoiceOptions) -> Self {
let (session, pushes, media) = session(dev, &options).await;
let mut client = Self {
session,
pushes,
media,
server: 0,
default_channel: 0,
seat: v1::VoiceState::default(),
voices: BTreeMap::new(),
};
let list = Op::List(v1::List { kind: v1::EntityKind::Server as i32, ..Default::default() });
let Answer::Entities(servers) = client.ask(list).await.expect("the server list") else {
panic!("the server list is not entities")
};
let server = servers
.items
.iter()
.find_map(|e| match &e.kind {
Some(Kind::Server(server)) => Some(server.clone()),
_ => None,
})
.expect("the host lists its server");
client.server = server.id;
client.default_channel = server.default_channel_id;
for scope in [
scope(v1::ScopeKind::Home, 0),
scope(v1::ScopeKind::Server, server.id),
scope(v1::ScopeKind::Live, server.id),
] {
client.subscribe(scope).await;
}
client.seat = client.join(client.default_channel, "").await.expect("a seat in voice");
client.settle().await;
client
}
/// A request, answered within [`WAIT`].
async fn ask(&self, op: Op) -> Result<Answer, SessionError> {
within("an answer", self.session.request(op)).await
}
/// Subscribe `scope` and take its sync off the push channel.
async fn subscribe(&mut self, scope: v1::Scope) {
let op = Op::Subscribe(v1::Subscribe { scope: Some(scope), ..Default::default() });
self.ask(op).await.expect("a subscription");
self.until("the end of the sync", |push| match &push.body {
Some(v1::push::Body::SyncEnd(end)) if end.scope == Some(scope) => Some(()),
_ => None,
})
.await;
}
/// `JoinVoice`: our seat, or why not.
async fn join(&self, channel: u64, password: &str) -> Result<v1::VoiceState, SessionError> {
let join = v1::JoinVoice {
server_id: self.server,
channel_id: channel,
password: password.into(),
..Default::default()
};
match self.ask(Op::JoinVoice(join)).await? {
Answer::Entities(entities) => entities
.items
.into_iter()
.find_map(|e| match e.kind {
Some(Kind::Voice(voice)) => Some(voice),
_ => None,
})
.ok_or_else(|| SessionError::Protocol("no voice state in the answer".into())),
other => Err(SessionError::Protocol(format!("unexpected answer {other:?}"))),
}
}
/// Keep track of what a push says about the server and its voice states.
fn absorb(&mut self, push: &v1::Push) {
let Some(v1::push::Body::Change(change)) = &push.body else { return };
for entity in &change.put {
match &entity.kind {
Some(Kind::Voice(voice)) => {
self.voices.insert(voice.participant_id, voice.clone());
}
Some(Kind::Server(server)) if server.default_channel_id != 0 => {
self.default_channel = server.default_channel_id;
}
_ => {}
}
}
for entity in &change.del {
if let Some(Kind::Voice(voice)) = &entity.kind {
self.voices.remove(&voice.participant_id);
}
}
}
/// The next push `f` picks, skipping (and keeping track of) the others.
async fn until<T>(&mut self, what: &str, mut f: impl FnMut(&v1::Push) -> Option<T>) -> T {
within(what, async {
loop {
let push = self.pushes.recv().await.expect("the session lives");
self.absorb(&push);
if let Some(t) = f(&push) {
return t;
}
}
})
.await
}
/// Wait until the host shows our seat in LIVE: the first snapshot of the
/// TeamSpeak link may come after the session was handed out, so the syncs
/// can be empty and the voice states follow as changes. The seat then
/// names the channel we are in.
async fn settle(&mut self) {
let participant = self.seat.participant_id;
within("our voice state to appear", async {
while !self.voices.contains_key(&participant) {
let push = self.pushes.recv().await.expect("the session lives");
self.absorb(&push);
}
})
.await;
self.seat = self.voices[&participant].clone();
}
/// The next message `Change` of the CHAT scope of `channel` with `text`.
async fn message(&mut self, channel: u64, text: &str) -> v1::Message {
let chat = Some(scope(v1::ScopeKind::Chat, channel));
self.until(&format!("the message {text:?}"), |push| match &push.body {
Some(v1::push::Body::Change(change)) if change.scope == chat => {
change.put.iter().find_map(|e| match &e.kind {
Some(Kind::Message(message)) if message.text == text => Some(message.clone()),
_ => None,
})
}
_ => None,
})
.await
}
async fn close(self) {
self.session.close(v1::CloseCode::Normal, "");
within("the session to close", self.session.closed()).await;
}
}
// ---- the conformance suite ----------------------------------------------------
/// What a case is expected to do against a TeamSpeak session, and why.
enum Expect {
/// Every assertion of the case holds.
Passes,
/// The session lacks the feature the case needs (`Verdict::Skipped`).
Skipped(&'static str),
/// The case does not apply: it cannot run, or cannot pass, for this reason
/// (`cases_that_do_not_apply_fail` runs them and watches them fail).
NotRun(&'static str),
}
use Expect::{NotRun, Passes, Skipped};
/// Every case of the suite of the protocol repository at `c8e0e5a`, in its
/// order, with what a TeamSpeak session does with it. A case the suite gains
/// fails `the_suite_is_known` until it is listed here.
///
/// The suite is written for a backend that is a `FakeHost`. A case that needs
/// the backend gets the `FakeHandle` of an unrelated fake host, so the cases
/// that hold, kill or read it, or push into it, cannot run against a session of
/// a TeamSpeak server; the others write to places a TeamSpeak server does not
/// have (the suite's channels, a server with another id, `ScheduledEvent`,
/// `Emoji`, attachments). Each reason is what the case did when it was run.
const EXPECTED: [(&str, Expect); 17] = [
("welcome_matches_features", Passes),
(
"subscribe_syncs_the_scope",
NotRun("writes to channel 4001: rejected (NotFound) no such channel"),
),
(
"subscribe_resumes_from_a_cursor",
NotRun("writes to channel 4002: rejected (NotFound) no such channel"),
),
(
"put_answers_entities_and_pushes_the_change_with_the_same_rev",
NotRun("writes to channel 4003: rejected (NotFound) no such channel"),
),
(
"delete_answers_an_ack_and_pushes_the_removal",
NotRun(
"writes to channel 4004 first (no such channel); and TeamSpeak cannot delete a message, \
where the case needs only `chat`, not `chat.delete` (P8)",
),
),
(
"a_key_names_an_entity_without_its_server",
NotRun(
"rejected (NotFound) no such server; and it creates a ScheduledEvent and an Emoji, \
which TeamSpeak lacks, though it needs no feature (P8)",
),
),
("a_stale_rev_conflicts_and_a_patch_writes_only_its_paths", Skipped("chat.edit")),
("requests_apply_in_the_order_they_were_issued", Skipped("chat.edit")),
("list_pages_history", Skipped("chat.history")),
(
"cancel_before_apply_is_cancelled",
NotRun("holds the unrelated fake host, so the request is answered while it \"holds\""),
),
("idempotency_keys_apply_a_put_once", Skipped("idempotency")),
(
"notifications_are_fire_and_forget",
NotRun("reads the request log of the unrelated fake host: the notification never arrives"),
),
(
"renew_account_follows_the_feature",
NotRun("pushes a HostUpdate into the unrelated fake session's closed push channel"),
),
(
"media_loops_back",
NotRun(
"a TeamSpeak server does not return a client's own voice: the packet never loops back",
),
),
(
"files_round_trip",
NotRun(
"writes an AttachmentSlot: rejected (Unsupported) attachments are not offered; \
TeamSpeak has channel files, and the case needs `files`, not `chat.attachments` (P8)",
),
),
("close_ends_the_session", Passes),
(
"the_backend_can_end_the_session",
NotRun(
"kills the unrelated fake session, so closed() of this one never resolves; and a \
kick is Network(text), not Remote{KICKED}, until H1",
),
),
];
/// A fixture on a TeamSpeak session. The suite wants a `FakeHandle` on the
/// backend behind the session; a TeamSpeak server has none, so it gets the one
/// of an unrelated fake host, which the cases that are run never touch.
async fn fixture(dev: Dev) -> Fixture {
let (session, pushes, media) =
session(&dev, &VoiceOptions::new(dev.voice, dev.nick("conf"))).await;
let unrelated = FakeConnector::new();
let (params, _media) = voelin_proto::test_util::connect_params("fake://unrelated");
unrelated.connect(params).await.expect("a fake session");
let backend = unrelated.last_session().expect("a fake session");
Fixture::new(session, pushes, media, backend)
}
fn the_suite_is_known() {
let known: Vec<_> = EXPECTED.iter().map(|(name, _)| *name).collect();
let cases: Vec<_> = conformance::CASES.iter().map(|case| case.name).collect();
assert_eq!(known, cases, "the suite changed: list the new cases in EXPECTED");
}
/// The cases that apply run and pass, the ones that need a feature the session
/// lacks are skipped, and the rest are not run (their reason is in
/// [`EXPECTED`]).
async fn conformance_subset(dev: Dev) {
the_suite_is_known();
let harness = move || fixture(dev);
let (mut passed, mut skipped) = (0, 0);
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
match expect {
Passes => {
let verdict = conformance::run_case(&harness, case).await;
assert_eq!(verdict, Verdict::Passed, "{name} on {}", dev.name);
passed += 1;
}
Skipped(feature) => {
let verdict = conformance::run_case(&harness, case).await;
assert_eq!(verdict, Verdict::Skipped(feature), "{name} on {}", dev.name);
skipped += 1;
}
NotRun(reason) => eprintln!("{} {name}: not run: {reason}", dev.name),
}
}
assert_eq!((passed, skipped), (2, 4));
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_conformance_subset() {
if live() {
conformance_subset(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_conformance_subset() {
if live() {
conformance_subset(TS6).await;
}
}
// ---- what the suite cannot reach ----------------------------------------------
/// A message in the own channel is answered with the message as written, and
/// pushed to the CHAT scope of every session in the channel: to the other one
/// as a `Change`, and back to ours (the ids agree only with the native
/// session of H1: the answer has a local id, the echo the one of the
/// `Change`).
async fn chat_in_the_own_channel(dev: Dev) {
let mut a = Client::connect(&dev, &dev.nick("chat-a")).await;
let mut b = Client::connect(&dev, &dev.nick("chat-b")).await;
assert_eq!(a.seat.channel_id, b.seat.channel_id, "both sessions are in the default channel");
let channel = a.seat.channel_id;
a.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
b.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
let text = format!("live-chat-{}", std::process::id());
let message = v1::Message { channel_id: channel, text: text.clone(), ..Default::default() };
let write = v1::Write {
entity: Some(v1::Entity { kind: Some(Kind::Message(message)) }),
paths: Vec::new(),
};
let put = Op::Put(v1::Put { writes: vec![write], ..Default::default() });
let Answer::Entities(answer) = a.ask(put).await.expect("the message is accepted") else {
panic!("a message is answered with entities")
};
let written = match &answer.items[..] {
[v1::Entity { kind: Some(Kind::Message(message)) }] => message.clone(),
other => panic!("one message expected, got {other:?}"),
};
assert_eq!((written.channel_id, written.text.as_str()), (channel, text.as_str()));
let heard = b.message(channel, &text).await;
assert_ne!(heard.id, 0);
assert_eq!(heard.channel_id, channel);
// And ours, back from the server: the same words, once.
let echo = a.message(channel, &text).await;
assert_ne!(echo.id, 0);
a.close().await;
b.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_chat_in_the_own_channel() {
if live() {
chat_in_the_own_channel(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_chat_in_the_own_channel() {
if live() {
chat_in_the_own_channel(TS6).await;
}
}
/// A move into a channel with a password or without room is refused with the
/// code the seam names: `PASSWORD` and `FULL`.
async fn refused_moves(dev: Dev) {
use voelin_query::{Command as Query, QueryClient};
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
let tag = std::process::id() % 10_000;
let create = |name: &str| {
Query::new("channelcreate")
.arg("channel_name", format!("{name}-{tag}"))
.arg("channel_flag_semi_permanent", 1)
};
let locked =
admin.send(&create("seam-locked").arg("channel_password", "secret")).await.unwrap()[0]
.parse::<u64>("cid")
.unwrap();
let full = create("seam-full")
.arg("channel_maxclients", 0)
.arg("channel_flag_maxclients_unlimited", 0);
let full = admin.send(&full).await.unwrap()[0].parse::<u64>("cid").unwrap();
// A key for the Normal group, which has to keep to passwords and limits.
let token = group_token(&admin, "Normal").await;
let check = {
let token = token.clone();
tokio::spawn(async move {
let mut options = VoiceOptions::new(dev.voice, dev.nick("moves"));
options.token = Some(token);
let client = Client::connect_with(&dev, options).await;
let code = |result: Result<v1::VoiceState, SessionError>| match result {
Err(SessionError::Rejected(error)) => error.code(),
other => panic!("expected a refusal, got {other:?}"),
};
assert_eq!(code(client.join(locked, "").await), v1::ErrorCode::Password);
assert_eq!(code(client.join(locked, "wrong").await), v1::ErrorCode::Password);
let seat = client.join(locked, "secret").await.expect("the right password");
assert_eq!(seat.channel_id, locked);
assert_eq!(code(client.join(full, "").await), v1::ErrorCode::Full);
client.close().await;
})
};
let result = check.await;
// Clean up before reporting a failure; the key is gone once used.
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
for cid in [locked, full] {
admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap();
}
if let Err(error) = result {
std::panic::resume_unwind(error.into_panic());
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_refused_moves() {
if live() {
refused_moves(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_refused_moves() {
if live() {
refused_moves(TS6).await;
}
}
/// A poke is a `Signal` to a participant: the other session gets it, with
/// the participant and the words of the sender.
async fn poke_between_sessions(dev: Dev) {
let a = Client::connect(&dev, &dev.nick("poke-a")).await;
let mut b = Client::connect(&dev, &dev.nick("poke-b")).await;
let text = format!("live-poke-{}", std::process::id());
let target = v1::SignalTarget {
server_id: a.server,
participant_id: b.seat.participant_id,
..Default::default()
};
let signal = v1::Signal {
to: Some(target),
body: Some(v1::signal::Body::Poke(v1::Poke { message: text.clone() })),
..Default::default()
};
a.ask(Op::Signal(signal)).await.expect("the poke is accepted");
let from = b
.until("the poke", |push| match &push.body {
Some(v1::push::Body::Signal(signal)) => match &signal.body {
Some(v1::signal::Body::Poke(poke)) if poke.message == text => {
Some(signal.from_participant)
}
_ => None,
},
_ => None,
})
.await;
assert_eq!(from, a.seat.participant_id);
a.close().await;
b.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_poke_between_sessions() {
if live() {
poke_between_sessions(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_poke_between_sessions() {
if live() {
poke_between_sessions(TS6).await;
}
}
/// One frame of Opus (20 ms, mono, fullband).
const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe];
fn rtp(flow: FlowId, sequence: u16, marker: bool, payload: &[u8]) -> MediaPacket {
let mut header = RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960);
header.marker = marker;
let mut out = bytes::BytesMut::new();
header.write(flow, &mut out).expect("a header");
out.extend_from_slice(payload);
MediaPacket { flow, rtp: out.freeze() }
}
/// Voice sent on our slot arrives on the sender's slot at the other session's
/// media sink: the frames in order (the sequence is TeamSpeak's packet id, so
/// it only has to count up), the marker on the first, and an empty payload at
/// the end.
async fn voice_between_sessions(dev: Dev) {
let a = Client::connect(&dev, &dev.nick("voice-a")).await;
let mut b = Client::connect(&dev, &dev.nick("voice-b")).await;
assert_eq!(a.seat.channel_id, b.seat.channel_id);
let flow = FlowId::new(a.seat.slot, voice_sub::CHANNEL);
for n in 0..5u8 {
let frame = [0xf8, 0xff, 0xfe, n];
let packet = rtp(flow, u16::from(n), n == 0, &frame);
a.session.send_media(MediaClass::Voice, packet).expect("our own slot");
tokio::time::sleep(Duration::from_millis(20)).await;
}
a.session.send_media(MediaClass::Voice, rtp(flow, 5, false, &[])).expect("the end");
let mut heard = Vec::new();
while let Some(packet) = b.media.recv_within(Duration::from_secs(5)).await {
let view = RtpView::parse(&packet.rtp).expect("RTP");
heard.push((packet.flow, view.sequence(), view.marker(), view.payload().to_vec()));
if view.payload().is_empty() {
break;
}
}
assert!(heard.len() >= 2, "{heard:?}");
assert!(heard.iter().all(|(heard_flow, ..)| *heard_flow == flow), "{heard:?}");
let (_, _, first_marker, first_payload) = &heard[0];
assert!(*first_marker, "the first packet of the spurt carries the marker: {heard:?}");
assert_eq!(&first_payload[..3], &OPUS[..], "{heard:?}");
let (end_flow, _, end_marker, end_payload) = heard.last().expect("an end");
assert!(
end_payload.is_empty() && !*end_marker,
"the spurt ends with an empty payload: {heard:?}"
);
assert_eq!(*end_flow, flow);
let sequences: Vec<_> = heard.iter().map(|(_, sequence, ..)| *sequence).collect();
assert!(
sequences.windows(2).all(|pair| pair[1] == pair[0].wrapping_add(1)),
"the sequence counts up by one: {sequences:?}"
);
// Voice on a slot that is not ours is refused before it reaches the server.
let other = FlowId::new(a.seat.slot + 1000, voice_sub::CHANNEL);
assert!(a.session.send_media(MediaClass::Voice, rtp(other, 0, true, &OPUS)).is_err());
a.close().await;
b.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_voice_between_sessions() {
if live() {
voice_between_sessions(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_voice_between_sessions() {
if live() {
voice_between_sessions(TS6).await;
}
}
/// A channel file written with `write_file` and read back from an offset with
/// `read_file`: the head names the file and its size, the body starts where
/// the offset says.
async fn channel_file_from_an_offset(dev: Dev) {
use voelin_query::{Command as Query, QueryClient};
// Guests may not upload: a key for the Server Admin group.
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
let token = group_token(&admin, "Server Admin").await;
let check = tokio::spawn({
let token = token.clone();
async move { channel_file_with_a_key(dev, token).await }
});
let result = check.await;
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
if let Err(error) = result {
std::panic::resume_unwind(error.into_panic());
}
}
/// A one-time key for the server group `name` (a template group, type 1).
async fn group_token(admin: &voelin_query::QueryClient, name: &str) -> String {
use voelin_query::Command as Query;
let groups = admin.send(&Query::new("servergrouplist")).await.unwrap();
let group = groups
.iter()
.find(|g| g.get("name") == Some(name) && g.get("type") == Some("1"))
.and_then(|g| g.parse::<u64>("sgid"))
.unwrap_or_else(|| panic!("a {name} server group"));
let key =
Query::new("privilegekeyadd").arg("tokentype", 0).arg("tokenid1", group).arg("tokenid2", 0);
admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned()
}
async fn channel_file_with_a_key(dev: Dev, token: String) {
let mut options = VoiceOptions::new(dev.voice, dev.nick("files"));
options.token = Some(token);
let a = Client::connect_with(&dev, options).await;
let channel = a.seat.channel_id;
let name = format!("seam-{}.bin", std::process::id());
let path = format!("/{name}");
let data: Vec<u8> = (0..3_000usize).map(|i| (i * 7 % 251) as u8).collect();
let target = v1::FilePath { channel_id: channel, path: path.clone(), password: String::new() };
let write = v1::FileWrite {
target: Some(v1::file_write::Target::Path(target.clone())),
size: data.len() as u64,
offset: 0,
overwrite: true,
sha256: Default::default(),
};
let mut upload =
within("the upload to open", a.session.write_file(write)).await.expect("an upload");
upload.body.write_all(&data).await.expect("the body");
upload.body.shutdown().await.expect("the end of the body");
let stored = within("the server to keep it", upload.done).await.expect("the file is stored");
assert!(
stored.items.iter().any(|e| matches!(&e.kind, Some(Kind::File(f)) if f.name == name)),
"{stored:?}"
);
let read = v1::FileRead {
target: Some(v1::file_read::Target::Path(target.clone())),
offset: 1_000,
length: 0,
};
let mut download =
within("the download to open", a.session.read_file(read)).await.expect("a download");
let size = download.head.items.iter().find_map(|e| match &e.kind {
Some(Kind::File(file)) => Some(file.size),
_ => None,
});
assert_eq!(size, Some(3_000), "{:?}", download.head);
let mut body = Vec::new();
within("the body", download.body.read_to_end(&mut body)).await.expect("the body");
assert_eq!(body, data[1_000..], "the body starts at the offset");
// Clean up what we put on the server.
let key = v1::FileEntry { channel_id: channel, path: "/".into(), name, ..Default::default() };
let delete = Op::Delete(v1::Delete {
keys: vec![v1::Entity { kind: Some(Kind::File(key)) }],
..Default::default()
});
let _ = a.ask(delete).await;
a.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_channel_file_from_an_offset() {
if live() {
channel_file_from_an_offset(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_channel_file_from_an_offset() {
if live() {
channel_file_from_an_offset(TS6).await;
}
}
// ---- the cases that do not apply ----------------------------------------------
/// The cases of [`EXPECTED`] that do not apply fail against a session of a
/// TeamSpeak server, each with a panic of its own (its first line is printed):
/// the reasons of the table are what they did when they were run. A case that
/// passes one day (with the native session of H1) is to be moved to `Passes`.
///
/// Ignored by default: the cases that wait for a backend that is not there
/// take their three seconds each.
async fn cases_that_do_not_apply_fail(dev: Dev) {
// A case the suite gained is not in `EXPECTED`, and the zip below would leave
// it out without a word.
the_suite_is_known();
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
let NotRun(reason) = expect else { continue };
let harness = move || async move {
let mut fixture = fixture(dev).await;
fixture.step = Duration::from_secs(3);
fixture
};
match tokio::spawn(async move { conformance::run_case(&harness, case).await }).await {
Err(error) if error.is_panic() => {
let payload = error.into_panic();
let message = payload
.downcast_ref::<String>()
.cloned()
.or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned()))
.unwrap_or_default();
let first = message.lines().next().unwrap_or_default();
eprintln!("{} {name}: failed as expected ({reason}): {first}", dev.name);
}
other => panic!("{name} on {} was expected to fail, and: {other:?}", dev.name),
}
}
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
async fn ts3_cases_that_do_not_apply_fail() {
if live() {
cases_that_do_not_apply_fail(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
async fn ts6_cases_that_do_not_apply_fail() {
if live() {
cases_that_do_not_apply_fail(TS6).await;
}
}
@@ -0,0 +1,245 @@
//! Voice across the seam, TeamSpeak side (`docs/session-seam.md` section
//! 6.2): TeamSpeak's Opus packets as RTP on the talker's slot, and RTP on our
//! own slot as TeamSpeak's `EncodedVoice`. Nothing is transcoded
//! (protocol section 1.2): the Opus payload is the same bytes both ways.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use bytes::BytesMut;
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
use voelin_proto::media::opus::{self, Toc};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, OPUS_CLOCK_RATE, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
use super::entities::slot;
/// Silence this long between two packets of a talker starts a new talk spurt
/// (the marker bit is set on the first packet of it).
const SPURT_GAP: Duration = Duration::from_millis(250);
/// What is kept of the last packet of a talker.
struct Talker {
timestamp: u32,
sequence: u16,
at: Instant,
/// The 48 kHz ticks the last packet spans.
ticks: u32,
/// The last packet ended the spurt.
ended: bool,
}
/// Wraps what a TeamSpeak connection receives into RTP.
#[derive(Default)]
pub(super) struct Downlink {
talkers: HashMap<u16, Talker>,
}
impl Downlink {
/// `packet` as the RTP packet of its talker's slot. The sequence number is
/// TeamSpeak's packet id (both 16 bits); the timestamp advances by each
/// packet's duration (its Opus table-of-contents byte) on the packet id's
/// counter, so it never goes back when the id wraps, and by wall-clock time
/// across silences, so a silence is not compressed. The marker is set on
/// the first packet after an end or a gap, and an end is an empty payload.
pub(super) fn wrap(&mut self, packet: &VoicePacket, now: Instant) -> Option<MediaPacket> {
let id = packet.talker.0;
let sub = if packet.whisper { voice_sub::FIRST_TALK_TARGET } else { voice_sub::CHANNEL };
let flow = FlowId::new(slot(id), sub);
let end = packet.is_end();
let (timestamp, marker) = match self.talkers.get(&id) {
None => (0, !end),
Some(last) => {
let gap = now.saturating_duration_since(last.at);
if last.ended || gap > SPURT_GAP {
// A new spurt: the time that passed since the last packet.
let wall = (gap.as_micros() * u128::from(OPUS_CLOCK_RATE) / 1_000_000) as u32;
(last.timestamp.wrapping_add(last.ticks.max(wall)), !end)
} else {
let ahead = packet.seq.wrapping_sub(last.sequence);
if ahead == 0 || ahead >= 0x8000 {
// A duplicate or a late packet: where it belongs, and the
// state keeps what the latest packet said.
let back = u32::from(last.sequence.wrapping_sub(packet.seq));
let at = last.timestamp.wrapping_sub(back * last.ticks);
return self.finish(flow, packet, at, false);
}
(last.timestamp.wrapping_add(u32::from(ahead) * last.ticks), false)
}
}
};
let ticks =
if end { 0 } else { opus::packet_ticks(&packet.payload).unwrap_or(OPUS_20_MS_TICKS) };
self.talkers
.insert(id, Talker { timestamp, sequence: packet.seq, at: now, ticks, ended: end });
self.finish(flow, packet, timestamp, marker)
}
fn finish(
&self,
flow: FlowId,
packet: &VoicePacket,
timestamp: u32,
marker: bool,
) -> Option<MediaPacket> {
let mut header = RtpHeader::new(PT_OPUS, packet.seq, timestamp);
header.marker = marker;
// An end is an empty payload, also where the server sent one byte.
let payload = if packet.is_end() { &[][..] } else { &packet.payload[..] };
let mut out = BytesMut::with_capacity(header.encoded_len() + payload.len());
header.write(flow, &mut out).ok()?;
out.extend_from_slice(payload);
Some(MediaPacket { flow, rtp: out.freeze() })
}
/// Forget a talker (it left the server).
pub(super) fn forget(&mut self, client: u16) {
self.talkers.remove(&client);
}
}
/// The voice a media packet of our own slot carries, for TeamSpeak: its
/// payload, and `Music` when the Opus packet is stereo. `None` for a packet
/// that is no RTP.
pub(super) fn uplink(packet: &MediaPacket) -> Option<EncodedVoice> {
let view = RtpView::parse(&packet.rtp).ok()?;
let payload = view.payload();
let codec = match Toc::parse(payload) {
Ok(toc) if toc.stereo() => VoiceCodec::Music,
_ => VoiceCodec::Voice,
};
Some(EncodedVoice { codec, payload: payload.to_vec() })
}
/// An RTP packet of voice, for tests of both sides.
#[cfg(test)]
pub(super) fn rtp_packet(
flow: FlowId,
sequence: u16,
timestamp: u32,
marker: bool,
payload: &[u8],
) -> bytes::Bytes {
let mut header = RtpHeader::new(PT_OPUS, sequence, timestamp);
header.marker = marker;
let mut out = BytesMut::new();
header.write(flow, &mut out).unwrap();
out.extend_from_slice(payload);
out.freeze()
}
#[cfg(test)]
mod tests {
use bytes::Bytes;
use voelin_audio::TalkerId;
use super::*;
fn voice(talker: u16, seq: u16, payload: &[u8], whisper: bool) -> VoicePacket {
VoicePacket {
talker: TalkerId(talker),
seq,
codec: VoiceCodec::Voice,
whisper,
payload: payload.to_vec(),
}
}
/// An Opus packet of 20 ms in a CELT-only frame (config 16 is 2.5 ms; 19
/// is 20 ms), mono, one frame.
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
fn view(packet: &MediaPacket) -> RtpView<'_> {
RtpView::parse(&packet.rtp).unwrap()
}
#[test]
fn a_spurt_is_sequenced_by_the_packet_id_with_a_marker_on_its_first_packet() {
let mut down = Downlink::default();
let t0 = Instant::now();
let first = down.wrap(&voice(7, 65_534, &OPUS_20_MS, false), t0).unwrap();
let v = view(&first);
assert!(v.marker());
assert_eq!((v.ssrc(), first.flow), (FlowId::new(8, 0).0, FlowId::new(8, 0)));
assert_eq!((v.sequence(), v.timestamp()), (65_534, 0));
// The id wraps; the timestamp keeps counting.
let t1 = t0 + Duration::from_millis(20);
let second = down.wrap(&voice(7, 65_535, &OPUS_20_MS, false), t1).unwrap();
let third =
down.wrap(&voice(7, 0, &OPUS_20_MS, false), t1 + Duration::from_millis(20)).unwrap();
assert!(!view(&second).marker() && !view(&third).marker());
assert_eq!(view(&second).timestamp(), OPUS_20_MS_TICKS);
assert_eq!((view(&third).sequence(), view(&third).timestamp()), (0, 2 * OPUS_20_MS_TICKS));
}
#[test]
fn the_end_is_an_empty_payload_and_the_next_packet_has_a_marker() {
let mut down = Downlink::default();
let t0 = Instant::now();
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
let end = down.wrap(&voice(7, 2, &[], false), t0 + Duration::from_millis(20)).unwrap();
assert!(view(&end).payload().is_empty() && !view(&end).marker());
// TeamSpeak's single byte after a talk is an end too.
let mut down = Downlink::default();
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
let end = down.wrap(&voice(7, 2, &[0], false), t0 + Duration::from_millis(20)).unwrap();
assert!(view(&end).payload().is_empty());
let next =
down.wrap(&voice(7, 3, &OPUS_20_MS, false), t0 + Duration::from_millis(60)).unwrap();
assert!(view(&next).marker());
}
#[test]
fn a_silence_is_not_compressed() {
let mut down = Downlink::default();
let t0 = Instant::now();
let first = down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
let again =
down.wrap(&voice(7, 2, &OPUS_20_MS, false), t0 + Duration::from_secs(2)).unwrap();
assert!(view(&again).marker(), "a gap starts a spurt");
// Two seconds of wall-clock time are 96,000 ticks of the 48 kHz clock.
assert_eq!(view(&again).timestamp() - view(&first).timestamp(), 96_000);
}
#[test]
fn whispers_ride_sub_flow_1_and_talkers_have_slots_of_their_own() {
let mut down = Downlink::default();
let now = Instant::now();
let whisper = down.wrap(&voice(300, 1, &OPUS_20_MS, true), now).unwrap();
assert_eq!((whisper.flow.slot(), whisper.flow.sub()), (301, 1));
let channel = down.wrap(&voice(300, 2, &OPUS_20_MS, false), now).unwrap();
assert_eq!((channel.flow.slot(), channel.flow.sub()), (301, 0));
}
#[test]
fn a_packet_that_is_not_in_order_keeps_the_state_of_the_latest() {
let mut down = Downlink::default();
let t0 = Instant::now();
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0).unwrap();
down.wrap(&voice(7, 11, &OPUS_20_MS, false), t0 + Duration::from_millis(20)).unwrap();
let late =
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0 + Duration::from_millis(25)).unwrap();
assert_eq!(view(&late).timestamp(), 0, "where packet 10 belongs");
let next =
down.wrap(&voice(7, 12, &OPUS_20_MS, false), t0 + Duration::from_millis(40)).unwrap();
assert_eq!(view(&next).timestamp(), 2 * OPUS_20_MS_TICKS);
}
#[test]
fn our_voice_loses_its_header_and_stereo_is_music() {
let flow = FlowId::new(8, 0);
let mono = MediaPacket { flow, rtp: rtp_packet(flow, 0, 0, true, &OPUS_20_MS) };
let voice = uplink(&mono).unwrap();
assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..]));
// The same TOC with the stereo bit.
let stereo_toc = [OPUS_20_MS[0] | 0x04, 1, 2];
let stereo = MediaPacket { flow, rtp: rtp_packet(flow, 1, 960, false, &stereo_toc) };
assert_eq!(uplink(&stereo).unwrap().codec, VoiceCodec::Music);
// The end of a spurt: an empty payload.
let end = MediaPacket { flow, rtp: rtp_packet(flow, 2, 1920, false, &[]) };
assert!(uplink(&end).unwrap().is_end());
// Not RTP.
assert!(uplink(&MediaPacket { flow, rtp: Bytes::from_static(&[1, 2, 3]) }).is_none());
}
}
+855
View File
@@ -0,0 +1,855 @@
//! A TeamSpeak connection as a `voelin_proto::link::Session`
//! (`docs/session-seam.md`, "the TeamSpeak side").
//!
//! [`LinkSession`] is a `Session` over any [`ServerLink`]:
//! it turns the link's `LinkCmd`s and `LinkEvent`s (the client's older,
//! TeamSpeak-shaped vocabulary) into v1 entities, pushes and answers. With
//! `TsLink` inside it is the in-process TeamSpeak `Session`; with a fake link
//! inside it is what the link tests of the engine run through. [`TsConnector`]
//! is the `Connector` that makes them for `ts3server://` and `teamspeak://`
//! addresses.
//!
//! This module and the files it is made of are TeamSpeak's: they keep the
//! TeamSpeak types (`tsclientlib`'s identity and client version) in
//! [`inner_options`], the reverse of what the engine's `connect_params` wrote,
//! and everything else is v1 and the client's own model. In the second half
//! of the decoupling plan they move, with `TsLink`, to the TeamSpeak gateway
//! (`voelin-gateway-ts` of VoelinGateWay).
mod driver;
pub(crate) mod entities;
pub(crate) mod ids;
#[cfg(test)]
mod live_tests;
mod media;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncWrite};
use tokio::sync::{broadcast, mpsc, oneshot, watch};
use voelin_model::{Link, ServerDetails};
use voelin_proto::link::{
BoxFuture, CloseReason, ConnectParams, Connected, Connector, Credential, Download, Features,
LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, Placement, Sent, Session,
SessionError, Upload, placement, voice_sub,
};
use voelin_proto::v1::{self, response::Result as Answer};
use self::driver::{Cmd, Config, Driver, Parts, rejected};
use super::{ConnectOptions, ServerLink, TsLink, versions};
use crate::BackendInfo;
use crate::link::{
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
VERSION_PARAM,
};
/// The `Credential::Foreign` kind of a stored TeamSpeak identity.
const IDENTITY_KIND: &str = voelin_identity::KIND_TEAMSPEAK;
/// How long the link may take to report its first snapshot after it said it
/// is connected; the snapshot gives the `Welcome` its own user.
const FIRST_SNAPSHOT: Duration = Duration::from_millis(250);
static SESSIONS: AtomicU64 = AtomicU64::new(1);
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or_default()
}
// ---- what the engine hands a connector ------------------------------------
/// The options a TeamSpeak link is connected with: the reverse of
/// `link::connect_params`. A client version spec that [`versions::resolve`]
/// refuses fails the connect, in words.
fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOptions, SessionError> {
let link = match Link::parse(&params.address) {
Some(Link::Server(link)) => link,
_ => {
// Without the query: a channel password rides in it.
let shown = crate::link::without_query(&params.address);
return Err(SessionError::Protocol(format!("not a TeamSpeak server address: {shown}")));
}
};
let identity = match &params.credential {
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
Some(serde_json::from_slice(blob).map_err(|e| {
SessionError::Protocol(format!("the TeamSpeak identity cannot be read: {e}"))
})?)
}
_ => {
return Err(SessionError::Protocol(
"a TeamSpeak server needs a TeamSpeak identity".into(),
));
}
};
let spec = params
.address
.split_once('?')
.and_then(|(_, query)| {
query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}=")))
})
.map(|text| {
URL_SAFE_NO_PAD
.decode(text)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.ok_or_else(|| SessionError::Protocol("the client version cannot be read".into()))
})
.transpose()?;
let client_version = match spec {
None => None,
Some(spec) => versions::resolve(&spec).map_err(|e| {
SessionError::Protocol(format!("invalid client compatibility version: {e}"))
})?,
};
let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned());
Ok(ConnectOptions {
address: link.address(),
nickname: nonempty(&params.hello.nickname).or(link.nickname.clone()).unwrap_or_default(),
identity,
client_version,
server_password: nonempty(&params.hello.password).or(link.password.clone()),
channel: link.channel.clone(),
channel_password: link.channel_password.clone(),
token: nonempty(&params.hello.invite_code).or(link.token.clone()),
audio: ctx.audio,
stream_peer: ctx.stream_peer.clone(),
})
}
// ---- backend and features ---------------------------------------------------
/// The server software as v1 names it (table 4.7): `teamspeak` with the
/// flavor `ts3` or `ts6`; what is not a TeamSpeak product as it is.
pub(crate) fn backend_to_v1(backend: &BackendInfo) -> v1::BackendInfo {
let (product, flavor) = match backend.product.as_str() {
"TeamSpeak 3" => ("teamspeak", "ts3"),
"TeamSpeak 6" => ("teamspeak", "ts6"),
// A TeamSpeak server the engine does not recognise: the version it
// sent, no flavor.
"" => ("teamspeak", ""),
other => (other, ""),
};
v1::BackendInfo {
product: product.into(),
version: backend.version.clone(),
flavor: flavor.into(),
}
}
/// The features a TeamSpeak connection offers, from what its link can do
/// (`docs/session-seam.md` section 4.7).
pub(crate) fn features_of(capabilities: &voelin_model::Capabilities) -> Vec<&'static str> {
let mut features =
vec!["voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel"];
if capabilities.file_transfer {
features.extend(["files", "files.upload"]);
}
if capabilities.offline_messages {
features.push("mailbox");
}
if capabilities.streams {
features.extend(["streams", "streams.p2p", "streams.audio", "streams.approval"]);
}
features
}
// ---- the session ------------------------------------------------------------
/// A `Session` over a [`ServerLink`]: the TeamSpeak side of the seam.
pub(crate) struct LinkSession {
welcome: v1::Welcome,
features: Features,
cmds: mpsc::UnboundedSender<Cmd>,
closed: watch::Receiver<Option<CloseReason>>,
/// The media slot of our client; the driver changes it when we are another
/// client after TeamSpeak's own reconnect.
own_slot: Arc<AtomicU32>,
}
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> CloseReason {
closed.borrow().clone().unwrap_or_else(|| CloseReason::Network("the connection ended".into()))
}
impl Session for LinkSession {
fn welcome(&self) -> &v1::Welcome {
&self.welcome
}
fn features(&self) -> Features {
self.features.clone()
}
fn request(&self, op: v1::request::Op) -> BoxFuture<Result<Answer, SessionError>> {
let closed = self.closed.clone();
match placement(&op) {
Placement::Invalid => {
return Box::pin(async {
Err(SessionError::Protocol("a Hello is part of connecting".into()))
});
}
Placement::OwnStream
if matches!(op, v1::request::Op::FileRead(_) | v1::request::Op::FileWrite(_)) =>
{
return Box::pin(async {
Err(SessionError::Protocol("files go through read_file and write_file".into()))
});
}
_ => {}
}
// Queued now, in the order of the calls, not when the future is polled.
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Request { op, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> {
// Only an op of the control stream can go without an answer: a Hello is
// part of connecting, and a List and the file transfers have streams
// (and answers) of their own.
match placement(&op) {
Placement::Control => {}
Placement::Invalid => {
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
}
Placement::OwnStream => {
return Err(SessionError::Protocol(
"a List and the file transfers have a stream and an answer of their own, \
they cannot be sent without one"
.into(),
));
}
}
// The task may be on its way out and not have dropped its queue yet.
if self.closed.borrow().is_some() {
return Err(SessionError::Closed(closed_reason(&self.closed)));
}
self.cmds
.send(Cmd::Notify(op))
.map_err(|_| SessionError::Closed(closed_reason(&self.closed)))
}
fn read_file(&self, request: v1::FileRead) -> BoxFuture<Result<Download, SessionError>> {
let closed = self.closed.clone();
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Read { request, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn write_file(&self, request: v1::FileWrite) -> BoxFuture<Result<Upload, SessionError>> {
let closed = self.closed.clone();
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Write { request, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn send_media(&self, class: MediaClass, packet: MediaPacket) -> Result<Sent, MediaError> {
let flow = packet.flow;
if self.closed.borrow().is_some() {
return Err(MediaError::Closed);
}
if packet.rtp.len() > MAX_RTP {
return Err(MediaError::TooLarge { len: packet.rtp.len(), max: MAX_RTP });
}
// Only our voice to the channel: TeamSpeak whispers and priority voice,
// like video, are not offered here.
if class != MediaClass::Voice
|| flow.slot() != self.own_slot.load(Ordering::Relaxed)
|| flow.sub() != voice_sub::CHANNEL
{
return Err(MediaError::NotOwned(flow));
}
let voice = media::uplink(&packet).ok_or(MediaError::NotOwned(flow))?;
self.cmds.send(Cmd::Audio(voice)).map_err(|_| MediaError::Closed)?;
Ok(Sent::Queued)
}
fn stats(&self) -> LinkStats {
LinkStats { max_rtp: MAX_RTP, ..Default::default() }
}
fn close(&self, code: v1::CloseCode, reason: &str) {
let _ = self.cmds.send(Cmd::Close { code, reason: reason.to_owned() });
}
fn closed(&self) -> BoxFuture<CloseReason> {
let mut closed = self.closed.clone();
Box::pin(async move {
let reason = closed.wait_for(Option::is_some).await.ok().and_then(|r| r.clone());
reason.unwrap_or_else(|| closed_reason(&closed))
})
}
}
/// The write half of an upload: ending it tells the other half of the
/// upload that the file is all there.
struct UploadBody {
inner: tokio::io::WriteHalf<BoxDuplex>,
ended: Option<oneshot::Sender<()>>,
}
impl AsyncWrite for UploadBody {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let done = Pin::new(&mut self.inner).poll_shutdown(cx);
if matches!(done, Poll::Ready(Ok(())))
&& let Some(ended) = self.ended.take()
{
let _ = ended.send(());
}
done
}
}
/// An upload over the transfer connection `stream`: the body writes to it,
/// and `done` resolves once the body is shut down and the server has closed
/// the connection (or 30 s passed), with the file as `stored`.
fn upload(stream: BoxDuplex, stored: v1::FileEntry) -> Upload {
let (mut read, write) = tokio::io::split(stream);
let (ended, shut) = oneshot::channel();
let done: BoxFuture<Result<v1::Entities, SessionError>> = Box::pin(async move {
if shut.await.is_err() {
return Err(rejected(v1::ErrorCode::Cancelled, "the upload was dropped"));
}
// The server closes the connection once it has everything.
let _ = tokio::time::timeout(Duration::from_secs(30), read.read(&mut [0u8; 1])).await;
Ok(v1::Entities {
items: vec![v1::Entity { kind: Some(v1::entity::Kind::File(stored)) }],
..Default::default()
})
});
Upload { body: Box::pin(UploadBody { inner: write, ended: Some(ended) }), done }
}
// ---- the connector ----------------------------------------------------------
/// The `Connector` of a [`ServerLink`]: its sessions are [`LinkSession`]s.
#[derive(Clone)]
pub(crate) struct LinkConnector {
link: Arc<dyn ServerLink>,
schemes: &'static [&'static str],
/// Serves every scheme (the engine's tests give a link of their own).
any: bool,
}
impl LinkConnector {
/// A connector for `schemes`.
pub(crate) fn new(link: Arc<dyn ServerLink>, schemes: &'static [&'static str]) -> Self {
Self { link, schemes, any: false }
}
/// A connector for addresses of every scheme.
#[cfg(test)]
pub(crate) fn any(link: Arc<dyn ServerLink>) -> Self {
Self { link, schemes: &[], any: true }
}
}
impl Connector for LinkConnector {
fn schemes(&self) -> &'static [&'static str] {
self.schemes
}
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
let connect = connect_link(self.link.clone(), params, LocalCtx::standalone());
Box::pin(async move { Ok(connect.await?.connected) })
}
}
impl LocalConnector for LinkConnector {
fn accepts(&self, scheme: &str) -> bool {
self.any || self.schemes.contains(&scheme)
}
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
Box::pin(connect_link(self.link.clone(), params, ctx))
}
}
/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`)
/// with `tsclientlib`: a `LinkSession` over a `TsLink` for every connection.
///
/// Clones share one account: the main myTeamSpeak account that every
/// connection of the connector presents ([`TsConnector::set_myts_identity`],
/// [`TsConnector::set_myts_data`]), also those made before it was set.
/// Register a connector in the engine's registry with
/// [`Backends::register_teamspeak`](crate::Backends::register_teamspeak) and
/// keep a clone to set the account.
#[derive(Clone)]
pub struct TsConnector {
connector: LinkConnector,
link: Arc<TsLink>,
}
impl Default for TsConnector {
fn default() -> Self {
Self::new()
}
}
impl TsConnector {
/// A connector that presents no account until it is given one.
pub fn new() -> Self {
let link = Arc::new(TsLink::new());
Self { connector: LinkConnector::new(link.clone(), &["ts3server", "teamspeak"]), link }
}
/// The main account's proof for every current and future connection of
/// this connector (and its clones): a myTS ID signed with the account's
/// key. Connections that are up show the server the new proof, and those
/// that connect later present it from the start; `None` is a sign-out.
pub fn set_myts_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
self.link.account().set_identity(identity);
}
/// What servers are shown of the main account: its avatar and badges with
/// their certificates, its User Tag (TeamSpeak 6). It is sent to every
/// connection that presents the account's myTS ID, once connected and when
/// it changes; cleared on a sign-out (`None`).
pub fn set_myts_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
self.link.account().set_data(data);
}
}
impl Connector for TsConnector {
fn schemes(&self) -> &'static [&'static str] {
self.connector.schemes()
}
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
self.connector.connect(params)
}
}
impl LocalConnector for TsConnector {
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
self.connector.connect_local(params, ctx)
}
}
/// What the link told when it connected.
struct Joined {
name: String,
backend: BackendInfo,
capabilities: voelin_model::Capabilities,
own_client: u16,
server_uid: String,
own_uid: Option<String>,
}
fn ended_error(reason: Option<String>) -> SessionError {
SessionError::Closed(match reason {
Some(reason) => CloseReason::Network(reason),
None => CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() },
})
}
/// Wait for the link to say it is connected (or that it failed).
async fn wait_connected(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
) -> Result<Joined, SessionError> {
loop {
match events.recv().await {
Some(LinkEvent::Connected {
name,
backend,
capabilities,
own_client,
server_uid,
own_uid,
}) => {
return Ok(Joined { name, backend, capabilities, own_client, server_uid, own_uid });
}
Some(LinkEvent::Disconnected(reason)) => return Err(ended_error(reason)),
Some(_) => {}
None => return Err(ended_error(Some("the connection ended".into()))),
}
}
}
/// Open a [`LinkSession`] over `link` to the address in `params`.
async fn connect_link(
link: Arc<dyn ServerLink>,
params: ConnectParams,
ctx: LocalCtx,
) -> Result<LocalConnected, SessionError> {
let options = inner_options(&params, &ctx)?;
let nickname = options.nickname.clone();
let (inner_tx, inner_rx) = mpsc::unbounded_channel();
let (events_tx, mut events) = mpsc::unbounded_channel();
// The link answers requests on a bus of its own: this session reads the
// answers, and passes on the rest to the engine's.
let (bus_tx, bus) = broadcast::channel(4096);
let inner_ctx = LinkCtx { events: bus_tx, ..ctx.link.clone() };
link.spawn(options, inner_ctx, inner_rx, events_tx);
let joined = match tokio::time::timeout(params.timeout, wait_connected(&mut events)).await {
Ok(joined) => joined?,
Err(_) => {
let _ = inner_tx.send(LinkCmd::Disconnect);
return Err(SessionError::Timeout);
}
};
// The link reports its first snapshot right after it says it is connected;
// the session needs it to know the own user.
let mut early: Vec<LinkEvent> = Vec::new();
let _ = tokio::time::timeout(FIRST_SNAPSHOT, async {
while let Some(event) = events.recv().await {
let stop = matches!(event, LinkEvent::Presence(_) | LinkEvent::Disconnected(_));
early.push(event);
if stop {
break;
}
}
})
.await;
if let Some(LinkEvent::Disconnected(reason)) = early.last() {
return Err(ended_error(reason.clone()));
}
let own_database_id = early.iter().find_map(|event| match event {
LinkEvent::Presence(presence) => {
presence.clients.get(&joined.own_client).and_then(|c| c.database_id)
}
_ => None,
});
let ts6 = joined.backend.product == "TeamSpeak 6";
let own_user =
own_database_id.or_else(|| joined.own_uid.as_deref().map(ids::synthetic_user)).unwrap_or(0);
let features = features_of(&joined.capabilities);
let welcome = v1::Welcome {
user_id: own_user,
session_id: SESSIONS.fetch_add(1, Ordering::Relaxed),
uid: joined.own_uid.as_deref().and_then(ids::uid_bytes).unwrap_or_default().into(),
host: Some(v1::HostInfo {
host_key: Bytes::new(),
name: joined.name.clone(),
product: joined.backend.product.clone(),
version: joined.backend.version.clone(),
backend: Some(backend_to_v1(&joined.backend)),
icon: None,
}),
features: features.iter().map(|f| (*f).to_owned()).collect(),
limits: Some(v1::Limits {
max_message_chars: 1024,
max_page: 100,
// HOME, SERVER and LIVE, and the chats.
max_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS + 3,
max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS,
max_live_subscriptions: 8,
..Default::default()
}),
time_ms: now_ms(),
..Default::default()
};
let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
let own_slot = Arc::new(AtomicU32::new(entities::slot(joined.own_client)));
let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16));
let (closed_tx, closed_rx) = watch::channel(None);
let (port, streams) = if joined.capabilities.streams {
let (events_tx, events_rx) = mpsc::unbounded_channel();
let cmds = cmds_tx.clone();
let send = move |cmd| {
let _ = cmds.send(Cmd::Stream(cmd));
};
(Some(events_tx), Some(StreamPort::new(send, events_rx)))
} else {
(None, None)
};
let details = ServerDetails { uid: Some(joined.server_uid.clone()), ..Default::default() };
let driver = Driver::new(Parts {
cfg: Config {
ts6,
own_client: joined.own_client,
nickname,
own_uid: joined.own_uid.clone(),
files: joined.capabilities.file_transfer,
mail: joined.capabilities.offline_messages,
},
inner: inner_tx,
events,
early,
bus,
engine_bus: ctx.link.events.clone(),
pushes: pushes_tx,
media: params.media.clone(),
port,
closed: closed_tx,
own_slot: own_slot.clone(),
server: entities::server(&details, &joined.name, 0),
epoch: u64::try_from(now_ms()).unwrap_or(1).max(1),
});
let session = LinkSession {
welcome,
features: Features::new(features),
cmds: cmds_tx,
closed: closed_rx,
own_slot,
};
tokio::spawn(driver.run(cmds_rx));
Ok(LocalConnected {
connected: Connected {
session: Arc::new(session),
pushes: pushes_rx,
// A TeamSpeak server has no host key to pin.
host_uid: [0; 32],
},
streams,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::link::{Backends, VoiceOptions, connect_params};
use voelin_proto::link::IssuerTrust;
fn params(options: &VoiceOptions) -> ConnectParams {
let (media, _rx) = voelin_proto::test_util::media_channel();
connect_params(options, media, &Backends::empty()).unwrap()
}
fn back(options: &VoiceOptions) -> ConnectOptions {
inner_options(&params(options), &LocalCtx::standalone()).unwrap()
}
#[test]
fn the_options_of_a_bookmark_come_back_as_they_went() {
let mut options = VoiceOptions::new("ts.example.com:9988", "nick");
let same = back(&options);
assert_eq!(
(same.address.as_str(), same.nickname.as_str()),
("ts.example.com:9988", "nick")
);
assert!(same.identity.is_none() && same.client_version.is_none());
assert!(same.channel.is_none() && same.server_password.is_none() && same.token.is_none());
// Everything a connection can be told: the server password and the
// privilege key go in the hello, the channel and its password in the
// link, the identity as a credential.
options.server_password = Some("s3cret pass&word".into());
options.channel = Some("Games/Raid Night".into());
options.channel_password = Some("p w+%".into());
options.token = Some("tokenvalue".into());
let identity = tsclientlib::Identity::create();
options.identity = Some(crate::ts::identity::to_blob(&identity));
// A spec the user can give; the connector resolves it.
options.client_version = Some("generic".into());
options.audio = false;
let sent = params(&options);
assert_eq!(sent.hello.password, "s3cret pass&word");
assert_eq!(sent.hello.invite_code, "tokenvalue");
assert_eq!(sent.hello.nickname, "nick");
assert!(
sent.address.starts_with("ts3server://ts.example.com?port=9988"),
"{}",
sent.address
);
assert!(!sent.address.contains("s3cret") && !sent.address.contains("tokenvalue"));
let got = back(&options);
assert_eq!(got.address, "ts.example.com:9988");
assert_eq!(got.server_password, options.server_password);
assert_eq!(got.channel.as_deref(), Some("Games/Raid Night"));
assert_eq!(got.channel_password, options.channel_password);
assert_eq!(got.token.as_deref(), Some("tokenvalue"));
assert_eq!(got.client_version, versions::resolve("generic").unwrap());
assert!(got.client_version.is_some());
// The identity is the same key and counters.
let b = got.identity.as_ref().unwrap();
assert_eq!(serde_json::to_value(&identity).unwrap(), serde_json::to_value(b).unwrap());
}
#[test]
fn a_channel_by_id_and_an_address_that_is_a_link_are_kept() {
let mut options = VoiceOptions::new("[::1]:9987", "nick");
options.channel = Some("/12".into());
let got = back(&options);
assert_eq!(got.address, "[::1]:9987");
assert_eq!(got.channel.as_deref(), Some("/12"));
// A bookmark that is a link keeps its own parameters.
let options = VoiceOptions::new("ts3server://ts.example.com?port=1&channel=Lobby", "nick");
let got = back(&options);
assert_eq!(
(got.address.as_str(), got.channel.as_deref()),
("ts.example.com:1", Some("Lobby"))
);
// Another scheme is left as it is for the connector of that scheme.
let options = VoiceOptions::new("voelin://host/i/code", "nick");
assert_eq!(params(&options).address, "voelin://host/i/code");
}
#[test]
fn what_is_no_teamspeak_identity_is_refused() {
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential = Credential::Voelin(Arc::new(voelin_proto::test_util::FakeSigner));
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
assert!(matches!(error, SessionError::Protocol(_)));
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential =
Credential::Account { kind: "teamspeak", integration_id: Bytes::from_static(b"id") };
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential =
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(b"not json") };
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
// A host that wants trust is refused: TeamSpeak has no host key.
let backends = Backends::empty();
let confirm = backends.trust().confirm(voelin_proto::link::HostIdentity {
address: "x".into(),
uid: [0; 32],
previous: None,
});
assert!(!futures::executor::block_on(confirm));
}
#[test]
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
let sent = params(&VoiceOptions::new("ts.example.com", "nick"));
assert!(sent.account.is_none());
assert_eq!(sent.issuer_trust, IssuerTrust::Unknown);
assert!(sent.linked.is_empty() && sent.host_pin.is_none());
assert_eq!((sent.push_capacity, sent.timeout), (1024, Duration::from_secs(35)));
let client = sent.hello.client.unwrap();
assert_eq!(client.name, "Voelin");
assert_eq!(sent.hello.version, 1);
}
/// Why `connect_params` refused an address, if it did.
fn refused(address: &str) -> Option<String> {
let (media, _rx) = voelin_proto::test_util::media_channel();
match connect_params(&VoiceOptions::new(address, "nick"), media, &Backends::empty()) {
Ok(_) => None,
Err(SessionError::Protocol(text)) => Some(text),
Err(other) => panic!("{address}: {other}"),
}
}
#[test]
fn a_bookmark_the_link_would_change_is_refused() {
// A port that is no port, in any shape: the link would drop it and the
// connection would go to the default port.
for address in [
"ts.example.com:99999",
"ts.example.com:65536",
"ts.example.com:0",
"ts.example.com:abc",
"ts.example.com:",
"[::1]:70000",
"[::1]:",
"[::1]x",
] {
let text = refused(address).unwrap_or_else(|| panic!("{address} was accepted"));
assert!(text.contains("65535") && text.contains(address), "{text}");
}
// A host the link would cut or decode: a `?` hides the channel behind the
// next one, a `/` or `#` ends the host, a `%` is decoded.
for address in [
"",
" ",
"ts.example.com?x",
"ts.example.com#x",
"ts.example.com/x",
"a b",
"h%41",
"[::1",
] {
let text = refused(address).unwrap_or_else(|| panic!("{address:?} was accepted"));
assert!(text.starts_with("not a server address"), "{text}");
}
// The text names no query: a link keeps secrets in it.
let text = refused("ts.example.com?password=hunter2").unwrap();
assert!(!text.contains("hunter2"), "{text}");
}
#[test]
fn the_bookmarks_a_server_has_come_back_with_their_channel() {
for (address, host) in [
("ts.example.com", "ts.example.com"),
("ts.example.com:9987", "ts.example.com:9987"),
(" ts.example.com:1 ", "ts.example.com:1"),
("127.0.0.1:65535", "127.0.0.1:65535"),
("[::1]:9987", "[::1]:9987"),
// The brackets of a v6 address without a port are the link's to drop;
// the TeamSpeak library reads both forms.
("[::1]", "::1"),
("::1", "::1"),
("2001:db8::1", "2001:db8::1"),
] {
let mut options = VoiceOptions::new(address, "nick");
options.channel = Some("Games/Raid".into());
let got = back(&options);
assert_eq!((got.address.as_str(), got.channel.as_deref()), (host, Some("Games/Raid")));
}
}
/// The normalisations of the round trip, listed in `docs/session-seam.md`
/// (13): an empty option is none, and an empty nickname stays empty.
#[test]
fn empty_options_come_back_as_none() {
let mut options = VoiceOptions::new("ts.example.com", "");
options.server_password = Some(String::new());
options.channel = Some(String::new());
options.channel_password = Some(String::new());
options.token = Some(String::new());
let got = back(&options);
assert!(got.nickname.is_empty());
assert!(
got.server_password.is_none()
&& got.channel.is_none()
&& got.channel_password.is_none()
&& got.token.is_none()
);
}
}
@@ -8,7 +8,7 @@ use anyhow::{Context, Result, bail};
use base64::prelude::*;
use tsclientlib::Version;
const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declarations/Versions.csv");
const VERSIONS_CSV: &str = include_str!("../../../proto/tsproto-structs/declarations/Versions.csv");
/// The signed generic version of every platform, tsclientlib's default.
const GENERIC_VERSION: &str = "3.?.? [Build: 5680278000]";
File diff suppressed because it is too large. Load diff
+45 -5
View File
@@ -16,6 +16,7 @@ use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
use voelin_core::gateway::{GatewayRequest, GatewayUpdate};
use voelin_core::history::MessageSource;
use voelin_core::settings::Settings;
use voelin_core::ts::identity::to_blob;
use voelin_core::{Command, Engine, Event, History, HistoryMessage, HistorySource, ObserveState};
use voelin_gateway_proto::{
ClientMsg, Envelope, ErrorCode, HistoryEntry, HistoryPage, PinInfo, ReactionCount, ServerMsg,
@@ -448,7 +449,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
engine.send(Command::ObserveGateway {
session,
urls: vec![gw.url.clone()],
identity: Box::new(identity),
identity: Box::new(to_blob(&identity)),
});
}
@@ -742,7 +743,7 @@ async fn an_unreachable_gateway_is_tried_again_quietly() {
engine.send(Command::ObserveGateway {
session: 3,
urls: vec![format!("ws://127.0.0.1:{port}/v1")],
identity: Box::new(tsclientlib::Identity::create()),
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
});
// The first attempts fail (the next ones about 1 s, then 2 s later):
// still connecting, and the user is told nothing.
@@ -819,7 +820,7 @@ async fn the_next_published_gateway_is_used_when_one_fails() {
engine.send(Command::ObserveGateway {
session: 4,
urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()],
identity: Box::new(tsclientlib::Identity::create()),
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
});
// Within one round: sooner than the shortest wait after a failed round
// (1 s, less 30 %).
@@ -904,7 +905,7 @@ async fn a_login_the_gateway_cannot_do_yet_is_tried_again() {
engine.send(Command::ObserveGateway {
session,
urls: vec![gw.url.clone()],
identity: Box::new(tsclientlib::Identity::create()),
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
});
// After the first wait: about 1 s.
quietly_until(&mut rx, session, Duration::from_secs(3), "observing", observing(session))
@@ -932,6 +933,45 @@ async fn a_refused_login_ends_observing() {
assert_eq!(gw.logins(), 1);
}
/// An identity that cannot be read will not be better tomorrow: like a refused
/// login, observing ends, and the gateway is not even asked.
#[tokio::test(flavor = "multi_thread")]
async fn an_identity_that_cannot_be_read_ends_observing_without_a_login() {
let gw = FakeGateway::start().await;
let engine = Engine::start();
let mut rx = engine.subscribe();
let not_an_identity = voelin_core::IdentityBlob::teamspeak("x", 0, "not an identity");
engine.send(Command::ObserveGateway {
session: 10,
urls: vec![gw.url.clone()],
identity: Box::new(not_an_identity),
});
wait(&mut rx, "connecting", |e| match e {
Event::State { session: 10, state } if state.observe == ObserveState::Connecting => {
Some(())
}
_ => None,
})
.await;
wait(&mut rx, "observing off", |e| match e {
Event::State { session: 10, state } if state.observe == ObserveState::Off => Some(()),
_ => None,
})
.await;
tokio::time::sleep(Duration::from_millis(500)).await;
assert_eq!(gw.logins(), 0);
// The public entry refuses it the same way.
let error = voelin_core::gateway::connect(
&gw.url,
&voelin_core::IdentityBlob::new("voelin", "x", 0, "{}"),
)
.await
.err()
.expect("a refusal");
assert_eq!(error.code(), Some(ErrorCode::AuthFailed), "{error}");
assert_eq!(gw.logins(), 0);
}
/// Selecting the server again while its gateway is still connecting does
/// not start it over, and ends the wait for the next attempt.
#[tokio::test(flavor = "multi_thread")]
@@ -944,7 +984,7 @@ async fn asking_again_while_connecting_tries_at_once() {
let ask = || Command::ObserveGateway {
session: 9,
urls: vec![gw.url.clone()],
identity: Box::new(identity.clone()),
identity: Box::new(to_blob(&identity)),
};
engine.send(ask());
// Three logins fail (waits of about 1 and 2 s); the next wait is about 5 s.
+23 -2
View File
@@ -5,7 +5,10 @@ use std::time::Duration;
use tokio::sync::broadcast::Receiver;
use tokio::time::{Instant, timeout_at};
use voelin_core::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState};
use voelin_core::{
Command, Engine, Event, ObserveState, QueryLogin, QueryTransport, Source, VoiceOptions,
VoiceState,
};
use voelin_model::ChatTarget;
fn live() -> bool {
@@ -45,7 +48,7 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
.await;
// Session 2: invisible, through own query credentials.
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(query) });
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(login(&query)) });
let (mut observing, mut sees_voice_client) = (false, false);
wait_for(&mut events, "query presence with the voice client", |e| {
match e {
@@ -93,6 +96,24 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
tokio::time::sleep(Duration::from_millis(500)).await;
}
/// The credentials of a query connection, as the engine takes them.
fn login(connect: &voelin_query::Connect) -> QueryLogin {
QueryLogin {
transport: match connect.transport {
voelin_query::Transport::Raw => QueryTransport::Raw,
voelin_query::Transport::Ssh => QueryTransport::Ssh,
voelin_query::Transport::Http => QueryTransport::Http,
},
address: connect.addr.clone(),
user: connect.user.clone(),
secret: connect.secret.clone(),
server_port: connect.server_port,
server_id: connect.server_id,
// The development servers allowlist their clients.
allowlisted: connect.line.rate_limit.is_none(),
}
}
fn query(transport: voelin_query::Transport, addr: &str) -> voelin_query::Connect {
voelin_query::Connect {
transport,
@@ -0,0 +1,124 @@
//! The engine on a `voelin_proto::link::Session` that no TeamSpeak code
//! made: `Engine::start_with_backends` takes the connector registry, and the
//! scheme of a session's address picks the connector. The fake host of the
//! protocol repository stands for a Voelin host here (the fuller tests of the
//! seam on the fake host come with the next slice of
//! `docs/session-seam.md`).
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::broadcast;
use voelin_core::settings::Settings;
use voelin_core::{
Backends, Command, Engine, Event, History, SessionState, VoiceOptions, VoiceState,
};
use voelin_proto::test_util::FakeConnector;
use voelin_proto::v1::{self, entity::Kind};
const SESSION: u64 = 1;
async fn next<T>(
events: &mut broadcast::Receiver<Event>,
mut f: impl FnMut(Event) -> Option<T>,
) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
if let Some(t) = f(events.recv().await.expect("engine events")) {
return t;
}
}
})
.await
.expect("an event in time")
}
fn host_with_two_channels(connector: &FakeConnector) {
let host = connector.host();
let put = |kind: Kind| host.put(v1::Entity { kind: Some(kind) }).unwrap();
put(Kind::Server(v1::Server {
id: 1,
name: "Fake Host".into(),
uid: "fake-host".into(),
default_channel_id: 10,
..Default::default()
}));
for (id, name, position) in [(10, "Lobby", 0), (11, "Games", 1024)] {
put(Kind::Channel(v1::Channel {
id,
server_id: 1,
kind: v1::ChannelKind::Voice as i32,
name: name.into(),
position,
..Default::default()
}));
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_session_of_a_registered_connector_is_the_engines_voice_source() {
let connector = FakeConnector::new();
host_with_two_channels(&connector);
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let engine = Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
let mut events = engine.subscribe();
engine.send(Command::ConnectVoice {
session: SESSION,
options: Box::new(VoiceOptions::new("fake://host", "tester")),
});
let (name, backend) = next(&mut events, |e| match e {
Event::ServerInfo { name, backend, .. } => Some((name, backend)),
_ => None,
})
.await;
assert_eq!((name.as_str(), backend.product.as_str()), ("Fake Host", "voelin-fake"));
let presence = next(&mut events, |e| match e {
Event::Presence { presence, .. } if !presence.channels.is_empty() => Some(presence),
_ => None,
})
.await;
let channels: Vec<_> =
presence.channels.values().map(|c| (c.id, c.name.as_str(), c.order)).collect();
assert_eq!(channels, [(10, "Lobby", 0), (11, "Games", 10)]);
// The host was asked once, with the nickname and the TeamSpeak-shaped
// credential the engine makes of its options for now.
let connects = connector.connects();
assert_eq!(connects.len(), 1);
assert_eq!(connects[0].address, "fake://host");
assert_eq!(connects[0].hello.nickname, "tester");
// A move is a request to the host; the host's voice state is where we are.
engine.send(Command::MoveToChannel { session: SESSION, channel: 11, password: None });
let state: SessionState = next(&mut events, |e| match e {
Event::State { state, .. } if state.own_channel == Some(11) => Some(state),
_ => None,
})
.await;
assert_eq!(state.voice, VoiceState::Connected);
engine.send(Command::DisconnectVoice { session: SESSION });
next(&mut events, |e| match e {
Event::State { state, .. } if state.voice == VoiceState::Disconnected => Some(()),
_ => None,
})
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn an_address_no_connector_serves_fails_with_the_registry_s_words() {
let engine =
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), Backends::empty());
let mut events = engine.subscribe();
engine.send(Command::ConnectVoice {
session: SESSION,
options: Box::new(VoiceOptions::new("voelin://host/i/code", "tester")),
});
let error = next(&mut events, |e| match e {
Event::Error { message, .. } => Some(message),
_ => None,
})
.await;
assert_eq!(error, "voice: no connector for voelin://host/i/code");
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -167,7 +167,7 @@ async fn ts6_stream_between_sessions() {
Event::StreamViewers { session: 1, viewers }
if viewers
.iter()
.any(|v| v.client.0 == viewer && v.state == ViewerState::Connected) =>
.any(|v| v.client == viewer && v.state == ViewerState::Connected) =>
{
Some(())
}
+1 -1
View File
@@ -24,7 +24,7 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync"], optional =
# TLS (`wss://`, as gateways run behind a proxy) with the system's
# certificates; rustls and its crates are in the tree already (reqwest).
tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] }
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
tsproto-types = { path = "../proto/tsproto-types" }
[lints]
+1 -1
View File
@@ -29,7 +29,7 @@ toml = "1.1.6"
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
voelin-observer = { path = "../voelin-observer" }
voelin-query = { path = "../voelin-query" }
+8 -6
View File
@@ -40,11 +40,9 @@ wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols
# model (PP-HumanSeg, ONNX, bundled in `models/`) run on the CPU by tract.
# Without it the background is cut around a centred oval.
segment = ["dep:tract-onnx"]
# Conversion between `Codec` and `str0m::format::Codec`.
str0m = ["dep:str0m"]
# The studio's WHIP output: a WebRTC session (str0m) set up over HTTP. Needs
# str0m's crypto provider, the same one voelin-stream uses.
whip = ["str0m", "str0m/aws-lc-rs", "dep:reqwest"]
whip = ["str0m/aws-lc-rs", "dep:reqwest"]
[dependencies]
bzip2 = { version = "0.6.1", optional = true }
@@ -61,7 +59,9 @@ serde = { version = "1", features = ["derive"] }
ab_glyph = "0.2.32"
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png"] }
sha2 = { version = "0.10.9", optional = true }
str0m = { version = "0.23.1", default-features = false, optional = true }
# Its media types (`MediaKind`, `MediaTime`) are in `stream::EncodedFrame`, and
# `Codec` converts to and from its codec type.
str0m = { version = "0.23.1", default-features = false }
thiserror = "2.0.21"
tract-onnx = { version = "0.23.8", optional = true }
tokio = { version = "1", features = ["sync"] }
@@ -97,8 +97,10 @@ criterion = "0.8"
opus2 = "0.4"
serde_json = "1"
# The H.264 `profile-level-id` the signalling offers, to check it against the
# SPS the encoders really emit (`tests/ffmpeg.rs`). No cycle: voelin-stream
# does not depend on this crate.
# SPS the encoders really emit (`tests/ffmpeg.rs`). A cycle through a
# dev-dependency, which cargo allows: voelin-stream depends on this crate for
# the frame and layer types, so this crate's unit tests see itself twice, and
# only primitives and voelin-stream's own types cross between the copies.
voelin-stream = { path = "../voelin-stream" }
# Logs of integration tests (`RUST_LOG`).
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+3 -4
View File
@@ -95,7 +95,6 @@ impl FromStr for Codec {
}
}
#[cfg(feature = "str0m")]
impl From<Codec> for str0m::format::Codec {
fn from(c: Codec) -> Self {
match c {
@@ -108,7 +107,6 @@ impl From<Codec> for str0m::format::Codec {
}
}
#[cfg(feature = "str0m")]
impl TryFrom<str0m::format::Codec> for Codec {
type Error = Error;
@@ -226,7 +224,9 @@ pub struct EncodedChunk<'a> {
pub pts_90khz: u64,
}
/// One encoded frame, ready for `voelin_stream::Peer::write`.
/// One frame as an encoder makes it. A stream takes it as a
/// [`stream::EncodedFrame`](crate::stream::EncodedFrame), which adds the kind
/// of media, the RTP time and the layer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncodedFrame {
pub data: Vec<u8>,
@@ -1039,7 +1039,6 @@ mod tests {
assert_eq!(Codec::Av1.to_string(), "AV1");
}
#[cfg(feature = "str0m")]
#[test]
fn str0m_mapping() {
for c in Codec::ALL {
+210
View File
@@ -0,0 +1,210 @@
//! Simulcast layers: several encodings of one stream, each with its own size,
//! frame rate and bitrate.
//!
//! The streamer encodes every layer of its [`LayerSpec`] list and tags each
//! [`EncodedFrame`](crate::stream::EncodedFrame) with its [`LayerId`]. Each
//! viewer connection gets the layer that fits its bandwidth estimate; peers
//! that negotiate RID simulcast (`a=simulcast`) get all of them. There is no
//! limit on the number of layers.
//!
//! The types are the media side's vocabulary; the stream transports (the
//! `voelin-stream` crate, and whatever else carries a stream) and the client
//! engine use them as they are.
use std::fmt;
/// A simulcast layer. Layer 0 is the one a stream without simulcast has.
pub type LayerId = u16;
/// One encoding of the stream. Compared bit for bit (`scale` by its bits),
/// so it is `Eq`.
#[derive(Clone, Debug)]
pub struct LayerSpec {
pub id: LayerId,
/// Output size relative to the source (1.0: the source's size). Ignored
/// when [`size`](Self::size) is set.
pub scale: f32,
/// Exact output size in pixels, instead of `scale`.
pub size: Option<(u32, u32)>,
/// Frame rate cap; `None`: the source's frame rate.
pub max_fps: Option<u32>,
/// Bitrate the encoder starts with, in bit/s. Bandwidth estimates move it
/// down (and back up to this value, or [`max_bitrate`](Self::max_bitrate)).
pub bitrate: u64,
/// Highest bitrate bandwidth estimates may raise the layer to; `None`: no
/// maximum.
pub max_bitrate: Option<u64>,
/// Estimate (bit/s) a viewer needs to receive this layer; below it the
/// viewer moves to the next smaller layer.
pub min_bitrate: u64,
/// RTP stream id for peers that negotiate RID simulcast.
pub rid: Option<String>,
}
impl PartialEq for LayerSpec {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
&& self.scale.to_bits() == other.scale.to_bits()
&& self.size == other.size
&& self.max_fps == other.max_fps
&& self.bitrate == other.bitrate
&& self.max_bitrate == other.max_bitrate
&& self.min_bitrate == other.min_bitrate
&& self.rid == other.rid
}
}
impl Eq for LayerSpec {}
impl LayerSpec {
/// A stream without simulcast: layer 0 at the source's size and rate.
pub fn single(bitrate: u64) -> Self {
Self {
id: 0,
scale: 1.0,
size: None,
max_fps: None,
bitrate,
max_bitrate: None,
min_bitrate: 0,
rid: None,
}
}
/// Output size for a source of `width` x `height`: [`size`](Self::size),
/// or the scaled source size rounded down to even numbers (I420), at least
/// 2x2.
pub fn output_size(&self, width: u32, height: u32) -> (u32, u32) {
let (w, h) = self.size.unwrap_or_else(|| {
let scale = if self.scale.is_finite() && self.scale > 0.0 { self.scale } else { 1.0 };
((width as f32 * scale) as u32, (height as f32 * scale) as u32)
});
((w & !1).max(2), (h & !1).max(2))
}
}
/// A set of layers, e.g. those waiting for a keyframe. Grows as needed.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct LayerSet {
words: Vec<u64>,
}
impl LayerSet {
pub const fn new() -> Self {
Self { words: Vec::new() }
}
/// Adds `layer`; `true` if it was not in the set.
pub fn insert(&mut self, layer: LayerId) -> bool {
let (word, bit) = Self::position(layer);
if self.words.len() <= word {
self.words.resize(word + 1, 0);
}
let new = self.words[word] & bit == 0;
self.words[word] |= bit;
new
}
/// Removes `layer`; `true` if it was in the set.
pub fn remove(&mut self, layer: LayerId) -> bool {
let (word, bit) = Self::position(layer);
match self.words.get_mut(word) {
Some(w) if *w & bit != 0 => {
*w &= !bit;
true
}
_ => false,
}
}
pub fn contains(&self, layer: LayerId) -> bool {
let (word, bit) = Self::position(layer);
self.words.get(word).is_some_and(|w| w & bit != 0)
}
pub fn is_empty(&self) -> bool {
self.words.iter().all(|w| *w == 0)
}
pub fn len(&self) -> usize {
self.words.iter().map(|w| w.count_ones() as usize).sum()
}
/// Empties the set, keeping its memory.
pub fn clear(&mut self) {
self.words.fill(0);
}
/// Adds every layer of `other`.
pub fn union_with(&mut self, other: &LayerSet) {
if self.words.len() < other.words.len() {
self.words.resize(other.words.len(), 0);
}
for (w, o) in self.words.iter_mut().zip(&other.words) {
*w |= o;
}
}
/// The layers in ascending order.
pub fn iter(&self) -> impl Iterator<Item = LayerId> + '_ {
self.words.iter().enumerate().flat_map(|(i, &word)| {
(0..64).filter(move |b| word & (1 << b) != 0).map(move |b| (i * 64 + b) as LayerId)
})
}
fn position(layer: LayerId) -> (usize, u64) {
(usize::from(layer) / 64, 1 << (layer % 64))
}
}
impl FromIterator<LayerId> for LayerSet {
fn from_iter<I: IntoIterator<Item = LayerId>>(iter: I) -> Self {
let mut set = Self::new();
for layer in iter {
set.insert(layer);
}
set
}
}
impl fmt::Debug for LayerSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layer_set() {
let mut set = LayerSet::new();
assert!(set.is_empty());
assert!(set.insert(3));
assert!(!set.insert(3));
assert!(set.insert(200));
assert!(set.insert(LayerId::MAX));
assert_eq!(set.iter().collect::<Vec<_>>(), [3, 200, LayerId::MAX]);
assert_eq!(set.len(), 3);
assert!(set.contains(200) && !set.contains(4));
assert!(set.remove(200) && !set.remove(200));
let other: LayerSet = [1, 3].into_iter().collect();
set.union_with(&other);
assert_eq!(format!("{set:?}"), format!("{{1, 3, {}}}", LayerId::MAX));
set.clear();
assert!(set.is_empty());
}
#[test]
fn output_size() {
let mut layer = LayerSpec::single(1_000_000);
assert_eq!(layer.output_size(1921, 1081), (1920, 1080));
layer.scale = 0.5;
assert_eq!(layer.output_size(2560, 1440), (1280, 720));
layer.scale = 0.0001;
assert_eq!(layer.output_size(640, 360), (2, 2));
layer.size = Some((853, 480));
assert_eq!(layer.output_size(1920, 1080), (852, 480));
}
}
+9 -2
View File
@@ -5,6 +5,10 @@
//! (interleaved `f32`, 48 kHz)
//! - [`convert`]: YUV ↔ RGB conversion (BT.601 limited range, the WebRTC
//! default), e.g. RGBA for rendering and I420 for encoding
//! - [`layer`] and [`stream`]: the simulcast layers of a stream
//! ([`LayerSpec`]) and its frames on the way to the viewers
//! ([`stream::EncodedFrame`], the encoder's frame plus kind, RTP time and
//! layer)
//! - [`codec`]: [`VideoEncoder`] / [`VideoDecoder`] traits, codec preference
//! and the backends: libvpx (VP8/VP9, feature `vpx`), Cisco's OpenH264
//! loaded at runtime (H.264, feature `openh264`), dav1d (AV1 decoding,
@@ -24,8 +28,8 @@
//! scaling and the [`scale::Pyramid`] of simulcast sizes), and
//! [`convert::Converter`] (borrowed capture buffers straight to I420)
//!
//! Encoded frames go to `voelin_stream::Peer::write` with an RTP time of
//! [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to
//! Encoded frames go to a stream as [`stream::EncodedFrame`]s with an RTP time
//! of [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to
//! [`VideoDecoder::decode`].
pub mod capture;
@@ -35,10 +39,12 @@ pub mod convert;
pub mod ffmpeg;
pub mod frame;
pub mod handoff;
pub mod layer;
pub mod mix;
pub mod pool;
pub mod queue;
pub mod scale;
pub mod stream;
pub mod studio;
pub mod workers;
@@ -51,6 +57,7 @@ pub use codec::{
pub use frame::{
AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
};
pub use layer::{LayerId, LayerSet, LayerSpec};
pub use queue::{FrameReceiver, FrameSender, frame_channel};
/// Errors of this crate.
+34
View File
@@ -0,0 +1,34 @@
//! The frames of a stream on their way to its viewers.
//!
//! An [`EncodedFrame`] is what the streamer's encoders and the Opus encoder
//! hand to a stream: the encoder's output ([`codec::EncodedFrame`]) plus what
//! the transport needs, which media it is, its RTP time and its simulcast
//! layer. The engine's stream sink, the stream sessions (`voelin-stream`) and
//! the tools that feed a stream by hand all pass it on unchanged.
//!
//! [`codec::EncodedFrame`]: crate::codec::EncodedFrame
use std::sync::Arc;
use str0m::media::{MediaKind, MediaTime};
use crate::layer::LayerId;
/// One encoded video or audio frame of a stream, ready to be sent.
///
/// Not the encoder's [`codec::EncodedFrame`](crate::codec::EncodedFrame),
/// which has neither a kind nor a layer and counts time on the 90 kHz clock
/// only.
#[derive(Clone, Debug)]
pub struct EncodedFrame {
pub kind: MediaKind,
/// RTP time: 90 kHz for video, 48 kHz for Opus.
pub time: MediaTime,
pub data: Arc<[u8]>,
/// The simulcast layer of a video frame (0 without simulcast, and for
/// audio).
pub layer: LayerId,
/// A video keyframe: viewers can start decoding (or switch to this layer)
/// here.
pub keyframe: bool,
}
-18
View File
@@ -1,18 +0,0 @@
[package]
name = "voelin-model"
version = "0.1.0"
description = "UI-facing domain model shared by the client engine, gateway and UI (no IO)."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
serde = { version = "1", features = ["derive"] }
[dev-dependencies]
serde_json = "1"
[lints]
workspace = true
-94
View File
@@ -1,94 +0,0 @@
uid,name,description,filename,codes
4b27be5a-b92a-4b30-8b2d-14b59653f427,20th Anniversary,Celebrating 20 Years of TeamSpeak,20_years,
f81ad44d-e931-47d1-a3ef-5fd160217cf8,4Netplayers,4Netplayers customer,4netplayers,
b78a0f3e-8758-4572-b102-42a79b4a0342,????,Reads between the line,hat,
2bf80270-8efe-46dc-a472-3280a0479145,Alpha Tester,Helped to test our software. THANK YOU!,Alpha,
05114019-6b46-4b13-b5a1-e5179ef69fb5,April Fools!,"Roses are red, gaming is fun, you are carrying too much to be able to run :(",rpg,
1a518885-520c-4f54-9f49-8b1acb674771,Braindance,I’m chippin’ in,Braindance,P4TEKZ80PZ
cbf5aafd-2554-4053-80bb-0cf82ec0a430,Bright Idea,TeamSpeak took my idea on board,FeatureBadge_Lightbulb,
d6062d9c-42a3-49c9-91dd-8c43a5a46805,Bug Catcher,I found a bug!,BugBadge_Splat,
dfc70674-0fd0-431e-b3a1-edc32d7b09b2,Challenge Accepted,"Unlocked at SCILL Play — Challenges, tournaments and more!",scill,
afed63f4-82f1-4479-ab02-0ef053f55723,Communities Early Adopter,Thank you for your Support!,communities_early_adopter,
54be472d-3163-4076-9059-7f46128d937e,Communities Purchase,Purchased a TeamSpeak Community,communities_purchase,
f85f7e21-753a-4566-b26a-4e3e9155d2ef,Cyberpunk,We have a city to burn,Cyberpunk,
c028298c-84ff-4e22-be4e-b8c17552b4bb,Digi,Digi joined your channel #DIGWIN,digi,
56df5ce2-6c5a-4a24-90e2-29e497e26170,Drone Champions League,I follow the Drone Champions League,DCL_Badge,DRONECHAMP
935e5a2a-954a-44ca-aa7a-55c79285b601,E3 2018 - Winner,Discovered at E3 2018,E3-2018,
61723e54-3da2-4f19-a33f-fcdc8ef5eaa0,Father's Day 2022,Not all heroes wear capes,fathersday2022,
b9c7d6ad-5b99-40fb-988c-1d02ab6cc130,Found Tim Speak,Found Tim Speak at Gamescom 2018,met_tim,XJN4WJZEJN
809bdd5a-2601-4152-82ff-a21d23d8fd46,G2 Esports,Aged 20 years being a G2 fan,G2_Esports,
62444179-0d99-42ba-a45c-c6b1557d079a,Gamescom 2014,Registered at Gamescom 2014,gamescom_2014,
50bbdbc8-0f2a-46eb-9808-602225b49627,Gamescom 2016,Registered during Gamescom 2016,gamescom_2016,
534c9582-ab02-4267-aec6-2d94361daa2a,Gamescom 2017,Visited TeamSpeak at Gamescom 2017,gamescom_2017,DK9JGRJH1Q
4eef1ecf-a0ea-423d-bfd0-496543a00305,Gamescom 2018,Visited TeamSpeak at Gamescom 2018,gamescom_2018,8CXB49KPJ4
b82a45a5-b235-4926-be77-de102222e5eb,Gamescom 2019,Visited TeamSpeak at Gamescom 2019,Gamescom19,PNKCB76VZ8
34dbfa8f-bd27-494c-aa08-a312fc0bb240,Gamescom Hero 2017,Gaming Hero at Gamescom 2017,hero_2017,
24512806-f886-4440-b579-9e26e4219ef6,Gamescom Hero 2018,Gamescom Exclusive Gaming Hero 2018,gamescom_2018_played,BJCFQBU53C
d49fd07e-99fb-41de-8d7b-c98064713171,GommeHD.net,Your #1 Minecraft Network for over 10 years,GMHD,
c565972a-3912-457b-826f-84820c1ba6ca,Halloween 2021,Happy Halloween 2021,halloween21,
133595e7-950f-4ef2-b113-f91a68b5770d,Halloween 2021 Special,Earned by participating in our Halloween 2021 special stream,halloween21_special,
fb154277-5fe7-428a-85a4-43c0bdcdda3d,Halloween 2022,Spooky_Scary_Skeletons.mp4,halloween22,
e6679ce2-d458-493c-8ffb-5660e47ac99f,Happy Hanami,Enjoy the view,hanami2023,
de7bd960-eb02-47e1-9ce2-a44f6e255d8f,Happy Holidays 2019,Happy holidays from everyone at TeamSpeak!,Happy_Holidays,
d4ea0251-ba46-4c1a-83b7-59db3f89e52c,Happy New Year 2021,Survived the great toilet paper crisis of 2020,firework_2020,
1519e001-06a0-458c-9195-a8a6d0ec87fc,Happy New Year 2023,"Aw man, here we go again",2023_NewYear,
834d4cc1-cd80-48d6-96c4-23d131d78649,Happy Summer 2023,heat death of the universe,happy_summer_2023,
c68bcc52-7aeb-4868-b4d2-e7b20716f9ba,Heatwave 2022,I'm melting... help,summer_icecream,
94242c4e-6742-4540-8b66-ce951ed57159,Helping Hand,\ pushed some buttons *beep* *bop* ~ thanks!,homebase,
288a56c6-4da3-48de-9c9f-bd9eede5d832,Immortal Roleplay,This is your life.,Immortal_Roleplay,
69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d,International Peace Day,"United we stand, divided we fall",peaceday2022,
9ea23c77-8755-4d82-b30c-92f4aac109ef,International Women's Day 2021,"To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day!",wft,
7d9fa2b1-b6fa-47ad-9838-c239a4ddd116,MIFCOM,MIFCOM | Entered Performance,mifcom,
ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776,Merry Christmas 2019,It’s the most wonderful ‘Tim’ of the Year,Christmas,
c6480fe2-ee25-4ee8-9853-243652c8ec54,Merry Christmas 2020,"Let it snow, let it snow, let it snow!",Christmas2020,
0581aa0f-8c2d-4681-bb9f-8492fec49977,Merry Christmas 2021,Look what Santa's left under the server tree!,christmas2021,
d4875b30-9908-43cb-a1eb-1a958e226078,Merry Christmas 2022,There's snow place like home,christmas2022,
87ccf9ea-67c9-45e5-adbc-77e210e6128a,Met Tim,Met Tim Speak IRL,tim_irl,
0d98391c-ecdf-4f26-931a-49bfd669cda7,Mind Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_MindEgg,
2fdda3c6-20e0-48f1-9c12-f39239a2ed02,Mother's Day 2022,Thanks for bearing with us,rose,
c3f823eb-5d5c-40f9-9dbd-3437d59a539d,Official TeamSpeak Gamer,New myTeamSpeak member,TS-2018,
8dfa37ac-b40d-4466-b393-ff2184a9adf3,Overwatch League,I follow the Overwatch League,OWL_Badge,
4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac,PGL Antwerp 2022,Watched the PGL CS:GO Major,PGLant,
fa3ece28-64df-431f-b1b3-90844bfdd2d9,Paris Games Week 2014,Registered at Paris Games Week 2014,paris_gamesweek_2014,
d95f9901-c42d-4bac-8849-7164fd9e2310,Paris Games Week 2016,Registered during Paris Games Week 2016,paris_gamesweek_2016,
0005232e-538e-4cb2-93b6-d7d83e873829,PietSmiet,Werde Snob auf PietSmiet.de ;),PietSmiet,
be932556-dfa9-4dc6-afd0-98de0ab25777,PolTeamgeist,WooOOHoohOOHooo,PolTeamgeist,
5f6d49e4-35c8-4809-8c81-6e71f7f749e9,Power Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_PowerEgg,
ceee2445-4fbf-4f06-9421-286f0f4e875a,Pride,Never be afraid to show your colors.,pride,
1aa375e8-7207-45bf-8b80-556bafafc834,Reality Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_RealityEgg,
f22c22f1-8e2d-4d99-8de9-f352dc26ac5b,Rocket Beans TV,Rocket Beans TV Community,rbtv,RWGE2NURJZ
2c9698c1-1fec-4baa-a28f-4845f045f42f,Soul Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SoulEgg,
641a4d85-2351-482c-97a1-02fc3b6abbb5,Space Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SpaceEgg,
63261116-4359-4842-873e-56820afbe068,SpartaTheOriginal,Olaf Toast @ twitch.tv/SpartaTheOriginal,Toast,
ef567ec5-f46e-4520-be07-6021023cf6bd,Sponsorship License,Sponsored by TeamSpeak,Sponsorship,
7a627d47-5496-4d68-83b5-2c4eafff9b30,"Stay Home, Stay Safe","Playing Apart, Staying Connected",StaySafeStayHome,
7262a528-c7df-4369-bc2c-d34bf5853d7b,TS Chat Alpha Tester,"Helped us test our new mobile app, thanks!",slim_golden,
6eee759e-b1e9-4937-b023-07fc778532a2,TS Gameday Participant,At least i tried...,silvered,
e1447b99-53b0-448a-98b7-ee7bad8bd268,TS Gameday Winner,As shiny as the golden frying pan,goldenjoystick,
1cb07348-34a4-4741-b50f-c41e584370f7,TeamSpeak Addon Author,Creator of TeamSpeak Addons,addon_author,
450f81c1-ab41-4211-a338-222fa94ed157,TeamSpeak Addon Developer (Bronze),Creator of at least 1 TeamSpeak Addon,addon_author_bronze,
94ec66de-5940-4e38-b002-970df0cf6c94,TeamSpeak Addon Developer (Gold),Creator of at least 5 TeamSpeak Addons,addon_author_gold,
c9e97536-5a2d-4c8e-a135-af404587a472,TeamSpeak Addon Developer (Silver),Creator of at least 3 TeamSpeak Addons,addon_author_silver,
9cd152a7-bf65-4ece-aeba-62d27678f79a,TeamSpeak Competition Winner Badge,TeamSpeak Competition Winner,CompWinnerBadge,
64221fd1-706c-4bb2-ba55-996c39effa79,TeamSpeak Jedi,myTeamSpeak early adopter,TS-OG,
6b187e83-873b-46b0-b2c2-a31af15e76a4,TeamSpeak Merch Badge,TeamSpeak Merch Owner - 1st Edition,cap_red,
22b9ec39-7694-453e-864c-dfc7b1b0d7c7,TeamSpeak Merch Badge 2.0,TeamSpeak Merch Owner - 2nd Edition,topper,
205916f3-a953-4754-8905-bc15069b1f91,TeamSpeak Merch Badge 3.0,TeamSpeak Merch Owner — 3rd Edition,Merch3,
8d843dfa-c51a-407f-87b3-94cfc8f03e96,TeamSpeak Staff,Official Staff Member,teamspeak_staff,
c2368518-3728-4260-bcd1-8b85e9f8984c,Test,"Testing, Testing.",Testing,
4086a249-a503-4f31-9e83-8a0a8e3089bd,Tim-o'-Lantern,Mwuhaahaahaahaahaa,Tim-O-Lantern,JQGCTAQWHT
089c7295-3aa2-48b0-b2f1-2dd1bec12caf,Time Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_TimeEgg,
904e232c-f369-44db-87f7-5142e15620cc,Time Machine,Worked like a machine to update addons in super-quick time.,time_machine,
4c61af66-22ef-4897-b0bb-25fcef2acf60,Undead Nightmare,I'm the last of my kind,undead_nightmare,
b0a36aea-3e46-4e83-a455-6e92ae1b9d94,Undead Nightmare,I'm the last of my kind,undead_nightmare,
0cd924ed-c5ea-459e-b60a-4f1bc0b65f07,"Up, Up and Away!",Find me on Mount Chiliad,"up,_up_and_away!",
4b0fd4f5-d456-4294-973d-853a1db5c7d8,Valentim's Day 2019,Valentim's Day 2019,Valentines_Badge,
92801833-e721-4b7e-84d4-6c02dbb332b9,Valentim's Day 2020,Valentim's Day 2020,Valentim2020,
958f904b-8260-48a4-a961-f786cbd39411,Valentine's Day 2023,Love you like my Tamagotchi,ValentinesDay23,
a676c708-da67-4784-ba7f-3fb7e8d2e865,Valentines Day 2021,"Roses are red, TS is blue, Servers are Sweet and so are you.",valentine21,
c54a9f92-07f7-4214-90f3-eafeea8005da,World Backup Day,Don't be an April Fool. Back up your data!,backupday_2023,
448a6d13-4e08-46a1-aafa-b4ff6d6c2d06,World Bonsai Day,"harmony, balance, patience",bonsai_day,
0f976a27-ddf5-447c-b79c-0644a8e8a297,Year of the Dragon 2024,"Arise, Shenron!",year_of_the_dragon_2024,
8c22fe26-30ac-4231-8b31-67d8a75c808a,Year of the Ox 2021,Only listen to the fortune cookie; disregard all other fortune telling units.,ox21,
970c70e6-00a1-41c1-ac5c-81c89a06c7a6,Year of the Rabbit 2023,Do a barrel roll!,chineseNY2023,
92356386-0451-4a97-87d9-10ff4f43260c,Year of the Tiger 2022,Rocky sends his regards,tiger,
1 uid name description filename codes
2 4b27be5a-b92a-4b30-8b2d-14b59653f427 20th Anniversary Celebrating 20 Years of TeamSpeak 20_years
3 f81ad44d-e931-47d1-a3ef-5fd160217cf8 4Netplayers 4Netplayers customer 4netplayers
4 b78a0f3e-8758-4572-b102-42a79b4a0342 ???? Reads between the line hat
5 2bf80270-8efe-46dc-a472-3280a0479145 Alpha Tester Helped to test our software. THANK YOU! Alpha
6 05114019-6b46-4b13-b5a1-e5179ef69fb5 April Fools! Roses are red, gaming is fun, you are carrying too much to be able to run :( rpg
7 1a518885-520c-4f54-9f49-8b1acb674771 Braindance I’m chippin’ in Braindance P4TEKZ80PZ
8 cbf5aafd-2554-4053-80bb-0cf82ec0a430 Bright Idea TeamSpeak took my idea on board FeatureBadge_Lightbulb
9 d6062d9c-42a3-49c9-91dd-8c43a5a46805 Bug Catcher I found a bug! BugBadge_Splat
10 dfc70674-0fd0-431e-b3a1-edc32d7b09b2 Challenge Accepted Unlocked at SCILL Play — Challenges, tournaments and more! scill
11 afed63f4-82f1-4479-ab02-0ef053f55723 Communities Early Adopter Thank you for your Support! communities_early_adopter
12 54be472d-3163-4076-9059-7f46128d937e Communities Purchase Purchased a TeamSpeak Community communities_purchase
13 f85f7e21-753a-4566-b26a-4e3e9155d2ef Cyberpunk We have a city to burn Cyberpunk
14 c028298c-84ff-4e22-be4e-b8c17552b4bb Digi Digi joined your channel #DIGWIN digi
15 56df5ce2-6c5a-4a24-90e2-29e497e26170 Drone Champions League I follow the Drone Champions League DCL_Badge DRONECHAMP
16 935e5a2a-954a-44ca-aa7a-55c79285b601 E3 2018 - Winner Discovered at E3 2018 E3-2018
17 61723e54-3da2-4f19-a33f-fcdc8ef5eaa0 Father's Day 2022 Not all heroes wear capes fathersday2022
18 b9c7d6ad-5b99-40fb-988c-1d02ab6cc130 Found Tim Speak Found Tim Speak at Gamescom 2018 met_tim XJN4WJZEJN
19 809bdd5a-2601-4152-82ff-a21d23d8fd46 G2 Esports Aged 20 years being a G2 fan G2_Esports
20 62444179-0d99-42ba-a45c-c6b1557d079a Gamescom 2014 Registered at Gamescom 2014 gamescom_2014
21 50bbdbc8-0f2a-46eb-9808-602225b49627 Gamescom 2016 Registered during Gamescom 2016 gamescom_2016
22 534c9582-ab02-4267-aec6-2d94361daa2a Gamescom 2017 Visited TeamSpeak at Gamescom 2017 gamescom_2017 DK9JGRJH1Q
23 4eef1ecf-a0ea-423d-bfd0-496543a00305 Gamescom 2018 Visited TeamSpeak at Gamescom 2018 gamescom_2018 8CXB49KPJ4
24 b82a45a5-b235-4926-be77-de102222e5eb Gamescom 2019 Visited TeamSpeak at Gamescom 2019 Gamescom19 PNKCB76VZ8
25 34dbfa8f-bd27-494c-aa08-a312fc0bb240 Gamescom Hero 2017 Gaming Hero at Gamescom 2017 hero_2017
26 24512806-f886-4440-b579-9e26e4219ef6 Gamescom Hero 2018 Gamescom Exclusive Gaming Hero 2018 gamescom_2018_played BJCFQBU53C
27 d49fd07e-99fb-41de-8d7b-c98064713171 GommeHD.net Your #1 Minecraft Network for over 10 years GMHD
28 c565972a-3912-457b-826f-84820c1ba6ca Halloween 2021 Happy Halloween 2021 halloween21
29 133595e7-950f-4ef2-b113-f91a68b5770d Halloween 2021 Special Earned by participating in our Halloween 2021 special stream halloween21_special
30 fb154277-5fe7-428a-85a4-43c0bdcdda3d Halloween 2022 Spooky_Scary_Skeletons.mp4 halloween22
31 e6679ce2-d458-493c-8ffb-5660e47ac99f Happy Hanami Enjoy the view hanami2023
32 de7bd960-eb02-47e1-9ce2-a44f6e255d8f Happy Holidays 2019 Happy holidays from everyone at TeamSpeak! Happy_Holidays
33 d4ea0251-ba46-4c1a-83b7-59db3f89e52c Happy New Year 2021 Survived the great toilet paper crisis of 2020 firework_2020
34 1519e001-06a0-458c-9195-a8a6d0ec87fc Happy New Year 2023 Aw man, here we go again 2023_NewYear
35 834d4cc1-cd80-48d6-96c4-23d131d78649 Happy Summer 2023 heat death of the universe happy_summer_2023
36 c68bcc52-7aeb-4868-b4d2-e7b20716f9ba Heatwave 2022 I'm melting... help summer_icecream
37 94242c4e-6742-4540-8b66-ce951ed57159 Helping Hand \ pushed some buttons *beep* *bop* ~ thanks! homebase
38 288a56c6-4da3-48de-9c9f-bd9eede5d832 Immortal Roleplay This is your life. Immortal_Roleplay
39 69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d International Peace Day United we stand, divided we fall peaceday2022
40 9ea23c77-8755-4d82-b30c-92f4aac109ef International Women's Day 2021 To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day! wft
41 7d9fa2b1-b6fa-47ad-9838-c239a4ddd116 MIFCOM MIFCOM | Entered Performance mifcom
42 ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776 Merry Christmas 2019 It’s the most wonderful ‘Tim’ of the Year Christmas
43 c6480fe2-ee25-4ee8-9853-243652c8ec54 Merry Christmas 2020 Let it snow, let it snow, let it snow! Christmas2020
44 0581aa0f-8c2d-4681-bb9f-8492fec49977 Merry Christmas 2021 Look what Santa's left under the server tree! christmas2021
45 d4875b30-9908-43cb-a1eb-1a958e226078 Merry Christmas 2022 There's snow place like home christmas2022
46 87ccf9ea-67c9-45e5-adbc-77e210e6128a Met Tim Met Tim Speak IRL tim_irl
47 0d98391c-ecdf-4f26-931a-49bfd669cda7 Mind Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_MindEgg
48 2fdda3c6-20e0-48f1-9c12-f39239a2ed02 Mother's Day 2022 Thanks for bearing with us rose
49 c3f823eb-5d5c-40f9-9dbd-3437d59a539d Official TeamSpeak Gamer New myTeamSpeak member TS-2018
50 8dfa37ac-b40d-4466-b393-ff2184a9adf3 Overwatch League I follow the Overwatch League OWL_Badge
51 4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac PGL Antwerp 2022 Watched the PGL CS:GO Major PGLant
52 fa3ece28-64df-431f-b1b3-90844bfdd2d9 Paris Games Week 2014 Registered at Paris Games Week 2014 paris_gamesweek_2014
53 d95f9901-c42d-4bac-8849-7164fd9e2310 Paris Games Week 2016 Registered during Paris Games Week 2016 paris_gamesweek_2016
54 0005232e-538e-4cb2-93b6-d7d83e873829 PietSmiet Werde Snob auf PietSmiet.de ;) PietSmiet
55 be932556-dfa9-4dc6-afd0-98de0ab25777 PolTeamgeist WooOOHoohOOHooo PolTeamgeist
56 5f6d49e4-35c8-4809-8c81-6e71f7f749e9 Power Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_PowerEgg
57 ceee2445-4fbf-4f06-9421-286f0f4e875a Pride Never be afraid to show your colors. pride
58 1aa375e8-7207-45bf-8b80-556bafafc834 Reality Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_RealityEgg
59 f22c22f1-8e2d-4d99-8de9-f352dc26ac5b Rocket Beans TV Rocket Beans TV Community rbtv RWGE2NURJZ
60 2c9698c1-1fec-4baa-a28f-4845f045f42f Soul Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_SoulEgg
61 641a4d85-2351-482c-97a1-02fc3b6abbb5 Space Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_SpaceEgg
62 63261116-4359-4842-873e-56820afbe068 SpartaTheOriginal Olaf Toast @ twitch.tv/SpartaTheOriginal Toast
63 ef567ec5-f46e-4520-be07-6021023cf6bd Sponsorship License Sponsored by TeamSpeak Sponsorship
64 7a627d47-5496-4d68-83b5-2c4eafff9b30 Stay Home, Stay Safe Playing Apart, Staying Connected StaySafeStayHome
65 7262a528-c7df-4369-bc2c-d34bf5853d7b TS Chat Alpha Tester Helped us test our new mobile app, thanks! slim_golden
66 6eee759e-b1e9-4937-b023-07fc778532a2 TS Gameday Participant At least i tried... silvered
67 e1447b99-53b0-448a-98b7-ee7bad8bd268 TS Gameday Winner As shiny as the golden frying pan goldenjoystick
68 1cb07348-34a4-4741-b50f-c41e584370f7 TeamSpeak Addon Author Creator of TeamSpeak Addons addon_author
69 450f81c1-ab41-4211-a338-222fa94ed157 TeamSpeak Addon Developer (Bronze) Creator of at least 1 TeamSpeak Addon addon_author_bronze
70 94ec66de-5940-4e38-b002-970df0cf6c94 TeamSpeak Addon Developer (Gold) Creator of at least 5 TeamSpeak Addons addon_author_gold
71 c9e97536-5a2d-4c8e-a135-af404587a472 TeamSpeak Addon Developer (Silver) Creator of at least 3 TeamSpeak Addons addon_author_silver
72 9cd152a7-bf65-4ece-aeba-62d27678f79a TeamSpeak Competition Winner Badge TeamSpeak Competition Winner CompWinnerBadge
73 64221fd1-706c-4bb2-ba55-996c39effa79 TeamSpeak Jedi myTeamSpeak early adopter TS-OG
74 6b187e83-873b-46b0-b2c2-a31af15e76a4 TeamSpeak Merch Badge TeamSpeak Merch Owner - 1st Edition cap_red
75 22b9ec39-7694-453e-864c-dfc7b1b0d7c7 TeamSpeak Merch Badge 2.0 TeamSpeak Merch Owner - 2nd Edition topper
76 205916f3-a953-4754-8905-bc15069b1f91 TeamSpeak Merch Badge 3.0 TeamSpeak Merch Owner — 3rd Edition Merch3
77 8d843dfa-c51a-407f-87b3-94cfc8f03e96 TeamSpeak Staff Official Staff Member teamspeak_staff
78 c2368518-3728-4260-bcd1-8b85e9f8984c Test Testing, Testing. Testing
79 4086a249-a503-4f31-9e83-8a0a8e3089bd Tim-o'-Lantern Mwuhaahaahaahaahaa Tim-O-Lantern JQGCTAQWHT
80 089c7295-3aa2-48b0-b2f1-2dd1bec12caf Time Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_TimeEgg
81 904e232c-f369-44db-87f7-5142e15620cc Time Machine Worked like a machine to update addons in super-quick time. time_machine
82 4c61af66-22ef-4897-b0bb-25fcef2acf60 Undead Nightmare I'm the last of my kind undead_nightmare
83 b0a36aea-3e46-4e83-a455-6e92ae1b9d94 Undead Nightmare I'm the last of my kind undead_nightmare
84 0cd924ed-c5ea-459e-b60a-4f1bc0b65f07 Up, Up and Away! Find me on Mount Chiliad up,_up_and_away!
85 4b0fd4f5-d456-4294-973d-853a1db5c7d8 Valentim's Day 2019 Valentim's Day 2019 Valentines_Badge
86 92801833-e721-4b7e-84d4-6c02dbb332b9 Valentim's Day 2020 Valentim's Day 2020 Valentim2020
87 958f904b-8260-48a4-a961-f786cbd39411 Valentine's Day 2023 Love you like my Tamagotchi ValentinesDay23
88 a676c708-da67-4784-ba7f-3fb7e8d2e865 Valentines Day 2021 Roses are red, TS is blue, Servers are Sweet and so are you. valentine21
89 c54a9f92-07f7-4214-90f3-eafeea8005da World Backup Day Don't be an April Fool. Back up your data! backupday_2023
90 448a6d13-4e08-46a1-aafa-b4ff6d6c2d06 World Bonsai Day harmony, balance, patience bonsai_day
91 0f976a27-ddf5-447c-b79c-0644a8e8a297 Year of the Dragon 2024 Arise, Shenron! year_of_the_dragon_2024
92 8c22fe26-30ac-4231-8b31-67d8a75c808a Year of the Ox 2021 Only listen to the fortune cookie; disregard all other fortune telling units. ox21
93 970c70e6-00a1-41c1-ac5c-81c89a06c7a6 Year of the Rabbit 2023 Do a barrel roll! chineseNY2023
94 92356386-0451-4a97-87d9-10ff4f43260c Year of the Tiger 2022 Rocky sends his regards tiger
-144
View File
@@ -1,144 +0,0 @@
//! myTeamSpeak badges: what the GUIDs a client shows (`client_badges`)
//! stand for, and where TeamSpeak keeps their pictures.
//!
//! The table is `data/badges.csv`: tsclientlib's list (2023, also in
//! `proto/tsproto-structs/declarations`) and the newer badges of
//! TeamSpeak's own list (`https://badges-content.teamspeak.com/list`, a
//! protobuf) as of October 2026. Badges added since are unknown here.
use std::collections::HashMap;
use std::sync::LazyLock;
/// How many badges a client shows at most (TeamSpeak lets one pick three).
pub const SHOWN: usize = 3;
/// TeamSpeak's server for the badges' pictures.
const CONTENT: &str = "https://badges-content.teamspeak.com";
/// One badge of the table.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BadgeInfo {
pub name: String,
pub description: String,
/// Its picture's name on TeamSpeak's server, without `.svg`.
pub filename: String,
}
/// The table by GUID (lower case), read once.
static BADGES: LazyLock<HashMap<String, BadgeInfo>> = LazyLock::new(|| {
// Columns: uid, name, description, filename, codes.
records(include_str!("../data/badges.csv"))
.into_iter()
.skip(1)
.filter_map(|mut fields| {
fields.truncate(4);
let [uid, name, description, filename] = <[String; 4]>::try_from(fields).ok()?;
Some((uid.to_ascii_lowercase(), BadgeInfo { name, description, filename }))
})
.collect()
});
/// What a badge GUID stands for; none for one the table does not know.
pub fn info(guid: &str) -> Option<&'static BadgeInfo> {
BADGES.get(&guid.to_ascii_lowercase())
}
/// The address of a badge's picture (an SVG); none for an unknown badge.
pub fn icon_url(guid: &str) -> Option<String> {
let info = info(guid)?;
Some(format!("{CONTENT}/{}/{}.svg", guid.to_ascii_lowercase(), info.filename))
}
/// The records of a CSV text (RFC 4180): fields split at commas; a quoted
/// field may hold commas and line breaks, and `""` for a quote.
fn records(text: &str) -> Vec<Vec<String>> {
let mut records = Vec::new();
let mut record = Vec::new();
let mut field = String::new();
let mut quoted = false;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' if quoted => {
if chars.next_if_eq(&'"').is_some() {
field.push('"');
} else {
quoted = false;
}
}
'"' if field.is_empty() => quoted = true,
',' if !quoted => record.push(std::mem::take(&mut field)),
'\r' if !quoted => {}
'\n' if !quoted => {
record.push(std::mem::take(&mut field));
records.push(std::mem::take(&mut record));
}
c => field.push(c),
}
}
if !field.is_empty() || !record.is_empty() {
record.push(field);
records.push(record);
}
records
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_badges() {
let info = info("4b27be5a-b92a-4b30-8b2d-14b59653f427").unwrap();
assert_eq!(info.name, "20th Anniversary");
assert_eq!(info.description, "Celebrating 20 Years of TeamSpeak");
assert_eq!(info.filename, "20_years");
// Upper case on the wire finds it too.
assert_eq!(super::info("4B27BE5A-B92A-4B30-8B2D-14B59653F427"), Some(info));
assert_eq!(
icon_url("4b27be5a-b92a-4b30-8b2d-14b59653f427").as_deref(),
Some(
"https://badges-content.teamspeak.com/4b27be5a-b92a-4b30-8b2d-14b59653f427/20_years.svg"
)
);
}
#[test]
fn quoted_fields_keep_their_commas() {
let fools = info("05114019-6b46-4b13-b5a1-e5179ef69fb5").unwrap();
assert_eq!(fools.name, "April Fools!");
assert_eq!(
fools.description,
"Roses are red, gaming is fun, you are carrying too much to be able to run :("
);
assert_eq!(fools.filename, "rpg");
let stay = info("7a627d47-5496-4d68-83b5-2c4eafff9b30").unwrap();
assert_eq!(stay.name, "Stay Home, Stay Safe");
assert_eq!(stay.description, "Playing Apart, Staying Connected");
let up = info("0cd924ed-c5ea-459e-b60a-4f1bc0b65f07").unwrap();
assert_eq!(up.filename, "up,_up_and_away!");
}
#[test]
fn unknown_badges() {
assert_eq!(info("00000000-0000-0000-0000-000000000000"), None);
assert_eq!(info(""), None);
assert_eq!(icon_url("00000000-0000-0000-0000-000000000000"), None);
}
#[test]
fn every_row_is_read() {
let rows = include_str!("../data/badges.csv").lines().count() - 1;
assert_eq!(BADGES.len(), rows);
assert!(BADGES.values().all(|b| !b.name.is_empty() && !b.filename.is_empty()));
}
#[test]
fn csv_records() {
assert_eq!(
records("a,\"b, \"\"c\"\"\",\r\n\"multi\nline\",d"),
[vec!["a", "b, \"c\"", ""], vec!["multi\nline", "d"]]
);
assert!(records("").is_empty());
}
}
-283
View File
@@ -1,283 +0,0 @@
//! Chat messages, from any source.
//!
//! Messages can link files in a channel's file browser: TeamSpeak clients
//! post them as `[URL=ts3file://…]name[/URL]`; [`ChatMessage::file_refs`]
//! finds them as [`FileRef`]s (for file cards) and [`FileRef::to_bbcode`]
//! writes one.
use serde::{Deserialize, Serialize};
use crate::percent;
use crate::presence::{ChannelId, ClientId};
fn is_false(b: &bool) -> bool {
!*b
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
pub enum ChatTarget {
/// Everyone on the server.
Server,
Channel(ChannelId),
/// Private chat, by the other side's unique id when known.
Private(String),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatMessage {
pub target: ChatTarget,
pub author_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub author_uid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub author_id: Option<ClientId>,
pub text: String,
/// Unix time in milliseconds.
pub ts_ms: i64,
/// Carried by a gateway or query relay rather than our own connection.
#[serde(default)]
pub via_relay: bool,
/// The author is blocked in our contacts (set by the engine when it
/// reports the message; never sent over the wire).
#[serde(default, skip_serializing_if = "is_false")]
pub blocked: bool,
}
impl ChatMessage {
/// The file links in the text, in order of appearance, each once.
pub fn file_refs(&self) -> Vec<FileRef> {
parse_file_links(&self.text)
}
}
/// A file in a channel's file browser, as a chat message links it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FileRef {
/// The server's unique id (`serverUID`), when the link tells it: a link
/// from another server cannot be downloaded here.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server_uid: Option<String>,
pub channel: ChannelId,
/// The directory, `/` for the channel's root.
pub path: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
#[serde(default, skip_serializing_if = "is_false")]
pub is_dir: bool,
/// Unix seconds of the last change, when the link tells it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub modified_s: Option<i64>,
/// The link as it appeared.
pub url: String,
}
/// URL schemes of file links (`ts3file`; later clients may use others of
/// the same form).
const FILE_SCHEMES: &[&str] = &["ts3file://", "tsfile://", "ts5file://", "ts6file://"];
impl FileRef {
/// The file's path in the channel: [`Self::path`] joined with [`Self::name`].
pub fn full_path(&self) -> String {
let dir = self.path.trim_end_matches('/');
format!("{dir}/{}", self.name)
}
/// Parse one link (`ts3file://name?serverUID=…&channel=…&path=…&filename=…&isDir=…&size=…&fileDateTime=…`).
pub fn parse(url: &str) -> Option<Self> {
let lower = url.get(..12).unwrap_or(url).to_ascii_lowercase();
let scheme = FILE_SCHEMES.iter().find(|s| lower.starts_with(**s))?;
let rest = &url[scheme.len()..];
let (host, query) = rest.split_once('?').unwrap_or((rest, ""));
let mut file = FileRef { url: url.to_owned(), path: "/".into(), ..Default::default() };
let mut channel = None;
for pair in query.split('&') {
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
let value = percent::decode(value);
match key.to_ascii_lowercase().as_str() {
"serveruid" => file.server_uid = Some(value).filter(|v| !v.is_empty()),
"channel" | "cid" => channel = value.parse().ok(),
"path" => file.path = if value.is_empty() { "/".into() } else { value },
"filename" | "name" => file.name = value,
"isdir" => file.is_dir = matches!(value.as_str(), "1" | "true"),
"size" => file.size = value.parse().ok(),
"filedatetime" => file.modified_s = value.parse().ok(),
_ => {}
}
}
if file.name.is_empty() {
file.name = percent::decode(host.trim_end_matches('/'));
}
file.channel = channel?;
(!file.name.is_empty()).then_some(file)
}
/// The link as TeamSpeak clients post it: `[URL=ts3file://…]name[/URL]`.
pub fn to_bbcode(&self) -> String {
let mut url = format!("ts3file://{}?", percent::encode(&self.name));
if let Some(uid) = &self.server_uid {
url.push_str(&format!("serverUID={}&", percent::encode(uid)));
}
url.push_str(&format!(
"channel={}&path={}&filename={}&isDir={}",
self.channel,
percent::encode(&self.path),
percent::encode(&self.name),
u8::from(self.is_dir)
));
if let Some(size) = self.size {
url.push_str(&format!("&size={size}"));
}
if let Some(t) = self.modified_s {
url.push_str(&format!("&fileDateTime={t}"));
}
format!("[URL={url}]{}[/URL]", self.name)
}
}
/// The file links in `text` (BBCode `[URL=…]`, `[URL]…[/URL]`, Markdown
/// `[name](…)` or bare), in order, each once.
pub fn parse_file_links(text: &str) -> Vec<FileRef> {
let lower = text.to_ascii_lowercase();
let mut found: Vec<FileRef> = Vec::new();
let mut at = 0;
while at < text.len() {
let next = FILE_SCHEMES.iter().filter_map(|s| lower[at..].find(s).map(|i| at + i)).min();
let Some(start) = next else { break };
let end = text[start..]
.find(|c: char| c.is_whitespace() || matches!(c, ']' | '[' | ')' | '"' | '<' | '>'))
.map_or(text.len(), |i| start + i);
if let Some(file) = FileRef::parse(&text[start..end])
&& !found.iter().any(|f| f.url == file.url)
{
found.push(file);
}
at = end.max(start + 1);
}
found
}
/// Format of messages a relay posts on behalf of a user.
pub fn relay_text(format: &str, nick: &str, text: &str) -> String {
format.replace("{nick}", nick).replace("{text}", text)
}
/// Split text so each part fits TeamSpeak's message limit (1024 bytes of
/// text), breaking at character boundaries.
pub fn split_message(text: &str, max_bytes: usize) -> Vec<String> {
let mut parts = Vec::new();
let mut current = String::new();
for c in text.chars() {
if current.len() + c.len_utf8() > max_bytes {
parts.push(std::mem::take(&mut current));
}
current.push(c);
}
if !current.is_empty() || parts.is_empty() {
parts.push(current);
}
parts
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn relay_format() {
assert_eq!(relay_text("[{nick}] {text}", "Alice", "hi"), "[Alice] hi");
}
#[test]
fn splits_on_char_boundaries() {
assert_eq!(split_message("abcdef", 4), vec!["abcd", "ef"]);
assert_eq!(split_message("", 4), vec![""]);
let parts = split_message("ääää", 3);
assert!(parts.iter().all(|p| p.len() <= 3));
assert_eq!(parts.concat(), "ääää");
}
#[test]
fn parses_ts3_file_links() {
let text = "look: [URL=ts3file://Report%20Q3.pdf?serverUID=l%2FHvD5zXg5r4%2F%2FC6Ht7J9Ts3Wmc%3D&channel=5&path=%2Fdocs&filename=Report%20Q3.pdf&isDir=0&size=12345&fileDateTime=1454598011]Report Q3.pdf[/URL] and [URL]ts3file://a.txt?channel=1&path=%2F&filename=a+b.txt[/URL]";
let files = parse_file_links(text);
assert_eq!(files.len(), 2);
let f = &files[0];
assert_eq!(f.server_uid.as_deref(), Some("l/HvD5zXg5r4//C6Ht7J9Ts3Wmc="));
assert_eq!((f.channel, f.path.as_str(), f.name.as_str()), (5, "/docs", "Report Q3.pdf"));
assert_eq!((f.size, f.modified_s, f.is_dir), (Some(12345), Some(1_454_598_011), false));
assert_eq!(f.full_path(), "/docs/Report Q3.pdf");
assert_eq!(files[1].name, "a+b.txt");
assert_eq!(files[1].full_path(), "/a+b.txt");
}
#[test]
fn file_links_in_other_forms() {
// Markdown, bare, a repeated link, a link without a channel.
let text = "[x](ts3file://x?channel=2&filename=x&isDir=true) ts3file://y?channel=3&path=/d/ \
ts3file://y?channel=3&path=/d/ ts3file://z?filename=z";
let files = parse_file_links(text);
assert_eq!(files.len(), 2);
assert!(files[0].is_dir);
assert_eq!((files[1].name.as_str(), files[1].full_path().as_str()), ("y", "/d/y"));
let msg = ChatMessage {
target: ChatTarget::Channel(1),
author_name: "a".into(),
author_uid: None,
author_id: None,
text: text.into(),
ts_ms: 0,
via_relay: false,
blocked: false,
};
assert_eq!(msg.file_refs(), files);
assert!(parse_file_links("no links, ts3file:// alone").is_empty());
}
#[test]
fn file_link_round_trip() {
let file = FileRef {
server_uid: Some("uid+/=".into()),
channel: 7,
path: "/a dir".into(),
name: "ä b&c.png".into(),
size: Some(10),
is_dir: false,
modified_s: Some(99),
url: String::new(),
};
let text = file.to_bbcode();
let parsed = parse_file_links(&text);
assert_eq!(parsed.len(), 1);
assert_eq!(FileRef { url: String::new(), ..parsed[0].clone() }, file);
assert!(text.ends_with("]ä b&c.png[/URL]"));
}
#[test]
fn blocked_flag_stays_off_the_wire() {
let msg = ChatMessage {
target: ChatTarget::Server,
author_name: "a".into(),
author_uid: None,
author_id: None,
text: "t".into(),
ts_ms: 1,
via_relay: false,
blocked: false,
};
let json = serde_json::to_string(&msg).unwrap();
assert!(!json.contains("blocked"));
let back: ChatMessage = serde_json::from_str(&json).unwrap();
assert_eq!(back, msg);
}
#[test]
fn target_json() {
assert_eq!(
serde_json::to_string(&ChatTarget::Channel(5)).unwrap(),
r#"{"kind":"channel","id":5}"#
);
assert_eq!(serde_json::to_string(&ChatTarget::Server).unwrap(), r#"{"kind":"server"}"#);
}
}
-23
View File
@@ -1,23 +0,0 @@
//! Domain model shared by the client engine, the gateway and the UI.
//!
//! Nothing in here does IO; the types describe what a server offers and what
//! the user sees.
pub mod badges;
mod chat;
mod link;
mod percent;
mod presence;
mod server;
mod tree;
pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, split_message};
pub use link::{Link, ServerLink, channel_path_id, join_channel_path, split_channel_path};
pub use presence::{
ChannelId, ChannelInfo, ClientId, ClientInfo, GroupId, GroupInfo, GroupNamingMode, GroupType,
Presence, PresenceDelta, PresenceSnapshot, myts_avatar_url, parse_badges, shown_badges,
};
pub use server::{
BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion,
};
pub use tree::{Spacer, TreeRow, channel_title, order_siblings, parse_spacer, tree_rows};
-420
View File
@@ -1,420 +0,0 @@
//! Server links: `ts3server://` (TeamSpeak 3 and 5), `teamspeak://`
//! (TeamSpeak 6) and TeamSpeak's short links on `tmspk.gg`, whose page sends
//! the browser on to a `teamspeak://` link.
use crate::percent;
use crate::presence::ChannelId;
/// What a link opens ([`Link::parse`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Link {
/// A server, and maybe a channel on it.
Server(ServerLink),
/// A TeamSpeak 6 invite code (`tmspk.gg/<code>`,
/// `teamspeak://invite=<code>`): only a TeamSpeak service knows the
/// server it stands for.
Invite(String),
}
/// A server link: the server, and what to join it with (none of it empty).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ServerLink {
/// A host name, an IP address (IPv6 without brackets) or a server
/// nickname.
pub host: String,
pub port: Option<u16>,
pub nickname: Option<String>,
/// The server's password.
pub password: Option<String>,
/// The channel to join: its names from the top, separated by `/` (a `/`
/// in a name as `\/`, [`split_channel_path`]), or `/<id>` (`cid=`).
pub channel: Option<String>,
pub channel_password: Option<String>,
/// A privilege key: it puts its user in a server or channel group.
pub token: Option<String>,
}
const SCHEMES: [&str; 2] = ["ts3server://", "teamspeak://"];
const WEB: [&str; 2] = ["https://", "http://"];
const SHORT_HOSTS: [&str; 2] = ["tmspk.gg", "www.tmspk.gg"];
impl Link {
/// Read a link: `ts3server://<host>?<query>` with the keys `port`,
/// `nickname`, `password`, `channel` (`A/B`), `cid`, `channelpassword`
/// and `token` (`teamspeak://` alike; the scheme and the keys in any
/// case, other keys ignored, a `+` kept as it is),
/// `https://tmspk.gg/s/<host>?<query>` (also `/s=<host>`), and the
/// invite codes `tmspk.gg/<code>` and `teamspeak://invite=<code>`. None
/// for anything else.
pub fn parse(text: &str) -> Option<Link> {
let text = text.trim();
// The same length in bytes: an index of one is one of the other.
let lower = text.to_ascii_lowercase();
match SCHEMES.iter().find(|s| lower.starts_with(**s)) {
Some(scheme) => parse_server(&text[scheme.len()..]),
None => parse_short(text, &lower),
}
}
}
impl ServerLink {
/// A link to the server at `address` (`host`, `host:port`, `[v6]`,
/// `[v6]:port` or a bare IPv6 address), joining nothing.
pub fn new(address: &str) -> Self {
let (host, port) = split_address(address.trim());
ServerLink { host: host.to_owned(), port, ..Default::default() }
}
/// The server's address as a bookmark keeps it: `host`, `host:port` or
/// `[v6]:port`.
pub fn address(&self) -> String {
match self.port {
Some(port) if self.host.contains(':') => format!("[{}]:{port}", self.host),
Some(port) => format!("{}:{port}", self.host),
None => self.host.clone(),
}
}
/// The link as TeamSpeak clients open it: `ts3server://<host>?port=…`,
/// then what is set of nickname, password, channel (or `cid` for
/// `/<id>`), channel password and privilege key.
pub fn to_url(&self) -> String {
let mut url = match self.port {
Some(_) if self.host.contains(':') => format!("ts3server://[{}]", self.host),
_ => format!("ts3server://{}", self.host),
};
let pair = |key: &str, value: &Option<String>| {
let value = value.as_deref().filter(|v| !v.is_empty())?;
Some(format!("{key}={}", percent::encode(value)))
};
let channel = self.channel.as_deref().filter(|c| !c.is_empty()).map(|path| {
match channel_path_id(path) {
Some(id) => format!("cid={id}"),
// A `/` between names, `%2F` in one.
None => {
let names: Vec<String> =
split_channel_path(path).iter().map(|n| percent::encode(n)).collect();
format!("channel={}", names.join("/"))
}
}
});
let query: Vec<String> = [
self.port.map(|port| format!("port={port}")),
pair("nickname", &self.nickname),
pair("password", &self.password),
channel,
pair("channelpassword", &self.channel_password),
pair("token", &self.token),
]
.into_iter()
.flatten()
.collect();
if !query.is_empty() {
url.push('?');
url.push_str(&query.join("&"));
}
url
}
}
/// A channel path's names from the top: `Gaming/Raid Night` →
/// `["Gaming", "Raid Night"]`, `AC\/DC` → `["AC/DC"]`.
pub fn split_channel_path(path: &str) -> Vec<String> {
let mut names = Vec::new();
let mut name = String::new();
let mut chars = path.chars().peekable();
while let Some(c) = chars.next() {
match c {
'\\' if chars.peek() == Some(&'/') => {
name.push('/');
chars.next();
}
'/' => names.push(std::mem::take(&mut name)),
c => name.push(c),
}
}
names.push(name);
names
}
/// A channel path from its names from the top, a `/` in a name as `\/`:
/// the reverse of [`split_channel_path`].
pub fn join_channel_path(names: &[impl AsRef<str>]) -> String {
names.iter().map(|n| n.as_ref().replace('/', "\\/")).collect::<Vec<_>>().join("/")
}
/// The channel id of a path `/<id>` (what `cid=` gives).
pub fn channel_path_id(path: &str) -> Option<ChannelId> {
let id = path.strip_prefix('/')?;
if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
id.parse().ok()
}
/// After `ts3server://` or `teamspeak://`: `<host>[:port][/]?<query>`, or
/// `invite=<code>`.
fn parse_server(rest: &str) -> Option<Link> {
let (head, query) = rest.split_once('?').unwrap_or((rest, ""));
let authority = head.split('/').next().unwrap_or_default();
if let Some(key) = authority.get(..7).filter(|k| k.eq_ignore_ascii_case("invite=")) {
let code = percent::decode(&authority[key.len()..]);
return (!code.is_empty()).then_some(Link::Invite(code));
}
let authority = percent::decode(authority);
let (host, port) = split_address(&authority);
if host.is_empty() || host.chars().any(|c| c.is_whitespace() || c.is_control()) {
return None;
}
let mut link = ServerLink { host: host.to_owned(), port, ..Default::default() };
let mut cid = None;
for pair in query.split('&') {
let (key, raw) = pair.split_once('=').unwrap_or((pair, ""));
let value = Some(percent::decode(raw)).filter(|v| !v.is_empty());
match key.to_ascii_lowercase().as_str() {
// One that is no port is ignored.
"port" => link.port = value.as_deref().and_then(parse_port).or(link.port),
"nickname" => link.nickname = value,
"password" => link.password = value,
// A `/` between names, `%2F` in one.
"channel" => {
let names: Vec<String> = raw.split('/').map(percent::decode).collect();
link.channel = Some(join_channel_path(&names)).filter(|_| names.concat() != "");
}
"cid" => cid = value.and_then(|v| v.parse::<ChannelId>().ok()).filter(|c| *c != 0),
"channelpassword" => link.channel_password = value,
"token" => link.token = value,
_ => {}
}
}
// The id names one channel for sure.
if let Some(cid) = cid {
link.channel = Some(format!("/{cid}"));
}
Some(Link::Server(link))
}
/// `tmspk.gg/s/<host>?…` (or `/s=`), with or without `https://`, goes where
/// its page sends the browser: `teamspeak://<host>?…`; any other path is an
/// invite code.
fn parse_short(text: &str, lower: &str) -> Option<Link> {
let start = WEB.iter().find(|s| lower.starts_with(**s)).map_or(0, |s| s.len());
let (host, path) = text[start..].split_once('/')?;
if !SHORT_HOSTS.contains(&host.to_ascii_lowercase().as_str()) {
return None;
}
if path.get(..2).is_some_and(|s| s.eq_ignore_ascii_case("s/") || s.eq_ignore_ascii_case("s=")) {
return parse_server(&path[2..]);
}
let code = path.split(['?', '#', '/']).next().unwrap_or_default();
let valid = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_');
(!code.is_empty() && code.bytes().all(valid)).then(|| Link::Invite(code.to_owned()))
}
/// `host`, `host:port`, `[v6]`, `[v6]:port` or a bare IPv6 address: the
/// host (an IPv6 address without its brackets) and the port, if one is
/// given that is one.
fn split_address(address: &str) -> (&str, Option<u16>) {
if let Some((host, after)) = address.strip_prefix('[').and_then(|a| a.split_once(']')) {
return (host, after.strip_prefix(':').and_then(parse_port));
}
match address.rsplit_once(':') {
// A port follows the only colon; more colons: an IPv6 address.
Some((host, port))
if !host.contains(':')
&& !port.is_empty()
&& port.bytes().all(|b| b.is_ascii_digit()) =>
{
(host, parse_port(port))
}
_ => (address, None),
}
}
fn parse_port(text: &str) -> Option<u16> {
text.parse().ok().filter(|p| *p != 0)
}
#[cfg(test)]
mod tests {
use super::*;
fn server(text: &str) -> ServerLink {
match Link::parse(text) {
Some(Link::Server(link)) => link,
other => panic!("{text}: {other:?}"),
}
}
fn host(host: &str, port: Option<u16>) -> ServerLink {
ServerLink { host: host.into(), port, ..Default::default() }
}
#[test]
fn every_parameter() {
let link = server(
"ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid+1&token=AbC%2Bd&addbookmark=Mine",
);
assert_eq!(
link,
ServerLink {
host: "ts.example.org".into(),
port: Some(9988),
nickname: Some("Nova X".into()),
password: Some("s3cr?t".into()),
channel: Some("Gaming/Raid Night".into()),
// A `+` stays.
channel_password: Some("raid+1".into()),
token: Some("AbC+d".into()),
}
);
assert_eq!(link.address(), "ts.example.org:9988");
assert_eq!(
link.to_url(),
"ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid%2B1&token=AbC%2Bd"
);
assert_eq!(Link::parse(&link.to_url()), Some(Link::Server(link)));
// A channel id names the channel, also next to a path.
assert_eq!(server("ts3server://h?cid=12").channel.as_deref(), Some("/12"));
assert_eq!(server("ts3server://h?channel=Lobby&cid=12").channel.as_deref(), Some("/12"));
assert_eq!(server("ts3server://h?cid=x&channel=Lobby").channel.as_deref(), Some("Lobby"));
assert_eq!(server("ts3server://h?cid=12").to_url(), "ts3server://h?cid=12");
// Empty values are none.
assert_eq!(server("ts3server://h?nickname=&channel=&password"), host("h", None));
}
#[test]
fn teamspeak_scheme_is_the_same() {
let query = "ts.example.org?port=9987&channel=Lobby&nickname=Nova";
assert_eq!(
Link::parse(&format!("teamspeak://{query}")),
Link::parse(&format!("ts3server://{query}"))
);
// Any case, of the scheme and the keys; the host as written.
let link = server("TeamSpeak://TS.Example.org/?PORT=9988&Channel=Lobby&CID=");
assert_eq!(
link,
ServerLink { channel: Some("Lobby".into()), ..host("TS.Example.org", Some(9988)) }
);
assert_eq!(server("TS3SERVER://h:9988"), host("h", Some(9988)));
}
#[test]
fn short_links() {
for text in [
"https://tmspk.gg/s/ts.example.org?port=9988&channel=Lobby",
"https://tmspk.gg/s=ts.example.org?port=9988&channel=Lobby",
"HTTPS://www.TMSPK.gg/S/ts.example.org?port=9988&channel=Lobby",
"tmspk.gg/s/ts.example.org/?port=9988&channel=Lobby",
"http://tmspk.gg/s/ts.example.org:9988?channel=Lobby",
] {
assert_eq!(
server(text),
ServerLink { channel: Some("Lobby".into()), ..host("ts.example.org", Some(9988)) },
"{text}"
);
}
let invite = |code: &str| Some(Link::Invite(code.into()));
assert_eq!(Link::parse("https://tmspk.gg/AbC12x"), invite("AbC12x"));
assert_eq!(Link::parse("tmspk.gg/AbC12x/?ref=1"), invite("AbC12x"));
assert_eq!(Link::parse("teamspeak://invite=AbC12x"), invite("AbC12x"));
assert_eq!(Link::parse("TEAMSPEAK://Invite=AbC12x/"), invite("AbC12x"));
for text in ["https://tmspk.gg/", "https://tmspk.gg", "tmspk.gg/a.b", "teamspeak://invite="]
{
assert_eq!(Link::parse(text), None, "{text}");
}
}
#[test]
fn ipv6() {
let v6 = host("2001:db8::1", Some(9987));
assert_eq!(server("ts3server://[2001:db8::1]?port=9987"), v6);
assert_eq!(server("ts3server://[2001:db8::1]:9987"), v6);
assert_eq!(v6.address(), "[2001:db8::1]:9987");
assert_eq!(v6.to_url(), "ts3server://[2001:db8::1]?port=9987");
// Without a port, with or without brackets.
let bare = host("2001:db8::1", None);
assert_eq!(server("ts3server://2001:db8::1"), bare);
assert_eq!(server("ts3server://[2001:db8::1]"), bare);
assert_eq!(bare.address(), "2001:db8::1");
assert_eq!(ServerLink::new(" [2001:db8::1]:9988 "), host("2001:db8::1", Some(9988)));
}
#[test]
fn escapes() {
let link = server("ts3server://h?channel=%C3%84rger/Caf%C3%A9&nickname=J%C3%BCrgen");
assert_eq!(link.channel.as_deref(), Some("Ärger/Café"));
assert_eq!(link.nickname.as_deref(), Some("Jürgen"));
// `%2F` is a `/` in a name.
let link = server("ts3server://h?channel=AC%2FDC/Live");
assert_eq!(link.channel.as_deref(), Some("AC\\/DC/Live"));
assert_eq!(split_channel_path("AC\\/DC/Live"), ["AC/DC", "Live"]);
assert_eq!(join_channel_path(&["AC/DC", "Live"]), "AC\\/DC/Live");
assert_eq!(link.to_url(), "ts3server://h?channel=AC%2FDC/Live");
assert_eq!(split_channel_path("Lobby"), ["Lobby"]);
assert_eq!(channel_path_id("/12"), Some(12));
assert_eq!(channel_path_id("12"), None);
assert_eq!(channel_path_id("/1a"), None);
}
#[test]
fn invalid_ports_are_ignored() {
for text in [
"ts3server://h?port=abc",
"ts3server://h?port=70000",
"ts3server://h?port=0",
"ts3server://h?port=",
"ts3server://h:70000",
] {
assert_eq!(server(text), host("h", None), "{text}");
}
// One in the address stays.
assert_eq!(server("ts3server://h:9988?port=x"), host("h", Some(9988)));
}
#[test]
fn other_links_are_none() {
for text in [
"",
"http://example.com",
"https://example.com/s/ts.example.org",
"ts3file://a.png?serverUID=x&channel=1",
"ts3server://",
"ts3server://?port=9987",
"ts3server://a b",
"ts.example.org",
"mailto:a@example.org",
] {
assert_eq!(Link::parse(text), None, "{text:?}");
}
}
#[test]
fn round_trip() {
// The invite links of voelin-ui (`vm::servers::invite_link`).
for (address, names, url) in [
(
"ts.example.com:9988",
&["Gaming", "Raid Night"][..],
"ts3server://ts.example.com?port=9988&channel=Gaming/Raid%20Night",
),
(" ts.example.com ", &[], "ts3server://ts.example.com"),
(
"[2001:db8::1]:9987",
&["Chill & Co"],
"ts3server://[2001:db8::1]?port=9987&channel=Chill%20%26%20Co",
),
("2001:db8::1", &[], "ts3server://2001:db8::1"),
("h:x", &["Ä/b"], "ts3server://h:x?channel=%C3%84%2Fb"),
] {
let mut link = ServerLink::new(address);
link.channel = (!names.is_empty()).then(|| join_channel_path(names));
assert_eq!(link.to_url(), url);
assert_eq!(Link::parse(url), Some(Link::Server(link.clone())), "{url}");
assert_eq!(link.address(), address.trim());
if let Some(path) = &link.channel {
assert_eq!(split_channel_path(path), names);
}
}
}
}
-54
View File
@@ -1,54 +0,0 @@
//! Percent escapes in links: file links ([`crate::FileRef`]) and server
//! links ([`crate::Link`]).
/// `%XX` escapes to bytes, read as UTF-8 (a `+` stays: file names and
/// passwords keep theirs).
pub(crate) fn decode(s: &str) -> String {
let bytes = s.as_bytes();
let hex = |b: u8| (b as char).to_digit(16);
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let (Some(h), Some(l)) =
(bytes.get(i + 1).and_then(|b| hex(*b)), bytes.get(i + 2).and_then(|b| hex(*b)))
{
out.push((h * 16 + l) as u8);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// Every byte but letters, digits and `-._~` as `%XX`.
pub(crate) fn encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes() {
assert_eq!(decode("Raid%20Night"), "Raid Night");
assert_eq!(decode("%C3%84b"), "Äb");
assert_eq!(decode("a+b"), "a+b");
// A broken escape stays as it is.
assert_eq!(decode("100%"), "100%");
assert_eq!(decode("%zz"), "%zz");
assert_eq!(encode("Chill & Co/Ä"), "Chill%20%26%20Co%2F%C3%84");
assert_eq!(decode(&encode("a b+c%")), "a b+c%");
}
}
-493
View File
@@ -1,493 +0,0 @@
//! Who is where: channels and the clients in them.
//!
//! The same model is fed from a voice connection, a query session or a
//! gateway. Sources send a [`PresenceSnapshot`] followed by
//! [`PresenceDelta`]s; sources that can only poll use [`Presence::diff`].
//!
//! A voice connection also knows the server's details (welcome message,
//! host banner, …) and its server and channel groups ([`Presence::server`],
//! [`Presence::server_groups`], [`Presence::channel_groups`]); snapshots and
//! deltas do not carry them (other sources leave them empty).
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::server::{BannerMode, ServerDetails};
pub type ChannelId = u64;
pub type ClientId = u16;
/// A server or channel group id.
pub type GroupId = u64;
fn is_zero_i32(n: &i32) -> bool {
*n == 0
}
fn is_zero_u32(n: &u32) -> bool {
*n == 0
}
fn is_false(b: &bool) -> bool {
!*b
}
fn is_default<T: Default + PartialEq>(v: &T) -> bool {
*v == T::default()
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelInfo {
pub id: ChannelId,
/// `0` for top-level channels.
pub parent: ChannelId,
/// Id of the sibling directly above, `0` for the first.
pub order: ChannelId,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub topic: Option<String>,
#[serde(default)]
pub has_password: bool,
/// `None` means unlimited.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_clients: Option<i32>,
#[serde(default)]
pub needed_subscribe_power: i32,
#[serde(default)]
pub needed_talk_power: i32,
#[serde(default)]
pub is_default: bool,
/// Icon id (`channel_icon_id`); 0: none.
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub icon: u32,
/// The address of the channel's banner picture (TeamSpeak 6,
/// `channel_banner_gfx_url`), drawn behind the channel.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub banner_gfx_url: Option<String>,
#[serde(default, skip_serializing_if = "is_default")]
pub banner_mode: BannerMode,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClientInfo {
pub id: ClientId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uid: Option<String>,
pub nickname: String,
pub channel: ChannelId,
/// ServerQuery clients (bots, our own relays). UIs normally hide them.
#[serde(default)]
pub is_query: bool,
/// Away, with the away message (empty without one); `None`: not away.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub away: Option<String>,
#[serde(default)]
pub input_muted: bool,
#[serde(default)]
pub output_muted: bool,
/// `None` when the source cannot tell (query sessions see no voice).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub talking: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub streaming: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub server_groups: Vec<GroupId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
/// MD5 hash of the client's avatar (`client_flag_avatar`, hex); `None`:
/// no avatar. A new hash means a new avatar.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub avatar: Option<String>,
/// The myTeamSpeak avatar's picture (TeamSpeak 6, an HTTPS link from
/// `client_myteamspeak_avatar`, [`myts_avatar_url`]): shown where the
/// server has no avatar for the client.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub myts_avatar: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "is_zero_i32")]
pub talk_power: i32,
/// Allowed to talk regardless of talk power (`client_is_talker`).
#[serde(default, skip_serializing_if = "is_false")]
pub talker: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel_group: Option<GroupId>,
/// Badge GUIDs, in display order ([`shown_badges`]).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub badges: Vec<String>,
/// Icon id (`client_icon_id`); 0: none.
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub icon: u32,
#[serde(default, skip_serializing_if = "is_false")]
pub recording: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub priority_speaker: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub channel_commander: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub database_id: Option<u64>,
}
/// Badge GUIDs of a `client_badges` value
/// (`Overwolf=0:badges=<guid>,<guid>`).
pub fn parse_badges(value: &str) -> Vec<String> {
value
.split(':')
.filter_map(|part| part.strip_prefix("badges="))
.flat_map(|list| list.split(','))
.map(str::trim)
.filter(|g| !g.is_empty())
.map(str::to_owned)
.collect()
}
/// The badges a client shows: those a TeamSpeak 6 server verified
/// (`client_signed_badges`, ids joined by `,`) first, then those of its
/// `client_badges` ([`parse_badges`]), each once.
pub fn shown_badges(badges: &str, signed: &str) -> Vec<String> {
let signed = signed.split(',').map(str::trim).filter(|g| !g.is_empty()).map(str::to_owned);
let mut shown: Vec<String> = Vec::new();
for guid in signed.chain(parse_badges(badges)) {
if !shown.iter().any(|g| g.eq_ignore_ascii_case(&guid)) {
shown.push(guid);
}
}
shown
}
/// The picture to show of a `client_myteamspeak_avatar` value (TeamSpeak
/// 6): `<state>,<url>;<state>,<url>…`, states as myTeamSpeak's
/// `AvatarState` (1 do not disturb, 2 online, 3 away, 4 offline). As the
/// official client reads it: an entry that is not `<number>,<url>` (an
/// empty one too, from a trailing `;`) makes the whole value no avatar;
/// the "online" picture is shown whatever the client's state (an unknown
/// state counts as online), else away, do not disturb, offline, the first
/// of a kind. Only an HTTPS link of at most 4 KiB.
pub fn myts_avatar_url(value: &str) -> Option<String> {
let mut best: Option<(u8, &str)> = None;
for entry in value.split(';') {
let mut parts = entry.split(',');
let state: u32 = parts.next()?.trim().parse().ok()?;
let url = parts.next()?.trim();
let rank = match state {
3 => 1,
1 => 2,
4 => 3,
_ => 0,
};
if best.is_none_or(|(r, _)| rank < r) {
best = Some((rank, url));
}
}
let url = best?.1;
(url.starts_with("https://") && url.len() <= 4096).then(|| url.to_owned())
}
/// How a group's name is shown next to its members.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GroupNamingMode {
#[default]
None,
/// Before the nickname: `[Admin] Alice`.
Before,
/// After the nickname: `Alice [Admin]`.
After,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GroupType {
/// For new virtual servers; nobody is a member.
Template,
#[default]
Regular,
/// ServerQuery clients.
Query,
}
/// A server or channel group.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GroupInfo {
pub id: GroupId,
pub name: String,
/// Icon id; 0: none.
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub icon: u32,
/// Display order: lower first, then by id.
#[serde(default)]
pub sort_id: i32,
#[serde(default)]
pub naming_mode: GroupNamingMode,
#[serde(default)]
pub group_type: GroupType,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PresenceSnapshot {
pub server_name: String,
pub channels: Vec<ChannelInfo>,
pub clients: Vec<ClientInfo>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PresenceDelta {
ChannelAdded(ChannelInfo),
ChannelChanged(ChannelInfo),
ChannelRemoved { id: ChannelId },
ClientJoined(ClientInfo),
ClientChanged(ClientInfo),
ClientMoved { id: ClientId, channel: ChannelId },
ClientLeft { id: ClientId },
ServerRenamed { name: String },
}
/// Current state; apply deltas as they arrive.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Presence {
pub server_name: String,
pub channels: BTreeMap<ChannelId, ChannelInfo>,
pub clients: BTreeMap<ClientId, ClientInfo>,
/// What the source knows about the server (a voice connection: all of
/// it; other sources: nothing).
pub server: ServerDetails,
pub server_groups: BTreeMap<GroupId, GroupInfo>,
pub channel_groups: BTreeMap<GroupId, GroupInfo>,
}
impl Presence {
pub fn from_snapshot(s: PresenceSnapshot) -> Self {
Self {
server_name: s.server_name,
channels: s.channels.into_iter().map(|c| (c.id, c)).collect(),
clients: s.clients.into_iter().map(|c| (c.id, c)).collect(),
..Self::default()
}
}
/// The client with this unique id, if present (the first of several
/// connections with the same identity).
pub fn client_by_uid(&self, uid: &str) -> Option<&ClientInfo> {
self.clients.values().find(|c| c.uid.as_deref() == Some(uid))
}
/// Groups in display order (sort id, then id).
pub fn sorted_groups(groups: &BTreeMap<GroupId, GroupInfo>) -> Vec<&GroupInfo> {
let mut sorted: Vec<_> = groups.values().collect();
sorted.sort_by_key(|g| (g.sort_id, g.id));
sorted
}
pub fn snapshot(&self) -> PresenceSnapshot {
PresenceSnapshot {
server_name: self.server_name.clone(),
channels: self.channels.values().cloned().collect(),
clients: self.clients.values().cloned().collect(),
}
}
/// Apply a delta. Returns `false` if it referred to something unknown
/// (the caller may want to resynchronise).
pub fn apply(&mut self, delta: &PresenceDelta) -> bool {
match delta {
PresenceDelta::ChannelAdded(c) | PresenceDelta::ChannelChanged(c) => {
self.channels.insert(c.id, c.clone());
true
}
PresenceDelta::ChannelRemoved { id } => self.channels.remove(id).is_some(),
PresenceDelta::ClientJoined(c) | PresenceDelta::ClientChanged(c) => {
self.clients.insert(c.id, c.clone());
true
}
PresenceDelta::ClientMoved { id, channel } => match self.clients.get_mut(id) {
Some(c) => {
c.channel = *channel;
true
}
None => false,
},
PresenceDelta::ClientLeft { id } => self.clients.remove(id).is_some(),
PresenceDelta::ServerRenamed { name } => {
self.server_name = name.clone();
true
}
}
}
/// Deltas that turn `self` into `new`, for sources that poll.
pub fn diff(&self, new: &Presence) -> Vec<PresenceDelta> {
let mut out = Vec::new();
if self.server_name != new.server_name {
out.push(PresenceDelta::ServerRenamed { name: new.server_name.clone() });
}
for (id, c) in &new.channels {
match self.channels.get(id) {
None => out.push(PresenceDelta::ChannelAdded(c.clone())),
Some(old) if old != c => out.push(PresenceDelta::ChannelChanged(c.clone())),
_ => {}
}
}
for (id, c) in &new.clients {
match self.clients.get(id) {
None => out.push(PresenceDelta::ClientJoined(c.clone())),
Some(old) if old == c => {}
Some(old) if ClientInfo { channel: c.channel, ..old.clone() } == *c => {
out.push(PresenceDelta::ClientMoved { id: *id, channel: c.channel });
}
Some(_) => out.push(PresenceDelta::ClientChanged(c.clone())),
}
}
for id in self.clients.keys().filter(|id| !new.clients.contains_key(id)) {
out.push(PresenceDelta::ClientLeft { id: *id });
}
// Channels last, so clients leave a removed channel first.
for id in self.channels.keys().filter(|id| !new.channels.contains_key(id)) {
out.push(PresenceDelta::ChannelRemoved { id: *id });
}
out
}
/// Clients in a channel, excluding query clients.
pub fn members(&self, channel: ChannelId) -> impl Iterator<Item = &ClientInfo> {
self.clients.values().filter(move |c| c.channel == channel && !c.is_query)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ch(id: u64, name: &str) -> ChannelInfo {
ChannelInfo { id, name: name.into(), ..Default::default() }
}
fn cl(id: u16, name: &str, channel: u64) -> ClientInfo {
ClientInfo { id, nickname: name.into(), channel, ..Default::default() }
}
fn presence(channels: Vec<ChannelInfo>, clients: Vec<ClientInfo>) -> Presence {
Presence::from_snapshot(PresenceSnapshot { server_name: "s".into(), channels, clients })
}
#[test]
fn diff_then_apply_reaches_target() {
let old = presence(
vec![ch(1, "Lobby"), ch(2, "Games")],
vec![cl(1, "Alice", 1), cl(2, "Bob", 1), cl(3, "Carol", 2)],
);
let mut muted = cl(2, "Bob", 1);
muted.input_muted = true;
let new = presence(
vec![ch(1, "Lobby"), ch(3, "New")],
vec![cl(1, "Alice", 3), muted, cl(4, "Dave", 1)],
);
let deltas = old.diff(&new);
assert!(deltas.contains(&PresenceDelta::ClientMoved { id: 1, channel: 3 }));
assert!(deltas.contains(&PresenceDelta::ClientLeft { id: 3 }));
assert!(deltas.contains(&PresenceDelta::ChannelRemoved { id: 2 }));
assert!(deltas.iter().any(|d| matches!(d, PresenceDelta::ClientChanged(c) if c.id == 2)));
let mut state = old.clone();
for d in &deltas {
assert!(state.apply(d));
}
assert_eq!(state, new);
assert!(new.diff(&new).is_empty());
}
#[test]
fn myts_avatars_as_the_official_client_reads_them() {
let on = "https://a.example.test/on.png";
assert_eq!(myts_avatar_url(&format!("3,https://a/away;2,{on}")).as_deref(), Some(on));
// Away before do not disturb before offline; the first of a kind.
assert_eq!(
myts_avatar_url("4,https://a/off;1,https://a/dnd;3,https://a/away;3,https://a/b")
.as_deref(),
Some("https://a/away")
);
assert_eq!(
myts_avatar_url("1,https://a/dnd;4,https://a/off").as_deref(),
Some("https://a/dnd")
);
// An unknown state counts as online.
assert_eq!(
myts_avatar_url("3,https://a/away;9,https://a/x").as_deref(),
Some("https://a/x")
);
// One bad entry spoils the value.
for bad in ["", "2", "x,https://a/on", "2,https://a/on;", "2,https://a/on;;3,https://a/b"] {
assert_eq!(myts_avatar_url(bad), None, "{bad:?}");
}
// Only HTTPS, and not endless.
assert_eq!(myts_avatar_url("2,http://a/on"), None);
assert_eq!(myts_avatar_url(&format!("2,https://a/{}", "x".repeat(4096))), None);
// Older JSON without the field still loads.
let client: ClientInfo =
serde_json::from_str(r#"{"id":1,"nickname":"a","channel":1}"#).unwrap();
assert_eq!(client.myts_avatar, None);
}
#[test]
fn badges_and_groups() {
assert_eq!(
parse_badges(
"Overwolf=0:badges=c9e97536-5a2d-4c8e-a135-af404587a472,450f81c1-ab41-4211-a338-222fa94ed157"
),
["c9e97536-5a2d-4c8e-a135-af404587a472", "450f81c1-ab41-4211-a338-222fa94ed157"]
);
assert!(parse_badges("").is_empty());
assert!(parse_badges("Overwolf=1").is_empty());
// TeamSpeak 6's verified badges first, each once.
assert_eq!(
shown_badges(
"Overwolf=0:badges=c9e97536-5a2d-4c8e-a135-af404587a472,450f81c1-ab41-4211-a338-222fa94ed157",
"450F81C1-AB41-4211-A338-222FA94ED157,1cb07348-34a4-4741-b50f-c41e584370f7"
),
[
"450F81C1-AB41-4211-A338-222FA94ED157",
"1cb07348-34a4-4741-b50f-c41e584370f7",
"c9e97536-5a2d-4c8e-a135-af404587a472"
]
);
assert!(shown_badges("", "").is_empty());
let group = |id, sort_id| GroupInfo { id, sort_id, ..Default::default() };
let groups = BTreeMap::from([(1, group(1, 20)), (2, group(2, 10)), (3, group(3, 10))]);
let order: Vec<_> = Presence::sorted_groups(&groups).iter().map(|g| g.id).collect();
assert_eq!(order, [2, 3, 1]);
let mut alice = cl(1, "Alice", 1);
alice.uid = Some("A=".into());
let p = presence(vec![ch(1, "Lobby")], vec![alice, cl(2, "Bob", 1)]);
assert_eq!(p.client_by_uid("A=").map(|c| c.id), Some(1));
assert!(p.client_by_uid("B=").is_none());
}
#[test]
fn old_json_without_new_fields() {
let c: ClientInfo =
serde_json::from_str(r#"{"id":1,"nickname":"a","channel":2,"away":""}"#).unwrap();
assert_eq!(c.away.as_deref(), Some(""));
assert_eq!((c.talk_power, c.avatar.as_ref(), c.badges.len()), (0, None, 0));
// Defaults stay off the wire.
assert_eq!(
serde_json::to_string(&cl(1, "a", 2)).unwrap(),
r#"{"id":1,"nickname":"a","channel":2,"is_query":false,"input_muted":false,"output_muted":false}"#
);
}
#[test]
fn members_skip_query_clients() {
let mut bot = cl(9, "bot", 1);
bot.is_query = true;
let p = presence(vec![ch(1, "Lobby")], vec![cl(1, "Alice", 1), bot]);
assert_eq!(p.members(1).count(), 1);
}
#[test]
fn delta_json_is_tagged() {
let json =
serde_json::to_string(&PresenceDelta::ClientMoved { id: 1, channel: 3 }).unwrap();
assert_eq!(json, r#"{"kind":"client_moved","id":1,"channel":3}"#);
let back: PresenceDelta = serde_json::from_str(&json).unwrap();
assert_eq!(back, PresenceDelta::ClientMoved { id: 1, channel: 3 });
}
}
-250
View File
@@ -1,250 +0,0 @@
//! Server software detection and the capabilities that follow from it.
use std::fmt;
use serde::{Deserialize, Serialize};
/// Parsed `virtualserver_version`, e.g. `3.13.8 [Build: 1779874471]` or
/// `6.0.0-beta13.1 [Build: 1790080330]`.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ServerVersion {
pub major: u32,
pub minor: u32,
pub patch: u32,
/// Pre-release tag such as `beta13.1`.
pub pre: Option<String>,
/// Build timestamp (seconds since the Unix epoch).
pub build: Option<u64>,
}
impl ServerVersion {
pub fn parse(s: &str) -> Option<Self> {
let s = s.trim();
let (version, rest) = s.split_once(' ').unwrap_or((s, ""));
let build = rest
.trim()
.strip_prefix("[Build:")
.and_then(|b| b.strip_suffix(']'))
.and_then(|b| b.trim().parse().ok());
let (numbers, pre) = match version.split_once('-') {
Some((n, p)) => (n, Some(p.to_string())),
None => (version, None),
};
let mut parts = numbers.split('.').map(|p| p.parse::<u32>());
let major = parts.next()?.ok()?;
let minor = parts.next().unwrap_or(Ok(0)).ok()?;
let patch = parts.next().unwrap_or(Ok(0)).ok()?;
Some(Self { major, minor, patch, pre, build })
}
}
impl fmt::Display for ServerVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
if let Some(pre) = &self.pre {
write!(f, "-{pre}")?;
}
Ok(())
}
}
/// Which server software we are talking to.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ServerFlavor {
/// TeamSpeak 3 server (3.x).
Ts3(ServerVersion),
/// TeamSpeak 6 server (6.x; TeamSpeak 5 server betas are treated alike).
Ts6(ServerVersion),
/// Unparseable or unexpected version string.
Unknown(String),
}
impl ServerFlavor {
/// Classify a `virtualserver_version` string.
pub fn from_version_string(s: &str) -> Self {
match ServerVersion::parse(s) {
Some(v) if v.major == 3 => ServerFlavor::Ts3(v),
Some(v) if v.major >= 5 => ServerFlavor::Ts6(v),
_ => ServerFlavor::Unknown(s.to_string()),
}
}
pub fn version(&self) -> Option<&ServerVersion> {
match self {
ServerFlavor::Ts3(v) | ServerFlavor::Ts6(v) => Some(v),
ServerFlavor::Unknown(_) => None,
}
}
pub fn capabilities(&self) -> Capabilities {
match self {
ServerFlavor::Ts3(_) => Capabilities {
streams: false,
raw_query: true,
ssh_query: true,
http_query: false,
file_transfer: true,
offline_messages: true,
},
// Verified against 6.0.0-beta13.1: file transfer and offline
// messages work as on TeamSpeak 3.
ServerFlavor::Ts6(_) => Capabilities {
streams: true,
raw_query: false,
ssh_query: true,
http_query: true,
file_transfer: true,
offline_messages: true,
},
ServerFlavor::Unknown(_) => Capabilities::default(),
}
}
}
/// Where the host message shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HostMessageMode {
/// Not shown.
#[default]
None,
/// In the chat log.
Log,
/// In a dialog.
Modal,
/// In a dialog; the connection ends when it is closed.
ModalQuit,
}
/// How a banner picture (the host banner, a TeamSpeak 6 channel banner) is
/// scaled to its area: `0`, `1` and `2` on the wire.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BannerMode {
/// As it is.
#[default]
NoAdjust,
/// Stretched to the banner area.
IgnoreAspect,
/// Scaled to fit, keeping its aspect ratio.
KeepAspect,
}
impl BannerMode {
/// From its number on the wire; an unknown one shows the picture as it
/// is.
pub fn from_wire(value: &str) -> Self {
match value.trim() {
"1" => Self::IgnoreAspect,
"2" => Self::KeepAspect,
_ => Self::NoAdjust,
}
}
}
/// What a server tells its (voice) clients about itself.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServerDetails {
pub name: String,
/// `virtualserver_unique_identifier` (the key of its chat history).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uid: Option<String>,
#[serde(default)]
pub welcome_message: String,
#[serde(default)]
pub host_message: String,
#[serde(default)]
pub host_message_mode: HostMessageMode,
/// Where a click on the banner leads.
#[serde(default)]
pub banner_url: String,
/// The banner image.
#[serde(default)]
pub banner_gfx_url: String,
/// Reload the banner image this often (seconds); 0: never.
#[serde(default)]
pub banner_gfx_interval_s: u64,
#[serde(default)]
pub banner_mode: BannerMode,
#[serde(default)]
pub host_button_tooltip: String,
#[serde(default)]
pub host_button_url: String,
/// The host button's image.
#[serde(default)]
pub host_button_gfx_url: String,
/// Icon id (`virtualserver_icon_id`); 0: none.
#[serde(default)]
pub icon: u32,
/// Server platform, e.g. `Linux`.
#[serde(default)]
pub platform: String,
/// `virtualserver_version`, e.g. `3.13.8 [Build: 1779874471]`.
#[serde(default)]
pub version: String,
#[serde(default)]
pub max_clients: u16,
/// How much everyone else is dimmed while a priority speaker talks
/// (dB, e.g. -18; `virtualserver_priority_speaker_dimm_modificator`,
/// rounded).
#[serde(default)]
pub priority_speaker_dimm_db: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_server_group: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_channel_group: Option<u64>,
}
/// Features that depend on the server software.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Capabilities {
/// Screen sharing / video streams (TeamSpeak 6).
pub streams: bool,
/// Raw TCP ServerQuery (TeamSpeak 3 only; may still be disabled by the admin).
pub raw_query: bool,
/// SSH ServerQuery.
pub ssh_query: bool,
/// HTTP WebQuery (TeamSpeak 6), request/response only, no events.
pub http_query: bool,
/// Channel file browsers, avatars and icons (`ftinit*` over TCP).
#[serde(default)]
pub file_transfer: bool,
/// Offline messages to a unique id (`messageadd`, `messagelist`, …).
#[serde(default)]
pub offline_messages: bool,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_ts3() {
let v = ServerVersion::parse("3.13.8 [Build: 1779874471]").unwrap();
assert_eq!((v.major, v.minor, v.patch), (3, 13, 8));
assert_eq!(v.pre, None);
assert_eq!(v.build, Some(1_779_874_471));
let flavor = ServerFlavor::from_version_string("3.13.8 [Build: 1779874471]");
assert!(matches!(flavor, ServerFlavor::Ts3(_)));
assert!(!flavor.capabilities().streams);
}
#[test]
fn parses_ts6_beta() {
let s = "6.0.0-beta13.1 [Build: 1790080330]";
let v = ServerVersion::parse(s).unwrap();
assert_eq!(v.pre.as_deref(), Some("beta13.1"));
assert_eq!(v.to_string(), "6.0.0-beta13.1");
let flavor = ServerFlavor::from_version_string(s);
assert!(matches!(flavor, ServerFlavor::Ts6(_)));
assert!(flavor.capabilities().streams);
assert!(!flavor.capabilities().raw_query);
}
#[test]
fn handles_garbage() {
assert!(matches!(ServerFlavor::from_version_string(""), ServerFlavor::Unknown(_)));
assert!(matches!(ServerFlavor::from_version_string("x.y"), ServerFlavor::Unknown(_)));
assert_eq!(ServerVersion::parse("3").unwrap().minor, 0);
}
}
-192
View File
@@ -1,192 +0,0 @@
//! Flatten presence into display rows in TeamSpeak's channel order, and
//! read the names of spacer channels.
use std::collections::HashMap;
use crate::presence::{ChannelId, ChannelInfo, ClientInfo, Presence};
/// One line of a channel tree.
#[derive(Clone, Debug, PartialEq)]
pub enum TreeRow<'a> {
Channel { depth: usize, channel: &'a ChannelInfo },
Client { depth: usize, client: &'a ClientInfo },
}
/// Sort siblings by following the `order` links (each channel names the
/// sibling directly above it). Channels whose predecessor is missing are
/// appended at the end, sorted by id, so nothing is ever dropped.
pub fn order_siblings(mut siblings: Vec<&ChannelInfo>) -> Vec<&ChannelInfo> {
siblings.sort_by_key(|c| c.id);
let mut by_prev: HashMap<ChannelId, &ChannelInfo> = HashMap::new();
for c in &siblings {
by_prev.entry(c.order).or_insert(c);
}
let mut sorted = Vec::with_capacity(siblings.len());
let mut prev = 0;
while let Some(c) = by_prev.remove(&prev) {
sorted.push(c);
prev = c.id;
}
for c in siblings {
if !sorted.iter().any(|s| s.id == c.id) {
sorted.push(c);
}
}
sorted
}
/// Channels and their (non-query) clients, depth-first. Clients are sorted by
/// name; `collapsed` channels hide their sub-channels and clients.
pub fn tree_rows<'a>(p: &'a Presence, collapsed: &dyn Fn(ChannelId) -> bool) -> Vec<TreeRow<'a>> {
let mut rows = Vec::new();
add_level(p, 0, 0, collapsed, &mut rows);
rows
}
fn add_level<'a>(
p: &'a Presence,
parent: ChannelId,
depth: usize,
collapsed: &dyn Fn(ChannelId) -> bool,
rows: &mut Vec<TreeRow<'a>>,
) {
let siblings = order_siblings(p.channels.values().filter(|c| c.parent == parent).collect());
for channel in siblings {
rows.push(TreeRow::Channel { depth, channel });
if collapsed(channel.id) {
continue;
}
let mut members: Vec<_> = p.members(channel.id).collect();
members.sort_by(|a, b| a.nickname.to_lowercase().cmp(&b.nickname.to_lowercase()));
for client in members {
rows.push(TreeRow::Client { depth: depth + 1, client });
}
add_level(p, channel.id, depth + 1, collapsed, rows);
}
}
/// How a TeamSpeak spacer channel draws its text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Spacer {
Left,
Center,
Right,
/// The text repeated across the row: a line such as `---`.
Fill,
}
impl Spacer {
/// Whether a spacer with this text only separates the rows around it
/// (a line, or no text): nothing to search for or pick.
pub fn separates(self, text: &str) -> bool {
self == Spacer::Fill || text.trim().is_empty()
}
}
/// A spacer name split into its kind and its text: `[cspacer]Games` is a
/// centred "Games", `[*spacer1]-=` repeats "-=", plain `[spacer3]` is an
/// empty row. The part between `spacer` and `]` only keeps the names
/// unique, so anything goes there. Anything else is not a spacer.
pub fn parse_spacer(name: &str) -> Option<(Spacer, &str)> {
let (inside, text) = name.strip_prefix('[')?.split_once(']')?;
let (kind, _suffix) = inside.split_once("spacer")?;
let kind = match kind {
"" | "l" => Spacer::Left,
"c" => Spacer::Center,
"r" => Spacer::Right,
"*" => Spacer::Fill,
_ => return None,
};
Some((kind, text))
}
/// A channel's name as shown, and its spacer kind. Only top-level channels
/// are spacers, as in TeamSpeak: a sub-channel keeps its name as it is.
/// Names sent to the server (joining by name, invite links) stay raw.
pub fn channel_title(channel: &ChannelInfo) -> (&str, Option<Spacer>) {
match parse_spacer(&channel.name).filter(|_| channel.parent == 0) {
Some((kind, text)) => (text, Some(kind)),
None => (&channel.name, None),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::presence::PresenceSnapshot;
fn ch(id: u64, parent: u64, order: u64, name: &str) -> ChannelInfo {
ChannelInfo { id, parent, order, name: name.into(), ..Default::default() }
}
fn cl(id: u16, name: &str, channel: u64) -> ClientInfo {
ClientInfo { id, nickname: name.into(), channel, ..Default::default() }
}
#[test]
fn follows_order_links() {
let channels = [ch(5, 0, 3, "c"), ch(3, 0, 7, "b"), ch(7, 0, 0, "a")];
let names: Vec<_> =
order_siblings(channels.iter().collect()).iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, ["a", "b", "c"]);
let broken = [ch(1, 0, 0, "a"), ch(2, 0, 99, "orphan")];
assert_eq!(order_siblings(broken.iter().collect())[1].name, "orphan");
}
#[test]
fn rows_depth_first_with_collapse() {
let mut bot = cl(9, "bot", 1);
bot.is_query = true;
let p = Presence::from_snapshot(PresenceSnapshot {
server_name: "s".into(),
channels: vec![ch(1, 0, 0, "Lobby"), ch(2, 0, 1, "Games"), ch(3, 2, 0, "Squad")],
clients: vec![cl(1, "zed", 1), cl(2, "Alice", 1), bot, cl(3, "Bob", 3)],
});
let describe = |rows: Vec<TreeRow>| -> Vec<String> {
rows.iter()
.map(|r| match r {
TreeRow::Channel { depth, channel } => format!("{depth}#{}", channel.name),
TreeRow::Client { depth, client } => format!("{depth}-{}", client.nickname),
})
.collect()
};
assert_eq!(
describe(tree_rows(&p, &|_| false)),
["0#Lobby", "1-Alice", "1-zed", "0#Games", "1#Squad", "2-Bob"]
);
assert_eq!(
describe(tree_rows(&p, &|c| c == 2)),
["0#Lobby", "1-Alice", "1-zed", "0#Games"]
);
}
#[test]
fn spacer_names() {
use Spacer::*;
for (name, spacer) in [
("[spacer0]", Some((Left, ""))),
("[spacer3]Hi", Some((Left, "Hi"))),
("[lspacer]Hi", Some((Left, "Hi"))),
("[rspacer9]Hi", Some((Right, "Hi"))),
("[cspacer]Hi", Some((Center, "Hi"))),
("[cspacerx]Hi", Some((Center, "Hi"))),
("[cspacer12]Гамесы [1]", Some((Center, "Гамесы [1]"))),
("[*spacer1]-=", Some((Fill, "-="))),
("[*spacer]", Some((Fill, ""))),
("[cspacer2Games", None),
("Games", None),
("[Spacer]x", None),
("[xspacer]x", None),
("[spacr]x", None),
("x[spacer]", None),
] {
assert_eq!(parse_spacer(name), spacer, "{name}");
}
assert!(Fill.separates("-=") && Left.separates("") && Center.separates(" "));
assert!(!Left.separates("Hi"));
// Only top-level channels are spacers: a sub-channel keeps its name.
assert_eq!(channel_title(&ch(1, 0, 0, "[rspacer]Staff")), ("Staff", Some(Right)));
assert_eq!(channel_title(&ch(2, 1, 0, "[rspacer]Staff")), ("[rspacer]Staff", None));
assert_eq!(channel_title(&ch(3, 0, 0, "Lobby")), ("Lobby", None));
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ publish.workspace = true
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt", "sync", "time"] }
tracing = "0.1"
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
voelin-query = { path = "../voelin-query" }
[dev-dependencies]
+2
View File
@@ -19,7 +19,9 @@ rusqlite = { version = "0.40.2", features = ["bundled"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
thiserror = "2.0.21"
tracing = "0.1.44"
tsclientlib = { path = "../proto/tsclientlib" }
voelin-identity = { workspace = true }
[lints]
workspace = true
+587
View File
@@ -0,0 +1,587 @@
//! The `identities` table as a [`voelin_identity::KeyStore`].
//!
//! The table holds identities of more than one kind: the TeamSpeak identities
//! the client has always had (`kind` `teamspeak`, `data` the JSON of a
//! `tsproto::Identity`), a Voelin key (`voelin`), the record of the account the
//! installation is signed in to (`account`) and whatever kind a later version
//! adds, which passes through untouched. A row is addressed by its
//! `(kind, uid)`, and `uid` stays `UNIQUE` across kinds: the uid forms of the
//! kinds do not overlap (a TeamSpeak uid is base64, a Voelin uid 52 characters
//! of `a-z2-7`, an account uid is written `account:<uid>`).
//!
//! Besides the blob a row carries the columns of the TeamSpeak-only world,
//! which a [`KeyStore`] does not see and keeps when it replaces a row: `name`,
//! `origin`, `is_default` and `created`. A blob of a new `(kind, uid)` becomes a
//! row named after its uid, of origin `user` and not the default.
//!
//! The TeamSpeak security level is not stored: it is computed from the key and
//! counter in `data`, as [`Store::identities`] always did, and the level of a
//! blob a caller puts is ignored. A TeamSpeak row whose JSON cannot be read
//! (it could only have been damaged outside this crate) lists and reads with
//! level 0 instead of failing the whole list, and a [`KeyStore::put`] that only
//! changes the binding of a row (the row of that `(kind, uid)` already holds
//! that `data`, as [`KeyStore::get`] reads it) writes the four binding columns,
//! does not look at `data` again and does not rewrite it. That is how
//! [`KeyStore::sign_out`] unbinds a device-only secret: a row whose `data` was
//! damaged outside this crate (JSON that is no identity, a BLOB, bytes that are
//! no UTF-8) does not keep the sign-out from unbinding it, and its `data` is
//! kept byte for byte.
//!
//! A row that is damaged elsewhere never fails a call that is not about it. A
//! row whose binding columns cannot be read (`synced = 2`, an `account` that is
//! no uid, a revision that is no integer; only something outside this crate
//! writes them) is listed and read as unbound, and a warning names the row and
//! the reason. [`KeyStore::list`] fails only when the database does, because
//! the trait's [`KeyStore::sign_out`] starts with it and then reads the account
//! record and the device key with [`KeyStore::get`]: one damaged row, the
//! record's own included, would otherwise keep a sign-out from ever finishing,
//! and with it the deletion of the key the user asked to forget. Unbound is the
//! reading that never deletes on a guess: a sign-out neither deletes such a row
//! as a synced copy nor writes it, it stays as it is until a `put` of it writes
//! four good binding columns. A `data` column that is not text (a BLOB, or text
//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so
//! that a record that cannot be read is deleted by the sign-out, as the trait
//! says, instead of its read failing. A [`KeyStore::put`] of the text that
//! [`KeyStore::get`] returned for such a row is taken for the data that is
//! there: it changes the binding and keeps the stored bytes, where any other
//! text replaces them (a TeamSpeak blob still has to be an identity). A row
//! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it
//! out with a warning.
//!
//! The rows are private keys, so a removed row is not left behind in the file:
//! every connection sets `secure_delete`, which makes SQLite overwrite what it
//! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as
//! [`Store::delete_identity`] does, so that the frame of the log that held the
//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with
//! `remove`, truncates the log once, after its last step, not after each
//! removal. The checkpoint waits for another connection for a moment at most
//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it,
//! and then the removal still succeeds and a warning says that the deleted
//! bytes may stay in the log file, until a later checkpoint truncates the log,
//! later writes overwrite those frames, or the last connection to the database
//! closes and the log is deleted.
//!
//! The device key is never a synced copy. The account record names the Voelin key
//! that is the installation's device key, and [`KeyStore::sign_out`] deletes
//! every identity bound with `synced = true` in its first step, before it reads
//! the record, so a key stored that way would be deleted whatever the record
//! says (a key that predates the account is to be kept). The store therefore
//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob
//! with `synced = true` while an account record names its uid as the device, or
//! while a record cannot be read, because then it cannot tell; and a put of an
//! account record that names a key which is stored as a synced copy. A binding
//! with `synced = false` is accepted: a sign-out unbinds such a key and then
//! follows the record. The check and the write are done under the store's lock;
//! a second process writing the same file at the same moment is not covered.
//!
//! A TeamSpeak blob that is refused says why in words that carry none of its
//! input: its `data` is the identity's private key, and an error reaches log
//! lines.
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, MutexGuard, PoisonError};
use rusqlite::types::ValueRef;
use rusqlite::{OptionalExtension, params};
use tsclientlib::Identity;
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
use voelin_identity::{
AccountBinding, BindingColumns, BlobError, DeviceKeyChoice, IdentityBlob, IdentityInfo,
KIND_ACCOUNT, KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, SignOut, Uid,
};
use crate::{Error, Result, Store};
/// A result of the key store seam.
type KsResult<T> = std::result::Result<T, KeyStoreError>;
/// The rows of [`KeyStore::list`]. The secret of a kind this crate does not
/// interpret is never read; a TeamSpeak row's `data` is, for its level.
const LIST: &str = "SELECT kind, uid, CASE WHEN kind = 'teamspeak' THEN data END,
account, integration, integration_rev, synced, id
FROM identities ORDER BY kind, uid";
/// Replace the binding of the row of this `(kind, uid)` if its `data` is
/// exactly the blob's: nothing else of the row is written.
const REBIND: &str = "UPDATE identities
SET account = ?4, integration = ?5, integration_rev = ?6, synced = ?7
WHERE kind = ?1 AND uid = ?2 AND data = ?3";
/// [`REBIND`] for a row whose `data` is not text and reads, as [`lossy_text`]
/// reads it, as the blob's: the same four columns, and the stored bytes stay.
const REBIND_BYTES: &str = "UPDATE identities
SET account = ?3, integration = ?4, integration_rev = ?5, synced = ?6
WHERE kind = ?1 AND uid = ?2";
/// Insert the blob, or replace the row of the same uid if it is of the same
/// kind. A row of another kind is left alone: the statement then changes
/// nothing, which `put` reports.
const PUT: &str = "INSERT INTO identities
(name, uid, data, kind, account, integration, integration_rev, synced)
VALUES (?1, ?1, ?2, ?3, ?4, ?5, ?6, ?7)
ON CONFLICT (uid) DO UPDATE SET
data = excluded.data, account = excluded.account,
integration = excluded.integration, integration_rev = excluded.integration_rev,
synced = excluded.synced
WHERE identities.kind = excluded.kind";
/// The identities of a client database as a [`KeyStore`]: every kind, with its
/// account binding.
///
/// It owns a [`Store`] behind a mutex, because a [`KeyStore`] is `Sync` and a
/// SQLite connection is not. Open it on the database file next to the
/// other connections of the app (the settings writer and the chat history do
/// the same): SQLite lets them share the file. [`Self::with_store`] gives
/// access to the TeamSpeak methods of the same connection.
///
/// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as
/// `voelin-identity` defines them, on top of the five methods here; the
/// sign-out only truncates the write-ahead log once, at its end.
pub struct SqliteKeyStore {
store: Mutex<Store>,
}
impl SqliteKeyStore {
/// The identities of an open [`Store`].
pub fn new(store: Store) -> Self {
Self { store: Mutex::new(store) }
}
/// Open or create the database at `path`, migrating it.
pub fn open(path: &Path) -> Result<Self> {
Ok(Self::new(Store::open(path)?))
}
/// A key store in memory: for tests.
pub fn open_in_memory() -> Result<Self> {
Ok(Self::new(Store::open_in_memory()?))
}
/// Run `f` on the [`Store`] behind this key store, holding its lock: the
/// TeamSpeak identity methods (`identities`, `default_identity`, ...) see
/// the same rows on the same connection.
pub fn with_store<R>(&self, f: impl FnOnce(&Store) -> R) -> R {
f(&self.lock())
}
fn lock(&self) -> MutexGuard<'_, Store> {
// A panic in another thread cannot leave the table half-updated: every
// write here is one statement, and `put` tries a second one only when
// the first changed nothing.
self.store.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl KeyStore for SqliteKeyStore {
fn list(&self) -> KsResult<Vec<IdentityInfo>> {
let store = self.lock();
let mut statement = store.db.prepare_cached(LIST).map_err(backend)?;
let rows = statement.query_map([], Columns::read).map_err(backend)?;
let mut infos = Vec::new();
for row in rows {
infos.extend(row.map_err(backend)?.map(Columns::into_info));
}
Ok(infos)
}
fn get(&self, kind: &str, uid: &str) -> KsResult<Option<IdentityBlob>> {
let store = self.lock();
let sql = format!(
"SELECT {SELECT_ACCOUNT_COLUMNS}, id FROM identities WHERE kind = ?1 AND uid = ?2"
);
let mut statement = store.db.prepare_cached(&sql).map_err(backend)?;
let mut rows = statement.query_map(params![kind, uid], Columns::read).map_err(backend)?;
Ok(rows.next().transpose().map_err(backend)?.flatten().map(Columns::into_blob))
}
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
let columns = blob.binding_columns()?;
let store = self.lock();
match blob.kind.as_str() {
KIND_VOELIN if blob.binding.is_some_and(|binding| binding.synced) => {
refuse_synced_device_key(&store, &blob.uid)?;
}
KIND_ACCOUNT => refuse_record_of_synced_key(&store, blob)?,
_ => {}
}
// A row that already holds this data changes its binding and nothing
// else, and is not checked again: it may have been damaged outside this
// crate, and a sign-out still has to unbind it. "Holds this data" is
// meant as `get` reads it: for a `data` that is not text, `get` hands out
// the text with the odd bytes replaced, `REBIND` cannot match that, and
// the second statement takes the blob for the data that is there.
let rebound = store
.db
.prepare_cached(REBIND)
.map_err(backend)?
.execute(params![
blob.kind,
blob.uid,
blob.json,
columns.account,
columns.integration,
columns.rev,
columns.synced,
])
.map_err(backend)?;
if rebound > 0 || rebind_stored_bytes(&store, blob, &columns)? {
return Ok(());
}
if blob.kind == KIND_TEAMSPEAK {
check_teamspeak(blob)?;
}
let changed = store
.db
.prepare_cached(PUT)
.map_err(backend)?
.execute(params![
blob.uid,
blob.json,
blob.kind,
columns.account,
columns.integration,
columns.rev,
columns.synced,
])
.map_err(backend)?;
if changed == 0 {
let held_by: String = store
.db
.query_row("SELECT kind FROM identities WHERE uid = ?1", [&blob.uid], |r| r.get(0))
.map_err(backend)?;
return Err(KeyStoreError::backend(Refused::UidHeld {
uid: blob.uid.clone(),
kind: held_by,
}));
}
Ok(())
}
fn remove(&self, kind: &str, uid: &str) -> KsResult<bool> {
let store = self.lock();
let removed = delete_row(&store, kind, uid)?;
if removed {
// The row may be a key: leave nothing of it in the log either.
store.truncate_wal();
}
Ok(removed)
}
/// The trait's sign-out, with the log truncated once after its last step
/// instead of after each of its removals: it removes up to a handful of
/// rows, and a checkpoint that another connection blocks costs a moment
/// (`Store::truncate_wal`) each time. The steps are the trait's own; they
/// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves
/// the checkpoint to this method.
fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult<SignOut> {
let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) };
let outcome = KeyStore::sign_out(&pass, account, device_key);
// Also after a failure: the removals before it have happened.
if pass.deleted.load(Ordering::Relaxed) {
self.lock().truncate_wal();
}
outcome
}
}
/// Delete the row of this `(kind, uid)`: whether there was one. The rows are
/// overwritten (`secure_delete`); the log is the caller's to truncate.
fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult<bool> {
let removed = store
.db
.prepare_cached("DELETE FROM identities WHERE kind = ?1 AND uid = ?2")
.map_err(backend)?
.execute(params![kind, uid])
.map_err(backend)?;
Ok(removed > 0)
}
/// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same
/// rows, but `remove` only notes that it deleted something, so that the sign-out
/// truncates the log once at its end.
struct SignOutPass<'a> {
store: &'a SqliteKeyStore,
/// Whether a row was deleted.
deleted: AtomicBool,
}
impl KeyStore for SignOutPass<'_> {
fn list(&self) -> KsResult<Vec<IdentityInfo>> {
self.store.list()
}
fn get(&self, kind: &str, uid: &str) -> KsResult<Option<IdentityBlob>> {
self.store.get(kind, uid)
}
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
self.store.put(blob)
}
fn remove(&self, kind: &str, uid: &str) -> KsResult<bool> {
let removed = delete_row(&self.store.lock(), kind, uid)?;
if removed {
self.deleted.store(true, Ordering::Relaxed);
}
Ok(removed)
}
}
/// Change only the binding of the row of the blob's `(kind, uid)` if its `data`
/// is not text but reads as exactly the blob's JSON, and say whether it did.
///
/// [`KeyStore::get`] reads a `data` that is a BLOB, or TEXT of bytes that are no
/// UTF-8, as text with the odd bytes replaced ([`lossy_text`]). The blob that a
/// sign-out puts back to unbind such a row carries that text, so `REBIND` finds
/// nothing, and writing the blob would replace the stored bytes with the
/// replaced text (and refuse a TeamSpeak row, whose replaced text is no
/// identity, for ever). The text `get` handed out is taken for the data that is
/// there, and the bytes are kept.
///
/// It is called after `REBIND` changed nothing, which is why the stored value is
/// known not to be exactly the blob's text. Any other JSON does not match, and
/// is a new identity for the uid as ever.
fn rebind_stored_bytes(
store: &Store,
blob: &IdentityBlob,
columns: &BindingColumns,
) -> KsResult<bool> {
let reads_as_blob = store
.db
.prepare_cached("SELECT data FROM identities WHERE kind = ?1 AND uid = ?2")
.map_err(backend)?
.query_row(params![blob.kind, blob.uid], |row| {
Ok(lossy_text(row.get_ref(0)?).is_some_and(|text| text == blob.json))
})
.optional()
.map_err(backend)?;
if reads_as_blob != Some(true) {
return Ok(false);
}
store
.db
.prepare_cached(REBIND_BYTES)
.map_err(backend)?
.execute(params![
blob.kind,
blob.uid,
columns.account,
columns.integration,
columns.rev,
columns.synced,
])
.map_err(backend)?;
Ok(true)
}
/// A TeamSpeak blob is stored only if it is what its kind says: the JSON of a
/// `tsproto::Identity` whose key has the uid the blob names.
///
/// The first keeps one bad row, which a service or a damaged file could hand
/// over, from failing the list of TeamSpeak identities for everyone. The
/// second keeps a blob from overwriting, by its uid, the key of a different
/// identity that is stored under that uid.
///
/// The parse error of serde is dropped, not forwarded: it can quote the text
/// it choked on, which is a private key, into a log line.
fn check_teamspeak(blob: &IdentityBlob) -> KsResult<()> {
let Ok(identity) = serde_json::from_str::<Identity>(&blob.json) else {
return Err(KeyStoreError::backend(Refused::NotATeamSpeakIdentity));
};
if identity.key().to_pub().get_uid() != blob.uid {
return Err(KeyStoreError::Blob(BlobError::UidMismatch));
}
Ok(())
}
/// Refuse to store the Voelin key `uid` as a synced copy while the device key
/// of the installation, as an account record names it, is this key.
///
/// A record that cannot be read could name it: it is refused then too, because
/// the sign-out that follows would delete the key on that guess.
fn refuse_synced_device_key(store: &Store, uid: &str) -> KsResult<()> {
let mut statement = store
.db
.prepare_cached("SELECT uid, data FROM identities WHERE kind = 'account'")
.map_err(backend)?;
let mut rows = statement.query([]).map_err(backend)?;
while let Some(row) = rows.next().map_err(backend)? {
// A record whose uid is not text cannot be addressed; it is not read.
let Ok(record_uid) = row.get_ref(0).map_err(backend)?.as_str() else { continue };
let data = lossy_text(row.get_ref(1).map_err(backend)?).unwrap_or_default();
match IdentityBlob::new(KIND_ACCOUNT, record_uid, 0, data).account_record() {
Ok(record) if record.device.to_base32() == uid => {
return Err(KeyStoreError::backend(Refused::SyncedDeviceKey {
uid: uid.to_owned(),
record: record_uid.to_owned(),
}));
}
Ok(_) => {}
Err(_) => {
return Err(KeyStoreError::backend(Refused::UnreadableRecord {
uid: uid.to_owned(),
record: record_uid.to_owned(),
}));
}
}
}
Ok(())
}
/// Refuse to store an account record whose device key is stored as a synced
/// copy: the same state as [`refuse_synced_device_key`] guards, reached from
/// the other side. A blob that is no readable record is not checked here; the
/// store has always kept what it is given for that kind, and a sign-out
/// deletes it.
fn refuse_record_of_synced_key(store: &Store, blob: &IdentityBlob) -> KsResult<()> {
let Ok(record) = blob.account_record() else { return Ok(()) };
let device = record.device.to_base32();
let synced: bool = store
.db
.prepare_cached(
"SELECT EXISTS (SELECT 1 FROM identities
WHERE kind = 'voelin' AND uid = ?1 AND synced = 1)",
)
.map_err(backend)?
.query_row([&device], |row| row.get(0))
.map_err(backend)?;
if synced {
return Err(KeyStoreError::backend(Refused::RecordNamesSyncedKey {
record: blob.uid.clone(),
device,
}));
}
Ok(())
}
/// A database error as the store's backend error.
fn backend(error: impl Into<Error>) -> KeyStoreError {
KeyStoreError::backend(error.into())
}
/// A [`KeyStore::put`] this store refuses.
#[derive(Debug, thiserror::Error)]
enum Refused {
/// The JSON is not that of a `tsproto::Identity`. The text is a private
/// key, so the error does not repeat it, nor serde's account of it.
#[error("the TeamSpeak identity JSON is not that of an identity")]
NotATeamSpeakIdentity,
/// `uid` is unique across kinds in this table.
#[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")]
UidHeld { uid: String, kind: String },
/// The Voelin key is the device key of an account record. A sign-out
/// deletes a synced copy without reading the record, so the key the record
/// says to keep would be deleted.
#[error(
"the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \
stored as a synced copy (synced = true): a sign-out would delete it whatever the record says"
)]
SyncedDeviceKey { uid: String, record: String },
/// An account record cannot be read, so the store cannot tell whether the
/// Voelin key is its device key.
#[error(
"the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \
record {record:?} cannot be read, so it may name this key as the device key"
)]
UnreadableRecord { uid: String, record: String },
/// The device key of the record is stored as a synced copy already.
#[error(
"the account record {record:?} names the Voelin key {device:?} as the device key, which is \
stored as a synced copy (synced = true): a sign-out would delete it whatever the record \
says"
)]
RecordNamesSyncedKey { record: String, device: String },
}
/// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it (with
/// the row id last), its binding already read.
struct Columns {
kind: String,
uid: String,
/// The identity itself. `LIST` leaves it out for kinds with no level.
data: Option<String>,
/// `None` for an unbound row and for one whose binding columns are damaged.
binding: Option<AccountBinding>,
}
/// Why binding columns cannot be read.
#[derive(Debug, thiserror::Error)]
enum Damage {
#[error(transparent)]
Binding(#[from] BlobError),
#[error("a binding column holds a value of the wrong type")]
WrongType,
}
impl Columns {
/// The row, or `None` for a row that cannot be addressed (its `kind` or
/// `uid` is not text) and is left out with a warning.
fn read(row: &rusqlite::Row<'_>) -> rusqlite::Result<Option<Self>> {
let id: i64 = row.get(7)?;
let (Ok(kind), Ok(uid)) = (row.get_ref(0)?.as_str(), row.get_ref(1)?.as_str()) else {
tracing::warn!(id, "an identities row whose kind or uid is not text is left out");
return Ok(None);
};
let binding = read_binding(row).unwrap_or_else(|damage| {
tracing::warn!(
id, kind, uid, %damage,
"the binding columns of an identity cannot be read: it is treated as unbound",
);
None
});
Ok(Some(Self {
kind: kind.to_owned(),
uid: uid.to_owned(),
data: lossy_text(row.get_ref(2)?),
binding,
}))
}
/// The security level of a TeamSpeak row, 0 for any other kind and for JSON
/// that is no identity.
fn level(&self) -> u8 {
match &self.data {
Some(json) if self.kind == KIND_TEAMSPEAK => {
serde_json::from_str::<Identity>(json).map_or(0, |identity| identity.level())
}
_ => 0,
}
}
fn into_info(self) -> IdentityInfo {
let level = self.level();
IdentityInfo { kind: self.kind, uid: self.uid, level, binding: self.binding }
}
fn into_blob(self) -> IdentityBlob {
let level = self.level();
let data = self.data.unwrap_or_default();
IdentityBlob::from_row(&self.kind, self.uid, level, data).with_binding(self.binding)
}
}
/// The binding of a row from its four columns (3 to 6 of both selects).
fn read_binding(row: &rusqlite::Row<'_>) -> std::result::Result<Option<AccountBinding>, Damage> {
let column = |index| row.get_ref(index).map_err(|_| Damage::WrongType);
let account = column(3)?.as_str_or_null().map_err(|_| Damage::WrongType)?;
let integration = column(4)?.as_str_or_null().map_err(|_| Damage::WrongType)?;
let rev = column(5)?.as_i64().map_err(|_| Damage::WrongType)?;
let synced = column(6)?.as_i64().map_err(|_| Damage::WrongType)?;
Ok(AccountBinding::from_columns(account, integration, rev, synced)?)
}
/// A `data` column as text, whatever it holds. Bytes that are no UTF-8 and
/// values of another type are damage; read as text they fail where the
/// blob's kind is checked, with that kind's own error, instead of failing the
/// read of the row.
fn lossy_text(value: ValueRef<'_>) -> Option<String> {
match value {
ValueRef::Null => None,
ValueRef::Integer(n) => Some(n.to_string()),
ValueRef::Real(x) => Some(x.to_string()),
ValueRef::Text(bytes) | ValueRef::Blob(bytes) => {
Some(String::from_utf8_lossy(bytes).into_owned())
}
}
}
+8
View File
@@ -7,9 +7,16 @@
//!
//! The schema is versioned (`PRAGMA user_version`): opening a database runs
//! the migrations it has not seen, each in one transaction, keeping the data.
//!
//! The `identities` table keeps identities of more than one kind. [`Store`]
//! has the TeamSpeak identities the client has always had; [`SqliteKeyStore`]
//! is the table as a `voelin_identity::KeyStore`: every kind (TeamSpeak, a
//! Voelin key, the record of the signed-in account), each with the binding that
//! says whether it belongs to an account, and the sign-out of that account.
pub mod chat;
pub mod contacts;
mod keystore;
mod secrets;
mod store;
@@ -18,6 +25,7 @@ pub use chat::{
StoredMessage, SyncState, WriteOutcome, Written,
};
pub use contacts::{Contact, ContactSeen, Relation};
pub use keystore::SqliteKeyStore;
#[cfg(feature = "keyring")]
pub use secrets::KeyringSecrets;
pub use secrets::{MemorySecrets, Secrets};
+499 -9
View File
@@ -1,6 +1,7 @@
//! The SQLite database.
use std::path::Path;
use std::time::Duration;
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
use serde::de::DeserializeOwned;
@@ -18,12 +19,21 @@ enum Migration {
/// Schema migrations; entry `i` upgrades from version `i` to `i + 1`
/// (`PRAGMA user_version`). Add new ones at the end; never change one that
/// shipped.
///
/// Versions 6 and 7 are the identity migrations of `voelin-identity` (the
/// protocol's Phase 2 tasks 7 and 28), run in this order: a `kind` column
/// (every row that exists is a `teamspeak` identity) and then the four
/// account-binding columns (every row that exists is unbound). Their SQL is
/// the protocol's; `the_identity_migrations_are_pinned` keeps it from changing
/// under a shipped version.
const MIGRATIONS: &[Migration] = &[
Migration::Sql(SCHEMA_1),
Migration::Code(crate::chat::migrate_2),
Migration::Sql(crate::contacts::SCHEMA_3),
Migration::Sql(SCHEMA_4),
Migration::Sql(crate::chat::SCHEMA_5),
Migration::Sql(voelin_identity::migrate::ADD_KIND_COLUMN),
Migration::Sql(voelin_identity::migrate::ADD_ACCOUNT_COLUMNS),
];
/// Version 4: where each identity came from ([`IdentityOrigin`]) and which
@@ -88,7 +98,7 @@ pub enum IdentityOrigin {
/// Made by the app on its own because it had none; nobody chose it, so
/// the official client's identity may take its place as the default.
Created,
/// From another client (`voelin_core::identity`).
/// From another client (`voelin_core::ts::identity`).
Imported,
/// Made or chosen as the default by the user.
User,
@@ -228,6 +238,12 @@ impl Bookmark {
}
}
/// How long the checkpoint that follows the deletion of a key waits for another
/// connection ([`Store::truncate_wal`]). Short on purpose: the connection's own
/// busy timeout is seconds, and the checkpoint holds the writer lock while it
/// waits.
const CHECKPOINT_WAIT: Duration = Duration::from_millis(150);
pub struct Store {
pub(crate) db: Connection,
}
@@ -261,6 +277,13 @@ impl Store {
// Statements run through `prepare_cached` are parsed once per connection.
db.set_prepared_statement_cache_capacity(64);
db.pragma_update(None, "foreign_keys", true)?;
// Identities hold private keys. By default a delete only unlinks the
// row: its bytes stay in the free space of the page, and in earlier
// frames of the write-ahead log. With this SQLite overwrites what it
// deletes with zeros, and `truncate_wal` then folds the log into the
// file after a key is removed. It is a setting of the connection, so
// every connection that opens the file sets it here.
db.pragma_update(None, "secure_delete", true)?;
// Each migration with its version bump in one write transaction: a
// second connection that opens the file at the same time (the
// settings writer, the chat history) waits, then sees the new version.
@@ -287,6 +310,10 @@ impl Store {
pub const SCHEMA_VERSION: i64 = MIGRATIONS.len() as i64;
// Identities
//
// These methods are the TeamSpeak identities (kind `teamspeak`) the client
// has always had, and act on those rows only: the other kinds of the
// `identities` table (a Voelin key, the signed-in account) are not theirs.
/// Store an identity; it is the default when no other one is.
pub fn add_identity(
@@ -306,7 +333,8 @@ impl Store {
pub fn identities(&self) -> Result<Vec<IdentityEntry>> {
let mut stmt = self.db.prepare(
"SELECT id, name, uid, data, origin, is_default FROM identities ORDER BY id",
"SELECT id, name, uid, data, origin, is_default FROM identities
WHERE kind = 'teamspeak' ORDER BY id",
)?;
let rows = stmt.query_map([], |r| {
Ok((
@@ -339,7 +367,11 @@ impl Store {
/// and is never replaced by an import again.
pub fn set_default_identity(&self, id: i64, by_user: bool) -> Result<()> {
let tx = self.db.unchecked_transaction()?;
if tx.execute("UPDATE identities SET is_default = 1 WHERE id = ?1", [id])? == 0 {
if tx.execute(
"UPDATE identities SET is_default = 1 WHERE id = ?1 AND kind = 'teamspeak'",
[id],
)? == 0
{
return Err(Error::NotFound("identity", id));
}
tx.execute("UPDATE identities SET is_default = 0 WHERE id <> ?1", [id])?;
@@ -356,7 +388,11 @@ impl Store {
pub fn identity(&self, id: i64) -> Result<Identity> {
let data: Option<String> = self
.db
.query_row("SELECT data FROM identities WHERE id = ?1", [id], |r| r.get(0))
.query_row(
"SELECT data FROM identities WHERE id = ?1 AND kind = 'teamspeak'",
[id],
|r| r.get(0),
)
.optional()?;
let data = data.ok_or(Error::NotFound("identity", id))?;
Ok(serde_json::from_str(&data)?)
@@ -365,23 +401,82 @@ impl Store {
/// Store an identity again, e.g. after its security level was improved.
pub fn update_identity(&self, id: i64, identity: &Identity) -> Result<()> {
let n = self.db.execute(
"UPDATE identities SET data = ?2 WHERE id = ?1",
"UPDATE identities SET data = ?2 WHERE id = ?1 AND kind = 'teamspeak'",
params![id, serde_json::to_string(identity)?],
)?;
if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) }
}
pub fn rename_identity(&self, id: i64, name: &str) -> Result<()> {
let n =
self.db.execute("UPDATE identities SET name = ?2 WHERE id = ?1", params![id, name])?;
let n = self.db.execute(
"UPDATE identities SET name = ?2 WHERE id = ?1 AND kind = 'teamspeak'",
params![id, name],
)?;
if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) }
}
/// Delete the identity, key included: SQLite overwrites the row
/// (`secure_delete`) and the write-ahead log is truncated, so the key is
/// in neither the database file nor its log afterwards
/// (`truncate_wal` says when it cannot be).
pub fn delete_identity(&self, id: i64) -> Result<()> {
self.db.execute("DELETE FROM identities WHERE id = ?1", [id])?;
let deleted =
self.db.execute("DELETE FROM identities WHERE id = ?1 AND kind = 'teamspeak'", [id])?;
if deleted > 0 {
self.truncate_wal();
}
Ok(())
}
/// Fold the write-ahead log into the database file and truncate it to
/// nothing. The delete of a key has overwritten its bytes in the page
/// (`secure_delete`), but the frame of the log that held the page when the
/// key was stored still has them until the log is reset, and a plain
/// checkpoint only copies the frames. Call it after the rows of a key were
/// deleted.
///
/// It is best effort, because the delete it follows has happened and a
/// sign-out must still finish. A checkpoint that cannot complete (another
/// connection keeps reading an old snapshot) or fails leaves the bytes in
/// the log file, and a warning says so; they go when a later checkpoint
/// truncates the log, when later writes overwrite those frames, or when the
/// last connection to the database closes and the log is deleted. It does
/// nothing to a database that is not in WAL mode and does not overwrite what
/// was deleted before `secure_delete` was on (`VACUUM` does).
///
/// It waits for another connection for [`CHECKPOINT_WAIT`] at most, not for
/// the busy timeout of the connection: while a checkpoint that truncates
/// waits for readers it holds the writer lock of the log, so every other
/// writer would wait with it, and fail with "database is locked" when its
/// own timeout is shorter than the wait. The timeout the connection had is
/// restored before this returns.
pub(crate) fn truncate_wal(&self) {
match self.checkpoint_truncate() {
Ok(0) => {}
Ok(_) => tracing::warn!(
"a deleted key may stay in the write-ahead log: another connection blocked the checkpoint"
),
Err(error) => tracing::warn!(
%error,
"a deleted key may stay in the write-ahead log: the checkpoint failed"
),
}
}
/// `PRAGMA wal_checkpoint(TRUNCATE)` under [`CHECKPOINT_WAIT`]: whether
/// another connection blocked it (`1`) or not (`0`).
fn checkpoint_truncate(&self) -> rusqlite::Result<i64> {
let previous: i64 = self.db.pragma_query_value(None, "busy_timeout", |r| r.get(0))?;
let previous = Duration::from_millis(u64::try_from(previous).unwrap_or_default());
self.db.busy_timeout(CHECKPOINT_WAIT)?;
let blocked =
self.db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get::<_, i64>(0));
if let Err(error) = self.db.busy_timeout(previous) {
tracing::warn!(%error, "the busy timeout of the connection could not be restored");
}
blocked
}
// Bookmarks
pub fn add_bookmark(&self, bookmark: &Bookmark) -> Result<i64> {
@@ -506,6 +601,57 @@ mod tests {
assert!(matches!(store.identity(id), Err(Error::NotFound(..))));
}
#[test]
fn every_connection_overwrites_what_it_deletes() {
let secure_delete = |store: &Store| -> i64 {
store.db.pragma_query_value(None, "secure_delete", |r| r.get(0)).unwrap()
};
assert_eq!(secure_delete(&Store::open_in_memory().unwrap()), 1);
let dir = scratch_dir("secure-delete");
let path = dir.join("client.db");
assert_eq!(secure_delete(&Store::open(&path).unwrap()), 1);
// A second connection to the same file sets it for itself.
assert_eq!(secure_delete(&Store::open(&path).unwrap()), 1);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was() {
let dir = scratch_dir("blocked-checkpoint");
let path = dir.join("client.db");
let wal = dir.join("client.db-wal");
let store = Store::open(&path).unwrap();
store.add_identity("first", &Identity::create(), IdentityOrigin::User).unwrap();
// A reader whose snapshot is older than the last write keeps the log
// from being reset.
let reader = Connection::open(&path).unwrap();
reader.execute_batch("BEGIN").unwrap();
reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap();
store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap();
// A value that is not the default, so that restoring a constant would show.
let timeout = |store: &Store| -> i64 {
store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap()
};
store.db.busy_timeout(Duration::from_millis(2345)).unwrap();
let started = std::time::Instant::now();
store.truncate_wal();
let elapsed = started.elapsed();
assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}");
assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset");
assert_eq!(timeout(&store), 2345);
// Without the reader the same call resets the log.
reader.execute_batch("COMMIT").unwrap();
store.truncate_wal();
assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0);
assert_eq!(timeout(&store), 2345);
drop(reader);
drop(store);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn the_default_identity() {
let store = Store::open_in_memory().unwrap();
@@ -595,7 +741,7 @@ mod tests {
.unwrap();
}
let store = Store::open(&path).unwrap();
assert_eq!(Store::SCHEMA_VERSION, 5);
assert_eq!(Store::SCHEMA_VERSION, 7);
assert_eq!(store.schema_version().unwrap(), Store::SCHEMA_VERSION);
let channel = ChatTarget::Channel(1);
let rows = store.messages("srv", &channel, PageQuery::default()).unwrap();
@@ -611,6 +757,350 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
/// What `serde_json::to_string(&tsproto::Identity)` writes for the test
/// identity of tsproto's own `identity_tests` (the fixture row of
/// `voelin-identity`'s `tests/storage.rs`): its unique id and security
/// level are checked against the real tsproto below.
const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#;
const TEAMSPEAK_UID: &str = "test/9PZ9vww/Bpf5vJxtJhpz80=";
const TEAMSPEAK_LEVEL: u8 = 21;
/// A `client.db` as it was at schema `version`: the migrations below
/// `version` applied by the code that runs them, nothing else.
fn database_at(path: &Path, version: usize) {
let mut db = rusqlite::Connection::open(path).unwrap();
for migration in &MIGRATIONS[..version] {
match migration {
Migration::Sql(sql) => db.execute_batch(sql).unwrap(),
Migration::Code(migrate) => {
let tx = db.transaction().unwrap();
migrate(&tx).unwrap();
tx.commit().unwrap();
}
}
}
db.pragma_update(None, "user_version", version as i64).unwrap();
}
fn scratch_dir(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-store-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn the_teamspeak_fixture_is_what_tsproto_writes() {
let identity: Identity = serde_json::from_str(TEAMSPEAK_JSON).unwrap();
assert_eq!(identity.key().to_pub().get_uid(), TEAMSPEAK_UID);
assert_eq!(identity.level(), TEAMSPEAK_LEVEL);
assert_eq!(serde_json::to_string(&identity).unwrap(), TEAMSPEAK_JSON);
}
/// The identity migrations are `voelin-identity`'s SQL, and a shipped
/// version never changes: a newer revision of the protocol repository
/// that touched either string would fail here instead of changing what
/// version 6 or 7 does to an installed database.
#[test]
fn the_identity_migrations_are_pinned() {
let sql = |index: usize| match &MIGRATIONS[index] {
Migration::Sql(sql) => *sql,
Migration::Code(_) => panic!("migration {index} is code"),
};
assert_eq!(MIGRATIONS.len(), 7);
assert_eq!(
sql(5),
"ALTER TABLE identities ADD COLUMN kind TEXT NOT NULL DEFAULT 'teamspeak';"
);
assert_eq!(
sql(6),
"ALTER TABLE identities ADD COLUMN account TEXT;\n\
ALTER TABLE identities ADD COLUMN integration TEXT;\n\
ALTER TABLE identities ADD COLUMN integration_rev INTEGER NOT NULL DEFAULT 0;\n\
ALTER TABLE identities ADD COLUMN synced INTEGER NOT NULL DEFAULT 0;"
);
}
/// A database of version 5 (what 0.1 ships) gets the `kind` column and
/// then the account columns in one open; every identity stays as it was:
/// kind `teamspeak`, unbound, its JSON byte for byte, its origin and
/// default flag, and the level computed from the key as before.
#[test]
fn migrates_version_5_identities_through_both_steps() {
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
use voelin_identity::{AccountBinding, IdentityBlob, KIND_TEAMSPEAK};
let dir = scratch_dir("v5");
let path = dir.join("client.db");
let other = Identity::create();
let other_json = serde_json::to_string(&other).unwrap();
let other_uid = other.key().to_pub().get_uid();
database_at(&path, 5);
{
let db = rusqlite::Connection::open(&path).unwrap();
assert_eq!(
db.pragma_query_value(None, "user_version", |r| r.get::<_, i64>(0)).unwrap(),
5
);
for (name, uid, json, origin, default) in [
("Main", TEAMSPEAK_UID, TEAMSPEAK_JSON, "imported", 1),
("Other", other_uid.as_str(), other_json.as_str(), "user", 0),
] {
db.execute(
"INSERT INTO identities (name, uid, data, origin, is_default)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![name, uid, json, origin, default],
)
.unwrap();
}
}
let store = Store::open(&path).unwrap();
assert_eq!(Store::SCHEMA_VERSION, 7);
assert_eq!(store.schema_version().unwrap(), 7);
// Read as the key store reads a row of the migrated table.
let rows: Vec<_> = store
.db
.prepare(&format!("SELECT {SELECT_ACCOUNT_COLUMNS} FROM identities ORDER BY id"))
.unwrap()
.query_map([], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
r.get::<_, Option<String>>(3)?,
r.get::<_, Option<String>>(4)?,
r.get::<_, i64>(5)?,
r.get::<_, i64>(6)?,
))
})
.unwrap()
.collect::<rusqlite::Result<_>>()
.unwrap();
assert_eq!(rows.len(), 2);
for ((kind, uid, data, account, integration, rev, synced), (want_uid, want_json)) in
rows.into_iter().zip([(TEAMSPEAK_UID, TEAMSPEAK_JSON), (&*other_uid, &*other_json)])
{
assert_eq!(kind, KIND_TEAMSPEAK);
let binding = AccountBinding::from_columns(
account.as_deref(),
integration.as_deref(),
rev,
synced,
)
.unwrap();
assert_eq!(binding, None, "an old row is unbound");
assert_eq!((uid.as_str(), data.as_str()), (want_uid, want_json), "byte for byte");
let blob = IdentityBlob::from_row(&kind, uid, 0, data);
assert!(blob.is_teamspeak());
}
// The old API sees what it saw before, origin and default included.
let list = store.identities().unwrap();
assert_eq!(list.len(), 2);
assert_eq!((list[0].name.as_str(), list[0].uid.as_str()), ("Main", TEAMSPEAK_UID));
assert_eq!(
(list[0].level, list[0].origin, list[0].is_default),
(21, IdentityOrigin::Imported, true)
);
assert_eq!((list[1].name.as_str(), list[1].uid.as_str()), ("Other", &*other_uid));
assert_eq!(
(list[1].level, list[1].origin, list[1].is_default),
(other.level(), IdentityOrigin::User, false)
);
assert_eq!(store.default_identity().unwrap().unwrap().id, list[0].id);
assert_eq!(store.identity(list[1].id).unwrap().counter(), other.counter());
drop(store);
// Opened again, nothing runs twice.
let store = Store::open(&path).unwrap();
assert_eq!(store.schema_version().unwrap(), 7);
assert_eq!(store.identities().unwrap(), list);
drop(store);
std::fs::remove_dir_all(dir).unwrap();
}
/// The acceptance of the migration for the key store: a `client.db` at the
/// version before the identity migrations (5), and at the one between them
/// (6), opens, and every identity loads through the key store unchanged:
/// kind `teamspeak`, no binding, its JSON byte for byte, the level computed
/// as before, and the origin and default flag the old API reports kept.
#[test]
fn a_migrated_database_loads_every_identity_unchanged_through_the_key_store() {
use crate::SqliteKeyStore;
use voelin_identity::{IdentityBlob, IdentityInfo, KIND_TEAMSPEAK, KeyStore};
for version in [5, 6] {
let dir = scratch_dir(&format!("keys-v{version}"));
let path = dir.join("client.db");
let other = Identity::create();
let other_json = serde_json::to_string(&other).unwrap();
let other_uid = other.key().to_pub().get_uid();
database_at(&path, version);
{
let db = rusqlite::Connection::open(&path).unwrap();
for (name, uid, json, origin, default) in [
("Main", TEAMSPEAK_UID, TEAMSPEAK_JSON, "imported", 1),
("Other", other_uid.as_str(), other_json.as_str(), "created", 0),
] {
db.execute(
"INSERT INTO identities (name, uid, data, origin, is_default)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![name, uid, json, origin, default],
)
.unwrap();
}
}
let keys = SqliteKeyStore::open(&path).unwrap();
assert_eq!(keys.with_store(|s| s.schema_version().unwrap()), 7);
let want = [
(TEAMSPEAK_UID.to_owned(), TEAMSPEAK_JSON.to_owned(), TEAMSPEAK_LEVEL),
(other_uid.clone(), other_json.clone(), other.level()),
];
let mut infos: Vec<_> = want
.iter()
.map(|(uid, _, level)| IdentityInfo {
kind: KIND_TEAMSPEAK.into(),
uid: uid.clone(),
level: *level,
binding: None,
})
.collect();
infos.sort_by(|a, b| a.uid.cmp(&b.uid));
assert_eq!(keys.list().unwrap(), infos, "version {version}");
for (uid, json, level) in want {
let blob = keys.get(KIND_TEAMSPEAK, &uid).unwrap().unwrap();
assert_eq!(blob, IdentityBlob::teamspeak(&uid, level, &json), "version {version}");
assert_eq!(blob.json, json, "byte for byte");
assert_eq!(blob.binding, None);
}
// What the TeamSpeak methods report is kept as well.
let entries = keys.with_store(|s| s.identities().unwrap());
let origin = |uid: &str| entries.iter().find(|e| e.uid == uid).unwrap();
assert_eq!(
(origin(TEAMSPEAK_UID).origin, origin(TEAMSPEAK_UID).is_default),
(IdentityOrigin::Imported, true)
);
assert_eq!(
(origin(&other_uid).origin, origin(&other_uid).is_default),
(IdentityOrigin::Created, false)
);
drop(keys);
std::fs::remove_dir_all(dir).unwrap();
}
}
/// A database of version 6 (the `kind` column, no account columns yet) takes
/// the second step alone, and its rows of other kinds stay what they are.
#[test]
fn migrates_version_6_identities_to_accounts() {
let dir = scratch_dir("v6");
let path = dir.join("client.db");
database_at(&path, 6);
{
let db = rusqlite::Connection::open(&path).unwrap();
db.execute(
"INSERT INTO identities (name, uid, data, origin, is_default)
VALUES ('Main', ?1, ?2, 'created', 1)",
params![TEAMSPEAK_UID, TEAMSPEAK_JSON],
)
.unwrap();
db.execute(
"INSERT INTO identities (name, uid, data, kind)
VALUES ('key', 'abc', '{\"v\":1}', 'voelin')",
[],
)
.unwrap();
}
let store = Store::open(&path).unwrap();
assert_eq!(store.schema_version().unwrap(), 7);
let (kind, account, integration, rev, synced): (
String,
Option<String>,
Option<String>,
i64,
i64,
) = store
.db
.query_row(
"SELECT kind, account, integration, integration_rev, synced FROM identities
WHERE uid = 'abc'",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
)
.unwrap();
assert_eq!(
(kind.as_str(), account, integration, rev, synced),
("voelin", None, None, 0, 0)
);
let list = store.identities().unwrap();
assert_eq!(list.len(), 1, "the Voelin row is not a TeamSpeak identity");
assert_eq!(
(list[0].origin, list[0].is_default, list[0].level),
(IdentityOrigin::Created, true, 21)
);
drop(store);
std::fs::remove_dir_all(dir).unwrap();
}
/// Rows of other kinds share the table with the TeamSpeak identities and
/// are none of the TeamSpeak methods' business: they are not listed, not
/// read as an identity, not renamed, changed, made the default or deleted
/// (the JSON of a Voelin key is not a `tsproto::Identity`, and listing
/// would fail on it).
#[test]
fn the_teamspeak_methods_leave_other_kinds_alone() {
let store = Store::open_in_memory().unwrap();
let mine = Identity::create();
let id = store.add_identity("mine", &mine, IdentityOrigin::User).unwrap();
let other_id = |kind: &str, uid: &str| {
store
.db
.execute(
"INSERT INTO identities (name, uid, data, kind) VALUES (?1, ?2, '{\"v\":1}', ?1)",
params![kind, uid],
)
.unwrap();
store.db.last_insert_rowid()
};
let voelin = other_id("voelin", "v1");
let account = other_id("account", "account:a1");
let list = store.identities().unwrap();
assert_eq!(list.iter().map(|e| e.id).collect::<Vec<_>>(), [id]);
assert_eq!(store.default_identity().unwrap().unwrap().id, id);
for other in [voelin, account] {
assert!(matches!(store.identity(other), Err(Error::NotFound(..))));
assert!(matches!(store.rename_identity(other, "x"), Err(Error::NotFound(..))));
assert!(matches!(store.update_identity(other, &mine), Err(Error::NotFound(..))));
assert!(matches!(store.set_default_identity(other, true), Err(Error::NotFound(..))));
store.delete_identity(other).unwrap();
}
let rows: i64 =
store.db.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 3, "nothing of another kind was deleted");
let names: Vec<String> = store
.db
.prepare("SELECT name FROM identities ORDER BY id")
.unwrap()
.query_map([], |r| r.get(0))
.unwrap()
.collect::<rusqlite::Result<_>>()
.unwrap();
assert_eq!(names, ["mine", "voelin", "account"]);
let defaults: i64 = store
.db
.query_row("SELECT count(*) FROM identities WHERE is_default", [], |r| r.get(0))
.unwrap();
assert_eq!(defaults, 1);
// A TeamSpeak identity is deleted as before.
store.delete_identity(id).unwrap();
assert!(store.identities().unwrap().is_empty());
}
#[test]
fn bookmarks_keep_order_and_fields() {
let store = Store::open_in_memory().unwrap();
File diff suppressed because it is too large. Load diff
+3
View File
@@ -22,6 +22,9 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync", "time"] }
tracing = "0.1"
tsclientlib = { path = "../proto/tsclientlib" }
tsproto-packets = { path = "../proto/tsproto-packets" }
# The frame and simulcast layer types (`EncodedFrame`, `LayerSpec`), which the
# media side owns; re-exported here.
voelin-media = { path = "../voelin-media", default-features = false }
[dev-dependencies]
anyhow = "1"
+5 -196
View File
@@ -1,83 +1,13 @@
//! Simulcast layers: several encodings of one stream, each with its own size,
//! frame rate and bitrate.
//! Simulcast layers of a stream. The types ([`LayerSpec`], [`LayerId`],
//! [`LayerSet`]) are `voelin-media`'s; this module keeps how a streamer's
//! offer lists its layers in the SDP, so that a Voelin viewer can pick one.
//!
//! The streamer encodes every layer of its [`LayerSpec`] list and tags each
//! [`EncodedFrame`](crate::EncodedFrame) with its [`LayerId`]. Each viewer
//! connection gets the layer that fits its bandwidth estimate; peers that
//! negotiate RID simulcast (`a=simulcast`) get all of them. There is no limit
//! on the number of layers.
//! negotiate RID simulcast (`a=simulcast`) get all of them.
use std::fmt;
/// A simulcast layer. Layer 0 is the one a stream without simulcast has.
pub type LayerId = u16;
/// One encoding of the stream. Compared bit for bit (`scale` by its bits),
/// so it is `Eq`.
#[derive(Clone, Debug)]
pub struct LayerSpec {
pub id: LayerId,
/// Output size relative to the source (1.0: the source's size). Ignored
/// when [`size`](Self::size) is set.
pub scale: f32,
/// Exact output size in pixels, instead of `scale`.
pub size: Option<(u32, u32)>,
/// Frame rate cap; `None`: the source's frame rate.
pub max_fps: Option<u32>,
/// Bitrate the encoder starts with, in bit/s. Bandwidth estimates move it
/// down (and back up to this value, or [`max_bitrate`](Self::max_bitrate)).
pub bitrate: u64,
/// Highest bitrate bandwidth estimates may raise the layer to; `None`: no
/// maximum.
pub max_bitrate: Option<u64>,
/// Estimate (bit/s) a viewer needs to receive this layer; below it the
/// viewer moves to the next smaller layer.
pub min_bitrate: u64,
/// RTP stream id for peers that negotiate RID simulcast.
pub rid: Option<String>,
}
impl PartialEq for LayerSpec {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
&& self.scale.to_bits() == other.scale.to_bits()
&& self.size == other.size
&& self.max_fps == other.max_fps
&& self.bitrate == other.bitrate
&& self.max_bitrate == other.max_bitrate
&& self.min_bitrate == other.min_bitrate
&& self.rid == other.rid
}
}
impl Eq for LayerSpec {}
impl LayerSpec {
/// A stream without simulcast: layer 0 at the source's size and rate.
pub fn single(bitrate: u64) -> Self {
Self {
id: 0,
scale: 1.0,
size: None,
max_fps: None,
bitrate,
max_bitrate: None,
min_bitrate: 0,
rid: None,
}
}
/// Output size for a source of `width` x `height`: [`size`](Self::size),
/// or the scaled source size rounded down to even numbers (I420), at least
/// 2x2.
pub fn output_size(&self, width: u32, height: u32) -> (u32, u32) {
let (w, h) = self.size.unwrap_or_else(|| {
let scale = if self.scale.is_finite() && self.scale > 0.0 { self.scale } else { 1.0 };
((width as f32 * scale) as u32, (height as f32 * scale) as u32)
});
((w & !1).max(2), (h & !1).max(2))
}
}
pub use voelin_media::layer::{LayerId, LayerSet, LayerSpec};
/// The session-level SDP attribute in which a Voelin streamer's offer lists
/// its layers, so that a Voelin viewer can pick one (`Signal::Layer`):
@@ -129,119 +59,10 @@ pub fn from_sdp(sdp: &str) -> Option<Vec<LayerSpec>> {
Some(value.split_whitespace().filter_map(layer).collect())
}
/// A set of layers, e.g. those waiting for a keyframe. Grows as needed.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct LayerSet {
words: Vec<u64>,
}
impl LayerSet {
pub const fn new() -> Self {
Self { words: Vec::new() }
}
/// Adds `layer`; `true` if it was not in the set.
pub fn insert(&mut self, layer: LayerId) -> bool {
let (word, bit) = Self::position(layer);
if self.words.len() <= word {
self.words.resize(word + 1, 0);
}
let new = self.words[word] & bit == 0;
self.words[word] |= bit;
new
}
/// Removes `layer`; `true` if it was in the set.
pub fn remove(&mut self, layer: LayerId) -> bool {
let (word, bit) = Self::position(layer);
match self.words.get_mut(word) {
Some(w) if *w & bit != 0 => {
*w &= !bit;
true
}
_ => false,
}
}
pub fn contains(&self, layer: LayerId) -> bool {
let (word, bit) = Self::position(layer);
self.words.get(word).is_some_and(|w| w & bit != 0)
}
pub fn is_empty(&self) -> bool {
self.words.iter().all(|w| *w == 0)
}
pub fn len(&self) -> usize {
self.words.iter().map(|w| w.count_ones() as usize).sum()
}
/// Empties the set, keeping its memory.
pub fn clear(&mut self) {
self.words.fill(0);
}
/// Adds every layer of `other`.
pub fn union_with(&mut self, other: &LayerSet) {
if self.words.len() < other.words.len() {
self.words.resize(other.words.len(), 0);
}
for (w, o) in self.words.iter_mut().zip(&other.words) {
*w |= o;
}
}
/// The layers in ascending order.
pub fn iter(&self) -> impl Iterator<Item = LayerId> + '_ {
self.words.iter().enumerate().flat_map(|(i, &word)| {
(0..64).filter(move |b| word & (1 << b) != 0).map(move |b| (i * 64 + b) as LayerId)
})
}
fn position(layer: LayerId) -> (usize, u64) {
(usize::from(layer) / 64, 1 << (layer % 64))
}
}
impl FromIterator<LayerId> for LayerSet {
fn from_iter<I: IntoIterator<Item = LayerId>>(iter: I) -> Self {
let mut set = Self::new();
for layer in iter {
set.insert(layer);
}
set
}
}
impl fmt::Debug for LayerSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layer_set() {
let mut set = LayerSet::new();
assert!(set.is_empty());
assert!(set.insert(3));
assert!(!set.insert(3));
assert!(set.insert(200));
assert!(set.insert(LayerId::MAX));
assert_eq!(set.iter().collect::<Vec<_>>(), [3, 200, LayerId::MAX]);
assert_eq!(set.len(), 3);
assert!(set.contains(200) && !set.contains(4));
assert!(set.remove(200) && !set.remove(200));
let other: LayerSet = [1, 3].into_iter().collect();
set.union_with(&other);
assert_eq!(format!("{set:?}"), format!("{{1, 3, {}}}", LayerId::MAX));
set.clear();
assert!(set.is_empty());
}
#[test]
fn layers_in_the_sdp() {
let layers = vec![
@@ -265,16 +86,4 @@ mod tests {
[LayerSpec { id: 2, ..LayerSpec::single(700_000) }]
);
}
#[test]
fn output_size() {
let mut layer = LayerSpec::single(1_000_000);
assert_eq!(layer.output_size(1921, 1081), (1920, 1080));
layer.scale = 0.5;
assert_eq!(layer.output_size(2560, 1440), (1280, 720));
layer.scale = 0.0001;
assert_eq!(layer.output_size(640, 360), (2, 2));
layer.size = Some((853, 480));
assert_eq!(layer.output_size(1920, 1080), (852, 480));
}
}
+1 -15
View File
@@ -8,24 +8,10 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use str0m::media::{Frequency, MediaKind, MediaTime};
pub use voelin_media::stream::EncodedFrame;
use crate::layer::{LayerId, LayerSpec};
/// One encoded video or audio frame.
#[derive(Clone, Debug)]
pub struct EncodedFrame {
pub kind: MediaKind,
/// RTP time: 90 kHz for video, 48 kHz for Opus.
pub time: MediaTime,
pub data: Arc<[u8]>,
/// The simulcast layer of a video frame (0 without simulcast, and for
/// audio).
pub layer: LayerId,
/// A video keyframe: viewers can start decoding (or switch to this layer)
/// here.
pub keyframe: bool,
}
/// Produces encoded frames in real time.
pub trait FrameSource: Send {
/// Append the frames that are due at `now`.
+39
View File
@@ -0,0 +1,39 @@
[package]
name = "voelin-ui-vm"
version = "0.0.1-alpha"
description = "Toolkit-free view models of the desktop client: engine state turned into plain rows, shared by the Slint and GPUI front ends."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[lib]
name = "voelin_ui_vm"
path = "src/lib.rs"
# No UI toolkit here (no slint, no gpui): `cargo tree -p voelin-ui-vm -e normal`
# must show neither. The front ends convert these types (docs/ui.md).
[dependencies]
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
# Picture sizes (the header of a file); PNG and JPEG are listed as the
# front end's toolkit used to bring them.
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] }
serde = { version = "1", features = ["derive"] }
# JSON values of the settings and the gateway's configuration keys.
serde_json = "1"
# The Twemoji archive's blocks (raw deflate).
miniz_oxide = "0.8"
# Grapheme clusters for emoji in chat text.
unicode-segmentation = "1.13"
voelin-audio = { path = "../voelin-audio", default-features = false }
voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] }
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
voelin-model = { workspace = true }
voelin-store = { path = "../voelin-store" }
[dev-dependencies]
png = "0.18"
[lints]
workspace = true
+11
View File
@@ -0,0 +1,11 @@
# Bundled assets
- `twemoji.bin`: the Twemoji 15.0 SVGs (3720 emoji, from the `@twemoji/svg`
15.0.0 package) packed by `scripts/pack-twemoji.py` into blocks of raw
deflate with an index; `src/emoji.rs` reads it. Twemoji graphics by Twitter,
Inc and other contributors, licensed under CC-BY 4.0
(https://creativecommons.org/licenses/by/4.0/). The files are unchanged
apart from surrounding whitespace.
It is credited in `THIRD_PARTY_NOTICES.md` and the About page, with the fonts
and icons of the Slint front end (`crates/voelin-ui/assets/README.md`).
File renamed without changes.
@@ -1,8 +1,10 @@
//! Avatars without pictures: initials on a colour from the name.
use slint::Color;
use unicode_segmentation::UnicodeSegmentation;
use crate::color::Rgb;
use crate::image::{ImageRef, ImageSource};
/// Background colours for initials; white text reads on all of them.
const TINTS: [u32; 10] = [
0x2d6bff, 0x7c4dff, 0xc2379a, 0xe0572e, 0xd08a00, 0x1f9d6b, 0x0c93b8, 0x5865f2, 0xa0439e,
@@ -31,10 +33,10 @@ pub fn first_letter(initials: &str) -> String {
initials.graphemes(true).next().unwrap_or_default().to_owned()
}
/// A picture from the engine's cache (an avatar, a group icon), decoded
/// once; an empty image when there is none.
pub fn image(path: Option<&std::path::PathBuf>) -> slint::Image {
path.map(|p| crate::images::file(p)).unwrap_or_default()
/// A picture from the engine's cache (an avatar, a group icon); none when
/// there is no path.
pub fn image(path: Option<&std::path::PathBuf>) -> ImageRef {
path.map(ImageSource::file).unwrap_or_default()
}
/// A stable number for a name, in any case (FNV-1a).
@@ -48,12 +50,12 @@ pub fn name_hash(name: &str) -> u32 {
}
/// `0xrrggbb` as a colour.
pub fn rgb(rgb: u32) -> Color {
Color::from_rgb_u8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8)
pub fn rgb(rgb: u32) -> Rgb {
Rgb::from(rgb)
}
/// A stable colour for a name.
pub fn tint(name: &str) -> Color {
pub fn tint(name: &str) -> Rgb {
rgb(TINTS[(name_hash(name) % TINTS.len() as u32) as usize])
}
@@ -86,10 +88,7 @@ mod tests {
fn tints_are_stable() {
assert_eq!(tint("Alice"), tint("alice"));
let distinct: std::collections::HashSet<_> =
["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"]
.iter()
.map(|n| tint(n).as_argb_encoded())
.collect();
["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"].iter().map(|n| tint(n).0).collect();
assert!(distinct.len() > 2);
}
}
File renamed without changes.
+934
View File
@@ -0,0 +1,934 @@
//! The bridge structs: the rows and forms the screens show, as plain
//! values. They mirror the Slint structs of `crates/voelin-ui/ui/bridge.slint`
//! field by field (strings are shared `Arc<str>`, pictures [`ImageRef`],
//! colours [`Rgb`], lists `Vec`); the Slint crate converts them
//! (`bind/convert.rs`), the GPUI client will render them as they are.
//! `MytsBadge` and `MytsForm` (account screens without a data source in this
//! build) stay in Slint.
use std::sync::Arc;
use crate::color::Rgb;
use crate::image::ImageRef;
/// A row or form of the bridge (the plain counterpart of the Slint struct `ServerItem`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ServerItem {
pub id: i32,
pub name: Arc<str>,
pub address: Arc<str>,
/// "offline", "connecting", "observing" or "connected"
pub status: Arc<str>,
/// Avatar of a server without an icon.
pub initials: Arc<str>,
pub tint: Rgb,
/// The server's icon, empty without one.
pub icon: ImageRef,
/// Unread messages in its chats.
pub unread: i32,
/// Someone streams in our channel there.
pub live: bool,
/// "9 online · 7 channels" while its presence is known, else the address.
pub detail: Arc<str>,
/// "TeamSpeak 6", "TeamSpeak 3", "" before it was reached.
pub product: Arc<str>,
/// Gateway or query credentials: presence without joining.
pub gateway: bool,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `TreeItem`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TreeItem {
pub is_channel: bool,
/// A TeamSpeak spacer channel, its name without the `[cspacer1]` part:
/// 0 none, 1 left, 2 centred, 3 right, 4 a line (the name repeats its
/// pattern across the row).
pub spacer: i32,
pub depth: i32,
pub id: i32,
pub name: Arc<str>,
pub own: bool,
pub talking: bool,
pub muted: bool,
pub sound_off: bool,
pub away: bool,
pub streaming: bool,
pub locked: bool,
pub collapsed: bool,
/// Local playback of this client: muted, or its volume in percent
/// (100 = unchanged).
pub local_muted: bool,
pub local_volume: i32,
/// Our own client.
pub myself: bool,
/// Avatar of a client.
pub initials: Arc<str>,
pub tint: Rgb,
/// The client's avatar picture, empty without one.
pub avatar: ImageRef,
/// Channels: clients inside, and the limit (-1: none).
pub members: i32,
pub max_members: i32,
/// Leading channel icon or trailing client icons, empty where absent: a channel's
/// icon; a client's server group icons, its channel group's and its own,
/// in that order (the first three).
pub icon: ImageRef,
pub icon_2: ImageRef,
pub icon_3: ImageRef,
/// A client's badges (myTeamSpeak), the first three in its order, empty
/// where absent; shown after the name.
pub badge: ImageRef,
pub badge_2: ImageRef,
pub badge_3: ImageRef,
/// A channel's banner picture (TeamSpeak 6), drawn behind the row;
/// Wire sizing metadata; compact decorative backgrounds always cover.
pub banner: ImageRef,
pub banner_mode: i32,
}
/// A client for the members panel (everyone on the server) and the voice
/// channel view (our channel).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MemberItem {
pub id: i32,
pub name: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
pub talking: bool,
pub muted: bool,
pub sound_off: bool,
pub away: bool,
pub streaming: bool,
pub myself: bool,
/// "Speaking", "Streaming", "Away", ...
pub status: Arc<str>,
/// The away message, empty without one.
pub away_message: Arc<str>,
/// The section the row is in (a server group, "In Voice",
/// "Streaming"), and the group's icon.
pub group: Arc<str>,
pub group_icon: ImageRef,
/// The first row of its section draws the heading, with the number of
/// rows in the section.
pub first_in_group: bool,
pub group_count: i32,
/// Badges: a crown for the server's admin groups.
pub admin: bool,
/// A moderator group's name, shown as a role next to the name.
pub role: Arc<str>,
pub priority: bool,
pub commander: bool,
pub recording: bool,
/// Its channel needs more talk power than it has (and it is no
/// talker): it cannot speak.
pub cannot_talk: bool,
/// myTeamSpeak badges, as in `TreeItem`.
pub badge: ImageRef,
pub badge_2: ImageRef,
pub badge_3: ImageRef,
}
/// A myTeamSpeak badge on the member card: "Badge" and its GUID for one
/// the app does not know; its picture is empty until it is downloaded.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BadgeItem {
pub name: Arc<str>,
pub description: Arc<str>,
pub icon: ImageRef,
}
/// The member card over a member row: everything about one client and what
/// can be done with them.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MemberCard {
pub open: bool,
pub id: i32,
pub name: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
pub status: Arc<str>,
pub description: Arc<str>,
/// Server groups, one per line.
pub groups: Vec<Arc<str>>,
/// The badges the client shows (at most three, in its order).
pub badges: Vec<BadgeItem>,
pub country: Arc<str>,
pub talk_power: i32,
pub friend: bool,
pub blocked: bool,
/// Local playback, in percent.
pub volume: f32,
pub muted: bool,
/// The client has a unique id, so contacts and private chats work.
pub known: bool,
/// The client streams: the card offers to watch it.
pub streaming: bool,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `ChatTab`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ChatTab {
/// "Lobby", "@alice", "Server"
pub title: Arc<str>,
/// The name alone ("Lobby").
pub name: Arc<str>,
/// 0 = server chat, 1 = channel chat, 2 = private chat
pub kind: i32,
pub id: i32,
pub unread: i32,
/// The channel's topic (channel chats).
pub topic: Arc<str>,
/// The last message ("Mira: the banner I promised") and its time.
pub last: Arc<str>,
pub time: Arc<str>,
/// The channel's banner picture behind the chat's header (as TreeItem).
pub banner: ImageRef,
pub banner_mode: i32,
}
/// A piece of a chat line: a word in its style, or an emoji shown as an
/// image (`emoji` is its Twemoji key, e.g. "1f600"; `text` then holds the
/// characters).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextRun {
pub text: Arc<str>,
pub emoji: Arc<str>,
pub bold: bool,
pub italic: bool,
pub underline: bool,
pub strike: bool,
/// Code: on a background.
pub code: bool,
/// The author's colour, made readable on each theme; transparent: the
/// text's own.
pub ink_dark: Option<Rgb>,
pub ink_light: Option<Rgb>,
/// Where it links to ("": nowhere), and whether its text shows something
/// else (a page's name, another address): asked about before it opens.
pub link: Arc<str>,
pub masked: bool,
}
/// A block of a chat line (`vm::bbcode`): its runs, and what it is.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextBlock {
pub runs: Vec<TextRun>,
/// 0 = a line, 1 = a quote's line, 2 = a line of code, 3 = a list item,
/// 4 = a rule (no runs)
pub kind: i32,
/// Who a quote quotes, on its first line.
pub caption: Arc<str>,
}
/// One emoji under a message, with how many put it there.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ReactionItem {
/// The Twemoji key of the first emoji in `text` ("1f389"), for the image.
pub key: Arc<str>,
pub text: Arc<str>,
pub count: i32,
/// We reacted with it.
pub me: bool,
}
/// A file linked in a message (`ChatMessage::file_refs`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FileItem {
pub name: Arc<str>,
/// "2.4 MB", or what the transfer is doing.
pub detail: Arc<str>,
/// Index of the link in the message (what `download-file` takes).
pub index: i32,
/// "", "running", "done", "failed"
pub state: Arc<str>,
/// 0 … 1 while it downloads.
pub progress: f32,
/// A picture, so the icon differs.
pub picture: bool,
/// The picture itself, once downloaded: shown inline instead of the card.
pub preview: ImageRef,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `ChatLine`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ChatLine {
/// A handle for this message in its chat, stable while the chat is open
/// (the engine's ids do not fit a Slint int).
pub key: i32,
pub author: Arc<str>,
/// The text without formatting, a line per block (shown as it is when
/// the message has neither formatting nor emoji, and read out).
pub text: Arc<str>,
pub time: Arc<str>,
/// The text in blocks of styled runs; only filled when it has
/// formatting or emoji (`rich`).
pub blocks: Vec<TextBlock>,
pub rich: bool,
/// Only one to three emoji: shown large.
pub jumbo: bool,
/// Same author as the line before, shortly after: no header.
pub continued: bool,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
/// From a blocked contact.
pub blocked: bool,
pub pinned: bool,
pub reactions: Vec<ReactionItem>,
pub files: Vec<FileItem>,
/// The gateway knows this message: it can be pinned, reacted to and
/// made into a topic.
pub remote: bool,
/// The topic it belongs to, "" outside a topic.
pub topic: Arc<str>,
/// Highlighted after jumping to it from the pins.
pub marked: bool,
/// The first web address it links to, "" if none.
pub link: Arc<str>,
/// The first new message: the "New" divider is above it (never
/// `continued`).
pub unread_start: bool,
}
/// A pinned message in the pins drawer.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PinItem {
pub line: ChatLine,
/// "pinned by Nova · 12:04"
pub by: Arc<str>,
}
/// A gateway topic (thread).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TopicItem {
pub id: i32,
pub title: Arc<str>,
pub creator: Arc<str>,
/// "12 messages · by Nova"
pub detail: Arc<str>,
/// "Last active 3 min ago", and whether that was within the hour.
pub activity: Arc<str>,
pub recent: bool,
pub archived: bool,
}
/// The server dialog: a bookmark (id -1: a new one) and, from a link, where
/// Connect goes.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BookmarkForm {
pub id: i32,
pub name: Arc<str>,
pub address: Arc<str>,
pub nickname: Arc<str>,
pub server_password: Arc<str>,
/// The server has voice: no Connect.
pub connected: bool,
/// From a link, not stored with the server: the channel to join (a
/// path, or /<id>), its password and a privilege key.
pub channel: Arc<str>,
pub channel_password: Arc<str>,
pub token: Arc<str>,
}
/// A stream on the server, ours first: a stream can be watched from any
/// channel. An empty id: a client that streams, but whose stream is still
/// being looked up (it started before we joined, or in another channel).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StreamItem {
pub id: Arc<str>,
pub name: Arc<str>,
pub streamer: Arc<str>,
/// The streamer's channel when it is not ours; empty in ours.
pub channel: Arc<str>,
/// The streamer's client id (their avatar in the members).
pub streamer_id: i32,
/// The streamer's avatar, as the members show it: their picture, or
/// their initials on their colour (also the card's picture's colour).
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
/// How many watch it (the gateway's directory; 0 unknown).
pub viewers: i32,
pub audio: bool,
/// "Screen", "Window", "Camera"; and the announced bitrate ("8 Mbit/s").
pub kind: Arc<str>,
pub bitrate: Arc<str>,
/// Shown in the viewer.
pub watching: bool,
/// Our own stream.
pub own: bool,
/// Ours from the Stream Studio: its preview is the card's picture.
pub studio: bool,
}
/// A viewer of our stream. state: "requested", "connecting" or "connected".
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ViewerItem {
pub client: i32,
pub name: Arc<str>,
pub state: Arc<str>,
pub message: Arc<str>,
/// Their avatar picture, empty without one.
pub avatar: ImageRef,
}
/// A capture source for the share dialog.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SourceItem {
pub name: Arc<str>,
pub detail: Arc<str>,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `ShareForm`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ShareForm {
pub source: i32,
pub name: Arc<str>,
/// Index into the frame rate choices (15, 30, 60, 120, 144, 240, 320).
pub fps_index: i32,
/// Frames per second as typed; a choice fills it in. Any number above 0.
pub fps: Arc<str>,
/// Index into the bitrate choices (Auto, 2.5, 4.6, 8, 10, 20, 40, 60
/// Mbit/s).
pub bitrate_index: i32,
/// Video bitrate in kbit/s as typed; a choice fills it in. Empty with
/// Auto: from the size and frame rate shared, up to 60 Mbit/s.
pub bitrate: Arc<str>,
pub audio: bool,
pub auto_accept: bool,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `AudioForm`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AudioForm {
/// 0 = system default, then the devices.
pub input_index: i32,
pub output_index: i32,
/// 0 = push-to-talk, 1 = voice activation, 2 = continuous.
pub transmit: i32,
/// dBFS.
pub vad_threshold: f32,
pub echo_cancellation: bool,
pub noise_suppression: bool,
/// 0 = low ... 3 = very high.
pub noise_level: i32,
pub auto_gain: bool,
/// dB.
pub input_gain: f32,
/// Percent.
pub output_volume: f32,
/// Milliseconds.
pub playback_buffer: f32,
}
/// Local playback settings of one client. volume in percent.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ClientAudio {
pub id: i32,
pub name: Arc<str>,
pub volume: f32,
pub muted: bool,
/// The client streams: the dialog offers to watch it.
pub streaming: bool,
}
/// The appearance settings (`ui.*` keys).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AppearanceForm {
/// "dark", "light" or "system"
pub theme: Arc<str>,
pub font_scale: f32,
/// Pixels.
pub narrow_breakpoint: f32,
pub image_cache_mb: f32,
}
/// A contact (friend, blocked or neutral) and where they are now.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ContactItem {
pub uid: Arc<str>,
pub name: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
/// "friend", "blocked" or "neutral"
pub relation: Arc<str>,
pub online: bool,
pub away: bool,
pub streaming: bool,
/// What they do: "In Chill Zone", "Streaming", "Away: brb", "Offline".
pub status: Arc<str>,
/// Where: the server of the first session that sees them, or "Last seen
/// 2 h ago on Nightfall Guild".
pub place: Arc<str>,
/// "12m ago": online since (this run), else when last seen.
pub when: Arc<str>,
pub note: Arc<str>,
/// Local playback in percent.
pub volume: f32,
pub muted: bool,
/// "Contact since 14 Jan 2022".
pub since: Arc<str>,
/// Every session that sees them: "Nightfall Guild · Chill Zone".
pub spots: Vec<Arc<str>>,
/// A voice connection sees them: they can be messaged, poked, joined.
pub reachable: bool,
pub selected: bool,
}
/// A live stream on one of our servers (home page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LiveItem {
/// The session (bookmark id) and the stream (directory or stream id).
pub session: i32,
pub id: Arc<str>,
pub title: Arc<str>,
pub streamer: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
pub server: Arc<str>,
pub channel: Arc<str>,
/// 0: unknown.
pub viewers: i32,
/// "Screen", "Camera", ...
pub kind: Arc<str>,
/// The server's colour, for the card's picture.
pub backdrop: Rgb,
/// In our voice channel: it can be watched at once.
pub watchable: bool,
}
/// A chat in the recent chats and in the direct messages list.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ConversationItem {
/// Index in Rust's list (what `open-conversation` takes).
pub key: i32,
/// 0 server chat, 1 channel chat, 2 private chat, 3 offline message.
pub kind: i32,
pub title: Arc<str>,
/// The server's name.
pub server: Arc<str>,
/// "You: That works!", "Sent a file".
pub preview: Arc<str>,
/// "11:42", "Yesterday", "Mon", "12 Mar".
pub time: Arc<str>,
/// "10m ago".
pub ago: Arc<str>,
pub unread: i32,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
pub online: bool,
pub selected: bool,
}
/// A notification of the bell.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NoticeItem {
pub key: i32,
/// "mention", "poke", "message", "event", "friend"
pub kind: Arc<str>,
pub title: Arc<str>,
pub body: Arc<str>,
/// "3 min ago"
pub time: Arc<str>,
pub unread: bool,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
}
/// A result of the search (Ctrl+K).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SearchItem {
/// "server", "channel", "person", "contact", "setting"
pub kind: Arc<str>,
pub title: Arc<str>,
pub subtitle: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
/// The first result of a group names it ("Servers", "People", ...).
pub header: Arc<str>,
}
/// Something on our servers: an event, a scheduled stream or server news.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct HappeningItem {
/// "event", "stream", "news"
pub kind: Arc<str>,
pub title: Arc<str>,
pub subtitle: Arc<str>,
/// "Sat 26 Apr · 19:00"
pub when: Arc<str>,
pub session: i32,
pub id: i32,
pub live: bool,
}
/// Home's "Continue where you left off": the voice channel we were in last.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ResumeItem {
/// There is one: its server is still a bookmark at the same address.
pub shown: bool,
pub server_id: i32,
pub server: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub icon: ImageRef,
/// The channel's name as the tree shows it.
pub channel: Arc<str>,
/// Voice is connected there: the button shows the server; else it
/// connects into the channel.
pub open: bool,
pub connecting: bool,
}
/// A scheduled event of a server's gateway.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EventItem {
pub id: i32,
pub title: Arc<str>,
pub description: Arc<str>,
/// The date block: "SAT", "26", "APR".
pub weekday: Arc<str>,
pub day: Arc<str>,
pub month: Arc<str>,
/// "Sat 26 Apr, 19:00 – 21:00"
pub when: Arc<str>,
/// "Raid Night" or "Server-wide".
pub place: Arc<str>,
/// A scheduled stream: "Exploring the Lands Between · Elden Ring".
pub stream: Arc<str>,
pub live: bool,
pub going: i32,
pub maybe: i32,
pub not_going: i32,
/// "going", "maybe", "not_going" or "".
pub rsvp: Arc<str>,
pub creator: Arc<str>,
/// We may edit and delete it (ours, or we moderate).
pub editable: bool,
/// "Starts in 15 min", "Started 5 min ago", "".
pub soon: Arc<str>,
/// "Nova (going)", ...; filled once the event was opened.
pub attendees: Vec<Arc<str>>,
pub expanded: bool,
}
/// The event form (create or edit).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EventForm {
/// -1: a new event.
pub id: i32,
pub title: Arc<str>,
pub description: Arc<str>,
/// "2026-10-04 19:00", local time.
pub start: Arc<str>,
/// Empty: no end.
pub end: Arc<str>,
/// Index into `event-channels` (0: server-wide).
pub channel: i32,
pub stream: bool,
pub stream_title: Arc<str>,
pub game: Arc<str>,
}
/// An offline message to write (mail the server keeps).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct OfflineForm {
/// The peer's unique id and name.
pub uid: Arc<str>,
pub to: Arc<str>,
pub subject: Arc<str>,
pub text: Arc<str>,
}
/// The open direct message: who, and what can be done.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DmPeer {
pub open: bool,
pub uid: Arc<str>,
pub name: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
pub online: bool,
/// "Online · Nightfall Guild · Chill Zone", "Offline · last seen 2 h ago".
pub status: Arc<str>,
pub description: Arc<str>,
pub groups: Vec<Arc<str>>,
pub note: Arc<str>,
pub since: Arc<str>,
/// Where they are now, or where they were last seen.
pub servers: Vec<Arc<str>>,
/// Pictures linked in the conversation that are downloaded, newest
/// first (at most six; `media-more` counts the others), and the other
/// files: name, "2.4 MB · Today at 11:36", picture.
pub media: Vec<ImageRef>,
pub media_more: i32,
pub files: Vec<FileItem>,
pub friend: bool,
pub blocked: bool,
pub volume: f32,
pub muted: bool,
/// Messages can be sent now (a voice connection that sees them).
pub can_send: bool,
/// Why not: "Kairo is offline.", "Connect to Nightfall Guild to send."
pub notice: Arc<str>,
/// The server keeps offline messages: offer one.
pub offline: bool,
/// Connect with voice to the server of this conversation.
pub can_connect: bool,
/// The messages come from the store, without a session: read-only.
pub stored: bool,
/// An offline message is shown instead of the conversation.
pub mail: bool,
pub mail_subject: Arc<str>,
pub mail_text: Arc<str>,
pub mail_time: Arc<str>,
}
/// An identity (Profiles page); never its key.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct IdentityItem {
pub id: i32,
pub name: Arc<str>,
/// Unique ids on TeamSpeak 3 and TeamSpeak 6 servers.
pub uid: Arc<str>,
pub uid6: Arc<str>,
pub level: i32,
/// The store's default: servers see us as this one unless a bookmark
/// names another.
pub default: bool,
/// Where it came from: "Made in Voelin", "Imported", "Chosen by you".
pub origin: Arc<str>,
/// Raising its level: the level aimed at and the best one reached (0: no).
pub improving: i32,
pub reached: i32,
/// The bookmarks that use it.
pub used_by: Arc<str>,
}
/// An identity found in another client's files (import).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FoundIdentity {
pub name: Arc<str>,
pub uid: Arc<str>,
pub level: i32,
pub source: Arc<str>,
/// Already in our identities.
pub known: bool,
pub picked: bool,
}
/// A bookmark and the identity it connects with (Profiles page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BookmarkIdentity {
pub id: i32,
pub name: Arc<str>,
/// Index into `identity-names` (0: the default identity).
pub identity: i32,
}
/// Camera, video and stream quality (Voice & Video page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct VideoForm {
/// Index into `cameras`.
pub camera: i32,
/// 0 none, 1 blur.
pub background: i32,
/// "auto", "1280x720", ...
pub resolution: Arc<str>,
/// `stream.fps` as typed.
pub fps: Arc<str>,
/// auto, vp8, vp9, h264, av1.
pub codec: i32,
pub hardware: bool,
pub mirror: bool,
/// everyone, friends, channel, nobody.
pub permissions: i32,
/// 0 auto, 1 720p, 2 1080p, 3 1440p, -1 other layers.
pub quality: i32,
/// kbit/s.
pub bitrate: f32,
/// The camera preview runs.
pub preview: bool,
}
/// A simulcast layer of our stream (Streaming page); numbers as typed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LayerItem {
/// "1920x1080", or a scale like "0.5".
pub size: Arc<str>,
/// Frames per second; "" no cap.
pub fps: Arc<str>,
/// kbit/s.
pub bitrate: Arc<str>,
pub min_bitrate: Arc<str>,
pub max_bitrate: Arc<str>,
}
/// An audio source mixed into our stream.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AudioSourceItem {
/// "desktop", "app", "window", "microphone", "synthetic"
pub kind: Arc<str>,
pub name: Arc<str>,
pub detail: Arc<str>,
/// Percent.
pub gain: f32,
pub muted: bool,
}
/// Stream defaults (Streaming page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StreamingForm {
pub fps: Arc<str>,
pub bitrate: Arc<str>,
/// auto, vp8, vp9, h264, av1.
pub codec: i32,
/// auto, portal, wlroots, x11.
pub capture: i32,
pub replay_seconds: Arc<str>,
pub replay_memory: Arc<str>,
pub recording_dir: Arc<str>,
}
/// Notification kinds: 0 off, 1 in the app, 2 also on the desktop.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NotifyForm {
pub mentions: i32,
pub pokes: i32,
pub messages: i32,
pub events: i32,
pub friends: i32,
}
/// Privacy & Safety.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PrivacyForm {
/// 0 hide, 1 show flagged.
pub block_mode: i32,
/// everyone, friends, nobody.
pub messages: i32,
pub pokes: i32,
}
/// A server's gateway (Integrations page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct GatewayItem {
pub session: i32,
pub server: Arc<str>,
pub url: Arc<str>,
/// "connected", "connecting", "off"
pub status: Arc<str>,
pub features: Vec<Arc<str>>,
pub admin: bool,
}
/// A gateway configuration key (gateway administration).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ConfigItem {
pub key: Arc<str>,
/// JSON.
pub value: Arc<str>,
pub source: Arc<str>,
pub description: Arc<str>,
pub kind: Arc<str>,
pub bootstrap: bool,
}
/// A gateway permission rule.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PermItem {
pub action: Arc<str>,
/// "Everyone", "Server groups 6, 7", "Default: server admins".
pub rule: Arc<str>,
pub source: Arc<str>,
pub everyone: bool,
pub server_groups: Arc<str>,
pub channel_groups: Arc<str>,
}
/// A video encoder backend (Integrations page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EncoderItem {
pub name: Arc<str>,
pub api: Arc<str>,
pub codec: Arc<str>,
pub hardware: bool,
pub ok: bool,
/// Why it does not work, or "used first".
pub status: Arc<str>,
}
/// Any registered setting (Advanced page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SettingItem {
pub key: Arc<str>,
pub doc: Arc<str>,
/// JSON.
pub value: Arc<str>,
/// "set here", "command line", "config file", "default".
pub source: Arc<str>,
}
/// A recording or clip of the Stream Studio (Library).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RecordingItem {
pub name: Arc<str>,
/// "12.3 MB · 3 Oct 18:04".
pub detail: Arc<str>,
pub clip: bool,
pub path: Arc<str>,
}
/// Encoders, chat history, cache and logs (Advanced page); numbers as typed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AdvancedForm {
pub encoder: Arc<str>,
pub hardware: bool,
/// `stream.decoder_backend`, `stream.hardware_decoding`.
pub decoder: Arc<str>,
pub hardware_decoding: bool,
pub store_history: bool,
pub history_page: Arc<str>,
pub dedupe_ms: Arc<str>,
pub retention_days: Arc<str>,
pub cache_mb: Arc<str>,
pub fetch_images: bool,
pub progress_ms: Arc<str>,
/// `ui.image_preview_kb`.
pub preview_kb: Arc<str>,
pub logs: Arc<str>,
pub crash_dir: Arc<str>,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `AccountForm`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AccountForm {
pub nickname: Arc<str>,
pub identity: Arc<str>,
pub uid: Arc<str>,
pub uid6: Arc<str>,
pub level: i32,
pub server: Arc<str>,
}
/// One emoji of the picker. `text` is what picking it inserts.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EmojiCell {
pub key: Arc<str>,
pub name: Arc<str>,
pub text: Arc<str>,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `EmojiRow`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EmojiRow {
pub cells: Vec<EmojiCell>,
}
@@ -6,17 +6,17 @@ use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::rc::Rc;
use slint::{Color, Image, ModelRc, VecModel};
use unicode_segmentation::UnicodeSegmentation;
use voelin_core::HistoryMessage;
use voelin_model::{ChatMessage, ChatTarget, FileRef, Presence};
use crate::app::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun};
use crate::avatar;
use crate::bbcode::{self, BlockKind, Doc, Span, Style};
use crate::bridge::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun};
use crate::color::Rgb;
use crate::emoji;
use crate::vm::avatar;
use crate::vm::bbcode::{self, BlockKind, Doc, Span, Style};
use crate::image::ImageRef;
/// Lines of the same author within this time are grouped (no header).
const GROUP_MS: i64 = 5 * 60 * 1000;
@@ -29,6 +29,7 @@ pub struct Previous {
}
impl Previous {
/// The line `message` is, as the line after it sees it.
pub fn of(message: &ChatMessage) -> Self {
Self { author: message.author_name.clone(), ts_ms: message.ts_ms }
}
@@ -40,7 +41,7 @@ pub struct LineCtx<'a> {
/// The message's handle in its chat.
pub key: i32,
/// The author's avatar picture.
pub avatar: Image,
pub avatar: ImageRef,
/// The gateway takes reactions and pins for this chat.
pub gateway: bool,
/// Highlighted (jumped to from the pins).
@@ -50,7 +51,7 @@ pub struct LineCtx<'a> {
/// The state of the downloads started from this message, by link index.
pub downloads: Vec<(usize, FileItem)>,
/// Pictures of the links shown inline, by link index.
pub previews: Vec<(usize, Image)>,
pub previews: Vec<(usize, ImageRef)>,
/// Pictures on the web in the engine's cache, by address: the `[img]`
/// pictures here show as picture cards, the others as links (`None`:
/// all as links).
@@ -137,7 +138,7 @@ pub fn size_text(bytes: u64) -> String {
#[derive(Clone, Default)]
struct Body {
text: String,
blocks: ModelRc<TextBlock>,
blocks: Vec<TextBlock>,
rich: bool,
jumbo: bool,
link: String,
@@ -152,10 +153,9 @@ struct Read {
}
/// What lines of a chat were built from, by message id, kept between
/// refreshes: a message whose text, reactions and cards did not change is
/// not read again and gets the same models (they compare by pointer), so
/// its line compares equal and `list::sync` leaves its row. (Not with an
/// empty picture: Slint's empty `Image` equals nothing, not even itself.)
/// refreshes: a message whose text did not change is not read again (its
/// BBCode parsed, its blocks and runs split), and builds the same line, so
/// the list diff leaves its row.
#[derive(Default)]
pub struct LineCache(RefCell<HashMap<i64, Parts>>);
@@ -166,8 +166,6 @@ struct Parts {
read: Option<Read>,
/// The body last built, and which pictures were cards then.
body: Option<(Vec<bool>, Body)>,
reactions: (Vec<ReactionItem>, ModelRc<ReactionItem>),
files: (Vec<FileItem>, ModelRc<FileItem>),
}
impl LineCache {
@@ -190,22 +188,6 @@ fn current<'a>(all: &'a mut HashMap<i64, Parts>, id: i64, rev: i64, text: &str)
parts
}
/// `rows` as a model: the one in `kept` when they are the same rows.
fn model_of<T: Clone + PartialEq + 'static>(
rows: Vec<T>,
kept: Option<&mut (Vec<T>, ModelRc<T>)>,
) -> ModelRc<T> {
match kept {
Some((old, model)) if *old == rows => model.clone(),
Some(kept) => {
let model = ModelRc::from(Rc::new(VecModel::from(rows.clone())));
*kept = (rows, model.clone());
model
}
None => ModelRc::from(Rc::new(VecModel::from(rows))),
}
}
/// A link to a channel's file, which the chat shows as a card.
fn is_file(address: &str) -> bool {
FileRef::parse(address).is_some()
@@ -236,11 +218,13 @@ pub fn web_pictures(text: &str) -> Vec<String> {
/// The colours of a span: the author's made readable on the dark and the
/// light theme, or transparent for the text's own.
fn inks(color: Option<[u8; 3]>) -> (Color, Color) {
let rgb = |[r, g, b]: [u8; 3]| Color::from_rgb_u8(r, g, b);
fn inks(color: Option<[u8; 3]>) -> (Option<Rgb>, Option<Rgb>) {
match color {
Some(c) => (rgb(bbcode::readable(c, true)), rgb(bbcode::readable(c, false))),
None => (Color::default(), Color::default()),
Some(c) => (
Some(Rgb::from(bbcode::readable(c, true))),
Some(Rgb::from(bbcode::readable(c, false))),
),
None => (None, None),
}
}
@@ -251,7 +235,7 @@ fn run(
emoji: Option<String>,
style: &Style,
masked: bool,
inks: (Color, Color),
inks: (Option<Rgb>, Option<Rgb>),
) -> TextRun {
TextRun {
text: text.into(),
@@ -356,11 +340,7 @@ fn blocks_of(doc: &Doc) -> Option<(Vec<TextBlock>, bool)> {
if count > bbcode::MAX_RUNS {
return None;
}
blocks.push(TextBlock {
runs: ModelRc::from(Rc::new(VecModel::from(runs))),
kind,
caption: caption.into(),
});
blocks.push(TextBlock { runs, kind, caption: caption.into() });
}
}
Some((blocks, any_emoji))
@@ -388,19 +368,13 @@ fn body_of(doc: &Doc, cards: &[bool]) -> Body {
let rich = !doc.is_plain() || words.iter().any(|w| w.emoji.is_some());
// Past the runs a line can have: its plain text.
match rich.then(|| blocks_of(&doc)).flatten() {
Some((blocks, _)) => Body {
text,
blocks: ModelRc::from(Rc::new(VecModel::from(blocks))),
rich: true,
jumbo,
link,
},
None => Body { text, blocks: ModelRc::default(), rich: false, jumbo, link },
Some((blocks, _)) => Body { text, blocks, rich: true, jumbo, link },
None => Body { text, blocks: Vec::new(), rich: false, jumbo, link },
}
}
/// The picture at `url`, if the engine has it and it can be shown.
fn picture(pictures: Option<&HashMap<String, PathBuf>>, url: &str) -> Option<Image> {
fn picture(pictures: Option<&HashMap<String, PathBuf>>, url: &str) -> Option<ImageRef> {
let image = avatar::image(pictures?.get(url));
(image.size().width > 0).then_some(image)
}
@@ -417,7 +391,7 @@ pub fn tab_title(presence: &Presence, target: &ChatTarget, peer: &str) -> String
match target {
ChatTarget::Channel(cid) => presence.channels.get(cid).map_or_else(
|| format!("Channel {cid}"),
|c| crate::vm::tree::channel_title(c).0.to_owned(),
|c| crate::tree::channel_title(c).0.to_owned(),
),
ChatTarget::Private(_) => format!("@{peer}"),
ChatTarget::Server => "Server".into(),
@@ -469,7 +443,7 @@ pub fn preview(message: &ChatMessage) -> (String, String) {
std::iter::once(read.doc.one_line()).chain(names).collect::<Vec<_>>().join(" ")
};
// A one-line text cannot show emoji (they are pictures): left out.
let mut text = crate::vm::social::without_emoji(&text);
let mut text = crate::social::without_emoji(&text);
if text.is_empty() {
text = "sent an emoji".into();
}
@@ -560,12 +534,11 @@ fn line_of(
&& previous.is_some_and(|p| {
p.author == message.author_name && (0..GROUP_MS).contains(&(message.ts_ms - p.ts_ms))
});
let cached = parts.is_some();
let mut own = Parts::default();
let parts = parts.unwrap_or(&mut own);
let read = parts.read.get_or_insert_with(|| read(message));
// Pictures on the web that are here are cards, after the files'.
let pictures: Vec<Option<Image>> =
let pictures: Vec<Option<ImageRef>> =
read.images.iter().map(|url| picture(ctx.pictures, url)).collect();
let shown: Vec<bool> = pictures.iter().map(Option::is_some).collect();
let body = match &parts.body {
@@ -612,8 +585,6 @@ fn line_of(
});
}
}
let files = model_of(cards, cached.then_some(&mut parts.files));
let reactions = model_of(reactions, cached.then_some(&mut parts.reactions));
ChatLine {
key: ctx.key,
author: message.author_name.clone().into(),
@@ -629,7 +600,7 @@ fn line_of(
blocked: message.blocked,
pinned: false,
reactions,
files,
files: cards,
remote: false,
topic: ctx.topic.clone().into(),
marked: ctx.marked,
@@ -645,6 +616,7 @@ pub fn picture_link(message: &ChatMessage, index: usize) -> Option<String> {
index.checked_sub(read.files.len()).and_then(|i| read.images.into_iter().nth(i))
}
/// Whether a file name is a picture's, by its extension.
pub fn is_picture(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
[".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"].iter().any(|e| lower.ends_with(e))
@@ -652,7 +624,7 @@ pub fn is_picture(name: &str) -> bool {
#[cfg(test)]
mod tests {
use slint::Model;
use crate::image::ImageSource;
use voelin_core::HistoryMessage;
use voelin_gateway_proto::ReactionCount;
use voelin_store::MessageSource;
@@ -690,7 +662,7 @@ mod tests {
let first = message("Alice", "hi", 1_000_000);
let a = line(&first, None);
assert!(!a.continued);
assert_eq!(a.initials, "AL");
assert_eq!(&*a.initials, "AL");
let prev = Previous::of(&first);
assert!(line(&message("Alice", "again", 1_060_000), Some(&prev)).continued);
assert!(!line(&message("Bob", "me", 1_060_000), Some(&prev)).continued);
@@ -744,27 +716,27 @@ mod tests {
/// The runs of block `i` of a line, as (text, emoji).
fn runs(line: &ChatLine, i: usize) -> Vec<TextRun> {
line.blocks.row_data(i).unwrap().runs.iter().collect()
line.blocks[i].runs.clone()
}
#[test]
fn emoji_runs() {
let plain = line(&message("A", "no emoji here\nnor here", 0), None);
assert!(!plain.rich && plain.blocks.row_count() == 0);
assert_eq!(plain.text, "no emoji here\nnor here");
assert!(!plain.rich && plain.blocks.is_empty());
assert_eq!(&*plain.text, "no emoji here\nnor here");
let rich = line(&message("A", "gg 🎉", 0), None);
assert!(rich.rich && !rich.jumbo);
assert_eq!(rich.blocks.row_count(), 1);
assert_eq!(rich.blocks.len(), 1);
let r = runs(&rich, 0);
assert_eq!((r.len(), r[0].text.as_str(), r[1].emoji.as_str()), (2, "gg ", "1f389"));
assert_eq!((r.len(), r[0].text.as_ref(), r[1].emoji.as_ref()), (2, "gg ", "1f389"));
assert!(line(&message("A", "🎉", 0), None).jumbo);
// Formatting around it: still large.
let jumbo = line(&message("A", "[b]🎉[/b]", 0), None);
assert!(jumbo.rich && jumbo.jumbo);
// Lines stay lines with emoji (they were run together).
let lines = line(&message("A", "first 🎉\nsecond", 0), None);
assert_eq!(lines.blocks.row_count(), 2);
assert_eq!(lines.text, "first 🎉\nsecond");
assert_eq!(lines.blocks.len(), 2);
assert_eq!(&*lines.text, "first 🎉\nsecond");
}
#[test]
@@ -775,10 +747,10 @@ mod tests {
let line = line(&message("A", text, 0), None);
assert!(line.rich && !line.jumbo);
assert_eq!(
line.text,
&*line.text,
"Raid at 8, see https://x.org/raid\n> Nova: bring elixirs\n• one\n• two\n---\na\n\nb"
);
assert_eq!(line.link, "https://x.org/raid");
assert_eq!(&*line.link, "https://x.org/raid");
let kinds: Vec<(i32, String)> =
line.blocks.iter().map(|b| (b.kind, b.caption.to_string())).collect();
let kind = |k: i32| (k, String::new());
@@ -787,15 +759,15 @@ mod tests {
[kind(0), (1, "Nova".into()), kind(3), kind(3), kind(4), kind(2), kind(2), kind(2)]
);
let first = runs(&line, 0);
assert!(first[0].bold && first[0].text == "Raid");
assert!(first[0].bold && &*first[0].text == "Raid");
let eight = first.iter().find(|r| r.text.starts_with('8')).unwrap();
// The author's red, readable on both themes.
assert!(eight.ink_dark.alpha() == 255 && eight.ink_light.alpha() == 255);
assert!(eight.ink_dark.red() > eight.ink_dark.green());
assert_eq!(first[0].ink_dark.alpha(), 0, "the text's own colour");
let (dark, light) = (eight.ink_dark.unwrap(), eight.ink_light.unwrap());
assert!(dark.r() > dark.g() && light.r() > light.g());
assert_eq!(first[0].ink_dark, None, "the text's own colour");
let address = first.iter().find(|r| !r.link.is_empty()).unwrap();
assert_eq!(
(address.text.as_str(), address.link.as_str()),
(address.text.as_ref(), address.link.as_ref()),
("https://x.org/raid", "https://x.org/raid")
);
assert!(!address.masked, "its own address");
@@ -807,10 +779,10 @@ mod tests {
// Inline code: one run.
let inline = super::line(&message("A", "run [code]/pull 10[/code]", 0), None);
let r = runs(&inline, 0);
assert!(r[1].code && r[1].text == "/pull 10");
assert!(r[1].code && &*r[1].text == "/pull 10");
// Not formatting: plain.
let relayed = super::line(&message("A", "[Nova] hi [1]", 0), None);
assert!(!relayed.rich && relayed.text == "[Nova] hi [1]" && relayed.link.is_empty());
assert!(!relayed.rich && &*relayed.text == "[Nova] hi [1]" && relayed.link.is_empty());
}
/// A link whose text is not its address asks before it opens: each of
@@ -916,15 +888,15 @@ mod tests {
let url = format!("https://x.org/{}", "a".repeat(40));
let line = line(&message("A", &format!("see {url}"), 0), None);
let r = runs(&line, 0);
let pieces: Vec<&str> = r[1..].iter().map(|r| r.text.as_str()).collect();
let pieces: Vec<&str> = r[1..].iter().map(|r| r.text.as_ref()).collect();
assert_eq!(pieces.concat(), url);
assert!(pieces.len() == 3 && pieces.iter().all(|p| p.chars().count() <= LONG_WORD));
assert!(r[1..].iter().all(|r| r.link == url.as_str()));
assert!(r[1..].iter().all(|r| &*r.link == url.as_str()));
let code = "cargo build --release --locked -j 1";
let line = super::line(&message("A", &format!("[code]{code}[/code]"), 0), None);
let r = runs(&line, 0);
assert!(r.len() > 1 && r.iter().all(|r| r.code));
assert_eq!(r.iter().map(|r| r.text.as_str()).collect::<String>(), code);
assert_eq!(r.iter().map(|r| r.text.as_ref()).collect::<String>(), code);
}
#[test]
@@ -933,9 +905,9 @@ mod tests {
let text = format!("loot [img]{url}[/img]");
// Not here (or not fetched): the address, as a link.
let link = line(&message("A", &text, 0), None);
assert_eq!(link.files.row_count(), 0);
assert_eq!(link.files.len(), 0);
let r = runs(&link, 0);
assert_eq!((r[1].text.as_str(), r[1].link.as_str()), (url, url));
assert_eq!((r[1].text.as_ref(), r[1].link.as_ref()), (url, url));
// Here: a picture card after the files, and no address.
let dir = std::env::temp_dir().join(format!("voelin-chat-picture-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
@@ -951,10 +923,10 @@ mod tests {
let stored = stored(message("A", &format!("{text} [URL={file}]plan.pdf[/URL]"), 0));
let ctx = LineCtx { pictures: Some(&pictures), ..Default::default() };
let shown = history_line(&stored, None, &ctx);
assert_eq!(shown.text, "loot");
assert_eq!(shown.files.row_count(), 2);
let card = shown.files.row_data(1).unwrap();
assert_eq!((card.name.as_str(), card.index, card.preview.size().width), ("loot.png", 1, 4));
assert_eq!(&*shown.text, "loot");
assert_eq!(shown.files.len(), 2);
let card = shown.files[1].clone();
assert_eq!((card.name.as_ref(), card.index, card.preview.size().width), ("loot.png", 1, 4));
assert_eq!(picture_link(&stored.message, 1).as_deref(), Some(url));
assert_eq!(picture_link(&stored.message, 0), None);
assert_eq!(web_pictures(&text), [url]);
@@ -962,20 +934,18 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
/// A line built again from an unchanged message is equal (its models
/// are the same), so `list::sync` leaves its row; a change builds anew.
/// A line built again from an unchanged message is equal (so the list diff
/// leaves its row), with the cache or without; a change builds anew.
#[test]
fn unchanged_lines_compare_equal() {
let cache = LineCache::default();
// An avatar: an empty picture is never equal.
let avatar = Image::from_rgba8(slint::SharedPixelBuffer::new(1, 1));
let avatar = ImageSource::rgba(1, 1, vec![0u8; 4]);
let ctx = LineCtx { key: 3, avatar, cache: Some(&cache), ..Default::default() };
let mut stored = stored(message("A", "[b]hi[/b] 🎉", 0));
let first = history_line(&stored, None, &ctx);
assert!(first == history_line(&stored, None, &ctx));
// Without the cache, models are new each time.
let plain = LineCtx { key: 3, avatar: ctx.avatar.clone(), ..Default::default() };
assert!(history_line(&stored, None, &plain) != history_line(&stored, None, &plain));
assert!(history_line(&stored, None, &plain) == first);
stored.reactions[0].count = 3;
let reacted = history_line(&stored, None, &ctx);
assert!(reacted != first && reacted.blocks == first.blocks);
@@ -983,7 +953,7 @@ mod tests {
stored.rev = 2;
let edited = history_line(&stored, None, &ctx);
assert!(edited.blocks != first.blocks);
assert_eq!(edited.text, "edited");
assert_eq!(&*edited.text, "edited");
cache.keep([], 0);
assert_eq!(cache.0.borrow().len(), 1, "few: kept");
}
@@ -994,9 +964,9 @@ mod tests {
let ctx = LineCtx { key: -1, cache: Some(&cache), ..Default::default() };
let welcome =
server_line("Nightfall", "Welcome to [b]Nightfall[/b]!", i64::MIN, false, &ctx);
assert_eq!((welcome.author.as_str(), welcome.time.as_str()), ("Nightfall", ""));
assert_eq!((welcome.author.as_ref(), welcome.time.as_ref()), ("Nightfall", ""));
assert!(welcome.rich && !welcome.continued && !welcome.remote && welcome.key == -1);
assert_eq!(welcome.text, "Welcome to Nightfall!");
assert_eq!(&*welcome.text, "Welcome to Nightfall!");
assert!(server_line("Nightfall", "News", i64::MIN + 1, true, &ctx).continued);
}
@@ -1005,9 +975,9 @@ mod tests {
let ctx = LineCtx { key: 4, gateway: true, ..Default::default() };
let line = history_line(&stored(message("A", "hi", 0)), None, &ctx);
assert!(line.pinned && line.remote && line.key == 4);
assert_eq!(line.reactions.row_count(), 1);
let r = line.reactions.row_data(0).unwrap();
assert_eq!((r.key.as_str(), r.count, r.me), ("1f389", 2, true));
assert_eq!(line.reactions.len(), 1);
let r = line.reactions[0].clone();
assert_eq!((r.key.as_ref(), r.count, r.me), ("1f389", 2, true));
// Without a gateway nothing can be pinned or reacted to.
let plain = history_line(&stored(message("A", "hi", 0)), None, &LineCtx::default());
assert!(!plain.remote);
@@ -1022,10 +992,10 @@ mod tests {
format!("here you go {url} 🎉"),
] {
let line = line(&message("A", &text, 0), None);
assert_eq!(line.files.row_count(), 1);
let file = line.files.row_data(0).unwrap();
assert_eq!((file.name.as_str(), file.detail.as_str()), ("plan.pdf", "2.0 kB"));
assert_eq!(line.text, "here you go 🎉");
assert_eq!(line.files.len(), 1);
let file = line.files[0].clone();
assert_eq!((file.name.as_ref(), file.detail.as_ref()), ("plan.pdf", "2.0 kB"));
assert_eq!(&*line.text, "here you go 🎉");
assert!(line.rich);
}
// Only the link: no text.
+55
View File
@@ -0,0 +1,55 @@
//! Colours without a toolkit.
/// An opaque colour as `0xrrggbb`. Where "no colour" means something (a
/// text's own colour), the field is an `Option<Rgb>`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Rgb(pub u32);
impl Rgb {
/// The colour with these channels.
pub const fn new(r: u8, g: u8, b: u8) -> Self {
Self((r as u32) << 16 | (g as u32) << 8 | b as u32)
}
/// The red channel.
pub const fn r(self) -> u8 {
(self.0 >> 16) as u8
}
/// The green channel.
pub const fn g(self) -> u8 {
(self.0 >> 8) as u8
}
/// The blue channel.
pub const fn b(self) -> u8 {
self.0 as u8
}
}
impl From<u32> for Rgb {
/// `0xrrggbb`; the top byte is ignored.
fn from(rgb: u32) -> Self {
Self(rgb & 0x00ff_ffff)
}
}
impl From<[u8; 3]> for Rgb {
fn from([r, g, b]: [u8; 3]) -> Self {
Self::new(r, g, b)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn channels() {
let c = Rgb::from(0x2d6bff);
assert_eq!((c.r(), c.g(), c.b()), (0x2d, 0x6b, 0xff));
assert_eq!(Rgb::new(0x2d, 0x6b, 0xff), c);
assert_eq!(Rgb::from([1, 2, 3]), Rgb(0x010203));
assert_eq!(Rgb::from(0xff12_3456), Rgb(0x123456));
}
}
@@ -119,12 +119,7 @@ impl Archive {
.map(|i| &self.entries[i])
}
/// Number of emoji in the archive.
#[cfg(test)]
pub fn len(&self) -> usize {
self.entries.len()
}
/// The archive has an emoji for this key (code points joined by `-`).
pub fn contains(&self, key: &str) -> bool {
self.find(key).is_some()
}
@@ -350,7 +345,7 @@ mod tests {
#[test]
fn archive_opens() {
let a = archive();
assert!(a.len() > 3000);
assert!(a.entries.len() > 3000);
assert!(a.contains("1f600"));
assert!(!a.contains("zzz"));
assert_eq!(a.name("1f600"), Some("grinning face"));
File renamed without changes.
+308
View File
@@ -0,0 +1,308 @@
//! Pictures without a toolkit: where a picture comes from, and how large it
//! is. A front end turns an [`ImageRef`] into its own image type (Slint's
//! `Image` through its decoded-picture cache, GPUI's `img()`).
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
/// A picture: shared, cheap to clone, compared by what it is made of.
pub type ImageRef = Arc<ImageSource>;
/// Where a picture comes from.
#[derive(Clone, Default, PartialEq, Eq)]
pub enum ImageSource {
/// No picture.
#[default]
None,
/// A file of the engine's picture cache (`avatars/<md5>`, `icons/<id>`,
/// banners): PNG, JPEG, GIF, WebP, BMP, ICO or SVG, told by content, not
/// by name. The engine writes a picture that arrives again into the same
/// file, so the reference carries the file's [`Stamp`]: a changed file is
/// another picture, and a list that shows it redraws the row.
File {
/// Where the file is.
path: PathBuf,
/// What the file was when the reference was made.
stamp: Stamp,
},
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
Rgba {
/// Width in pixels.
w: u32,
/// Height in pixels.
h: u32,
/// `w * h * 4` bytes.
bytes: Arc<[u8]>,
},
/// An SVG document.
Svg(Arc<[u8]>),
/// A picture file held in memory (a chat picture downloaded for its
/// preview): the file's bytes, and a key the front end may keep its
/// decoded picture under.
Memory {
/// Names the picture, for caches.
key: Arc<str>,
/// The file's bytes.
bytes: Arc<[u8]>,
},
}
impl fmt::Debug for ImageSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::None => f.write_str("None"),
Self::File { path, .. } => f.debug_tuple("File").field(path).finish(),
Self::Rgba { w, h, .. } => write!(f, "Rgba({w}x{h})"),
Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()),
Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()),
}
}
}
/// What identifies a file's content without reading it: its length and the
/// time it was last written. Both zero for a file that is missing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Stamp {
len: u64,
modified: Option<SystemTime>,
}
impl Stamp {
/// The stamp of the file at `path`.
pub fn of(path: &Path) -> Self {
std::fs::metadata(path)
.map(|meta| Self { len: meta.len(), modified: meta.modified().ok() })
.unwrap_or_default()
}
}
/// A picture's size in pixels.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Size {
/// Width, 0 for no picture.
pub width: u32,
/// Height, 0 for no picture.
pub height: u32,
}
impl ImageSource {
/// A reference to no picture.
pub fn none() -> ImageRef {
ImageRef::default()
}
/// A reference to a file of the picture cache, as the file is now.
pub fn file(path: impl Into<PathBuf>) -> ImageRef {
let path = path.into();
let stamp = Stamp::of(&path);
Arc::new(Self::File { path, stamp })
}
/// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue,
/// alpha); no picture if the length does not fit.
pub fn rgba(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> ImageRef {
let bytes = bytes.into();
if bytes.len() as u64 == u64::from(w) * u64::from(h) * 4 {
Arc::new(Self::Rgba { w, h, bytes })
} else {
Self::none()
}
}
/// The size the picture shows with; 0 by 0 when there is none or it can
/// not be shown: a file that is missing, is not a picture, or is too
/// large to decode (a front end drops those, as it would show nothing).
/// A file's size is read from its header, once while it stays as it is;
/// a vector picture has none of its own: its stated width and height,
/// else 1 by 1.
pub fn size(&self) -> Size {
match self {
Self::None => Size::default(),
Self::File { path, stamp } => file_size(path, *stamp),
Self::Rgba { w, h, .. } => Size { width: *w, height: *h },
Self::Svg(bytes) => svg_size(bytes),
Self::Memory { bytes, .. } => bytes_size(bytes),
}
}
/// There is no picture, or it can not be shown ([`Self::size`]).
pub fn is_empty(&self) -> bool {
self.size().width == 0
}
}
/// A picture with more pixels than this (as RGBA bytes) is not decoded.
const MAX_DECODED_BYTES: u64 = 128 << 20;
fn checked(width: u32, height: u32) -> Size {
if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES {
Size::default()
} else {
Size { width, height }
}
}
/// The size of a picture file's bytes, told by content.
fn bytes_size(bytes: &[u8]) -> Size {
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()
else {
return Size::default();
};
if reader.format().is_none() {
return if voelin_core::is_svg(bytes) { svg_size(bytes) } else { Size::default() };
}
reader.into_dimensions().map_or_else(|_| Size::default(), |(w, h)| checked(w, h))
}
/// The number at the start of an attribute's value ("48", "48px", "4.5em").
fn number(value: &str) -> Option<u32> {
let end = value.find(|c: char| !c.is_ascii_digit() && c != '.').unwrap_or(value.len());
value[..end].parse::<f32>().ok().filter(|v| *v >= 1.0).map(|v| v as u32)
}
/// The value of `name="…"` in the root tag of an SVG.
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
let mut rest = tag;
while let Some(at) = rest.find(name) {
let before = rest[..at].chars().next_back();
let after = &rest[at + name.len()..];
let after = after.trim_start();
if before.is_none_or(char::is_whitespace)
&& let Some(value) = after.strip_prefix('=')
{
let value = value.trim_start();
let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
return value[1..].split(quote).next();
}
rest = &rest[at + name.len()..];
}
None
}
fn svg_size(bytes: &[u8]) -> Size {
let text = String::from_utf8_lossy(bytes);
let Some(start) = text.find("<svg") else { return Size { width: 1, height: 1 } };
let tag = &text[start..];
let tag = &tag[..tag.find('>').unwrap_or(tag.len())];
let stated =
attribute(tag, "width").and_then(number).zip(attribute(tag, "height").and_then(number));
let boxed = || {
let mut parts = attribute(tag, "viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
let (_, _, w, h) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
number(w).zip(number(h))
};
let (width, height) = stated.or_else(boxed).unwrap_or((1, 1));
checked(width, height)
}
/// What a probe of a file found, and what the file was then.
type Probe = (Stamp, Size);
/// Probed files, so a picture shown in many rows is read once; entries are
/// checked against the file's length and time before use.
static PROBES: Mutex<Option<HashMap<PathBuf, Probe>>> = Mutex::new(None);
/// Probes kept at most; the picture cache is far smaller than this.
const MAX_PROBES: usize = 4096;
fn file_size(path: &Path, stamp: Stamp) -> Size {
if stamp == Stamp::default() {
return Size::default();
}
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
let probes = guard.get_or_insert_with(HashMap::new);
if let Some((was, size)) = probes.get(path)
&& *was == stamp
{
return *size;
}
// The file is read with the lock held; probes are short and rare.
let size = std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes));
if probes.len() >= MAX_PROBES {
probes.clear();
}
probes.insert(path.to_owned(), (stamp, size));
size
}
#[cfg(test)]
mod tests {
use super::*;
/// A PNG of `width` by `height` pixels.
pub(crate) fn png(width: u32, height: u32) -> Vec<u8> {
let mut bytes = Vec::new();
let mut encoder = ::png::Encoder::new(&mut bytes, width, height);
encoder.set_color(::png::ColorType::Rgba);
encoder.set_depth(::png::BitDepth::Eight);
let pixels = vec![200; width as usize * height as usize * 4];
encoder.write_header().unwrap().write_image_data(&pixels).unwrap();
bytes
}
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-ui-vm-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn pixels_and_nothing() {
assert_eq!(ImageSource::none().size(), Size::default());
assert!(ImageSource::none().is_empty());
let pixels = ImageSource::rgba(2, 3, vec![0u8; 24]);
assert_eq!(pixels.size(), Size { width: 2, height: 3 });
assert!(!pixels.is_empty());
// The wrong length is no picture.
assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty());
assert_eq!(format!("{pixels:?}"), "Rgba(2x3)");
}
#[test]
fn files_by_content() {
let dir = temp("files");
// No extension: the cache's files have none.
let path = dir.join("1234");
std::fs::write(&path, png(4, 2)).unwrap();
assert_eq!(ImageSource::file(&path).size(), Size { width: 4, height: 2 });
let before = ImageSource::file(&path);
// A changed file is read again.
std::fs::write(&path, png(5, 3)).unwrap();
let after = ImageSource::file(&path);
assert_eq!(after.size(), Size { width: 5, height: 3 });
// The same file, another picture: a list redraws the row.
assert_ne!(before, after);
assert_eq!(after, ImageSource::file(&path));
let junk = dir.join("junk");
std::fs::write(&junk, b"not a picture").unwrap();
assert!(ImageSource::file(&junk).is_empty());
assert!(ImageSource::file(dir.join("missing")).is_empty());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn vector_pictures() {
let size = |svg: &str| ImageSource::Svg(svg.as_bytes().into()).size();
assert_eq!(size("<svg width=\"32\" height=\"16\"/>"), Size { width: 32, height: 16 });
assert_eq!(size("<svg viewBox='0 0 24 12'/>"), Size { width: 24, height: 12 });
assert_eq!(size("<svg xmlns='http://www.w3.org/2000/svg'/>"), Size { width: 1, height: 1 });
assert_eq!(size("<svg width=\"4096px\" height=\"4096px\"/>").width, 4096);
// Too large to decode.
assert!(
ImageSource::Svg(b"<svg width=\"99999\" height=\"99999\"/>".as_slice().into())
.is_empty()
);
// An SVG file with a byte order mark and a prolog, and in memory.
let svg: &[u8] = b"\xef\xbb\xbf<?xml version=\"1.0\"?><svg width=\"8\" height=\"8\"/>";
let dir = temp("svg");
std::fs::write(dir.join("icon"), svg).unwrap();
assert_eq!(ImageSource::file(dir.join("icon")).size().width, 8);
let memory = ImageSource::Memory { key: "k".into(), bytes: png(3, 3).into() };
assert_eq!(memory.size(), Size { width: 3, height: 3 });
std::fs::remove_dir_all(dir).unwrap();
}
}
+26
View File
@@ -0,0 +1,26 @@
//! Toolkit-free view models of the desktop client: engine state turned into
//! plain rows and forms, with the logic that decides what the screens show.
//! Neither Slint nor GPUI is a dependency; each front end converts these
//! types (docs/ui.md, "Two crates").
pub mod avatar;
pub mod bbcode;
pub mod bridge;
pub mod chat;
pub mod color;
pub mod emoji;
pub mod home;
pub mod image;
pub mod list;
pub mod servers;
pub mod settings;
pub mod settings_pages;
pub mod social;
pub mod state;
pub mod streams;
pub mod studio;
pub mod studio_bridge;
pub mod tree;
pub use color::Rgb;
pub use image::{ImageRef, ImageSource, Size};
+138
View File
@@ -0,0 +1,138 @@
//! Incremental list updates: what changed between two versions of a list,
//! as row operations. A front end that keeps a list model (Slint's
//! `VecModel`) applies them row by row, so a client that starts talking
//! redraws one row of the tree; one that rebuilds from the list (GPUI) just
//! re-renders and has no use for them.
/// One row operation of a [`Changes`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Change {
/// Row `i` holds another value: `new[i]`.
Update(usize),
/// Row `i` is gone.
Remove(usize),
/// `new[i]` is a new row, at `i`.
Insert(usize),
}
/// Row operations that turn the old list into the new one, in the order to
/// apply them: updates, then removals (each at the index it has when its
/// turn comes), then insertions (in ascending order).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Changes(pub Vec<Change>);
impl Changes {
/// Nothing changed.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// How many rows are updated in place.
pub fn updated(&self) -> usize {
self.0.iter().filter(|c| matches!(c, Change::Update(_))).count()
}
/// How many rows are removed.
pub fn removed(&self) -> usize {
self.0.iter().filter(|c| matches!(c, Change::Remove(_))).count()
}
/// How many rows are inserted.
pub fn inserted(&self) -> usize {
self.0.iter().filter(|c| matches!(c, Change::Insert(_))).count()
}
/// Apply the changes to `rows` (the old list), which then equals `new`.
/// Also the reference for front ends: their models do the same
/// operations in the same order.
pub fn apply<T: Clone>(&self, rows: &mut Vec<T>, new: &[T]) {
for change in &self.0 {
match *change {
Change::Update(i) => rows[i] = new[i].clone(),
Change::Remove(i) => {
rows.remove(i);
}
Change::Insert(i) => rows.insert(i, new[i].clone()),
}
}
}
}
/// What changes `old` into `new` with few row operations: the rows both
/// share at the start and the end stay, rows in between are changed in
/// place where they differ, and the rest inserted or removed.
pub fn diff<T: PartialEq>(old: &[T], new: &[T]) -> Changes {
let min = old.len().min(new.len());
let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
let suffix = old[prefix..]
.iter()
.rev()
.zip(new[prefix..].iter().rev())
.take(min - prefix)
.take_while(|(a, b)| a == b)
.count();
let old_mid = old.len() - prefix - suffix;
let new_mid = new.len() - prefix - suffix;
let common = old_mid.min(new_mid);
let mut changes = Vec::new();
for i in prefix..prefix + common {
if old[i] != new[i] {
changes.push(Change::Update(i));
}
}
let at = prefix + common;
changes.extend((new_mid..old_mid).map(|_| Change::Remove(at)));
changes.extend((at..at + new_mid.saturating_sub(old_mid)).map(Change::Insert));
Changes(changes)
}
#[cfg(test)]
mod tests {
use super::*;
/// The changes from `old` to `new`; applying them gives `new`.
fn run(old: &[i32], new: &[i32]) -> Changes {
let changes = diff(old, new);
let mut rows = old.to_vec();
changes.apply(&mut rows, new);
assert_eq!(rows, new, "{old:?} -> {new:?}");
changes
}
fn counts(changes: &Changes) -> (usize, usize, usize) {
(changes.updated(), changes.inserted(), changes.removed())
}
#[test]
fn minimal_changes() {
assert!(run(&[1, 2, 3], &[1, 2, 3]).is_empty());
assert_eq!(run(&[1, 2, 3], &[1, 9, 3]), Changes(vec![Change::Update(1)]));
assert_eq!(run(&[1, 2, 3], &[1, 2, 7, 3]), Changes(vec![Change::Insert(2)]));
assert_eq!(run(&[1, 2, 3], &[1, 3]), Changes(vec![Change::Remove(1)]));
assert_eq!(counts(&run(&[], &[1, 2])), (0, 2, 0));
assert_eq!(counts(&run(&[1, 2], &[])), (0, 0, 2));
assert_eq!(run(&[1, 2, 3, 4], &[5, 6]).updated(), 2);
run(&[1, 1, 1], &[1, 1]);
run(&[1, 2, 1], &[1, 1, 2, 1]);
run(&[4, 5, 6], &[1, 2, 3, 4, 5, 6, 7]);
}
/// Whatever the lists, applying the changes gives the new list, and
/// rows that stay at the ends are not touched.
#[test]
fn every_small_pair() {
let lists: Vec<Vec<i32>> = (0..4usize)
.flat_map(|n| (0..3i32.pow(n as u32)).map(move |k| (n, k)))
.map(|(n, k)| (0..n as u32).map(|i| (k / 3i32.pow(i)) % 3).collect())
.collect();
for old in &lists {
for new in &lists {
let changes = run(old, new);
let kept = old.iter().zip(new).take_while(|(a, b)| a == b).count();
assert!(changes.0.iter().all(|c| match *c {
Change::Update(i) | Change::Remove(i) | Change::Insert(i) => i >= kept,
}));
}
}
}
}
@@ -1,16 +1,19 @@
//! The server rail, the server dialog, and joining a channel.
use slint::{Color, SharedString};
use std::sync::Arc;
use voelin_core::{ObserveState, SessionState, VoiceState};
use voelin_model::{ChannelId, ChannelInfo, Presence, ServerLink};
use voelin_store::Bookmark;
use crate::app::{BookmarkForm, ServerItem};
use crate::vm::avatar;
use crate::avatar;
use crate::bridge::{BookmarkForm, ServerItem};
use crate::color::Rgb;
use crate::image::ImageRef;
/// Restore a known server icon before any session exists. A missing/evicted
/// cache file falls back to initials; the bookmark stores no filesystem path.
pub fn cached_icon(bookmark: &Bookmark, cache: &voelin_core::Cache) -> slint::Image {
pub fn cached_icon(bookmark: &Bookmark, cache: &voelin_core::Cache) -> ImageRef {
avatar::image(bookmark.server_icon_id().and_then(|id| cache.icon(id)).as_ref())
}
@@ -33,7 +36,7 @@ const SERVER_TINTS: [u32; 10] = [
/// when an earlier server has it, it takes the next free one. So no two
/// share a colour until there are more servers than colours (then they
/// start over), and adding a server leaves the others' colours.
pub fn tints(bookmarks: &[Bookmark]) -> Vec<Color> {
pub fn tints(bookmarks: &[Bookmark]) -> Vec<Rgb> {
let n = SERVER_TINTS.len();
let mut taken = [false; SERVER_TINTS.len()];
bookmarks
@@ -65,7 +68,7 @@ pub fn status(state: &SessionState) -> &'static str {
/// A server of the rail and the home page. `unread`: messages in its
/// chats; `live`: streams on it; `detail`: who is there ("9 online · 7
/// channels"), empty for its address; `flavor`: "TeamSpeak 6" once
/// channels"), empty for its address; `product`: "TeamSpeak 6" once
/// reached; `icon`: the server's icon (empty: its initials) on `tint`
/// ([`tints`]).
#[allow(clippy::too_many_arguments)]
@@ -75,9 +78,9 @@ pub fn item(
unread: i32,
live: bool,
detail: String,
flavor: String,
icon: slint::Image,
tint: Color,
product: String,
icon: ImageRef,
tint: Rgb,
) -> ServerItem {
ServerItem {
id: bookmark.id as i32,
@@ -90,7 +93,7 @@ pub fn item(
unread,
live,
detail: if detail.is_empty() { bookmark.address.clone() } else { detail }.into(),
flavor: flavor.into(),
product: product.into(),
gateway: bookmark.gateway_url.is_some() || bookmark.query.is_some(),
}
}
@@ -106,7 +109,7 @@ pub fn form(
BookmarkForm {
id: bookmark.id as i32,
name: if bookmark.name == bookmark.address {
SharedString::new()
"".into()
} else {
bookmark.name.clone().into()
},
@@ -134,7 +137,7 @@ pub struct ConnectTo {
/// channel; and the link's privilege key.
pub fn connect_to(form: &BookmarkForm, saved: Option<&Bookmark>) -> Option<ConnectTo> {
let saved = saved?;
let given = |text: &SharedString| Some(text.to_string()).filter(|t| !t.is_empty());
let given = |text: &Arc<str>| Some(text.to_string()).filter(|t| !t.is_empty());
let channel = given(&form.channel);
Some(ConnectTo {
channel_password: channel.as_ref().and_then(|_| given(&form.channel_password)),
@@ -215,7 +218,7 @@ pub fn link_form(
mut form: BookmarkForm,
default_nickname: &str,
) -> BookmarkForm {
let text = |value: &Option<String>| SharedString::from(value.as_deref().unwrap_or_default());
let text = |value: &Option<String>| Arc::<str>::from(value.as_deref().unwrap_or_default());
if form.id < 0 {
form.address = link.address().into();
}
@@ -223,7 +226,7 @@ pub fn link_form(
form.nickname = link.nickname.as_deref().unwrap_or(default_nickname).into();
}
if let Some(password) = &link.password {
form.server_password = password.into();
form.server_password = password.as_str().into();
}
form.channel = text(&link.channel);
form.channel_password = text(&link.channel_password);
@@ -302,9 +305,9 @@ mod tests {
String::new(),
String::new(),
cached_icon(&bookmark, &cache),
Color::default(),
Rgb::default(),
);
assert_eq!(server.status.as_str(), "offline");
assert_eq!(server.status.as_ref(), "offline");
assert_eq!(server.icon.size().width, 4);
bookmark.address = "different.test".into();
assert_eq!(cached_icon(&bookmark, &cache).size().width, 0);
@@ -314,12 +317,34 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
/// The chip of a server reads the product its session reported.
#[test]
fn a_server_shows_the_product_it_runs() {
let bookmark = Bookmark { address: "example.test".into(), ..Default::default() };
let state = SessionState::default();
let on = |product: &str| {
item(
&bookmark,
&state,
0,
false,
String::new(),
product.into(),
Default::default(),
Rgb::default(),
)
};
assert_eq!(on("TeamSpeak 6").product.as_ref(), "TeamSpeak 6");
// Before the server answered, and for software nobody recognised: none.
assert_eq!(on("").product.as_ref(), "");
}
fn named(names: &[&str]) -> Vec<Bookmark> {
names.iter().map(|n| Bookmark { name: (*n).into(), ..Default::default() }).collect()
}
/// The colour a name picks.
fn own_tint(name: &str, step: usize) -> Color {
fn own_tint(name: &str, step: usize) -> Rgb {
let n = SERVER_TINTS.len();
avatar::rgb(SERVER_TINTS[(avatar::name_hash(name) as usize + step) % n])
}
@@ -329,7 +354,7 @@ mod tests {
let names: Vec<String> = (0..SERVER_TINTS.len()).map(|i| format!("Server {i}")).collect();
let mut bookmarks = named(&names.iter().map(String::as_str).collect::<Vec<_>>());
let distinct: std::collections::HashSet<_> =
tints(&bookmarks).iter().map(|t| t.as_argb_encoded()).collect();
tints(&bookmarks).iter().map(|t| t.0).collect();
assert_eq!(distinct.len(), SERVER_TINTS.len());
// One more starts over with its name's colour.
bookmarks.extend(named(&["One more"]));
@@ -363,8 +388,8 @@ mod tests {
};
let mut state = SessionState::default();
let f = form(&b, None, "pw");
assert_eq!((f.id, f.name.as_str(), f.address.as_str()), (3, "", "ts.example.test"));
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "pw"));
assert_eq!((f.id, f.name.as_ref(), f.address.as_ref()), (3, "", "ts.example.test"));
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "pw"));
assert!(!f.connected);
for (voice, connected) in [
(VoiceState::Disconnected, false),
@@ -380,7 +405,7 @@ mod tests {
state.observe = ObserveState::Observing;
assert!(!form(&b, Some(&state), "").connected);
let named = Bookmark { name: "Nightfall".into(), ..b };
assert_eq!(form(&named, None, "").name.as_str(), "Nightfall");
assert_eq!(form(&named, None, "").name.as_ref(), "Nightfall");
}
#[test]
@@ -546,16 +571,16 @@ mod tests {
// A new server: the link's address, nickname and password.
let new = BookmarkForm { id: -1, nickname: "Me".into(), ..Default::default() };
let f = link_form(&link, new.clone(), "Me");
assert_eq!((f.id, f.name.as_str(), f.address.as_str()), (-1, "", "ts.example.org:9988"));
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Link", "pw"));
assert_eq!((f.id, f.name.as_ref(), f.address.as_ref()), (-1, "", "ts.example.org:9988"));
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Link", "pw"));
assert_eq!(
(f.channel.as_str(), f.channel_password.as_str(), f.token.as_str()),
(f.channel.as_ref(), f.channel_password.as_ref(), f.token.as_ref()),
("Gaming/Raid Night", "raid", "key")
);
let f = link_form(&bare, new, "Me");
assert_eq!((f.address.as_str(), f.nickname.as_str()), ("ts.example.org", "Me"));
assert_eq!((f.address.as_ref(), f.nickname.as_ref()), ("ts.example.org", "Me"));
assert_eq!(
(f.server_password.as_str(), f.channel.as_str(), f.token.as_str()),
(f.server_password.as_ref(), f.channel.as_ref(), f.token.as_ref()),
("", "", "")
);
// A saved server keeps its address, name, nickname and password...
@@ -569,14 +594,14 @@ mod tests {
};
let f = link_form(&bare, saved.clone(), "Me");
assert_eq!(
(f.id, f.name.as_str(), f.address.as_str()),
(f.id, f.name.as_ref(), f.address.as_ref()),
(3, "Nightfall", "TS.example.org:9988")
);
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "stored"));
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "stored"));
// ...the link's password in place of the stored one.
let f = link_form(&link, saved, "Me");
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "pw"));
assert_eq!((f.channel.as_str(), f.token.as_str()), ("Gaming/Raid Night", "key"));
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "pw"));
assert_eq!((f.channel.as_ref(), f.token.as_ref()), ("Gaming/Raid Night", "key"));
}
#[test]
@@ -9,7 +9,7 @@ use voelin_audio::process::NoiseLevel;
use voelin_core::settings::{Key, Kind};
use voelin_core::{AudioSettings, TransmitMode};
use crate::app::AudioForm;
use crate::bridge::AudioForm;
/// The window's settings, one value (the `ui` blob of earlier versions).
pub static UI: Key<UiSettings> = Key::new(
@@ -39,6 +39,7 @@ pub enum ThemeChoice {
}
impl ThemeChoice {
/// The value stored for this choice.
pub fn as_str(self) -> &'static str {
match self {
Self::Dark => "dark",
@@ -47,6 +48,7 @@ impl ThemeChoice {
}
}
/// The choice a stored value names (dark for any other).
pub fn parse(text: &str) -> Self {
match text {
"light" => Self::Light,
@@ -133,10 +135,12 @@ pub enum NotifyLevel {
}
impl NotifyLevel {
/// The position in the settings' list (off, app, desktop).
pub fn index(self) -> i32 {
self as i32
}
/// The choice at a list position (desktop for any other).
pub fn from_index(index: i32) -> Self {
match index {
0 => Self::Off,
@@ -155,22 +159,26 @@ pub static NOTIFY_MENTIONS: Key<NotifyLevel> = Key::new(
"Our name in a channel or server chat: off, app (the bell) or desktop.",
NotifyLevel::default,
);
/// Private messages: off, app (the bell) or desktop.
pub static NOTIFY_MESSAGES: Key<NotifyLevel> = Key::new(
"notify.private_messages",
NOTIFY_LEVELS,
"Private messages: off, app (the bell) or desktop.",
NotifyLevel::default,
);
/// Pokes: off, app (the bell) or desktop.
pub static NOTIFY_POKES: Key<NotifyLevel> =
Key::new("notify.pokes", NOTIFY_LEVELS, "Pokes: off, app (the bell) or desktop.", || {
NotifyLevel::Desktop
});
/// Reminders of scheduled events: off, app (the bell) or desktop.
pub static NOTIFY_EVENTS: Key<NotifyLevel> = Key::new(
"notify.event_reminders",
NOTIFY_LEVELS,
"Reminders of scheduled events: off, app (the bell) or desktop.",
NotifyLevel::default,
);
/// Friends coming online: off, app (the bell) or desktop.
pub static NOTIFY_FRIENDS: Key<NotifyLevel> = Key::new(
"notify.friends_online",
NOTIFY_LEVELS,
@@ -253,11 +261,14 @@ pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 10] {
/// offers, in the order of its lists (`dialogs.slint`); any other value can
/// be typed in.
pub const FPS_CHOICES: [u32; 7] = [15, 30, 60, 120, 144, 240, 320];
/// The bitrates (kbit/s, 0 for automatic) the share dialog offers, in the
/// order of its list.
pub const BITRATE_CHOICES: [u32; 8] = [0, 2500, 4608, 8000, 10_000, 20_000, 40_000, 60_000];
/// The share dialog's lists before they grew, which [`ShareDefaults`]
/// indexes for older versions.
pub const LEGACY_FPS_CHOICES: [u32; 3] = [15, 30, 60];
/// The bitrates of the share dialog's list before it grew.
pub const LEGACY_BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000];
/// The index of the choice closest to `value`.
@@ -270,6 +281,8 @@ pub fn parse_positive(text: &str) -> Option<u32> {
text.trim().parse().ok().filter(|v| *v > 0)
}
/// The `ui` settings: what the front end keeps about itself (the push-to-talk
/// hotkey, codecs, the share dialog's defaults, the last voice channel).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct UiSettings {
@@ -347,11 +360,13 @@ impl Default for ClientPlayback {
}
impl ClientPlayback {
/// Nothing differs from the defaults, so there is nothing to store.
pub fn is_default(&self) -> bool {
*self == Self::default()
}
}
/// Each client's playback settings, by the client's unique id.
pub type ClientPlaybackMap = BTreeMap<String, ClientPlayback>;
/// Audio devices as listed in the settings: the system default first.
@@ -387,10 +402,14 @@ impl DeviceChoices {
choices
}
/// The index of the choice for device `id` (the system default for `None` or
/// an unknown id).
pub fn index_of(&self, id: Option<&str>) -> usize {
self.ids.iter().position(|i| i.as_deref() == id).unwrap_or(0)
}
/// The device id of choice `index`; `None` for the system default or an index
/// outside the list.
pub fn id_at(&self, index: i32) -> Option<String> {
usize::try_from(index).ok().and_then(|i| self.ids.get(i).cloned()).flatten()
}
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff. Show more