Implement Rust and Slint native client migration and fix desktop startup
ci / linux-arm64-cross (push) Successful in 4m7s
ci / linux-x64 (push) Successful in 4m42s

This commit is contained in:
omar committed 2026-11-10 15:45:24 +03:00
1 parent 0d11f8f99d
commit eb24965076
1303 files changed
+732670 -2375

No files matched your search

+3
View File
@@ -12,3 +12,6 @@ LIBOPUS_NO_PKG = "1"
# with Windows 10+ (no VCRUNTIME140.dll). cc/cmake-rs see `crt-static` and build libopus with /MT.
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
[target.aarch64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
+8 -8
View File
@@ -33,7 +33,7 @@ jobs:
- name: Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target wasm32-unknown-unknown
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain 1.96.0 --target wasm32-unknown-unknown
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: glibc baseline
@@ -57,10 +57,10 @@ jobs:
run: cargo build --manifest-path core/Cargo.toml --release --locked
- name: Core binary architecture
run: node scripts/binary-arch.mjs core/target/release/teamspeach-core --expect linux-x64
run: node scripts/binary-arch.mjs "${CARGO_TARGET_DIR:-target}/release/teamspeach-core" --expect linux-x64
- name: Core identity smoke (stdio, offline)
run: node scripts/core-smoke.mjs core/target/release/teamspeach-core
run: node scripts/core-smoke.mjs "${CARGO_TARGET_DIR:-target}/release/teamspeach-core"
- name: Electron UI smoke (Xvfb, offline, disposable profile)
env:
@@ -100,23 +100,23 @@ jobs:
- name: Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target aarch64-unknown-linux-gnu
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain 1.96.0 --target aarch64-unknown-linux-gnu
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Core cross build (aarch64-unknown-linux-gnu)
run: cargo build --manifest-path core/Cargo.toml --release --locked --target aarch64-unknown-linux-gnu
- name: Core binary architecture
run: node scripts/binary-arch.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --expect linux-arm64
run: node scripts/binary-arch.mjs "${CARGO_TARGET_DIR:-target}/aarch64-unknown-linux-gnu/release/teamspeach-core" --expect linux-arm64
- name: Required glibc symbols
run: aarch64-linux-gnu-objdump -T core/target/aarch64-unknown-linux-gnu/release/teamspeach-core | grep -o 'GLIBC_[0-9.]*' | sort -Vu | tail -n1
run: aarch64-linux-gnu-objdump -T "${CARGO_TARGET_DIR:-target}/aarch64-unknown-linux-gnu/release/teamspeach-core" | grep -o 'GLIBC_[0-9.]*' | sort -Vu | tail -n1
- name: 16 KiB page compatibility (Asahi) of the core ELF
run: node scripts/elf-pagesize.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --page 16384
run: node scripts/elf-pagesize.mjs "${CARGO_TARGET_DIR:-target}/aarch64-unknown-linux-gnu/release/teamspeach-core" --page 16384
- name: Core identity smoke under qemu-aarch64 (emulated, not native hardware)
run: node scripts/core-smoke.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"
run: node scripts/core-smoke.mjs "${CARGO_TARGET_DIR:-target}/aarch64-unknown-linux-gnu/release/teamspeach-core" --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"
# The unit tests (voice detector, resampler, identity keys, codecs, protocol) built for aarch64 and run
# under user-mode qemu. Emulated, not native hardware; the bridge smoke tests spawn the core binary and
+7 -7
View File
@@ -41,7 +41,7 @@ jobs:
- name: Rust toolchain
run: |
set -euo pipefail
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target wasm32-unknown-unknown
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain 1.96.0 --target wasm32-unknown-unknown
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Tests
@@ -57,8 +57,8 @@ jobs:
run: |
set -euo pipefail
cargo build --manifest-path core/Cargo.toml --release --locked
node scripts/binary-arch.mjs core/target/release/teamspeach-core --expect linux-x64
node scripts/core-smoke.mjs core/target/release/teamspeach-core
node scripts/binary-arch.mjs "${CARGO_TARGET_DIR:-target}/release/teamspeach-core" --expect linux-x64
node scripts/core-smoke.mjs "${CARGO_TARGET_DIR:-target}/release/teamspeach-core"
- name: Electron UI smoke (Xvfb, offline)
env:
@@ -124,16 +124,16 @@ jobs:
- name: Rust toolchain
run: |
set -euo pipefail
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target aarch64-unknown-linux-gnu --target wasm32-unknown-unknown
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain 1.96.0 --target aarch64-unknown-linux-gnu --target wasm32-unknown-unknown
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Core cross build and checks
run: |
set -euo pipefail
cargo build --manifest-path core/Cargo.toml --release --locked --target aarch64-unknown-linux-gnu
node scripts/binary-arch.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --expect linux-arm64
node scripts/elf-pagesize.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --page 16384
node scripts/core-smoke.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"
node scripts/binary-arch.mjs "${CARGO_TARGET_DIR:-target}/aarch64-unknown-linux-gnu/release/teamspeach-core" --expect linux-arm64
node scripts/elf-pagesize.mjs "${CARGO_TARGET_DIR:-target}/aarch64-unknown-linux-gnu/release/teamspeach-core" --page 16384
node scripts/core-smoke.mjs "${CARGO_TARGET_DIR:-target}/aarch64-unknown-linux-gnu/release/teamspeach-core" --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"
- name: Package
run: |
+1
View File
@@ -2,6 +2,7 @@
node_modules/
dist/
core-bin/
target/
core/target/
# local runtime data, logs and identities
+27
View File
@@ -2,6 +2,33 @@
## Unreleased
- Started the approved native migration with one Cargo workspace and lockfile, pinned Rust 1.96.0,
root-target artifact resolution and a separate `denoise` build profile. Existing core/DSP dependency
resolutions are preserved. The Electron reference remains operational until native acceptance passes.
- Added the native compatibility inventory; entries remain pending, not claims of feature completion.
Initial Slint software and Skia windows were exercised with a real pointer Close action;
this does not establish native voice, video, mobile support or whole-client migration completion.
- Extracted the protocol core into an embedded library with validated typed commands, joined session
lifetimes, generation-stamped events, bounded PCM and capture guards at the actual UDP-send boundary.
Diagnostic stdio remains independently usable by the reference client.
- Ported native profile import, local stores and session-bound file/icon/snapshot services. Imports retain
the original profile, preserve identity keys/UIDs and require bookmark passwords once again. Native
secret/preference pair commits recover interrupted writes; unknown staging directories are never discarded.
Windows isolated DPAPI and migration/restart smoke passed; other OS key stores and live mutations remain
separate verification gates. Snapshot format stays 0.0.1; native About labels legacy notices as historical.
- Added worker-owned CPAL audio, bounded timestamped callback queues, drift-aware Rubato conversion,
integrated Sonora AEC/NS/AGC and independent notification sinks. Capture/output revocation survives
queue congestion; source expiry remains attached through resampling to hardware presentation.
Controlled DSP/queue/permission and native worker smoke passed (generated PCM, no physical devices).
Official-peer voice, acoustic echo cancellation and mobile/Asahi hardware remain unverified.
- Added pinned source-built native WebRTC provisioning, checked desktop/mobile capture adapters and
generation-bound TS6 viewer/publisher state machines. Windows x64 CXX bridge compilation passed.
The production software decoder factory decoded synthetic H264 High, AV1, VP8 and VP9 fixtures;
all four 64×48 I420 outputs exactly matched independent FFmpeg decoding. Sustained native playback,
official TS6 peers, physical capture, hardware decode and other platforms remain separate gates.
- Proved a device-free native PeerConnection loopback through the real sender/decoder/display path
(13 decoded frames, 12 presented, terminal cleanup). Isolated WebRTC Opus symbols from the voice
core's existing codec without weakening linker checks or rewriting unrelated assembly objects.
- Rebuilt Privacy, Video, Notifications and About in the original section order. Unsupported account,
telemetry, Cisco/backend and content-report options are explicitly unavailable, never fake preferences.
Working Chromium decoder controls and installation/project details moved to linked subpages with
Generated
+9740
View File
File diff suppressed because it is too large. Load diff
+55
View File
@@ -0,0 +1,55 @@
[workspace]
resolver = "3"
members = ["core", "dsp", "native", "xtask"]
exclude = ["core/vendor/tsclientlib", "core/vendor/tsproto", "dsp/vendor/sonora", "dsp/vendor/sonora-agc2", "native/vendor/libwebrtc-0.4.0", "native/vendor/webrtc-sys-0.3.53", "native/vendor/katex-rs-0.3.0", "native/vendor/mermaid-rs-renderer-0.3.1", "native/vendor/cpal-0.18.2", "native/vendor/i-slint-backend-android-activity-1.18.1"]
[workspace.package]
version = "0.1.7"
edition = "2024"
rust-version = "1.96"
publish = false
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["raw_value", "preserve_order", "unbounded_depth"] }
thiserror = "2"
tokio = { version = "1", features = ["rt", "sync", "time", "macros"] }
slint = { version = "=1.18.1", default-features = false, features = ["std", "compat-1-18", "accessibility", "image-default-formats", "unstable-fontique-011"] }
slint-build = "=1.18.1"
cpal = "=0.18.2"
rubato = { version = "=5.0.1", default-features = false }
sonora = "=0.2.0"
sonora-ns = "=0.2.0"
libwebrtc = "=0.4.0"
webrtc-sys = "=0.3.53"
katex-native = "=0.1.1"
katex-rs = "=0.3.0"
mermaid-rs-renderer = { version = "=0.3.1", default-features = false }
cssparser = "=0.38.0"
[patch."https://github.com/ReSpeak/tsclientlib"]
tsproto = { path = "core/vendor/tsproto" }
[patch.crates-io]
sonora = { path = "dsp/vendor/sonora" }
sonora-agc2 = { path = "dsp/vendor/sonora-agc2" }
libwebrtc = { path = "native/vendor/libwebrtc-0.4.0" }
webrtc-sys = { path = "native/vendor/webrtc-sys-0.3.53" }
katex-rs = { path = "native/vendor/katex-rs-0.3.0" }
mermaid-rs-renderer = { path = "native/vendor/mermaid-rs-renderer-0.3.1" }
cpal = { path = "native/vendor/cpal-0.18.2" }
i-slint-backend-android-activity = { path = "native/vendor/i-slint-backend-android-activity-1.18.1" }
[profile.release]
lto = "thin"
codegen-units = 4
[profile.denoise]
inherits = "release"
opt-level = 3
lto = true
codegen-units = 1
panic = "abort"
debug = false
strip = true
incremental = false
+106
View File
@@ -1,5 +1,31 @@
# TeamsPeach ↔ TeamSpeak 6 server features
## Native migration verification (2026-11-10)
The Rust/Slint migration is not a completed product cutover. Historical Electron evidence below
does not establish native or mobile acceptance. The reference client remains available.
Windows x64 WebRTC was built from pinned SDK `88705b15086ecbe2c26ee91ede6203f974a0fc62` and
WebRTC `9c3a1386f07e4348c28cd85c066821cebc3b56e4`; `native/native-deps.lock.json` records the
resolved DEPS, patches, effective GN arguments, compiler, archive gates and artifact hashes.
The native CXX bridge compiled against that source-built archive. No mutable prebuilt was used.
`native/tools/codec_probe.cpp` exercised the production software-only decoder factory with four
independently encoded synthetic 64×48 single-frame fixtures. H264 High decoded through FFmpeg,
AV1 Profile 0 through dav1d, and VP8/VP9 through libvpx. Every output matched the corresponding
independent FFmpeg I420 reference byte-for-byte. Fixtures and outputs were generated under
`target/codec-fixtures`; this proves these small decode cases, not sustained playback, hardware
acceleration, official-peer compatibility or other targets.
A separate real native PeerConnection loopback negotiated and transported generated video through
the production sender, receiver and bounded display path: 13 frames decoded by libvpx, 12 presented
with the expected red pixels, and one source-stop callback. Terminal cleanup removed the pending
frame. `target/codec-fixtures/peer-loopback.png` is the captured decoded image, not a UI mock.
This check exposed and fixed duplicate Opus linkage: WebRTC's 443 external Opus symbols and their
references are isolated from the unchanged voice-core codec, while unrelated assembly objects are
preserved byte-for-byte. No physical microphone, speaker, camera, screen capture or working server
was used for these checks.
## Approved original panel composition
The owner selected the original TS6 composition for Privacy, Video, Notifications and About. Root
@@ -199,3 +225,83 @@ not a claim about every server configuration. Evidence: `docs/evidence/official-
explanation. Explicitly authorized test-only CDP viewport emulation exercises the real adopted video,
MediaStream, continuing RTP, child controls and restore/cleanup. It does not verify unmodified native
offscreen painting or a normal visible child window; production flags are not weakened for the test.
## Native runtime integration and Windows offline evidence
The native host now owns a dedicated Tokio application worker and constructs the existing profile,
connection, file, audio and stream services. `native/src/app/runtime/` routes captured shell/chat/settings
intents and authoritative core/audio/platform events; settings use an ordered bounded consumer with
pending control identities and explicit completion/error state. First-run profile/import/recovery
decisions precede writable profile ownership, and private-key import and staging-discard operations
require an explicit warning confirmation.
`ui::application::bind` constructs a generation-scoped Slint attachment without entering its event
loop. It keeps Slint objects on the UI thread, applies coalesced Send-only snapshots, drains bounded
effects/prompts, and updates latest video images without re-projecting the tree for each frame.
Native theme font bytes pass the existing confined asset policy and are registered with Slint's
pinned Fontique interface; CSS Color 4 token values are converted to the sRGB UI surface.
`AppConfig::isolated` disables network and OS/device actions. Runtime snapshots expose actual
audio-start event counters and structured settings completion errors so a denied action cannot be
mistaken for a successful operation or an unrelated stale error. Mobile call capabilities and UI
generations have separate lifetimes; desktop installation state comes from validated running-package
metadata, not a caller-supplied installed flag.
Windows x64 integration now builds through `xtask build --target x86_64-pc-windows-msvc
--test-harness true`. The full release-profile workspace test command passed, including 461 native
library tests, the real atomic-document replacement regression, connection lifetime tests and updater
contracts. The captured-speech quality test remains explicitly ignored without its external PCM fixture.
Executed native smoke reports (under the local `target/evidence/` directory):
- `native-offline-ui-03/result.json`: actual Slint software rasterization, account-free onboarding,
all twelve settings categories, EN/RU and dark/light at 390/800/1280 logical pixels, actual semantic
combobox values matching persisted selections, math/Mermaid images, literal HTML, real text-input
focus blocking local PTT, microphone permission denial with zero physical endpoint starts, refused
Unicode draft retention/undo/redo, two full profile restarts and stale session rejection.
- `native-migration-01/result.json`: generated legacy profile import, unchanged hashes of five source
files, preserved UID/default identity, security offset 42424242 and history. No existing user profile
was imported or modified. This run predates the controlled-combobox correction checked above.
- `native-media-loopback-01/result.json`: production native PeerConnections decoded moving generated
video (13 decoded, 12 presented, libvpx) and 46 decoded audio blocks / 22080 samples, RMS 0.06160.
Audio was observed at the real decoded AudioSink before the closed output gate; no speaker or
microphone was opened. This is same-host RTP/ICE/DTLS evidence, not official TS6 signaling acceptance.
Smoke failures found and corrected an OS-capability page which refused navigation, stale native
combobox captions despite persisted values, missing text-focus propagation to local shortcuts and
Windows atomic overwrite failing while the old reader remained open. Windows publication now uses
`FileRenameInformationEx` with POSIX replacement semantics, preserving existing reader handles.
These results do not establish acoustic AEC, physical capture, official-peer interoperability,
Asahi/mobile execution, OS accessibility, installed updater/relaunch or complete visual parity.
Existing Electron evidence above remains historical reference. The reference production path remains
intentionally present until the approved migration's full acceptance gates pass.
Windows test-only packaging produced an unsigned NSIS installer (38,668,543 bytes) and ZIP
(52,858,951 bytes) in `target/evidence/native-package-03/`. Its `x86_64-pc-windows-msvc/verification.json`
passed real archive extraction, application/helper ISA and imports, asset/license hashes and the
browser/Node/WASM exclusion checks. NSIS's x86 uninstaller/plugin are classified separately from the
x64 application. The executable extracted from that ZIP passed the complete offline UI smoke from
its own package directory: `target/evidence/native-packaged-smoke-01/result.json`.
The installer was not executed, no default installation was modified, and no release manifest/update
feed was published. Both artifacts have `testOnly=true` and `release_eligible=false`; they are not a
production migration or installed update/relaunch proof.
### Ordinary desktop startup correction
The first test ZIP failed normal Windows launch with `Attach the desktop lease after the Slint
window is realized`; offscreen smoke did not cover the winit startup ordering. Desktop attachment
now awaits Slint's native-window future on its UI executor, retains/cancels that task with the UI
generation, and propagates real initialization failures. Closing onboarding also now stops the
application before profile services exist (including failed profile inspection).
`native/examples/desktop_startup_smoke.rs` exercised the real Windows window and desktop lease,
captured its 1280×800 pixels and closed it through the normal close-request callback. Evidence:
`target/evidence/native-desktop-startup-02/`. The corrected portable `teamspeach.exe` was also started
normally with a fresh test profile, observed as a visible TeamsPeach window, then sent WM_CLOSE:
exit code 0, empty stdout/stderr. No microphone/speaker or server connection was started.
The desktop delivery is `TeamsPeach-0.1.7-win-x64-startup-fix/` and the matching ZIP; the executable
SHA256 is `9d4d898b7ea723a9e0cdff2ca47cf4dbbdb2981163a6403498ab010c7bad9a95`.
+7 -3
View File
@@ -14,12 +14,16 @@ have not been proven.
```
npm ci
rustup target add wasm32-unknown-unknown
node scripts/build-denoise.mjs # independent WASM noise reduction
cargo build --release --locked --manifest-path core/Cargo.toml # requires Rust ≥ 1.89, CMake and a C compiler
node scripts/build-denoise.mjs # workspace denoise profile, zero-import WASM
cargo build --release --locked --manifest-path core/Cargo.toml # pinned Rust 1.96.0, CMake and a C compiler
npm start
```
Electron looks for the core in `core/target/release` and `core/target/debug`, choosing the newer binary.
Electron looks for the core in workspace `target/release` and `target/debug`, choosing the newer binary.
`CARGO_TARGET_DIR` overrides that directory; relative paths resolve from the repository root in the
launch and packaging scripts. The workspace uses one root `Cargo.lock`; the `denoise` Cargo profile
retains the separate WASM optimization settings. The native migration is in progress, not a replacement
client release: `native/compatibility.json` tracks pending consumer contracts, not completed features.
If rustup installed Cargo without adding it to PATH on Windows, run
`%USERPROFILE%\.cargo\bin\cargo.exe` or open Developer PowerShell for VS. Use `-j 2` if linking runs out
of memory.
+1 -1
View File
@@ -116,7 +116,7 @@ const clientTarget = { client_id: boundedInt(1, 65535), uid: str(1, 128) };
const menuActionArgs = {
poke: { message: str(1, 1024, { maxBytes: 1024 }) },
connection_info: {}, commander: { enabled: bool },
move_to_own_channel: { password: optional(str(0, 1024, { maxBytes: 1024 })) },
move_to_own_channel: { password: optional(str(0, 1024, { maxBytes: 1024 })), expected_channel_id: boundedInt(1, Number.MAX_SAFE_INTEGER) },
delete_avatar: {},
server_group: { group_id: boundedInt(1, Number.MAX_SAFE_INTEGER), enabled: bool },
channel_group: { group_id: boundedInt(1, Number.MAX_SAFE_INTEGER), channel_id: boundedInt(1, Number.MAX_SAFE_INTEGER) },
+3 -2
View File
@@ -11,9 +11,10 @@ const RENDERER_DIR = path.join(APP_ROOT, 'app', 'renderer');
/** Candidate locations of the native core. Only main decides these; nothing comes from the renderer. */
function coreCandidates() {
if (app.isPackaged) return [path.join(process.resourcesPath, 'core', CORE_FILE)];
const targetDir = path.resolve(APP_ROOT, process.env.CARGO_TARGET_DIR || 'target');
return [
path.join(APP_ROOT, 'core', 'target', 'release', CORE_FILE),
path.join(APP_ROOT, 'core', 'target', 'debug', CORE_FILE),
path.join(targetDir, 'release', CORE_FILE),
path.join(targetDir, 'debug', CORE_FILE),
];
}
+1 -1
View File
@@ -468,7 +468,7 @@ class HotkeyHelper {
if (!down.delete(msg.id)) return;
if (down.size === 0) {
this.heldVariants.delete(id);
this.onEvent({ id, state: 'release', source: 'global' });
this.onEvent({ id, state: 'release', source: 'global', ...(msg.synthetic === true ? { synthetic: true } : {}) });
}
}
break;
Binary file not shown.
+1
View File
@@ -403,6 +403,7 @@ function showAction(session, action, fields = {}, detail = '') {
try {
if (action === 'move_to_own_channel') {
if (session.conn.snap.own_channel_id !== moveChannelId) throw new Error(label('targetGone'));
args.expected_channel_id = moveChannelId;
if (password) args.password = password.value;
}
if (action === 'avatar') {
-3
View File
@@ -60,6 +60,3 @@ windows-sys = { version = "0.61", features = [
dbus = { version = "0.9", features = ["vendored"] }
x11rb = "0.13"
[profile.release]
lto = "thin"
codegen-units = 4
+186 -57
View File
@@ -204,12 +204,52 @@ pub const HINT_PERMISSIONS: &[&str] = &[
#[derive(Clone, Debug, PartialEq)]
pub enum PrivilegeKeyKind { ServerGroup, ChannelGroup }
#[derive(Clone, Copy, Debug, PartialEq)]
enum PropertyScope { ChannelCreate, ChannelEdit, ServerEdit }
/// Immutable, scope-bound wire properties. Constructors accept typed JSON values,
/// not serialized JSON or wire strings: booleans/numbers retain their types and
/// password values are plaintext at this boundary and hashed exactly once.
/// The derived channel password flag cannot be supplied by the caller.
#[derive(Clone, Debug, PartialEq)]
pub struct Properties {
scope: PropertyScope,
values: Vec<(&'static str, String)>,
}
impl Properties {
pub fn channel_create(value: Map<String, Value>) -> Result<Self, ErrorObj> {
let values = properties(value, CHANNEL_CREATE)?;
if !values.iter().any(|(k, _)| *k == "channel_name") { return Err(bad("channel_name is required")); }
Ok(Self { scope: PropertyScope::ChannelCreate, values })
}
pub fn channel_edit(value: Map<String, Value>) -> Result<Self, ErrorObj> {
let values = properties(value, CHANNEL_EDIT)?;
if values.is_empty() { return Err(bad("properties must not be empty")); }
Ok(Self { scope: PropertyScope::ChannelEdit, values })
}
pub fn server_edit(value: Map<String, Value>) -> Result<Self, ErrorObj> {
let values = properties(value, SERVER_EDIT)?;
if values.is_empty() { return Err(bad("properties must not be empty")); }
Ok(Self { scope: PropertyScope::ServerEdit, values })
}
fn check_scope(&self, scope: PropertyScope) -> Result<(), ErrorObj> {
if self.scope != scope { return Err(bad("properties belong to a different command")); }
Ok(())
}
}
impl std::ops::Deref for Properties {
type Target = [(&'static str, String)];
fn deref(&self) -> &Self::Target { &self.values }
}
#[derive(Clone, Debug, PartialEq)]
pub enum AdminCommand {
Extra(extra::Command),
Context,
ChannelCreate { generation: u64, parent_id: u64, properties: Vec<(&'static str, String)> },
ChannelEdit { generation: u64, channel_id: u64, properties: Vec<(&'static str, String)> },
ChannelCreate { generation: u64, parent_id: u64, properties: Properties },
ChannelEdit { generation: u64, channel_id: u64, properties: Properties },
ChannelMove { generation: u64, channel_id: u64, parent_id: u64, order: Option<u64> },
ChannelDelete { generation: u64, channel_id: u64, force: bool, confirm: String },
ChannelSubscribe { channel_id: u64, subscribe: bool },
@@ -230,7 +270,7 @@ pub enum AdminCommand {
TempPasswordAdd { generation: u64, password: String, description: String, duration_s: u64, channel_id: u64, channel_password: String },
TempPasswordDelete { generation: u64, password: String, confirm: String },
ServerInfo,
ServerEdit { generation: u64, confirm: String, properties: Vec<(&'static str, String)> },
ServerEdit { generation: u64, confirm: String, properties: Properties },
ServerGroupPermList { group_id: u64 },
ChannelGroupPermList { group_id: u64 },
ChannelPermList { channel_id: u64 },
@@ -466,130 +506,165 @@ struct ServerEditArgs { generation: u64, confirm: String, properties: Map<String
pub fn parse(cmd: &str, raw: Option<&serde_json::value::RawValue>) -> Result<AdminCommand, ErrorObj> {
use AdminCommand as C;
let token = |t: &str| check_str("token", t, 255, false);
if extra::recognizes(cmd) { return extra::parse(cmd, raw).map(C::Extra); }
Ok(match cmd {
let command = match cmd {
"admin_context" => { args::<Empty>(raw)?; C::Context }
"channel_create" => {
let a: CreateArgs = args(raw)?;
let properties = properties(a.properties, CHANNEL_CREATE)?;
if !properties.iter().any(|(k, _)| *k == "channel_name") {
return Err(bad("channel_name is required"));
}
C::ChannelCreate { generation: generation(a.generation)?, parent_id: a.parent_id, properties }
let properties = Properties::channel_create(a.properties)?;
C::ChannelCreate { generation: a.generation, parent_id: a.parent_id, properties }
}
"channel_edit" => {
let a: EditArgs = args(raw)?;
let properties = properties(a.properties, CHANNEL_EDIT)?;
if properties.is_empty() { return Err(bad("properties must not be empty")); }
C::ChannelEdit { generation: generation(a.generation)?, channel_id: positive("channel_id", a.channel_id)?, properties }
let properties = Properties::channel_edit(a.properties)?;
C::ChannelEdit { generation: a.generation, channel_id: a.channel_id, properties }
}
"channel_move" => {
let a: MoveArgs = args(raw)?;
if a.parent_id == a.channel_id { return Err(bad("a channel cannot be its own parent")); }
C::ChannelMove { generation: generation(a.generation)?, channel_id: positive("channel_id", a.channel_id)?, parent_id: a.parent_id, order: a.order }
C::ChannelMove { generation: a.generation, channel_id: a.channel_id, parent_id: a.parent_id, order: a.order }
}
"channel_delete" => {
let a: DeleteArgs = args(raw)?;
C::ChannelDelete { generation: generation(a.generation)?, channel_id: positive("channel_id", a.channel_id)?, force: a.force, confirm: a.confirm }
C::ChannelDelete { generation: a.generation, channel_id: a.channel_id, force: a.force, confirm: a.confirm }
}
"channel_subscribe" => {
let a: SubscribeArgs = args(raw)?;
C::ChannelSubscribe { channel_id: positive("channel_id", a.channel_id)?, subscribe: a.subscribe }
C::ChannelSubscribe { channel_id: a.channel_id, subscribe: a.subscribe }
}
"channel_subscribe_all" => C::ChannelSubscribeAll { subscribe: args::<SubscribeAllArgs>(raw)?.subscribe },
"channel_description" => C::ChannelDescription { channel_id: positive("channel_id", args::<ChannelArgs>(raw)?.channel_id)? },
"channel_description" => C::ChannelDescription { channel_id: args::<ChannelArgs>(raw)?.channel_id },
"set_away" => {
let a: AwayArgs = args(raw)?;
if !a.away && a.message.is_some() { return Err(bad("message is only allowed with away: true")); }
check_opt("message", &a.message, 80)?;
C::SetAway { away: a.away, message: a.message }
}
"talk_request" => {
let a: TalkRequestArgs = args(raw)?;
if !a.request && a.message.is_some() { return Err(bad("message is only allowed with request: true")); }
check_opt("message", &a.message, 50)?;
C::TalkRequest { request: a.request, message: a.message }
}
"talk_power" => {
let a: TalkPowerArgs = args(raw)?;
let target = menu::Target { client_id: a.client_id, uid: a.uid };
menu::validate_target(&target)?;
C::TalkPower { generation: generation(a.generation)?, target, grant: a.grant }
C::TalkPower { generation: a.generation, target, grant: a.grant }
}
"ban_list" => { args::<Empty>(raw)?; C::BanList }
"ban_add" => {
let a: BanAddArgs = args(raw)?;
for (field, v) in [("ip", &a.ip), ("name", &a.name), ("uid", &a.uid)] { check_opt(field, v, 255)?; }
check_opt("reason", &a.reason, 512)?;
let given = |v: &Option<String>| v.as_deref().is_some_and(|s| !s.is_empty());
if !given(&a.ip) && !given(&a.name) && !given(&a.uid) {
return Err(bad("at least one of ip, name or uid is required"));
}
if a.duration_s > u32::MAX as u64 { return Err(bad("duration_s is too large")); }
C::BanAdd { generation: generation(a.generation)?, ip: a.ip, name: a.name, uid: a.uid, duration_s: a.duration_s, reason: a.reason }
C::BanAdd { generation: a.generation, ip: a.ip, name: a.name, uid: a.uid, duration_s: a.duration_s, reason: a.reason }
}
"ban_delete" => {
let a: BanDeleteArgs = args(raw)?;
C::BanDelete { generation: generation(a.generation)?, ban_id: positive("ban_id", a.ban_id)?, confirm: a.confirm }
C::BanDelete { generation: a.generation, ban_id: a.ban_id, confirm: a.confirm }
}
"ban_delete_all" => {
let a: ConfirmArgs = args(raw)?;
C::BanDeleteAll { generation: generation(a.generation)?, confirm: a.confirm }
C::BanDeleteAll { generation: a.generation, confirm: a.confirm }
}
"privilege_key_list" => { args::<Empty>(raw)?; C::PrivilegeKeyList }
"privilege_key_add" => {
let a: KeyAddArgs = args(raw)?;
check_str("description", &a.description, 255, true)?;
let (kind, channel_id) = match (a.kind.as_str(), a.channel_id) {
("server_group", None) => (PrivilegeKeyKind::ServerGroup, 0),
("channel_group", Some(cid)) => (PrivilegeKeyKind::ChannelGroup, positive("channel_id", cid)?),
("channel_group", Some(cid)) => (PrivilegeKeyKind::ChannelGroup, cid),
("server_group", Some(_)) => return Err(bad("channel_id is only allowed for kind channel_group")),
("channel_group", None) => return Err(bad("channel_id is required for kind channel_group")),
_ => return Err(bad("kind must be 'server_group' or 'channel_group'")),
};
C::PrivilegeKeyAdd { generation: generation(a.generation)?, kind, group_id: positive("group_id", a.group_id)?, channel_id, description: a.description }
C::PrivilegeKeyAdd { generation: a.generation, kind, group_id: a.group_id, channel_id, description: a.description }
}
"privilege_key_delete" => {
let a: TokenArgs = args(raw)?;
token(&a.token)?;
let confirm = a.confirm.ok_or_else(|| bad("confirm is required"))?;
C::PrivilegeKeyDelete { generation: generation(a.generation)?, token: a.token, confirm }
C::PrivilegeKeyDelete { generation: a.generation, token: a.token, confirm }
}
"privilege_key_use" => {
let a: TokenArgs = args(raw)?;
token(&a.token)?;
if a.confirm.is_some() { return Err(bad("confirm is not used by privilege_key_use")); }
C::PrivilegeKeyUse { generation: generation(a.generation)?, token: a.token }
C::PrivilegeKeyUse { generation: a.generation, token: a.token }
}
"temp_password_list" => { args::<Empty>(raw)?; C::TempPasswordList }
"temp_password_add" => {
let a: TempAddArgs = args(raw)?;
check_str("password", &a.password, 255, false)?;
check_str("description", &a.description, 255, true)?;
check_str("channel_password", &a.channel_password, 255, true)?;
if a.duration_s == 0 || a.duration_s > u32::MAX as u64 { return Err(bad("duration_s must be 1..=4294967295")); }
if a.channel_id == 0 && !a.channel_password.is_empty() { return Err(bad("channel_password needs channel_id")); }
C::TempPasswordAdd { generation: generation(a.generation)?, password: a.password, description: a.description, duration_s: a.duration_s, channel_id: a.channel_id, channel_password: a.channel_password }
C::TempPasswordAdd { generation: a.generation, password: a.password, description: a.description, duration_s: a.duration_s, channel_id: a.channel_id, channel_password: a.channel_password }
}
"temp_password_delete" => {
let a: TempDeleteArgs = args(raw)?;
check_str("password", &a.password, 255, false)?;
C::TempPasswordDelete { generation: generation(a.generation)?, password: a.password, confirm: a.confirm }
C::TempPasswordDelete { generation: a.generation, password: a.password, confirm: a.confirm }
}
"server_info" => { args::<Empty>(raw)?; C::ServerInfo }
"server_edit" => {
let a: ServerEditArgs = args(raw)?;
let properties = properties(a.properties, SERVER_EDIT)?;
if properties.is_empty() { return Err(bad("properties must not be empty")); }
C::ServerEdit { generation: generation(a.generation)?, confirm: a.confirm, properties }
let properties = Properties::server_edit(a.properties)?;
C::ServerEdit { generation: a.generation, confirm: a.confirm, properties }
}
"server_group_perm_list" => C::ServerGroupPermList { group_id: positive("group_id", args::<GroupArgs>(raw)?.group_id)? },
"channel_group_perm_list" => C::ChannelGroupPermList { group_id: positive("group_id", args::<GroupArgs>(raw)?.group_id)? },
"channel_perm_list" => C::ChannelPermList { channel_id: positive("channel_id", args::<ChannelArgs>(raw)?.channel_id)? },
"server_group_client_list" => C::ServerGroupClientList { group_id: positive("group_id", args::<GroupArgs>(raw)?.group_id)? },
"server_group_perm_list" => C::ServerGroupPermList { group_id: args::<GroupArgs>(raw)?.group_id },
"channel_group_perm_list" => C::ChannelGroupPermList { group_id: args::<GroupArgs>(raw)?.group_id },
"channel_perm_list" => C::ChannelPermList { channel_id: args::<ChannelArgs>(raw)?.channel_id },
"server_group_client_list" => C::ServerGroupClientList { group_id: args::<GroupArgs>(raw)?.group_id },
other => return Err(ErrorObj::new(ErrorCode::UnknownCommand, format!("unknown command {other:?}"))),
})
};
Ok(command)
}
/// Checks fields that native callers can construct directly. Property values are
/// already unforgeably validated by their scope-specific constructors.
pub(crate) fn validate(command: &AdminCommand) -> Result<(), ErrorObj> {
use AdminCommand as C;
if let C::Extra(c) = command { return c.validate(); }
if let Some(g) = command.generation() { generation(g)?; }
match command {
C::ChannelCreate { properties, .. } => properties.check_scope(PropertyScope::ChannelCreate)?,
C::ChannelEdit { channel_id, properties, .. } => {
properties.check_scope(PropertyScope::ChannelEdit)?;
positive("channel_id", *channel_id)?;
}
C::ServerEdit { properties, .. } => properties.check_scope(PropertyScope::ServerEdit)?,
C::ChannelMove { channel_id, parent_id, .. } => {
if parent_id == channel_id { return Err(bad("a channel cannot be its own parent")); }
positive("channel_id", *channel_id)?;
}
C::ChannelDelete { channel_id, .. } | C::ChannelSubscribe { channel_id, .. }
| C::ChannelDescription { channel_id } | C::ChannelPermList { channel_id } => { positive("channel_id", *channel_id)?; }
C::SetAway { away, message } => {
if !away && message.is_some() { return Err(bad("message is only allowed with away: true")); }
check_opt("message", message, 80)?;
}
C::TalkRequest { request, message } => {
if !request && message.is_some() { return Err(bad("message is only allowed with request: true")); }
check_opt("message", message, 50)?;
}
C::TalkPower { target, .. } => menu::validate_target(target)?,
C::BanAdd { ip, name, uid, duration_s, reason, .. } => {
for (field, value) in [("ip", ip), ("name", name), ("uid", uid)] { check_opt(field, value, 255)?; }
check_opt("reason", reason, 512)?;
if ![ip, name, uid].iter().any(|v| v.as_deref().is_some_and(|s| !s.is_empty())) {
return Err(bad("at least one of ip, name or uid is required"));
}
if *duration_s > u32::MAX as u64 { return Err(bad("duration_s is too large")); }
}
C::BanDelete { ban_id, .. } => { positive("ban_id", *ban_id)?; }
C::PrivilegeKeyAdd { kind, group_id, channel_id, description, .. } => {
check_str("description", description, 255, true)?;
match kind {
PrivilegeKeyKind::ServerGroup if *channel_id != 0 => return Err(bad("channel_id is only allowed for kind channel_group")),
PrivilegeKeyKind::ChannelGroup => { positive("channel_id", *channel_id)?; }
PrivilegeKeyKind::ServerGroup => {}
}
positive("group_id", *group_id)?;
}
C::PrivilegeKeyDelete { token, .. } | C::PrivilegeKeyUse { token, .. } => check_str("token", token, 255, false)?,
C::TempPasswordAdd { password, description, duration_s, channel_id, channel_password, .. } => {
check_str("password", password, 255, false)?;
check_str("description", description, 255, true)?;
check_str("channel_password", channel_password, 255, true)?;
if *duration_s == 0 || *duration_s > u32::MAX as u64 { return Err(bad("duration_s must be 1..=4294967295")); }
if *channel_id == 0 && !channel_password.is_empty() { return Err(bad("channel_password needs channel_id")); }
}
C::TempPasswordDelete { password, .. } => check_str("password", password, 255, false)?,
C::ServerGroupPermList { group_id } | C::ChannelGroupPermList { group_id } | C::ServerGroupClientList { group_id } => { positive("group_id", *group_id)?; }
C::Extra(_) | C::Context | C::ChannelSubscribeAll { .. } | C::BanList | C::BanDeleteAll { .. }
| C::PrivilegeKeyList | C::TempPasswordList | C::ServerInfo => {}
}
Ok(())
}
// ------------------------------------------------------------ replies
@@ -855,6 +930,60 @@ pub fn talk_power(client_id: u16, grant: bool) -> OutCommand {
mod tests {
use super::*;
fn parse(name: &str, raw: Option<&serde_json::value::RawValue>) -> Result<AdminCommand, ErrorObj> {
let command = super::parse(name, raw)?;
validate(&command)?;
Ok(command)
}
#[test]
fn typed_properties_hash_once_and_cannot_cross_scopes() {
let properties = Properties::channel_create(Map::from_iter([
("channel_name".into(), Value::String("Lobby".into())),
("channel_password".into(), Value::String("secret".into())),
])).unwrap();
let expected = encode_password(b"secret");
assert!(properties.contains(&("channel_password", expected.clone())));
assert!(properties.contains(&("channel_flag_password", "1".into())));
let command = AdminCommand::ChannelCreate { generation: 1, parent_id: 0, properties: properties.clone() };
let checked = crate::protocol::validate_command(crate::protocol::Command::Admin(command.clone())).unwrap();
assert_eq!(checked.into_inner(), crate::protocol::Command::Admin(command));
let wrong_scope = AdminCommand::ChannelEdit { generation: 1, channel_id: 7, properties };
assert_eq!(validate(&wrong_scope).unwrap_err().code, ErrorCode::BadRequest);
for value in [
json!({"channel_flag_password":true}), json!({"channel_codec_quality":11}),
json!({"channel_password":42}), json!({"channel_flag_permanent":true,"channel_flag_semi_permanent":true}),
] {
assert_eq!(Properties::channel_edit(value.as_object().unwrap().clone()).unwrap_err().code, ErrorCode::BadRequest);
}
assert!(Properties::channel_create(Map::new()).is_err());
assert!(Properties::channel_edit(Map::new()).is_err());
assert!(Properties::server_edit(Map::new()).is_err());
}
#[test]
fn direct_admin_and_permission_arguments_reject_invalid_values() {
use extra::{Command as E, GroupKind, Permission};
let invalid = [
AdminCommand::BanDelete { generation: 0, ban_id: 1, confirm: "1".into() },
AdminCommand::SetAway { away: false, message: Some("reason".into()) },
AdminCommand::TalkRequest { request: true, message: Some("x".repeat(51)) },
AdminCommand::TalkPower { generation: 1, target: menu::Target { client_id: 7, uid: String::new() }, grant: true },
AdminCommand::PrivilegeKeyUse { generation: 1, token: "bad\n".into() },
AdminCommand::PrivilegeKeyAdd { generation: 1, kind: PrivilegeKeyKind::ServerGroup, group_id: 1, channel_id: 7, description: String::new() },
AdminCommand::TempPasswordAdd { generation: 1, password: "pw".into(), description: String::new(), duration_s: 1, channel_id: 0, channel_password: "pw".into() },
AdminCommand::ServerGroupPermList { group_id: 0 },
AdminCommand::Extra(E::GroupSetPermissions { generation: 1, kind: GroupKind::Server, group_id: 7, permissions: vec![] }),
AdminCommand::Extra(E::ChannelSetPermissions { generation: 1, channel_id: 7, permissions: vec![Permission { id: "b_test".into(), value: 1, negate: true, skip: false }] }),
AdminCommand::Extra(E::GroupDeletePermissions { generation: 1, kind: GroupKind::Server, group_id: 7, permissions: vec!["0".into()] }),
AdminCommand::Extra(E::GroupDelete { generation: 1, kind: GroupKind::Server, group_id: 7, force: true, confirm: "8".into() }),
AdminCommand::Extra(E::ClientDatabaseDelete { generation: 1, client_database_id: 7, confirm: "8".into() }),
];
for command in invalid {
assert_eq!(crate::protocol::validate_command(crate::protocol::Command::Admin(command)).unwrap_err().code, ErrorCode::BadRequest);
}
}
fn parse_json(cmd: &str, v: Value) -> Result<AdminCommand, ErrorObj> {
let raw = serde_json::value::RawValue::from_string(v.to_string()).unwrap();
parse(cmd, Some(&raw))
+2 -2
View File
@@ -55,7 +55,7 @@ impl Command {
|Self::GroupSetPermissions{generation,..}|Self::ChannelSetPermissions{generation,..}|Self::ServerGroupAddClient{generation,..}
|Self::GroupDelete{generation,..}|Self::GroupDeletePermissions{generation,..}|Self::ChannelDeletePermissions{generation,..}=>Some(*generation), _=>None,
}}
fn validate(&self) -> Result<(),ErrorObj> {
pub(super) fn validate(&self) -> Result<(),ErrorObj> {
let positive=|id:u64| if id==0 {Err(menu::bad("target ID must be positive"))}else{Ok(())};
let text=|s:&str,max:usize| if s.is_empty()||s.len()>max||s.chars().any(char::is_control){Err(menu::bad("invalid text argument"))}else{Ok(())};
if let Some(g)=self.generation(){positive(g)?;}
@@ -168,5 +168,5 @@ pub fn parse(name:&str,raw:Option<&serde_json::value::RawValue>)->Result<Command
let obj=v.as_object_mut().ok_or_else(||menu::bad("args must be an object"))?;
if obj.contains_key("command"){return Err(menu::bad("unexpected command argument"));}
obj.insert("command".into(),Value::String(name.into()));
let cmd:Command=serde_json::from_value(v).map_err(|e|menu::bad(e.to_string()))?;cmd.validate()?;Ok(cmd)
serde_json::from_value(v).map_err(|e|menu::bad(e.to_string()))
}
+222 -24
View File
@@ -1,7 +1,13 @@
//! Profileless selected-application audio helper. Never substitutes endpoint/system loopback.
//! Profileless selected-application audio. Never substitutes endpoint/system loopback.
//! Native consumers receive bounded PCM directly; only `run` uses the CLI transport.
use std::io::{Read, Write};
use std::process::ExitCode;
use serde_json::json;
use std::sync::{Arc, atomic::{AtomicBool, Ordering}, mpsc};
use std::thread::JoinHandle;
use std::time::Duration;
use base64::{Engine, engine::general_purpose::STANDARD};
use serde_json::{json, Value};
#[cfg(windows)]
#[path = "app_audio_windows.rs"]
@@ -14,9 +20,116 @@ mod platform;
#[allow(dead_code)]
mod linux_contract_tests;
pub const PCM_BYTES: usize = 960 * 2 * 2;
const EVENT_CAPACITY: usize = 4;
/// Explicit, clonable cancellation shared by enumeration and capture operations.
#[derive(Clone, Default)]
pub struct Cancellation(Arc<AtomicBool>);
impl Cancellation {
pub fn cancel(&self) { self.0.store(true, Ordering::Release); }
pub fn is_cancelled(&self) -> bool { self.0.load(Ordering::Acquire) }
pub(super) fn check(&self) -> Result<(), String> {
if self.is_cancelled() { Err("Application audio cancelled".into()) } else { Ok(()) }
}
}
/// Fixed 20 ms, 48 kHz stereo signed little-endian PCM. Sequence gaps denote drops.
#[derive(Debug)]
pub enum CaptureEvent {
Format,
Pcm { sequence: u64, bytes: [u8; PCM_BYTES] },
}
#[derive(Clone)]
pub(super) struct Sink(mpsc::SyncSender<CaptureEvent>);
impl Sink {
pub(super) fn format(&self) -> Result<(), String> {
self.0.try_send(CaptureEvent::Format).map_err(|_| "Application audio consumer stopped".into())
}
pub(super) fn pcm(&self, sequence: u64, bytes: [u8; PCM_BYTES]) -> Result<(), String> {
match self.0.try_send(CaptureEvent::Pcm { sequence, bytes }) {
Ok(()) | Err(mpsc::TrySendError::Full(_)) => Ok(()),
Err(mpsc::TrySendError::Disconnected(_)) => Err("Application audio consumer stopped".into()),
}
}
}
/// Owns the capture worker and its bounded output. Drop cancels and joins it.
/// Host callbacks run on the caller, never on a capture or helper-reader thread.
/// Drain continuously; a slow consumer drops new PCM, never blocks capture.
/// The terminal success/error is returned by `join`/`stop`, not a droppable event.
/// `stop`, `join`, and Drop block: use an owner/shutdown worker, never the UI thread.
pub struct Capture {
cancel: Cancellation,
events: mpsc::Receiver<CaptureEvent>,
worker: Option<JoinHandle<Result<(), String>>>,
}
impl Capture {
pub fn cancel(&self) { self.cancel.cancel(); }
pub fn is_finished(&self) -> bool { self.worker.as_ref().is_none_or(JoinHandle::is_finished) }
pub fn recv_timeout(&self, timeout: Duration) -> Result<CaptureEvent, mpsc::RecvTimeoutError> {
if self.cancel.is_cancelled() { return Err(mpsc::RecvTimeoutError::Disconnected); }
let event = self.events.recv_timeout(timeout)?;
if self.cancel.is_cancelled() { return Err(mpsc::RecvTimeoutError::Disconnected); }
Ok(event)
}
/// Dispatch no more than the queue capacity, even while capture produces more.
pub fn dispatch_pending(&self, mut callback: impl FnMut(CaptureEvent)) -> usize {
let mut count = 0;
while count < EVENT_CAPACITY && !self.cancel.is_cancelled() {
let Ok(event) = self.events.try_recv() else { break };
callback(event);
count += 1;
}
count
}
pub fn join(mut self) -> Result<(), String> { self.join_worker() }
pub fn stop(mut self) -> Result<(), String> { self.cancel(); self.join_worker() }
fn join_worker(&mut self) -> Result<(), String> {
self.worker.take().map_or(Ok(()), |worker| worker.join().unwrap_or_else(|_| Err("Application audio worker panicked".into())))
}
}
impl Drop for Capture {
fn drop(&mut self) { self.cancel(); let _ = self.join_worker(); }
}
/// Enumerate without recording. Retains platform capability and isolation metadata.
pub fn list(cancel: &Cancellation) -> Result<Value, String> {
cancel.check()?;
#[cfg(any(windows, target_os = "linux"))]
{ platform::list(cancel) }
#[cfg(not(any(windows, target_os = "linux")))]
{ Ok(json!({"supported":false,"platform":std::env::consts::OS,"reason":unsupported_reason(),"applications":[]})) }
}
#[cfg(not(any(windows, target_os = "linux")))]
fn unsupported_reason() -> &'static str {
if cfg!(target_os = "macos") {
"Selected-application audio requires an implemented Core Audio process-tap or ScreenCaptureKit helper, macOS SDK build, app signing and user audio-recording consent; this build has no macOS application-audio backend."
} else { "This platform has no selected-application audio capture backend." }
}
/// Start only an exact identity returned by `list`; initialization failures are joined.
pub fn capture(id: &str, cancel: Cancellation) -> Result<Capture, String> {
cancel.check()?;
#[cfg(any(windows, target_os = "linux"))]
{
let id = id.to_owned();
spawn_capture(cancel, move |cancel, sink| platform::capture(&id, cancel, sink))
}
#[cfg(not(any(windows, target_os = "linux")))]
{ let _ = id; Err(unsupported_reason().into()) }
}
fn spawn_capture(cancel: Cancellation, run: impl FnOnce(&Cancellation, &Sink) -> Result<(), String> + Send + 'static) -> Result<Capture, String> {
let (tx, events) = mpsc::sync_channel(EVENT_CAPACITY);
let requested = cancel.clone();
let worker = std::thread::Builder::new().name("app-audio-capture".into()).spawn(move || run(&requested, &Sink(tx))).map_err(|e| e.to_string())?;
Ok(Capture { cancel, events, worker: Some(worker) })
}
pub fn run(args: &[String]) -> ExitCode {
let result = dispatch(args);
match result {
match dispatch(args) {
Ok(()) => ExitCode::SUCCESS,
Err(message) => {
eprintln!("{}", json!({"event":"error","code":"application_audio","message":message}));
@@ -26,26 +139,111 @@ pub fn run(args: &[String]) -> ExitCode {
}
fn dispatch(args: &[String]) -> Result<(), String> {
#[cfg(any(windows, target_os = "linux"))]
{
match args {
[command] if command == "list" => platform::list(),
[command, id] if command == "capture" => platform::capture(id),
_ => Err("usage: teamspeach-core app-audio list | app-audio capture <observed-id>".into()),
}
}
#[cfg(not(any(windows, target_os = "linux")))]
{
let reason = if cfg!(target_os = "macos") {
"Selected-application audio requires an implemented Core Audio process-tap or ScreenCaptureKit helper, macOS SDK build, app signing and user audio-recording consent; this build has no macOS application-audio backend."
} else {
"This platform has no selected-application audio capture backend."
};
if matches!(args, [command] if command == "list") {
println!("{}", json!({"supported":false,"platform":std::env::consts::OS,"reason":reason,"applications":[]}));
let cancel = Cancellation::default();
match args {
[command] if command == "list" => {
println!("{}", list(&cancel)?);
Ok(())
} else {
Err(reason.into())
}
},
[command, id] if command == "capture" => {
let capture = capture(id, cancel.clone())?;
// Only the standalone CLI owns this blocking stdin thread; library workers do not.
std::thread::Builder::new().name("app-audio-stop".into()).spawn(move || {
let _ = std::io::stdin().read(&mut [0u8; 1]);
cancel.cancel();
}).map_err(|e| e.to_string())?;
let mut stdout = std::io::stdout().lock();
let mut encoded = String::with_capacity(PCM_BYTES * 4 / 3);
loop {
match capture.recv_timeout(Duration::from_millis(50)) {
Ok(CaptureEvent::Format) => writeln!(stdout, "{{\"event\":\"format\",\"sampleRate\":48000,\"channels\":2,\"format\":\"s16le\",\"frames\":960}}"),
Ok(CaptureEvent::Pcm { sequence, bytes }) => {
encoded.clear(); STANDARD.encode_string(bytes, &mut encoded);
writeln!(stdout, "{{\"event\":\"pcm\",\"sequence\":{sequence},\"pcm\":\"{encoded}\"}}")
},
Err(mpsc::RecvTimeoutError::Timeout) => continue,
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}.and_then(|_| stdout.flush()).map_err(|e| e.to_string())?;
}
capture.join()
},
_ => Err("usage: teamspeach-core app-audio list | app-audio capture <observed-id>".into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bounded_consumer_preserves_format_and_drops_without_blocking() {
let capture = spawn_capture(Cancellation::default(), |_, sink| {
sink.format()?;
for sequence in 0..100 { sink.pcm(sequence, [7; PCM_BYTES])?; }
Ok(())
}).unwrap();
while !capture.is_finished() { std::thread::yield_now(); }
let mut events = Vec::new();
assert_eq!(capture.dispatch_pending(|event| events.push(event)), EVENT_CAPACITY);
assert!(matches!(events[0], CaptureEvent::Format));
assert!(matches!(events[1], CaptureEvent::Pcm { sequence: 0, .. }));
assert_eq!(capture.dispatch_pending(|_| panic!("queue should be empty")), 0);
capture.join().unwrap();
}
#[test]
fn cancellation_discards_queued_pcm_before_host_callback() {
let capture = spawn_capture(Cancellation::default(), |_, sink| {
sink.format()?;
sink.pcm(0, [9; PCM_BYTES])
}).unwrap();
while !capture.is_finished() { std::thread::yield_now(); }
capture.cancel();
assert_eq!(capture.dispatch_pending(|_| panic!("cancelled capture forwarded data")), 0);
assert!(matches!(capture.recv_timeout(Duration::ZERO), Err(mpsc::RecvTimeoutError::Disconnected)));
capture.stop().unwrap();
}
#[test]
fn callback_cancellation_stops_current_dispatch_batch() {
let cancel = Cancellation::default();
let capture = spawn_capture(cancel.clone(), |_, sink| {
sink.format()?;
sink.pcm(0, [9; PCM_BYTES])
}).unwrap();
while !capture.is_finished() { std::thread::yield_now(); }
assert_eq!(capture.dispatch_pending(|_| cancel.cancel()), 1);
capture.join().unwrap();
}
#[test]
fn missing_consumer_fails_without_blocking() {
let (tx, rx) = mpsc::sync_channel(EVENT_CAPACITY);
drop(rx);
let sink = Sink(tx);
assert!(sink.format().is_err());
assert!(sink.pcm(0, [0; PCM_BYTES]).is_err());
}
#[test]
fn drop_cancels_and_joins_worker() {
let finished = Arc::new(AtomicBool::new(false));
let completed = finished.clone();
let capture = spawn_capture(Cancellation::default(), move |cancel, _| {
while !cancel.is_cancelled() { std::thread::sleep(Duration::from_millis(1)); }
completed.store(true, Ordering::Release);
Ok(())
}).unwrap();
drop(capture);
assert!(finished.load(Ordering::Acquire));
}
#[test]
fn worker_errors_and_panics_are_joined() {
let capture = spawn_capture(Cancellation::default(), |_, _| Err("source ended".into())).unwrap();
assert_eq!(capture.join().unwrap_err(), "source ended");
let capture = spawn_capture(Cancellation::default(), |_, _| panic!("fixture")).unwrap();
assert_eq!(capture.join().unwrap_err(), "Application audio worker panicked");
}
#[test]
fn cancelled_enumeration_does_not_access_platform() {
let cancel = Cancellation::default();
cancel.cancel();
assert!(list(&cancel).is_err());
assert!(capture("not-observed", cancel).is_err());
}
}
+150 -80
View File
@@ -2,11 +2,11 @@
//! Runtime prerequisites: pactl with JSON output and parec with --monitor-stream.
//! No sink moves, volume changes, defaults, modules or persistent graph edits.
use std::io::{Read, Write};
use std::io::Read;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, atomic::{AtomicBool, Ordering}, mpsc};
use std::time::{Duration, Instant};
use base64::{Engine, engine::general_purpose::STANDARD};
use super::{Cancellation, Sink};
use serde::Serialize;
use serde_json::{json, Value};
@@ -15,9 +15,26 @@ const MAX_JSON: u64 = 4 * 1024 * 1024;
const TIMEOUT: Duration = Duration::from_secs(3);
const PREREQUISITE: &str = "Linux application audio requires pactl JSON support, parec --monitor-stream, and an accessible PulseAudio or PipeWire-Pulse user audio server with recording permission; native PipeWire without pipewire-pulse is not supported by this backend";
struct OwnedChild(Child);
struct OwnedChild {
child: Child,
readers: Vec<std::thread::JoinHandle<()>>,
}
impl OwnedChild {
fn new(child: Child) -> Self { Self { child, readers: Vec::new() } }
}
impl Drop for OwnedChild {
fn drop(&mut self) { let _ = self.0.kill(); let _ = self.0.wait(); }
fn drop(&mut self) {
// Only these exact helper children are terminated. Killing before joining
// releases blocking pipe reads, including early-return and panic paths.
let _ = self.child.kill();
let _ = self.child.wait();
for reader in self.readers.drain(..) { let _ = reader.join(); }
}
}
struct EndForwarding(Arc<AtomicBool>);
impl Drop for EndForwarding {
fn drop(&mut self) { self.0.store(true, Ordering::Release); }
}
fn command(program: &str) -> Command {
@@ -29,7 +46,7 @@ fn command(program: &str) -> Command {
unsafe extern "C" { fn prctl(option: i32, ...) -> i32; fn getppid() -> i32; }
let parent = std::process::id() as i32;
unsafe { command.pre_exec(move || {
// Kill our subprocess if the helper is forcibly terminated by Electron.
// Kill this owned subprocess if its native/CLI host is forcibly terminated.
if prctl(1, 15, 0, 0, 0) != 0 || getppid() != parent { return Err(std::io::Error::last_os_error()); }
Ok(())
}); }
@@ -37,30 +54,46 @@ fn command(program: &str) -> Command {
command
}
fn output(program: &str, args: &[&str]) -> Result<Vec<u8>, String> {
let mut child = OwnedChild(command(program).args(args).spawn().map_err(|e| format!("{PREREQUISITE}: {program}: {e}"))?);
let stdout = child.0.stdout.take().ok_or("Missing command stdout")?;
fn output(program: &str, args: &[&str], cancel: &Cancellation) -> Result<Vec<u8>, String> {
cancel.check()?;
let child = OwnedChild::new(command(program).args(args).spawn().map_err(|e| format!("{PREREQUISITE}: {program}: {e}"))?);
collect_output(child, program, cancel)
}
fn collect_output(mut child: OwnedChild, program: &str, cancel: &Cancellation) -> Result<Vec<u8>, String> {
let stdout = child.child.stdout.take().ok_or("Missing command stdout")?;
let (tx, rx) = mpsc::sync_channel(1);
std::thread::spawn(move || {
child.readers.push(std::thread::Builder::new().name("app-audio-query".into()).spawn(move || {
let mut bytes = Vec::new();
let result = stdout.take(MAX_JSON + 1).read_to_end(&mut bytes).map(|_| bytes);
let _ = tx.send(result);
});
}).map_err(|e| e.to_string())?);
let start = Instant::now();
let mut result = None;
loop {
if let Some(status) = child.0.try_wait().map_err(|e| e.to_string())? {
cancel.check()?;
if result.is_none() {
match rx.try_recv() {
Ok(bytes) => {
let bytes = bytes.map_err(|e| e.to_string())?;
if bytes.len() as u64 > MAX_JSON { return Err("Audio server response exceeds limit".into()); }
result = Some(bytes);
},
Err(mpsc::TryRecvError::Empty) => {},
Err(mpsc::TryRecvError::Disconnected) => return Err("Audio server output reader stopped".into()),
}
}
if let Some(status) = child.child.try_wait().map_err(|e| e.to_string())? {
if !status.success() { return Err(format!("{PREREQUISITE}: {program} exited with {status}")); }
let bytes = rx.recv_timeout(TIMEOUT).map_err(|_| "Audio server output timed out")?.map_err(|e| e.to_string())?;
if bytes.len() as u64 > MAX_JSON { return Err("Audio server response exceeds limit".into()); }
return Ok(bytes);
if let Some(bytes) = result { return Ok(bytes); }
}
if start.elapsed() >= TIMEOUT { return Err(format!("{program}: audio server timeout")); }
std::thread::sleep(Duration::from_millis(10));
}
}
fn rows(kind: &str) -> Result<Vec<Value>, String> {
serde_json::from_slice(&output("pactl", &["--format=json", "list", kind])?).map_err(|e| format!("pactl JSON: {e}"))
fn rows(kind: &str, cancel: &Cancellation) -> Result<Vec<Value>, String> {
serde_json::from_slice(&output("pactl", &["--format=json", "list", kind], cancel)?).map_err(|e| format!("pactl JSON: {e}"))
}
fn number(value: &Value) -> Option<u64> { value.as_u64().or_else(|| value.as_str()?.parse().ok()) }
fn process_stat(text: &str) -> Option<(u32, u64)> {
@@ -101,9 +134,9 @@ fn application(row: &Value, sinks: &[Value], start_time: u64, ancestors: Vec<u32
})
}
fn applications() -> Result<Vec<Application>, String> {
let sinks = rows("sinks")?;
let streams = rows("sink-inputs")?;
fn applications(cancel: &Cancellation) -> Result<Vec<Application>, String> {
let sinks = rows("sinks", cancel)?;
let streams = rows("sink-inputs", cancel)?;
let mut result = Vec::new();
for row in streams {
let Some(pid) = number(&row["properties"]["application.process.id"]).and_then(|p| u32::try_from(p).ok()) else { continue };
@@ -119,114 +152,151 @@ fn applications() -> Result<Vec<Application>, String> {
Ok(result)
}
fn prerequisites() -> Result<(), String> {
let help = output("parec", &["--help"])?;
fn prerequisites(cancel: &Cancellation) -> Result<(), String> {
let help = output("parec", &["--help"], cancel)?;
if !String::from_utf8_lossy(&help).contains("--monitor-stream") { return Err(PREREQUISITE.into()); }
Ok(())
}
pub fn list() -> Result<(), String> {
let result = prerequisites().and_then(|_| applications());
match result {
Ok(apps) => println!("{}", json!({"supported":true,"platform":"linux","scope":"audio-stream","backend":"pulseaudio-monitor-stream","applications":apps})),
Err(reason) => println!("{}", json!({"supported":false,"platform":"linux","reason":reason,"applications":[]})),
}
Ok(())
pub fn list(cancel: &Cancellation) -> Result<Value, String> {
let result = prerequisites(cancel).and_then(|_| applications(cancel));
cancel.check()?;
Ok(match result {
Ok(apps) => json!({"supported":true,"platform":"linux","scope":"audio-stream","backend":"pulseaudio-monitor-stream","applications":apps}),
Err(reason) => json!({"supported":false,"platform":"linux","reason":reason,"applications":[]}),
})
}
pub fn capture(id: &str) -> Result<(), String> {
prerequisites()?;
let app = applications()?.into_iter().find(|a| a.id == id).ok_or("Selected audio-stream identity is stale; refresh the application list")?;
let stop = Arc::new(AtomicBool::new(false));
let requested = Arc::new(AtomicBool::new(false));
let request = requested.clone();
let cancel = stop.clone();
std::thread::spawn(move || {
let _ = std::io::stdin().read(&mut [0; 1]);
request.store(true, Ordering::Release);
cancel.store(true, Ordering::Release);
});
pub fn capture(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
match capture_inner(id, cancel, sink) {
Err(_) if cancel.is_cancelled() => Ok(()),
result => result,
}
}
fn capture_inner(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
prerequisites(cancel)?;
let app = applications(cancel)?.into_iter().find(|a| a.id == id).ok_or("Selected audio-stream identity is stale; refresh the application list")?;
// Monitor removal/change before starting capture. Any selected-stream change fails closed.
let mut subscription = OwnedChild(command("pactl").arg("subscribe").spawn().map_err(|e| e.to_string())?);
let subscription_out = subscription.0.stdout.take().ok_or("Missing subscription stdout")?;
let mut subscription = OwnedChild::new(command("pactl").arg("subscribe").spawn().map_err(|e| e.to_string())?);
let subscription_out = subscription.child.stdout.take().ok_or("Missing subscription stdout")?;
let changed = Arc::new(AtomicBool::new(false));
let changed_reader = changed.clone();
let target = format!("on sink-input #{}", app.index);
std::thread::spawn(move || {
subscription.readers.push(std::thread::Builder::new().name("app-audio-subscribe".into()).spawn(move || {
use std::io::BufRead;
let mut reader = std::io::BufReader::new(subscription_out);
loop {
let mut line = String::new();
match reader.by_ref().take(4097).read_line(&mut line) {
Ok(n) if n > 0 && n <= 4096 => {
if line.trim_end().ends_with(&target) { changed_reader.store(true, Ordering::Release); break; }
if line.trim_end().ends_with(&target) { break; }
},
_ => { changed_reader.store(true, Ordering::Release); break; }
_ => break,
}
}
});
changed_reader.store(true, Ordering::Release);
}).map_err(|e| e.to_string())?);
let monitor_arg = format!("--device={}", app.monitor);
let index_arg = format!("--monitor-stream={}", app.index);
let mut recorder = OwnedChild(command("parec").args(["--raw", "--format=s16le", "--rate=48000", "--channels=2", "--latency-msec=20", &monitor_arg, &index_arg]).spawn().map_err(|e| e.to_string())?);
cancel.check()?;
let mut recorder = OwnedChild::new(command("parec").args(["--raw", "--format=s16le", "--rate=48000", "--channels=2", "--latency-msec=20", &monitor_arg, &index_arg]).spawn().map_err(|e| e.to_string())?);
// Re-enumerate before forwarding anything: never use a recycled or moved stream index.
if !applications()?.iter().any(|a| a.id == id && a.monitor == app.monitor) || changed.load(Ordering::Acquire) {
if !applications(cancel)?.iter().any(|a| a.id == id && a.monitor == app.monitor) || changed.load(Ordering::Acquire) {
return Err("Selected audio stream changed during activation".into());
}
let mut pcm = recorder.0.stdout.take().ok_or("Missing recorder stdout")?;
let (tx, rx) = mpsc::sync_channel::<(u64, [u8; BYTES])>(4);
let cancel = stop.clone();
std::thread::spawn(move || {
let mut pcm = recorder.child.stdout.take().ok_or("Missing recorder stdout")?;
sink.format()?;
let pcm_sink = sink.clone();
let pcm_changed = changed.clone();
let requested = cancel.clone();
recorder.readers.push(std::thread::Builder::new().name("app-audio-read".into()).spawn(move || {
let mut sequence = 0;
while !cancel.load(Ordering::Acquire) {
while !requested.is_cancelled() && !pcm_changed.load(Ordering::Acquire) {
let mut block = [0; BYTES];
if pcm.read_exact(&mut block).is_err() { break; }
let _ = tx.try_send((sequence, block));
if requested.is_cancelled() || pcm_changed.load(Ordering::Acquire) { break; }
if pcm_sink.pcm(sequence, block).is_err() { break; }
sequence += 1;
}
cancel.store(true, Ordering::Release);
});
let writer_stop = stop.clone();
let writer_changed = changed.clone();
std::thread::spawn(move || {
let mut stdout = std::io::stdout().lock();
let mut encoded = String::with_capacity(BYTES * 4 / 3);
let result = (|| -> std::io::Result<()> {
writeln!(stdout, "{{\"event\":\"format\",\"sampleRate\":48000,\"channels\":2,\"format\":\"s16le\",\"frames\":960}}")?;
stdout.flush()?;
while let Ok((sequence, block)) = rx.recv() {
if writer_stop.load(Ordering::Acquire) || writer_changed.load(Ordering::Acquire) { break; }
encoded.clear(); STANDARD.encode_string(block, &mut encoded);
writeln!(stdout, "{{\"event\":\"pcm\",\"sequence\":{sequence},\"pcm\":\"{encoded}\"}}")?;
stdout.flush()?;
}
Ok(())
})();
if result.is_err() { writer_stop.store(true, Ordering::Release); }
});
}).map_err(|e| e.to_string())?);
let _end_forwarding = EndForwarding(changed.clone());
let mut checked = Instant::now();
while !stop.load(Ordering::Acquire) {
if changed.load(Ordering::Acquire) { return Err("Selected audio stream changed or disappeared".into()); }
if recorder.0.try_wait().map_err(|e| e.to_string())?.is_some() { return Err("Selected application recorder stopped".into()); }
while !cancel.is_cancelled() {
if changed.load(Ordering::Acquire) || subscription.readers.iter().any(|reader| reader.is_finished()) { return Err("Selected audio stream changed or disappeared".into()); }
if recorder.child.try_wait().map_err(|e| e.to_string())?.is_some() { return Err("Selected application recorder stopped".into()); }
if checked.elapsed() >= Duration::from_millis(250) {
if !applications()?.iter().any(|a| a.id == id && a.monitor == app.monitor) { return Err("Selected audio-stream identity changed or disappeared".into()); }
if !applications(cancel)?.iter().any(|a| a.id == id && a.monitor == app.monitor) { return Err("Selected audio-stream identity changed or disappeared".into()); }
checked = Instant::now();
}
if recorder.readers.iter().any(|reader| reader.is_finished()) { return Err("Selected application PCM transport stopped".into()); }
std::thread::sleep(Duration::from_millis(10));
}
if !requested.load(Ordering::Acquire) { return Err("Selected application PCM transport stopped".into()); }
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn blocking_child() -> OwnedChild {
let (program, prefix) = crate::test_exec::self_invocation();
OwnedChild::new(command(&program).args(prefix)
.args(["app_audio_blocking_child_fixture", "--nocapture", "--test-threads=1"])
.env("TEAMSPEACH_APP_AUDIO_CHILD_FIXTURE", "1").spawn().unwrap())
}
#[test]
fn app_audio_blocking_child_fixture() {
if std::env::var_os("TEAMSPEACH_APP_AUDIO_CHILD_FIXTURE").is_none() { return; }
use std::io::Write;
println!("APP_AUDIO_CHILD_READY");
std::io::stdout().flush().unwrap();
std::thread::sleep(Duration::from_secs(30));
}
#[test]
fn dropping_child_unblocks_and_joins_pipe_reader() {
use std::io::BufRead;
let mut child = blocking_child();
let stdout = child.child.stdout.take().unwrap();
let finished = Arc::new(AtomicBool::new(false));
let completed = finished.clone();
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
child.readers.push(std::thread::spawn(move || {
let mut reader = std::io::BufReader::new(stdout);
let mut line = String::new();
while reader.read_line(&mut line).unwrap_or(0) != 0 {
if line.contains("APP_AUDIO_CHILD_READY") { let _ = ready_tx.try_send(()); }
line.clear();
}
completed.store(true, Ordering::Release);
}));
ready_rx.recv_timeout(Duration::from_secs(5)).unwrap();
let start = Instant::now();
drop(child);
assert!(finished.load(Ordering::Acquire));
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn cancellation_interrupts_blocked_helper_output() {
let child = blocking_child();
let cancel = Cancellation::default();
let requested = cancel.clone();
let canceller = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(50));
requested.cancel();
});
let start = Instant::now();
let result = collect_output(child, "fixture", &cancel);
canceller.join().unwrap();
assert_eq!(result.unwrap_err(), "Application audio cancelled");
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn controlled_executable_output_and_failure() {
let (program, prefix) = crate::test_exec::self_invocation();
let run = |option: &'static str| {
let mut args: Vec<&str> = prefix.iter().map(String::as_str).collect();
args.push(option);
output(&program, &args)
output(&program, &args, &Cancellation::default())
};
let data = run("--list").unwrap();
assert!(String::from_utf8(data).unwrap().contains("identity_uses_start_time_serial_and_exact_monitor"));
+49 -57
View File
@@ -2,10 +2,9 @@
//! Activation follows Microsoft's ApplicationLoopback sample; COM bindings are windows-rs.
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Write};
use std::sync::{Arc, atomic::{AtomicBool, Ordering}, mpsc};
use std::time::Duration;
use base64::{Engine, engine::general_purpose::STANDARD};
use std::sync::mpsc;
use super::{Cancellation, Sink};
use std::time::{Duration, Instant};
use serde::Serialize;
use serde_json::json;
use windows::core::{implement, Interface, HRESULT, PCWSTR, PWSTR};
@@ -20,7 +19,6 @@ use windows::Win32::System::Variant::VT_BLOB;
const FRAMES: usize = 960;
const BYTES: usize = FRAMES * 2 * 2;
const QUEUE: usize = 4;
#[link(name = "ntdll")]
extern "system" { fn RtlGetVersion(version: *mut OSVERSIONINFOW) -> i32; }
@@ -69,13 +67,14 @@ fn process(pid: u32) -> Result<(Handle, String, String), String> {
Ok((h, format!("{pid}:{time:016x}"), label))
}
fn parents() -> Result<BTreeMap<u32, u32>, String> {
fn parents(cancel: &Cancellation) -> Result<BTreeMap<u32, u32>, String> {
let snapshot = Handle(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }.map_err(error)?);
let mut entry = PROCESSENTRY32W { dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32, ..Default::default() };
let mut result = BTreeMap::new();
unsafe {
Process32FirstW(snapshot.0, &mut entry).map_err(error)?;
loop {
cancel.check()?;
result.insert(entry.th32ProcessID, entry.th32ParentProcessID);
if Process32NextW(snapshot.0, &mut entry).is_err() { break; }
}
@@ -83,18 +82,20 @@ fn parents() -> Result<BTreeMap<u32, u32>, String> {
Ok(result)
}
fn applications() -> Result<Vec<Application>, String> {
let tree = parents()?;
fn applications(cancel: &Cancellation) -> Result<Vec<Application>, String> {
let tree = parents(cancel)?;
let mut ids = BTreeSet::new();
unsafe {
let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(error)?;
let devices = enumerator.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE).map_err(error)?;
for index in 0..devices.GetCount().map_err(error)? {
cancel.check()?;
let device = devices.Item(index).map_err(error)?;
// A disappearing endpoint must not silently turn enumeration into an all-system selection.
let manager: IAudioSessionManager2 = device.Activate(CLSCTX_ALL, None).map_err(error)?;
let sessions = manager.GetSessionEnumerator().map_err(error)?;
for index in 0..sessions.GetCount().map_err(error)? {
cancel.check()?;
let session = sessions.GetSession(index).map_err(error)?;
if session.GetState().map_err(error)? == AudioSessionStateExpired { continue; }
let session: IAudioSessionControl2 = session.cast().map_err(error)?;
@@ -105,6 +106,7 @@ fn applications() -> Result<Vec<Application>, String> {
}
let mut result = Vec::new();
for pid in ids {
cancel.check()?;
// Inaccessible/protected/exited processes are not selectable.
let Ok((_handle, id, label)) = process(pid) else { continue };
let mut ancestors = Vec::new();
@@ -119,13 +121,13 @@ fn applications() -> Result<Vec<Application>, String> {
Ok(result)
}
pub fn list() -> Result<(), String> {
pub fn list(cancel: &Cancellation) -> Result<serde_json::Value, String> {
cancel.check()?;
if !supported() {
println!("{}", json!({"supported":false,"platform":"win32","reason":"WASAPI process-loopback requires Windows build 20348 or later","applications":[]}));
return Ok(());
return Ok(json!({"supported":false,"platform":"win32","reason":"WASAPI process-loopback requires Windows build 20348 or later","applications":[]}));
}
let _com = Com::new()?;
let tree = parents()?;
let tree = parents(cancel)?;
let mut host_ancestors = Vec::new();
let mut current = std::process::id();
while let Some(&parent) = tree.get(&current) {
@@ -133,8 +135,9 @@ pub fn list() -> Result<(), String> {
host_ancestors.push(parent);
current = parent;
}
println!("{}", json!({"supported":true,"platform":"win32","scope":"process-tree","hostAncestors":host_ancestors,"applications":applications()?}));
Ok(())
let apps = applications(cancel)?;
cancel.check()?;
Ok(json!({"supported":true,"platform":"win32","scope":"process-tree","hostAncestors":host_ancestors,"applications":apps}))
}
#[implement(IActivateAudioInterfaceCompletionHandler)]
@@ -150,7 +153,7 @@ impl IActivateAudioInterfaceCompletionHandler_Impl for Completion_Impl {
}
}
fn activate(pid: u32) -> Result<IAudioClient, String> {
fn activate(pid: u32, cancel: &Cancellation) -> Result<IAudioClient, String> {
let mut params = Box::new(AUDIOCLIENT_ACTIVATION_PARAMS {
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 { ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
@@ -168,7 +171,15 @@ fn activate(pid: u32) -> Result<IAudioClient, String> {
let (tx, rx) = mpsc::sync_channel(1);
let completion: IActivateAudioInterfaceCompletionHandler = Completion { tx, _params: params }.into();
let operation = unsafe { ActivateAudioInterfaceAsync(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, &IAudioClient::IID, Some(&*variant), &completion) }.map_err(error)?;
rx.recv_timeout(Duration::from_secs(10)).map_err(|_| "Application audio activation timed out".to_owned())?;
let start = Instant::now();
loop {
cancel.check()?;
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(()) => break,
Err(mpsc::RecvTimeoutError::Timeout) if start.elapsed() < Duration::from_secs(10) => {},
_ => return Err("Application audio activation timed out".into()),
}
}
let mut status = HRESULT(0);
let mut object = None;
unsafe { operation.GetActivateResult(&mut status, &mut object) }.map_err(error)?;
@@ -176,15 +187,24 @@ fn activate(pid: u32) -> Result<IAudioClient, String> {
object.ok_or("Application audio activation returned no interface")?.cast().map_err(error)
}
struct Packet { sequence: u64, bytes: Box<[u8; BYTES]> }
pub fn capture(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
match capture_inner(id, cancel, sink) {
Err(_) if cancel.is_cancelled() => Ok(()),
result => result,
}
}
pub fn capture(id: &str) -> Result<(), String> {
fn capture_inner(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
if cancel.is_cancelled() { return Ok(()); }
if !supported() { return Err("WASAPI process-loopback requires Windows build 20348 or later".into()); }
let _com = Com::new()?;
let app = applications()?.into_iter().find(|app| app.id == id).ok_or("Selected application identity is stale or no longer has an audio session; refresh the list")?;
let app = applications(cancel)?.into_iter().find(|app| app.id == id).ok_or("Selected application identity is stale or no longer has an audio session; refresh the list")?;
let (target, current_id, _) = process(app.pid)?;
if current_id != id { return Err("Selected application identity changed before capture".into()); }
let client = activate(app.pid)?;
let client = match activate(app.pid, cancel) {
Err(_) if cancel.is_cancelled() => return Ok(()),
result => result?,
};
// Recheck after asynchronous activation; never start an audio client for a recycled PID.
let (_recheck, current_id, _) = process(app.pid)?;
if current_id != id || unsafe { WaitForSingleObject(target.0, 0) } != WAIT_TIMEOUT {
@@ -195,45 +215,19 @@ pub fn capture(id: &str) -> Result<(), String> {
let event = Handle(unsafe { CreateEventW(None, false, false, PCWSTR::null()) }.map_err(error)?);
unsafe { client.SetEventHandle(event.0) }.map_err(error)?;
let reader: IAudioCaptureClient = unsafe { client.GetService() }.map_err(error)?;
let stopped = Arc::new(AtomicBool::new(false));
let stop = stopped.clone();
std::thread::Builder::new().name("app-audio-stop".into()).spawn(move || {
let _ = std::io::stdin().read(&mut [0u8; 1]);
stop.store(true, Ordering::Release);
}).map_err(|e| e.to_string())?;
let (ready_tx, ready_rx) = mpsc::sync_channel::<Packet>(QUEUE);
let (free_tx, free_rx) = mpsc::sync_channel::<Box<[u8; BYTES]>>(QUEUE + 2);
for _ in 0..QUEUE + 2 { free_tx.send(Box::new([0; BYTES])).map_err(|e| e.to_string())?; }
let free_return = free_tx.clone();
if cancel.is_cancelled() { return Ok(()); }
unsafe { client.Start() }.map_err(error)?;
let _started = Started(client);
let stop = stopped.clone();
std::thread::Builder::new().name("app-audio-pcm".into()).spawn(move || {
let mut stdout = std::io::stdout().lock();
let mut encoded = String::with_capacity(BYTES * 4 / 3);
let result = (|| -> std::io::Result<()> {
writeln!(stdout, "{{\"event\":\"format\",\"sampleRate\":48000,\"channels\":2,\"format\":\"s16le\",\"frames\":960}}")?;
stdout.flush()?;
while let Ok(packet) = ready_rx.recv() {
encoded.clear();
STANDARD.encode_string(packet.bytes.as_ref(), &mut encoded);
writeln!(stdout, "{{\"event\":\"pcm\",\"sequence\":{},\"pcm\":\"{}\"}}", packet.sequence, encoded)?;
stdout.flush()?;
let _ = free_tx.try_send(packet.bytes);
}
Ok(())
})();
if result.is_err() { stop.store(true, Ordering::Release); }
}).map_err(|e| e.to_string())?;
let mut block = free_rx.recv().map_err(|e| e.to_string())?;
sink.format()?;
let mut block = [0u8; BYTES];
let mut used = 0;
let mut sequence = 0;
while !stopped.load(Ordering::Acquire) {
while !cancel.is_cancelled() {
if unsafe { WaitForSingleObject(target.0, 0) } != WAIT_TIMEOUT { return Err("Selected application exited".into()); }
let wait = unsafe { WaitForSingleObject(event.0, 50) };
if wait == WAIT_TIMEOUT { continue; }
if wait != WAIT_OBJECT_0 { return Err("Application audio capture event failed".into()); }
while unsafe { reader.GetNextPacketSize() }.map_err(error)? > 0 {
while !cancel.is_cancelled() && unsafe { reader.GetNextPacketSize() }.map_err(error)? > 0 {
let mut data = std::ptr::null_mut();
let mut frames = 0;
let mut flags = 0;
@@ -253,12 +247,10 @@ pub fn capture(id: &str) -> Result<(), String> {
used += count;
offset += count;
if used == BYTES {
if let Ok(next) = free_rx.try_recv() {
let packet = Packet { sequence, bytes: std::mem::replace(&mut block, next) };
if let Err(e) = ready_tx.try_send(packet) {
// Recover the unsent buffer without allocation; a full queue drops this interval.
let packet = match e { mpsc::TrySendError::Full(p) | mpsc::TrySendError::Disconnected(p) => p };
let _ = free_return.try_send(packet.bytes);
if !cancel.is_cancelled() {
if let Err(message) = sink.pcm(sequence, block) {
unsafe { reader.ReleaseBuffer(frames) }.map_err(error)?;
return Err(message);
}
}
used = 0;
+250 -44
View File
@@ -4,6 +4,7 @@
use std::collections::{HashSet, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use audiopus::coder::Encoder;
use audiopus::{Application, Bitrate, Channels, SampleRate};
@@ -23,25 +24,38 @@ const MAX_OPUS_PACKET: usize = 1275;
// ---------------------------------------------------------------- input queue
/// A capture-clock-stamped frame. Producers retain these tags through DSP and VAD;
/// a device callback must hand PCM to a worker rather than lock this queue itself.
#[derive(Clone, Debug)]
pub struct CapturedFrame {
pub pcm: Frame,
pub captured_at: Instant,
pub connection_generation: u64,
pub capture_epoch: u64,
/// A whisper frame may only use this registered whisper route, never normal voice.
pub whisper: Option<u32>,
}
pub enum AudioIn {
/// Captured for ordinary voice to the own channel.
Frame(Box<Frame>),
/// Captured while a whisper key was held: may only be sent to the whisper target registered under
/// exactly this epoch (`whisper_start`), never as ordinary voice.
Whisper(Box<Frame>, u32),
Frame(CapturedFrame),
End,
}
impl AudioIn {
fn is_frame(&self) -> bool { matches!(self, AudioIn::Frame(_) | AudioIn::Whisper(..)) }
fn is_frame(&self) -> bool { matches!(self, AudioIn::Frame(_)) }
}
/// Bounded single-consumer queue between the stdin reader and the session; drops the oldest
/// frame when full.
/// Capture age is checked both on ingress and immediately before encoding/sending.
pub const MAX_CAPTURE_AGE: Duration = Duration::from_millis(200);
/// Bounded single-consumer queue between capture/DSP workers and the session.
/// The mutex also serializes synchronous network enqueue against invalidation.
pub struct AudioInQueue {
items: Mutex<VecDeque<AudioIn>>,
notify: Notify,
dropped: AtomicU64,
capture_epoch: AtomicU64,
connection_generation: AtomicU64,
}
/// Upper bound of queued entries: at most [`TX_QUEUE_FRAMES`] frames, and End markers are never
@@ -54,37 +68,103 @@ impl AudioInQueue {
items: Mutex::new(VecDeque::with_capacity(TX_QUEUE_ENTRIES)),
notify: Notify::new(),
dropped: AtomicU64::new(0),
capture_epoch: AtomicU64::new(1),
connection_generation: AtomicU64::new(0),
}
}
pub fn push(&self, item: AudioIn) {
pub fn epoch(&self) -> u64 { self.capture_epoch.load(Ordering::Acquire) }
pub fn generation(&self) -> u64 { self.connection_generation.load(Ordering::Acquire) }
/// A preliminary check, not a send permit. Use `with_valid_frame` for network enqueue.
pub fn validate(&self, frame: &CapturedFrame) -> bool {
self.validate_at(frame, Instant::now())
}
fn validate_at(&self, frame: &CapturedFrame, now: Instant) -> bool {
frame.capture_epoch == self.epoch()
&& frame.connection_generation == self.generation()
&& now.checked_duration_since(frame.captured_at).is_some_and(|age| age <= MAX_CAPTURE_AGE)
}
/// Execute encoding and synchronous network enqueue while invalidation is excluded.
/// Never await, block on network, or call queue-mutating methods in `send`.
/// Recheck `validate(frame)` after encoding, immediately before network enqueue:
/// encoding can itself exhaust the capture-age limit. Release this guard before
/// asynchronous error reporting. Once invalidation returns no old send can start.
pub fn with_valid_frame<R>(&self, frame: &CapturedFrame, send: impl FnOnce() -> R) -> Option<R> {
let _guard = self.items.lock().expect("audio queue poisoned");
self.validate(frame).then(send)
}
fn invalidate_locked(&self, q: &mut VecDeque<AudioIn>) -> u64 {
let epoch = self.epoch().checked_add(1).expect("capture epoch exhausted");
self.capture_epoch.store(epoch, Ordering::Release);
q.clear();
// The consumer must also stop its encoder/VAD burst, even if no PCM remains.
q.push_back(AudioIn::End);
epoch
}
/// Revoke queued, dequeued and VAD-held frames and ask the consumer to end its burst.
pub fn invalidate(&self) -> u64 {
let epoch = {
let mut q = self.items.lock().expect("audio queue poisoned");
self.invalidate_locked(&mut q)
};
self.notify.notify_one();
epoch
}
/// Every connection boundary revokes capture, including reapplying a generation.
pub fn set_generation(&self, generation: u64) {
{
let mut q = self.items.lock().expect("audio queue poisoned");
match item {
// Consecutive ends carry no extra information.
AudioIn::End if matches!(q.back(), Some(AudioIn::End)) => {}
AudioIn::End => q.push_back(item),
AudioIn::Frame(_) | AudioIn::Whisper(..) => {
let frames = q.iter().filter(|i| i.is_frame()).count();
if frames >= TX_QUEUE_FRAMES {
if let Some(pos) = q.iter().position(AudioIn::is_frame) {
q.remove(pos);
self.dropped.fetch_add(1, Ordering::Relaxed);
// Dropping a burst's only frame can leave two ends side by side.
if pos > 0
&& matches!(q.get(pos - 1), Some(AudioIn::End))
&& matches!(q.get(pos), Some(AudioIn::End))
{
q.remove(pos);
}
}
self.connection_generation.store(generation, Ordering::Release);
self.invalidate_locked(&mut q);
}
self.notify.notify_one();
}
/// Reject expired or wrong-boundary frames without ever allocating per frame.
pub fn try_push(&self, frame: CapturedFrame) -> bool {
{
let mut q = self.items.lock().expect("audio queue poisoned");
if !self.validate(&frame) { return false; }
let frames = q.iter().filter(|i| i.is_frame()).count();
if frames >= TX_QUEUE_FRAMES {
if let Some(pos) = q.iter().position(AudioIn::is_frame) {
q.remove(pos);
self.dropped.fetch_add(1, Ordering::Relaxed);
// Removing a burst's only frame can leave adjacent ends.
if pos > 0
&& matches!(q.get(pos - 1), Some(AudioIn::End))
&& matches!(q.get(pos), Some(AudioIn::End))
{
q.remove(pos);
}
q.push_back(item);
}
}
q.push_back(AudioIn::Frame(frame));
debug_assert!(q.len() <= TX_QUEUE_ENTRIES);
}
self.notify.notify_one();
true
}
pub fn push(&self, item: AudioIn) {
match item {
AudioIn::Frame(frame) => { self.try_push(frame); }
AudioIn::End => {
{
let mut q = self.items.lock().expect("audio queue poisoned");
if !matches!(q.back(), Some(AudioIn::End)) { q.push_back(AudioIn::End); }
debug_assert!(q.len() <= TX_QUEUE_ENTRIES);
}
self.notify.notify_one();
}
}
}
#[cfg(test)]
@@ -92,8 +172,8 @@ impl AudioInQueue {
pub fn pop(&self) -> Option<AudioIn> { self.items.lock().expect("audio queue poisoned").pop_front() }
/// Discards everything queued, e.g. frames captured under a previous transmit mode. Returns the number
/// of discarded frames (not counted as overflow drops).
/// Discard queued entries without revoking dequeued frames. Privacy/routing
/// boundaries must use `invalidate` instead. Overflow statistics are unchanged.
pub fn clear(&self) -> usize {
let mut q = self.items.lock().expect("audio queue poisoned");
let frames = q.iter().filter(|i| i.is_frame()).count();
@@ -107,6 +187,18 @@ impl AudioInQueue {
pub fn take_dropped(&self) -> u64 { self.dropped.swap(0, Ordering::Relaxed) }
}
impl tsclientlib::AudioSendGuard for AudioInQueue {
fn with_valid_audio(&self, metadata: &tsclientlib::AudioSendMetadata, send: &mut dyn FnMut()) {
let _guard = self.items.lock().expect("audio queue poisoned");
if metadata.capture_epoch == self.epoch()
&& metadata.connection_generation == self.generation()
&& Instant::now().checked_duration_since(metadata.captured_at).is_some_and(|age| age <= MAX_CAPTURE_AGE)
{
send();
}
}
}
// ---------------------------------------------------------------- transmit
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -544,7 +636,7 @@ mod tests {
fn clear_discards_queued_frames_without_counting_drops() {
let q = AudioInQueue::new();
for _ in 0..3 {
q.push(AudioIn::Frame(Box::new([1; FRAME_SAMPLES])));
q.push(AudioIn::Frame(captured(&q, 1)));
}
q.push(AudioIn::End);
assert_eq!(q.clear(), 3);
@@ -710,10 +802,16 @@ mod tests {
assert_eq!(output, expected);
}
fn frame(tag: i16) -> AudioIn {
let mut f = Box::new([0i16; FRAME_SAMPLES]);
f[0] = tag;
AudioIn::Frame(f)
fn captured(q: &AudioInQueue, tag: i16) -> CapturedFrame {
let mut pcm = [0i16; FRAME_SAMPLES];
pcm[0] = tag;
CapturedFrame {
pcm,
captured_at: Instant::now(),
connection_generation: q.generation(),
capture_epoch: q.epoch(),
whisper: None,
}
}
#[test]
@@ -723,13 +821,13 @@ mod tests {
q.push(AudioIn::End);
}
assert_eq!(q.len(), 1);
q.push(frame(1));
q.push(AudioIn::Frame(captured(&q, 1)));
for _ in 0..1000 {
q.push(AudioIn::End);
}
assert_eq!(q.len(), 3);
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(matches!(q.pop(), Some(AudioIn::Frame(f)) if f[0] == 1));
assert!(matches!(q.pop(), Some(AudioIn::Frame(f)) if f.pcm[0] == 1));
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(q.pop().is_none());
}
@@ -738,7 +836,7 @@ mod tests {
fn alternating_bursts_overflow_stays_bounded_and_terminated() {
let q = AudioInQueue::new();
for i in 0..500i16 {
q.push(frame(i));
q.push(AudioIn::Frame(captured(&q, i)));
q.push(AudioIn::End);
q.push(AudioIn::End);
assert!(q.len() <= TX_QUEUE_ENTRIES, "len {}", q.len());
@@ -751,7 +849,7 @@ mod tests {
while let Some(item) = q.pop() {
match item {
AudioIn::Frame(f) => {
frames.push(f[0]);
frames.push(f.pcm[0]);
prev_end = false;
last_is_end = false;
}
@@ -760,13 +858,121 @@ mod tests {
prev_end = true;
last_is_end = true;
}
AudioIn::Whisper(_, _) => panic!("ordinary queue test received whisper"),
}
}
assert!(last_is_end);
assert_eq!(frames, (490..500).collect::<Vec<i16>>());
}
#[test]
fn capture_age_is_inclusive_and_never_accepts_future_frames() {
let q = AudioInQueue::new();
let mut frame = captured(&q, 1);
let now = frame.captured_at;
assert!(q.validate_at(&frame, now));
assert!(q.validate_at(&frame, now + MAX_CAPTURE_AGE));
// Windows Instant arithmetic rounds to the performance-counter resolution, not nanoseconds.
assert!(!q.validate_at(&frame, now + MAX_CAPTURE_AGE + Duration::from_millis(1)));
assert!(!q.validate_at(&frame, now - Duration::from_millis(1)));
frame.captured_at = Instant::now() - Duration::from_millis(600);
assert!(!q.try_push(frame));
let mut future = captured(&q, 2);
future.captured_at += Duration::from_secs(60);
assert!(!q.try_push(future));
assert!(q.pop().is_none());
assert_eq!(q.take_dropped(), 0);
}
#[test]
fn invalidation_revokes_dequeued_frames_and_preserves_one_end() {
let q = AudioInQueue::new();
let frame = captured(&q, 7);
assert!(q.try_push(frame.clone()));
let Some(AudioIn::Frame(dequeued)) = q.pop() else { panic!("missing frame") };
assert!(q.try_push(captured(&q, 8)));
q.push(AudioIn::End);
let epoch = q.invalidate();
assert_eq!(epoch, frame.capture_epoch + 1);
assert!(!q.validate(&dequeued));
assert!(!q.try_push(frame));
assert!(q.with_valid_frame(&dequeued, || panic!("revoked frame sent")).is_none());
q.invalidate();
q.push(AudioIn::End);
assert_eq!(q.len(), 1);
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(q.try_push(captured(&q, 9)));
assert!(matches!(q.pop(), Some(AudioIn::Frame(frame)) if frame.pcm[0] == 9));
assert_eq!(q.take_dropped(), 0);
}
#[test]
fn generation_boundary_revokes_epoch_and_rejects_wrong_tags() {
let q = AudioInQueue::new();
let old = captured(&q, 1);
q.set_generation(7);
assert_eq!(q.generation(), 7);
assert_eq!(q.epoch(), old.capture_epoch + 1);
assert!(!q.validate(&old));
let mut wrong_generation = captured(&q, 2);
wrong_generation.connection_generation = 6;
assert!(!q.try_push(wrong_generation));
let mut wrong_epoch = captured(&q, 3);
wrong_epoch.capture_epoch += 1;
assert!(!q.try_push(wrong_epoch));
let epoch = q.epoch();
q.set_generation(7);
assert_eq!(q.epoch(), epoch + 1);
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(q.pop().is_none());
}
#[test]
fn whisper_envelope_survives_queue_without_normal_voice_fallback() {
let q = AudioInQueue::new();
let mut frame = captured(&q, 4);
frame.whisper = Some(42);
let captured_at = frame.captured_at;
assert!(q.try_push(frame));
let Some(AudioIn::Frame(frame)) = q.pop() else { panic!("missing whisper frame") };
assert_eq!(frame.whisper, Some(42));
assert_eq!(frame.captured_at, captured_at);
assert_eq!(frame.pcm[0], 4);
}
#[test]
fn send_guard_serializes_invalidation_and_rechecks_capture_age() {
let q = AudioInQueue::new();
let frame = captured(&q, 1);
let order = AtomicU64::new(0);
std::thread::scope(|scope| {
let q = &q;
let frame = &frame;
let order = &order;
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let sender = scope.spawn(move || {
q.with_valid_frame(frame, || {
assert!(q.items.try_lock().is_err(), "send must exclude invalidation");
entered_tx.send(()).unwrap();
release_rx.recv().unwrap();
assert_eq!(order.fetch_add(1, Ordering::SeqCst), 0);
})
});
entered_rx.recv().unwrap();
let invalidator = scope.spawn(move || {
q.invalidate();
assert_eq!(order.fetch_add(1, Ordering::SeqCst), 1);
});
release_tx.send(()).unwrap();
assert!(sender.join().unwrap().is_some());
invalidator.join().unwrap();
});
assert!(q.with_valid_frame(&frame, || panic!("old send after invalidation")).is_none());
let mut expired = captured(&q, 2);
expired.captured_at -= Duration::from_millis(600);
assert!(q.with_valid_frame(&expired, || panic!("expired frame encoded")).is_none());
}
#[test]
fn reset_rearms_unsupported_codec_report() {
let mut rx = Receiver::new();
@@ -784,14 +990,14 @@ mod tests {
fn queue_drops_oldest_frames() {
let q = AudioInQueue::new();
for i in 0..(TX_QUEUE_FRAMES + 3) {
let mut f = Box::new([0i16; FRAME_SAMPLES]);
f[0] = i as i16;
q.push(AudioIn::Frame(f));
let mut pcm = [0i16; FRAME_SAMPLES];
pcm[0] = i as i16;
q.try_push(CapturedFrame { pcm, captured_at: Instant::now(), connection_generation: q.generation(), capture_epoch: q.epoch(), whisper: None });
}
q.push(AudioIn::End);
assert_eq!(q.take_dropped(), 3);
match q.pop() {
Some(AudioIn::Frame(f)) => assert_eq!(f[0], 3),
Some(AudioIn::Frame(f)) => assert_eq!(f.pcm[0], 3),
_ => panic!(),
}
let mut n = 1;
+112 -74
View File
@@ -238,23 +238,18 @@ fn channel(id: u64) -> Result<u64, ErrorObj> {
if id == 0 { Err(bad("channel_id must be a channel (not 0)")) } else { Ok(id) }
}
fn password(p: Option<String>) -> Result<String, ErrorObj> {
let p = p.unwrap_or_default();
fn check_password(p: &str) -> Result<(), ErrorObj> {
if p.chars().count() > MAX_PASSWORD_CHARS || p.chars().any(char::is_control) {
return Err(bad("channel_password is invalid"));
}
Ok(p)
Ok(())
}
fn host_path(field: &str, p: &str) -> Result<PathBuf, ErrorObj> {
if p.is_empty() || p.len() > 4096 || p.contains('\0') {
return Err(bad(format!("{field} is invalid")));
}
let path = PathBuf::from(p);
if !path.is_absolute() {
return Err(bad(format!("{field} must be absolute")));
}
Ok(path)
fn check_host_path(field: &str, path: &Path) -> Result<(), ErrorObj> {
let p = path.to_str().ok_or_else(|| bad(format!("{field} is invalid")))?;
if p.is_empty() || p.len() > 4096 || p.contains('\0') { return Err(bad(format!("{field} is invalid"))); }
if !path.is_absolute() { return Err(bad(format!("{field} must be absolute"))); }
Ok(())
}
// Channel zero is reserved for the virtual server's icons (main-owned snapshots and icon manager),
@@ -278,94 +273,90 @@ pub fn wire_name(channel_id: u64, path: &str) -> &str {
/// Parse a `file_*` bridge command.
pub fn parse(name: &str, raw: Option<&RawValue>) -> Result<Request, ErrorObj> {
Ok(match name {
let request = match name {
"file_config" => {
let a: ConfigArgs = args(raw)?;
if a.download_slots > 9 || a.upload_slots > 9 || a.download_slots + a.upload_slots > 10
|| a.download_limit > 26_843_545_600 || a.upload_limit > 26_843_545_600 {
return Err(bad("invalid transfer scheduler limits"));
}
Request::Config { download_slots: a.download_slots, upload_slots: a.upload_slots, download_limit: a.download_limit, upload_limit: a.upload_limit }
}
"file_list" => {
"file_list" | "file_mkdir" => {
let a: PathArgs = args(raw)?;
let path = remote_dir(&a.path)?;
let channel_id = if a.channel_id == 0 && path == "/icons/" { 0 } else { channel(a.channel_id)? };
Request::List { channel_id, path, password: password(a.channel_password)? }
}
"file_mkdir" => {
let a: PathArgs = args(raw)?;
Request::Mkdir { channel_id: channel(a.channel_id)?, path: remote_item(&a.path)?, password: password(a.channel_password)? }
if name == "file_list" { Request::List { channel_id: a.channel_id, path: a.path, password: a.channel_password.unwrap_or_default() } }
else { Request::Mkdir { channel_id: a.channel_id, path: a.path, password: a.channel_password.unwrap_or_default() } }
}
"file_rename" => {
let a: RenameArgs = args(raw)?;
let target = match (a.target_channel_id, a.target_channel_password) {
(Some(id), pw) => Some((channel(id)?, password(pw)?)),
(Some(id), pw) => Some((id, pw.unwrap_or_default())),
(None, Some(_)) => return Err(bad("target_channel_password requires target_channel_id")),
(None, None) => None,
};
let (from, to) = (remote_item(&a.from)?, remote_item(&a.to)?);
if from == to && target.as_ref().is_none_or(|t| t.0 == a.channel_id) {
return Err(bad("from and to are the same path"));
}
Request::Rename { channel_id: channel(a.channel_id)?, password: password(a.channel_password)?, from, to, target }
Request::Rename { channel_id: a.channel_id, password: a.channel_password.unwrap_or_default(), from: a.from, to: a.to, target }
}
"file_delete" => {
let a: DeleteArgs = args(raw)?;
if a.paths.is_empty() || a.paths.len() > MAX_DELETE {
return Err(bad(format!("paths must hold 1-{MAX_DELETE} entries")));
}
let paths = a.paths.iter().map(|p| remote_item(p)).collect::<Result<Vec<_>, _>>()?;
// Channel 0 deletes only server icons; every path must name one.
let channel_id = if a.channel_id == 0 {
for p in &paths { transfer_channel(0, p)?; }
0
} else { a.channel_id };
Request::Delete { channel_id, password: password(a.channel_password)?, paths }
Request::Delete { channel_id: a.channel_id, password: a.channel_password.unwrap_or_default(), paths: a.paths }
}
"file_download" => {
let a: DownloadArgs = args(raw)?;
if a.subdirs.len() > MAX_SUBDIRS {
return Err(bad("too many subdirs"));
}
for s in &a.subdirs {
local_component(s)?;
}
let path = remote_item(&a.path)?;
local_component(file_name(&path))?;
Request::Download {
channel_id: transfer_channel(a.channel_id, &path)?,
password: password(a.channel_password)?,
path,
dest_dir: host_path("dest_dir", &a.dest_dir)?,
subdirs: a.subdirs,
overwrite: a.overwrite,
}
Request::Download { channel_id: a.channel_id, password: a.channel_password.unwrap_or_default(), path: a.path,
dest_dir: PathBuf::from(a.dest_dir), subdirs: a.subdirs, overwrite: a.overwrite }
}
"file_upload" => {
let a: UploadArgs = args(raw)?;
let path = remote_item(&a.path)?;
Request::Upload {
channel_id: transfer_channel(a.channel_id, &path)?,
password: password(a.channel_password)?,
path,
source: host_path("source", &a.source)?,
overwrite: a.overwrite,
}
Request::Upload { channel_id: a.channel_id, password: a.channel_password.unwrap_or_default(), path: a.path,
source: PathBuf::from(a.source), overwrite: a.overwrite }
}
"file_cancel" => Request::Cancel { transfer_id: args::<CancelArgs>(raw)?.transfer_id },
"file_pause" => Request::Pause { transfer_id: args::<CancelArgs>(raw)?.transfer_id },
"file_resume" => Request::Resume { transfer_id: args::<CancelArgs>(raw)?.transfer_id },
"file_fetch_image" => {
let a: ImageArgs = args(raw)?;
Request::FetchImage { channel_id: channel(a.channel_id)?, path: remote_item(&a.path)? }
}
"file_transfers" => {
args::<Empty>(raw)?;
Request::Transfers
Request::FetchImage { channel_id: a.channel_id, path: a.path }
}
"file_transfers" => { args::<Empty>(raw)?; Request::Transfers }
other => return Err(ErrorObj::new(ErrorCode::UnknownCommand, format!("unknown command {other}"))),
})
};
Ok(request)
}
pub(crate) fn validate(request: &mut Request) -> Result<(), ErrorObj> {
match request {
Request::Config { download_slots, upload_slots, download_limit, upload_limit } => {
if *download_slots > 9 || *upload_slots > 9 || *download_slots + *upload_slots > 10
|| *download_limit > 26_843_545_600 || *upload_limit > 26_843_545_600 { return Err(bad("invalid transfer scheduler limits")); }
}
Request::List { channel_id, path, password } => {
check_remote_dir(path)?;
if !path.ends_with('/') { path.push('/'); }
if *channel_id != 0 || path.as_str() != "/icons/" { channel(*channel_id)?; }
check_password(password)?;
}
Request::Mkdir { channel_id, path, password } => { channel(*channel_id)?; check_remote_item(path)?; check_password(password)?; }
Request::Rename { channel_id, password, from, to, target } => {
if let Some((id, pw)) = target { channel(*id)?; check_password(pw)?; }
check_remote_item(from)?; check_remote_item(to)?;
if from == to && target.as_ref().is_none_or(|t| t.0 == *channel_id) { return Err(bad("from and to are the same path")); }
channel(*channel_id)?; check_password(password)?;
}
Request::Delete { channel_id, password, paths } => {
if paths.is_empty() || paths.len() > MAX_DELETE { return Err(bad(format!("paths must hold 1-{MAX_DELETE} entries"))); }
for path in paths { check_remote_item(path)?; transfer_channel(*channel_id, path)?; }
check_password(password)?;
}
Request::Download { channel_id, password, path, dest_dir, subdirs, .. } => {
if subdirs.len() > MAX_SUBDIRS { return Err(bad("too many subdirs")); }
for subdir in subdirs { local_component(subdir)?; }
check_remote_item(path)?; local_component(file_name(path))?;
transfer_channel(*channel_id, path)?; check_password(password)?; check_host_path("dest_dir", dest_dir)?;
}
Request::Upload { channel_id, password, path, source, .. } => {
check_remote_item(path)?; transfer_channel(*channel_id, path)?;
check_password(password)?; check_host_path("source", source)?;
}
Request::FetchImage { channel_id, path } => { channel(*channel_id)?; check_remote_item(path)?; }
Request::Cancel { .. } | Request::Pause { .. } | Request::Resume { .. } | Request::Transfers => {}
}
Ok(())
}
// ------------------------------------------------------------------ paths
@@ -396,11 +387,16 @@ fn check_path_text(p: &str) -> Result<(), ErrorObj> {
/// Remote folder path, normalized to `/` or `/a/b/`.
pub fn remote_dir(p: &str) -> Result<String, ErrorObj> {
check_remote_dir(p)?;
if p.ends_with('/') { Ok(p.to_owned()) } else { Ok(format!("{p}/")) }
}
fn check_remote_dir(p: &str) -> Result<(), ErrorObj> {
check_path_text(p)?;
let inner = p.trim_start_matches('/').trim_end_matches('/');
if inner.is_empty() {
if p.chars().all(|c| c == '/') && p.len() == 1 {
return Ok("/".into());
return Ok(());
}
return Err(bad("remote path contains an empty component"));
}
@@ -410,11 +406,16 @@ pub fn remote_dir(p: &str) -> Result<String, ErrorObj> {
for c in inner.split('/') {
remote_component(c)?;
}
Ok(format!("/{inner}/"))
Ok(())
}
/// Remote file or folder path `/a/b` (no trailing slash; not the root).
pub fn remote_item(p: &str) -> Result<String, ErrorObj> {
check_remote_item(p)?;
Ok(p.to_owned())
}
fn check_remote_item(p: &str) -> Result<(), ErrorObj> {
check_path_text(p)?;
let inner = &p[1..];
if inner.is_empty() || inner.ends_with('/') {
@@ -423,7 +424,7 @@ pub fn remote_item(p: &str) -> Result<String, ErrorObj> {
for c in inner.split('/') {
remote_component(c)?;
}
Ok(p.to_owned())
Ok(())
}
/// Last component of a validated remote item path.
@@ -1479,6 +1480,43 @@ pub async fn upload(
mod tests {
use super::*;
fn parse(name: &str, raw: Option<&RawValue>) -> Result<Request, ErrorObj> {
let mut request = super::parse(name, raw)?;
validate(&mut request)?;
Ok(request)
}
#[test]
fn direct_list_normalization_preserves_the_wire_path_boundary() {
let path = format!("/{}/{}", "a".repeat(MAX_NAME_CHARS), "b".repeat(MAX_NAME_CHARS));
assert_eq!(path.len(), MAX_PATH_CHARS);
let command = crate::protocol::Command::Files(Request::List { channel_id: 7, path: path.clone(), password: String::new() });
let validated = crate::protocol::validate_command(command).unwrap();
let expected = crate::protocol::Command::Files(Request::List { channel_id: 7, path: format!("{path}/"), password: String::new() });
assert_eq!(validated.into_inner(), expected);
let line = serde_json::json!({"id":"boundary","cmd":"file_list","args":{"channel_id":7,"path":path}}).to_string();
let crate::protocol::Input::Request { cmd, .. } = crate::protocol::parse_line(&line) else { panic!("valid boundary path rejected") };
assert_eq!(cmd.into_inner(), expected);
}
#[test]
fn direct_file_requests_reject_paths_passwords_and_unsafe_destinations() {
let invalid = [
Request::List { channel_id: 7, path: "/a//b".into(), password: String::new() },
Request::Mkdir { channel_id: 7, path: "/a".into(), password: "pw\n".into() },
Request::Rename { channel_id: 7, password: String::new(), from: "/a".into(), to: "/a".into(), target: None },
Request::Rename { channel_id: 7, password: String::new(), from: "/a".into(), to: "/b".into(), target: Some((0, String::new())) },
Request::Delete { channel_id: 7, password: String::new(), paths: vec![] },
Request::Delete { channel_id: 0, password: String::new(), paths: vec!["/private".into()] },
Request::Download { channel_id: 7, password: String::new(), path: "/file".into(), dest_dir: std::env::temp_dir(), subdirs: vec!["..".into()], overwrite: false },
Request::Download { channel_id: 7, password: String::new(), path: "/CON".into(), dest_dir: std::env::temp_dir(), subdirs: vec![], overwrite: false },
Request::FetchImage { channel_id: 0, path: "/icons/icon_1".into() },
];
for command in invalid {
assert_eq!(crate::protocol::validate_command(crate::protocol::Command::Files(command)).unwrap_err().code, ErrorCode::BadRequest);
}
}
fn raw(name: &str, items: &[&[(&str, &str)]]) -> RawNotification {
RawNotification {
name: name.into(),
+238 -61
View File
@@ -1,10 +1,11 @@
//! Scoped global-shortcut helper. No keyboard hooks or unrestricted key-state scans.
//! Wire contract: app/main/whisper-main.js (newline-delimited JSON on stdio).
//! Native callback service and CLI adapter (newline-delimited JSON on stdio).
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};
use std::error::Error;
use std::io::{self, BufRead, Write};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::{atomic::{AtomicBool, Ordering}, mpsc::{self, RecvTimeoutError}, Arc};
use std::thread::JoinHandle;
use std::time::Duration;
mod keys;
@@ -30,19 +31,19 @@ enum Command {
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Binding {
id: String,
code: String,
pub struct Binding {
pub id: String,
pub code: String,
#[serde(default)]
ctrl: bool,
pub ctrl: bool,
#[serde(default)]
alt: bool,
pub alt: bool,
#[serde(default)]
shift: bool,
pub shift: bool,
#[serde(default)]
meta: bool,
pub meta: bool,
#[serde(default)]
description: String,
pub description: String,
}
impl Binding {
@@ -98,12 +99,12 @@ impl State {
true
}
fn release_all(&mut self, out: &mut impl Write) -> io::Result<()> {
// Clear each flag even if stdout has gone away; cleanup must still unregister OS bindings.
fn release_all(&mut self, out: &mut impl FnMut(serde_json::Value) -> io::Result<()>) -> io::Result<()> {
// Clear every flag even when the consumer fails; OS cleanup must still run.
let mut failure = None;
for (id, held) in &mut self.registered {
if std::mem::replace(held, false) {
if let Err(error) = emit(out, &serde_json::json!({ "event": "release", "id": id })) {
if let Err(error) = out(serde_json::json!({ "event": "release", "id": id, "synthetic": true })) {
failure = Some(error);
}
}
@@ -112,22 +113,22 @@ impl State {
failure.map_or(Ok(()), Err)
}
fn event(&mut self, event: Event, out: &mut impl Write) -> io::Result<()> {
fn event(&mut self, event: Event, out: &mut impl FnMut(serde_json::Value) -> io::Result<()>) -> io::Result<()> {
match event {
Event::Key { id, down } => {
if self.transition(&id, down) {
emit(out, &serde_json::json!({ "event": if down { "press" } else { "release" }, "id": id }))?;
out(serde_json::json!({ "event": if down { "press" } else { "release" }, "id": id }))?;
}
}
Event::Bound { seq, results } => {
self.release_all(out)?;
self.registered.extend(results.iter().filter(|r| r.ok).map(|r| (r.id.clone(), false)));
emit(out, &serde_json::json!({ "event": "bound", "seq": seq, "results": results }))?;
out(serde_json::json!({ "event": "bound", "seq": seq, "results": results }))?;
}
Event::Rebound { results } => {
self.release_all(out)?;
self.registered.extend(results.iter().filter(|r| r.ok).map(|r| (r.id.clone(), false)));
emit(out, &serde_json::json!({ "event": "rebound", "results": results }))?;
out(serde_json::json!({ "event": "rebound", "results": results }))?;
}
}
Ok(())
@@ -140,25 +141,28 @@ fn emit(out: &mut impl Write, value: &impl Serialize) -> io::Result<()> {
out.flush()
}
fn validate_bindings(bindings: &[Binding]) -> Result<()> {
if bindings.len() > MAX_BINDINGS { return Err("at most 64 hotkey bindings".into()); }
let mut ids = HashSet::with_capacity(bindings.len());
let mut chords = HashSet::with_capacity(bindings.len());
for b in bindings {
if b.id.is_empty() || b.id.len() > 128 || b.id.chars().any(char::is_control)
|| b.code.is_empty() || b.code.len() > 32 || !b.code.bytes().all(|c| c.is_ascii_alphanumeric())
|| b.description.len() > 256 || b.description.chars().any(char::is_control)
{
return Err("invalid hotkey id, code or description".into());
}
if !ids.insert(&b.id) || !chords.insert((&b.code, b.modifiers())) {
return Err("duplicate hotkey id or chord".into());
}
}
Ok(())
}
fn parse(line: &[u8]) -> Result<Command> {
if line.len() > MAX_LINE { return Err("hotkey input line exceeds 64 KiB".into()); }
let command: Command = serde_json::from_slice(line)?;
if let Command::Bind { bindings, .. } = &command {
if bindings.len() > MAX_BINDINGS { return Err("at most 64 hotkey bindings".into()); }
let mut ids = HashSet::with_capacity(bindings.len());
let mut chords = HashSet::with_capacity(bindings.len());
for b in bindings {
if b.id.is_empty() || b.id.len() > 128 || b.id.chars().any(char::is_control)
|| b.code.is_empty() || b.code.len() > 32 || !b.code.bytes().all(|c| c.is_ascii_alphanumeric())
|| b.description.len() > 256 || b.description.chars().any(char::is_control)
{
return Err("invalid hotkey id, code or description".into());
}
if !ids.insert(&b.id) || !chords.insert((&b.code, b.modifiers())) {
return Err("duplicate hotkey id or chord".into());
}
}
}
if let Command::Bind { bindings, .. } = &command { validate_bindings(bindings)?; }
Ok(command)
}
@@ -196,8 +200,207 @@ fn open_backend() -> Result<Box<dyn Backend>> {
{ Err("global shortcuts are unavailable on this platform".into()) }
}
/// A startup, validation, queue or backend failure. No OS registrations survive stop.
#[derive(Clone, Debug)]
pub struct HotkeyError(String);
impl std::fmt::Display for HotkeyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) }
}
impl Error for HotkeyError {}
/// Owns a backend thread and bounded ordered events. Drop requests cancellation;
/// call `stop` off the UI thread to wait for OS cleanup, then dispatch final events.
pub struct HotkeyHandle {
commands: mpsc::SyncSender<Result<Command, String>>,
cancelled: Arc<AtomicBool>,
worker: Option<JoinHandle<Result<(), HotkeyError>>>,
events: mpsc::Receiver<serde_json::Value>,
held: std::collections::BTreeSet<String>,
terminal: Option<Result<(), HotkeyError>>,
terminal_delivered: bool,
}
const EVENT_CAPACITY: usize = 256;
impl HotkeyHandle {
/// Replace the complete binding profile. Success means queued; the callback's
/// `bound` event with this sequence carries the actual registration results.
/// A full queue returns an error without replacing any pending profile.
pub fn update(&self, seq: u32, bindings: Vec<Binding>) -> Result<(), HotkeyError> {
validate_bindings(&bindings).map_err(|e| HotkeyError(e.to_string()))?;
if self.cancelled.load(Ordering::Acquire) { return Err(HotkeyError("hotkey service has stopped".into())); }
self.commands.try_send(Ok(Command::Bind { seq, bindings })).map_err(|error| {
HotkeyError(match error {
mpsc::TrySendError::Full(_) => "hotkey command queue is full",
mpsc::TrySendError::Disconnected(_) => "hotkey service has stopped",
}.into())
})
}
/// Cancel pending updates, release held keys, unregister and join the worker.
/// Call off the UI thread; callbacks are never run by the backend worker.
/// Afterwards call `dispatch` to consume final releases/errors.
pub fn stop(&mut self) -> Result<(), HotkeyError> {
self.cancel();
if let Some(worker) = self.worker.take() {
self.terminal = Some(worker.join().unwrap_or_else(|_| Err(HotkeyError("hotkey worker panicked".into()))));
}
self.terminal.clone().unwrap_or(Ok(()))
}
fn cancel(&self) {
self.cancelled.store(true, Ordering::Release);
// Wake an idle worker; cancellation remains effective with a full queue.
let _ = self.commands.try_send(Ok(Command::Shutdown {}));
}
/// Deliver a bounded batch on the calling thread, plus final releases/errors.
/// No callback runs on the OS backend thread, so a stalled consumer cannot
/// prevent unregister. Queue overflow terminates the backend; cancellation
/// discards undelivered events. Every consumer-held key is released before the
/// terminal error, even if the bounded queue had no room for its release.
/// Callback failure cancels the backend; call again to receive final releases.
pub fn dispatch(&mut self, mut callback: impl FnMut(serde_json::Value) -> io::Result<()>) -> Result<usize, HotkeyError> {
let mut delivered = 0;
let mut disconnected = false;
if self.worker.as_ref().is_some_and(|worker| worker.is_finished()) { let _ = self.stop(); }
if matches!(&self.terminal, Some(Err(_))) {
// Failed service events must not reactivate PTT when a stalled host
// resumes. The joined worker cannot refill this bounded queue.
while self.events.try_recv().is_ok() {}
}
for _ in 0..EVENT_CAPACITY {
let value = match self.events.try_recv() {
Ok(value) => value,
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => { disconnected = true; break; }
};
if self.cancelled.load(Ordering::Acquire) { continue; }
let release_id = if value["event"] == "release" { value["id"].as_str().map(str::to_owned) } else { None };
if value["event"] == "press" {
if let Some(id) = value["id"].as_str() { self.held.insert(id.to_owned()); }
}
if let Err(error) = callback(value) {
self.cancel();
return Err(HotkeyError(error.to_string()));
}
if let Some(id) = release_id { self.held.remove(&id); }
delivered += 1;
}
if self.worker.as_ref().is_some_and(|worker| worker.is_finished()) { let _ = self.stop(); }
if disconnected && self.terminal.is_some() && !self.terminal_delivered {
while let Some(id) = self.held.first().cloned() {
callback(serde_json::json!({ "event": "release", "id": id, "synthetic": true })).map_err(|e| HotkeyError(e.to_string()))?;
self.held.remove(&id);
delivered += 1;
}
if let Some(Err(error)) = &self.terminal {
callback(serde_json::json!({ "event": "error", "detail": error.to_string() })).map_err(|e| HotkeyError(e.to_string()))?;
delivered += 1;
}
self.terminal_delivered = true;
}
Ok(delivered)
}
}
impl Drop for HotkeyHandle {
fn drop(&mut self) { self.cancel(); }
}
/// Explicitly open the platform backend, without registering any bindings.
/// Call off the UI thread: startup waits for backend discovery. `update` is the
/// only registration request. Call `dispatch` regularly to deliver callback
/// events with the CLI JSON shape and no serialization round trip.
pub fn start() -> Result<HotkeyHandle, HotkeyError> {
start_with_backend(open_backend)
}
fn start_with_backend(
factory: impl FnOnce() -> Result<Box<dyn Backend>> + Send + 'static,
) -> Result<HotkeyHandle, HotkeyError> {
let (commands, rx) = mpsc::sync_channel(8);
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
let (events_tx, events) = mpsc::sync_channel(EVENT_CAPACITY);
let cancelled = Arc::new(AtomicBool::new(false));
let stop = Arc::clone(&cancelled);
let worker = std::thread::Builder::new().name("hotkeys".into()).spawn(move || {
let mut out = |value: serde_json::Value| {
// Native errors are delivered once after final held-key releases.
if value["event"] == "error" { return Ok(()); }
events_tx.try_send(value).map_err(|error| io::Error::other(match error {
mpsc::TrySendError::Full(_) => "hotkey event queue overflow",
mpsc::TrySendError::Disconnected(_) => "hotkey event consumer closed",
}))
};
let mut backend = match factory() {
Ok(backend) => backend,
Err(error) => {
let detail = error.to_string();
let _ = out(serde_json::json!({ "event": "ready", "backend": "unavailable", "global": false, "release": false, "detail": detail }));
let _ = ready_tx.send(Err(detail.clone()));
return Err(HotkeyError(detail));
}
};
if let Err(error) = out(serde_json::json!({ "event": "ready", "backend": backend.name(), "global": true, "release": true })) {
let _ = backend.clear();
let _ = ready_tx.send(Err(error.to_string()));
return Err(HotkeyError(error.to_string()));
}
let _ = ready_tx.send(Ok(()));
serve(&mut *backend, rx, &stop, &mut out).map_err(|e| HotkeyError(e.to_string()))
}).map_err(|e| HotkeyError(e.to_string()))?;
let mut handle = HotkeyHandle { commands, cancelled, worker: Some(worker), events,
held: Default::default(), terminal: None, terminal_delivered: false };
match ready_rx.recv() {
Ok(Ok(())) => Ok(handle),
Ok(Err(error)) => { let _ = handle.stop(); Err(HotkeyError(error)) }
Err(_) => { let _ = handle.stop(); Err(HotkeyError("hotkey worker stopped during startup".into())) }
}
}
fn serve(
backend: &mut dyn Backend,
rx: mpsc::Receiver<Result<Command, String>>,
cancelled: &AtomicBool,
out: &mut impl FnMut(serde_json::Value) -> io::Result<()>,
) -> Result<()> {
let mut state = State::default();
let mut events = Vec::with_capacity(MAX_BINDINGS);
let result = (|| -> Result<()> {
while !cancelled.load(Ordering::Acquire) {
let command = rx.recv_timeout(Duration::from_millis(8));
if cancelled.load(Ordering::Acquire) { break; }
match command {
Ok(Ok(Command::Shutdown {})) | Err(RecvTimeoutError::Disconnected) => break,
Ok(Err(error)) => return Err(error.into()),
Ok(Ok(Command::Bind { seq, bindings })) => {
state.release_all(out)?;
backend.clear()?;
backend.bind(seq, bindings, &mut events)?;
}
Err(RecvTimeoutError::Timeout) => {}
}
if cancelled.load(Ordering::Acquire) { break; }
backend.poll(&mut events)?;
for event in events.drain(..) { state.event(event, out)?; }
}
Ok(())
})();
let released = state.release_all(out);
let cleared = backend.clear();
if let Err(error) = &result {
let _ = out(serde_json::json!({ "event": "error", "detail": error.to_string() }));
}
result?;
released?;
cleared
}
/// Runs only when explicitly selected by the `hotkeys` CLI subcommand.
/// Tests exercise parsing/state only and never construct a platform backend.
/// Blocking input and stdout serialization belong exclusively to this adapter.
pub fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
let stdout = io::stdout();
let mut out = stdout.lock();
@@ -226,31 +429,5 @@ pub fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
if tx.send(item).is_err() || terminal { break; }
}
})?;
let mut state = State::default();
let mut events = Vec::with_capacity(MAX_BINDINGS);
let result = (|| -> Result<()> {
loop {
match rx.recv_timeout(Duration::from_millis(8)) {
Ok(Ok(Command::Shutdown {})) | Err(RecvTimeoutError::Disconnected) => break,
Ok(Err(error)) => return Err(error.into()),
Ok(Ok(Command::Bind { seq, bindings })) => {
state.release_all(&mut out)?;
backend.clear()?;
backend.bind(seq, bindings, &mut events)?;
}
Err(RecvTimeoutError::Timeout) => {}
}
backend.poll(&mut events)?;
for event in events.drain(..) { state.event(event, &mut out)?; }
}
Ok(())
})();
let released = state.release_all(&mut out);
let cleared = backend.clear();
if let Err(error) = &result {
let _ = emit(&mut out, &serde_json::json!({ "event": "error", "detail": error.to_string() }));
}
result?;
released?;
cleared
serve(&mut *backend, rx, &AtomicBool::new(false), &mut |value| emit(&mut out, &value))
}
+163 -5
View File
@@ -83,10 +83,13 @@ fn replacement_releases_held_ids_before_new_bound_event() {
state.registered.insert("old".into(), true);
let mut out = Vec::new();
state.event(Event::Bound { seq: 2, results: vec![BindResult::success(&binding("new", "KeyN"), "n".into()),
BindResult::failure(&binding("bad", "Unknown"), "unsupported_key", "unsupported")] }, &mut out).unwrap();
BindResult::failure(&binding("bad", "Unknown"), "unsupported_key", "unsupported")] }, &mut |value| emit(&mut out, &value)).unwrap();
let messages: Vec<serde_json::Value> = out.split(|b| *b == b'\n').filter(|b| !b.is_empty())
.map(|b| serde_json::from_slice(b).unwrap()).collect();
assert_eq!(messages[0], serde_json::json!({ "event": "release", "id": "old" }));
assert_eq!(messages[0]["event"], "release");
assert_eq!(messages[0]["id"], "old");
// Replacement is cancellation, not a physical key-up that can trigger a command.
assert_eq!(messages[0]["synthetic"], true);
assert_eq!(messages[1]["event"], "bound");
assert_eq!(messages[1]["seq"], 2);
assert!(state.transition("new", true));
@@ -99,9 +102,9 @@ fn shutdown_and_failure_release_all_once() {
let mut state = State::default();
state.registered.extend([("a".into(), true), ("b".into(), true), ("c".into(), false)]);
let mut out = Vec::new();
state.release_all(&mut out).unwrap();
state.release_all(&mut |value| emit(&mut out, &value)).unwrap();
let written = out.len();
state.release_all(&mut out).unwrap();
state.release_all(&mut |value| emit(&mut out, &value)).unwrap();
assert_eq!(out.len(), written);
assert_eq!(out.iter().filter(|&&b| b == b'\n').count(), 2);
assert!(state.registered.is_empty());
@@ -116,7 +119,7 @@ fn broken_stdout_still_clears_all_held_state() {
}
let mut state = State::default();
state.registered.extend([("a".into(), true), ("b".into(), true)]);
assert!(state.release_all(&mut Broken).is_err());
assert!(state.release_all(&mut |value| emit(&mut Broken, &value)).is_err());
assert!(state.registered.is_empty());
}
@@ -134,3 +137,158 @@ fn key_allowlist_and_portal_trigger_are_explicit() {
b.meta = true;
assert_eq!(keys::trigger(&b, &keys::lookup(&b.code).unwrap()), "CTRL+SHIFT+LOGO+a");
}
// The same service factory/loop used by native callers, with no platform access.
struct FakeBackend {
binds: Arc<std::sync::atomic::AtomicUsize>,
clears: Arc<std::sync::atomic::AtomicUsize>,
dropped: Arc<AtomicBool>,
bursts: mpsc::Receiver<usize>,
active: Option<String>,
}
impl Backend for FakeBackend {
fn name(&self) -> &'static str { "test" }
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()> {
self.binds.fetch_add(1, Ordering::SeqCst);
self.active = bindings.first().map(|b| b.id.clone());
let results = bindings.iter().map(|b| BindResult::success(b, b.code.clone())).collect();
events.push(Event::Bound { seq, results });
if let Some(id) = &self.active { events.push(Event::Key { id: id.clone(), down: true }); }
Ok(())
}
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()> {
if let (Some(id), Ok(count)) = (&self.active, self.bursts.try_recv()) {
for n in 0..count { events.push(Event::Key { id: id.clone(), down: n % 2 != 0 }); }
}
Ok(())
}
fn clear(&mut self) -> Result<()> {
self.clears.fetch_add(1, Ordering::SeqCst);
self.active = None;
Ok(())
}
}
impl Drop for FakeBackend {
fn drop(&mut self) { self.dropped.store(true, Ordering::Release); }
}
struct Fixture {
handle: HotkeyHandle,
binds: Arc<std::sync::atomic::AtomicUsize>,
clears: Arc<std::sync::atomic::AtomicUsize>,
dropped: Arc<AtomicBool>,
bursts: mpsc::SyncSender<usize>,
}
fn fake_service() -> Fixture {
let binds = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let clears = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let dropped = Arc::new(AtomicBool::new(false));
let (bursts, rx) = mpsc::sync_channel(1);
let backend = FakeBackend { binds: binds.clone(), clears: clears.clone(), dropped: dropped.clone(), bursts: rx, active: None };
let handle = start_with_backend(move || Ok(Box::new(backend))).unwrap();
Fixture { handle, binds, clears, dropped, bursts }
}
fn eventually(mut condition: impl FnMut() -> bool) {
let deadline = std::time::Instant::now() + Duration::from_secs(3);
while !condition() {
assert!(std::time::Instant::now() < deadline, "hotkey lifecycle did not complete");
std::thread::sleep(Duration::from_millis(1));
}
}
fn dispatch_until(handle: &mut HotkeyHandle, messages: &mut Vec<serde_json::Value>, event: &str, id: &str) {
let consumer_thread = std::thread::current().id();
eventually(|| {
handle.dispatch(|value| {
assert_eq!(std::thread::current().id(), consumer_thread);
messages.push(value);
Ok(())
}).unwrap();
messages.iter().any(|v| v["event"] == event && v["id"] == id)
});
}
#[test]
fn native_profiles_release_before_replace_and_join_before_restart() {
for _ in 0..100 {
let mut fixture = fake_service();
assert_eq!(fixture.binds.load(Ordering::SeqCst), 0, "startup must not register");
let mut messages = Vec::new();
fixture.handle.update(1, vec![binding("old", "KeyA")]).unwrap();
dispatch_until(&mut fixture.handle, &mut messages, "press", "old");
assert!(fixture.handle.update(2, vec![binding("x", "KeyA"), binding("x", "KeyB")]).is_err());
assert_eq!(fixture.binds.load(Ordering::SeqCst), 1);
fixture.handle.update(3, vec![binding("new", "KeyB")]).unwrap();
dispatch_until(&mut fixture.handle, &mut messages, "press", "new");
let released = messages.iter().position(|v| v["event"] == "release" && v["id"] == "old").unwrap();
let rebound = messages.iter().position(|v| v["event"] == "bound" && v["seq"] == 3).unwrap();
assert!(released < rebound);
fixture.handle.stop().unwrap();
assert!(fixture.dropped.load(Ordering::Acquire), "stop must join backend destruction");
assert_eq!(fixture.clears.load(Ordering::SeqCst), 3);
dispatch_until(&mut fixture.handle, &mut messages, "release", "new");
assert!(fixture.handle.update(4, vec![]).is_err());
let count = messages.len();
fixture.handle.stop().unwrap();
fixture.handle.dispatch(|v| { messages.push(v); Ok(()) }).unwrap();
assert_eq!(messages.len(), count, "stop/release must be idempotent");
}
}
#[test]
fn stalled_event_consumer_unregisters_and_receives_final_release_on_overflow() {
let mut fixture = fake_service();
let mut messages = Vec::new();
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
dispatch_until(&mut fixture.handle, &mut messages, "press", "ptt");
fixture.bursts.send(EVENT_CAPACITY + 1).unwrap();
// Do not dispatch: a backend must terminate independently of the consumer.
eventually(|| fixture.dropped.load(Ordering::Acquire));
assert!(fixture.handle.stop().unwrap_err().to_string().contains("overflow"));
eventually(|| {
fixture.handle.dispatch(|v| { messages.push(v); Ok(()) }).unwrap();
messages.iter().any(|v| v["event"] == "error")
});
let mut held = false;
for message in &messages {
match message["event"].as_str().unwrap() {
"press" => { assert!(!held); held = true; }
"release" => { assert!(held); held = false; }
"error" => assert!(!held, "overflow must release PTT before reporting failure"),
_ => {}
}
}
assert!(!held);
assert_eq!(fixture.clears.load(Ordering::SeqCst), 2);
}
#[test]
fn callback_failure_cancels_without_stranding_consumer_held_key() {
let mut fixture = fake_service();
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
eventually(|| fixture.handle.dispatch(|value| {
if value["event"] == "press" { Err(io::Error::other("consumer failed")) } else { Ok(()) }
}).is_err());
fixture.handle.stop().unwrap();
let mut messages = Vec::new();
dispatch_until(&mut fixture.handle, &mut messages, "release", "ptt");
assert_eq!(messages.iter().filter(|v| v["event"] == "release").count(), 1);
assert!(fixture.dropped.load(Ordering::Acquire));
}
#[test]
fn dropping_service_requests_cleanup_without_dispatch() {
let mut fixture = fake_service();
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
dispatch_until(&mut fixture.handle, &mut Vec::new(), "press", "ptt");
drop(fixture.handle);
eventually(|| fixture.dropped.load(Ordering::Acquire));
assert_eq!(fixture.clears.load(Ordering::SeqCst), 2);
}
+18 -3
View File
@@ -1,9 +1,11 @@
//! Disposable identity CLI. Keys never enter stdout or process arguments.
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Write};
use std::io::{BufRead, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
use std::time::Duration;
use serde_json::{json, Value};
use crate::profile::{Store, store_error};
use crate::protocol::{ErrorCode, ErrorObj};
@@ -17,6 +19,19 @@ pub fn emit(value: &Value) {
let _ = writeln!(out, "{value}");
let _ = out.flush();
}
// Only the standalone CLI owns a blocking stdin cancellation reader. The
// embeddable improvement entrypoint never starts or waits for this reader.
fn improve(store: &Store, uid: &str, target: u8, seconds: u64) -> Result<Value, ErrorObj> {
let cancel = Arc::new(AtomicBool::new(false));
let signal = cancel.clone();
std::thread::spawn(move || {
let mut line = String::new();
// Cancel on explicit command, stdin closure or transport failure.
let _ = std::io::stdin().lock().read_line(&mut line);
signal.store(true, Ordering::Relaxed);
});
crate::identity_improve::improve(store, uid, target, Duration::from_secs(seconds), &cancel, |event| emit(&event))
}
fn execute(args: &[String]) -> Result<Value, ErrorObj> {
let action = args.first().ok_or_else(|| bad("identity action required"))?;
let allowed: &[&str] = match action.as_str() {
@@ -39,7 +54,7 @@ fn execute(args: &[String]) -> Result<Value, ErrorObj> {
// Atomic vault reads need no profile lock; exports remain available during standalone sessions.
// Mutations share the core lock and Store serializes writers/protects connected identities.
let _guard = if action == "list" || action == "export" { None } else {
Some(crate::lock_dir(&dir, true).map_err(|e| ErrorObj::new(ErrorCode::Io, e))?)
Some(crate::locks::lock_dir(&dir, true).map_err(|e| ErrorObj::new(ErrorCode::Io, e))?)
};
let store = Store::new(dir);
let uid = || required(&values, "--uid");
@@ -68,7 +83,7 @@ fn execute(args: &[String]) -> Result<Value, ErrorObj> {
let target = required(&values,"--target")?.parse::<u8>().map_err(|_| bad("invalid target"))?;
let seconds = values.get("--seconds").map(|v| v.parse::<u64>()).transpose().map_err(|_| bad("invalid duration"))?.unwrap_or(30);
if !(1..=crate::profile::MAX_TARGET_LEVEL).contains(&target) || !(1..=60).contains(&seconds) { return Err(bad("target must be 1–100; duration 1–60 seconds")); }
crate::identity_improve::run(&store, uid()?, target, seconds)
improve(&store, uid()?, target, seconds)
},
_ => unreachable!(),
}
+71 -29
View File
@@ -1,11 +1,10 @@
//! Bounded, cancellable hash-cash work. One core at <=25% duty cycle for at most 60 seconds.
use std::io::{self, BufRead};
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use sha1::{Digest, Sha1};
use serde_json::{json, Value};
use crate::profile::{Store, store_error};
use crate::protocol::ErrorObj;
use crate::protocol::{ErrorCode, ErrorObj};
// TeamSpeak counts trailing bits of each SHA1 byte, starting with the first byte.
// Decimal conversion uses a stack buffer: no allocation per candidate.
@@ -24,7 +23,22 @@ fn quality(prefix: &Sha1, mut offset: u64) -> u8 {
}
level
}
fn search(store: &Store, uid: &str, target: u8, duration: Duration, cancel: &AtomicBool) -> Result<Value, ErrorObj> {
/// Improve an identity on the caller's worker, persisting progress before notifying it.
/// Cancellation is caller-owned; this function creates no threads or transport readers.
/// Returning (including cancellation) completes the final durable checkpoint.
pub fn improve(
store: &Store,
uid: &str,
target: u8,
duration: Duration,
cancel: &AtomicBool,
mut progress: impl FnMut(Value),
) -> Result<Value, ErrorObj> {
if !(1..=crate::profile::MAX_TARGET_LEVEL).contains(&target)
|| duration.is_zero() || duration > Duration::from_secs(60)
{
return Err(ErrorObj::new(ErrorCode::BadRequest, "target must be 1–100; duration greater than zero and at most 60 seconds"));
}
let start = store.improve_start(uid).map_err(store_error)?;
let mut prefix = Sha1::new(); prefix.update(start.omega.as_bytes());
let begun = Instant::now();
@@ -44,7 +58,7 @@ fn search(store: &Store, uid: &str, target: u8, duration: Duration, cancel: &Ato
}
if checkpoint.elapsed() >= Duration::from_millis(500) || level >= target || exhausted {
level = store.record_improvement(uid, best.take(), next).map_err(store_error)?;
crate::identity_cli::emit(&json!({"event":"identity_progress","uid":uid,"level":level,"target":target,"searched":next.to_string(),"elapsed_ms":begun.elapsed().as_millis()}));
progress(json!({"event":"identity_progress","uid":uid,"level":level,"target":target,"searched":next.to_string(),"elapsed_ms":begun.elapsed().as_millis()}));
checkpoint = Instant::now();
}
if exhausted { break; }
@@ -53,17 +67,6 @@ fn search(store: &Store, uid: &str, target: u8, duration: Duration, cancel: &Ato
level = store.record_improvement(uid, best, next).map_err(store_error)?;
Ok(json!({"uid":uid,"level":level,"target":target,"reached":level>=target,"canceled":cancel.load(Ordering::Relaxed),"bounded":level<target,"exhausted":exhausted,"searched":next.to_string()}))
}
pub fn run(store: &Store, uid: &str, target: u8, seconds: u64) -> Result<Value, ErrorObj> {
let cancel = Arc::new(AtomicBool::new(false));
let signal = cancel.clone();
std::thread::spawn(move || {
let mut line = String::new();
// Cancel on explicit command, stdin closure or transport failure.
let _ = io::stdin().lock().read_line(&mut line);
signal.store(true, Ordering::Relaxed);
});
search(store, uid, target, Duration::from_secs(seconds), &cancel)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -86,11 +89,33 @@ mod tests {
let store = Store::new(&dir.0);
let identity = store.create_identity("Temporary", "Temporary").unwrap();
let before = store.export_ini(&identity.uid).unwrap();
let result = search(&store, &identity.uid, 100, Duration::from_secs(1), &AtomicBool::new(true)).unwrap();
let result = std::thread::scope(|scope| {
scope.spawn(|| improve(&store, &identity.uid, 100, Duration::from_secs(1), &AtomicBool::new(true), |_| panic!("pre-canceled work must not report progress")))
.join().expect("native worker joins without a stdin reader").unwrap()
});
assert_eq!(result["canceled"], true);
assert_eq!(before, store.export_ini(&identity.uid).unwrap());
}
#[test]
fn native_bounds_reject_before_touching_identity() {
let dir = crate::profile::tests::TempDir::new("improve-invalid");
let store = Store::new(&dir.0);
let info = store.create_identity("Temporary", "Temporary").unwrap();
let before = store.export_ini(&info.uid).unwrap();
let start = store.improve_start(&info.uid).unwrap().start;
for (target, duration) in [
(0, Duration::from_secs(1)),
(101, Duration::from_secs(1)),
(100, Duration::ZERO),
(100, Duration::from_secs(61)),
] {
let error = improve(&store, &info.uid, target, duration, &AtomicBool::new(false), |_| panic!("invalid work must not report progress")).unwrap_err();
assert_eq!(serde_json::to_value(error).unwrap()["code"], "bad_request");
}
assert_eq!(before, store.export_ini(&info.uid).unwrap());
assert_eq!(start, store.improve_start(&info.uid).unwrap().start);
}
#[test]
fn quality_matches_protocol_identity_and_deadline_resumes() {
let dir = crate::profile::tests::TempDir::new("improve-bound");
let store = Store::new(&dir.0);
@@ -99,7 +124,7 @@ mod tests {
let start = store.improve_start(&info.uid).unwrap();
let mut prefix = Sha1::new(); prefix.update(start.omega.as_bytes());
assert_eq!(quality(&prefix, stored.identity.counter()), stored.identity.level());
let result = search(&store, &info.uid, 100, Duration::from_millis(20), &AtomicBool::new(false)).unwrap();
let result = improve(&store, &info.uid, 100, Duration::from_millis(20), &AtomicBool::new(false), |_| {}).unwrap();
assert_eq!(result["bounded"], true);
let resumed = store.improve_start(&info.uid).unwrap();
assert!(resumed.start > start.start);
@@ -108,19 +133,36 @@ mod tests {
assert_eq!(resumed.start.to_string(), result["searched"].as_str().unwrap());
}
#[test]
fn cancellation_during_search_preserves_checkpoint() {
fn cancellation_during_search_preserves_checkpoint_and_resumes() {
let dir = crate::profile::tests::TempDir::new("improve-running-cancel");
let store = Store::new(&dir.0);
let info = store.create_identity("Temporary", "Temporary").unwrap();
let cancel = Arc::new(AtomicBool::new(false));
let signal = cancel.clone();
let canceller = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(25));
signal.store(true, Ordering::Relaxed);
});
let result = search(&store, &info.uid, 100, Duration::from_secs(1), &cancel).unwrap();
canceller.join().unwrap();
assert_eq!(result["canceled"], true);
assert_eq!(store.improve_start(&info.uid).unwrap().start.to_string(), result["searched"].as_str().unwrap());
let original_key = store.load_identity().unwrap().unwrap().identity.key().to_ts();
let mut previous = store.improve_start(&info.uid).unwrap().start;
for _ in 0..2 {
let cancel = AtomicBool::new(false);
let mut checkpoint = None;
// Cancel synchronously at a durable checkpoint, without a timing race
// against a detached canceller or relying on thread scheduling.
let result = improve(&store, &info.uid, 100, Duration::from_secs(60), &cancel, |event| {
assert_eq!(event["uid"], info.uid);
let persisted = store.improve_start(&info.uid).unwrap();
assert_eq!(event["searched"], persisted.start.to_string());
checkpoint = Some(persisted.start);
cancel.store(true, Ordering::Relaxed);
}).unwrap();
assert_eq!(result["canceled"], true);
let next = checkpoint.expect("search must report a durable checkpoint");
assert!(next > previous);
let persisted = store.improve_start(&info.uid).unwrap();
assert_eq!(persisted.start, next);
assert_eq!(result["searched"], next.to_string());
let loaded = store.load_identity().unwrap().unwrap();
assert_eq!(loaded.uid, info.uid);
assert_eq!(loaded.identity.key().to_ts(), original_key);
let mut prefix = Sha1::new(); prefix.update(persisted.omega.as_bytes());
assert_eq!(quality(&prefix, loaded.identity.counter()), persisted.level);
previous = next;
}
}
}
+28
View File
@@ -0,0 +1,28 @@
//! Embedded TeamSpeak domain services and the independent diagnostic CLI adapters.
pub mod admin;
pub mod app_audio;
pub mod audio;
mod events;
pub mod file_transfer;
pub mod hotkeys;
mod keyfmt;
pub mod identity_cli;
pub mod identity_improve;
pub mod locks;
pub mod media;
pub mod menu;
pub mod output;
pub mod profile;
pub mod protocol;
pub mod recording;
mod rawcmd;
pub mod runtime;
pub mod secure_fs;
pub mod session;
mod snapshot;
pub mod stdio;
#[cfg(test)]
mod test_exec;
pub mod vad;
pub mod voice_dsp;
pub mod whisper;
+23
View File
@@ -0,0 +1,23 @@
use std::fs::{File, OpenOptions, TryLockError};
use std::path::Path;
use crate::secure_fs;
/// Cooperates with diagnostic CLI and embedded sessions without copying private identity keys.
pub fn lock_dir(dir: &Path, shared: bool) -> Result<File, String> {
secure_fs::ensure_private_dir(dir).map_err(|e| format!("cannot create data dir {}: {e}", dir.display()))?;
let path = dir.join("core.lock");
let file = OpenOptions::new().create(true).truncate(false).write(true).open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
match if shared { file.try_lock_shared() } else { file.try_lock() } {
Ok(()) => Ok(file),
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
}
}
pub fn lock_run(data_dir: &Path, connection_dir: Option<&Path>) -> Result<Vec<File>, String> {
match connection_dir {
None => Ok(vec![lock_dir(data_dir, false)?]),
Some(conn) => Ok(vec![lock_dir(data_dir, true)?, lock_dir(conn, false)?]),
}
}
+8 -68
View File
@@ -1,32 +1,7 @@
//! TeamsPeach core: TeamSpeak protocol backend speaking newline-delimited JSON on stdio.
//! Contract: `docs/bridge.md`.
mod admin;
mod app_audio;
mod audio;
mod events;
mod file_transfer;
mod hotkeys;
mod keyfmt;
mod identity_cli;
mod identity_improve;
mod media;
mod menu;
mod profile;
mod protocol;
mod recording;
mod rawcmd;
mod secure_fs;
mod session;
mod snapshot;
mod stdio;
#[cfg(test)]
mod test_exec;
mod vad;
mod voice_dsp;
mod whisper;
use std::fs::{File, OpenOptions, TryLockError};
use teamspeach_core::{app_audio, audio, hotkeys, identity_cli, locks, output, profile, protocol, session, stdio};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;
@@ -36,10 +11,10 @@ use serde_json::json;
use tokio::sync::mpsc;
use tracing::{error, info};
use crate::audio::AudioInQueue;
use crate::profile::Store;
use crate::protocol::PROTOCOL_VERSION;
use crate::stdio::Out;
use audio::AudioInQueue;
use profile::Store;
use protocol::PROTOCOL_VERSION;
use output::Out;
const EXIT_FATAL: u8 = 1;
const EXIT_USAGE: u8 = 2;
@@ -82,45 +57,10 @@ fn parse_args(args: &[String]) -> Result<Mode, String> {
Ok(Mode::Run { data_dir, connection_dir })
}
/// Lock on `<dir>/core.lock`, held for the process lifetime.
///
/// - exclusive (`shared == false`): a single-connection core.
/// - shared: simultaneous connection cores and the identity CLI on the same profile.
/// Store serializes identity writes separately with `profile.lock`.
fn lock_dir(dir: &Path, shared: bool) -> Result<File, String> {
secure_fs::ensure_private_dir(dir).map_err(|e| format!("cannot create data dir {}: {e}", dir.display()))?;
let path = dir.join("core.lock");
let file = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
let result = if shared { file.try_lock_shared() } else { file.try_lock() };
match result {
Ok(()) => Ok(file),
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
}
}
fn lock_data_dir(dir: &Path) -> Result<File, String> { lock_dir(dir, false) }
/// Profile locks for `run`: exclusive on the profile alone, or shared on the profile plus exclusive
/// on the connection's own directory (two cores never serve the same connection slot).
fn lock_run(data_dir: &Path, connection_dir: Option<&Path>) -> Result<Vec<File>, String> {
match connection_dir {
None => Ok(vec![lock_data_dir(data_dir)?]),
Some(conn) => {
let profile = lock_dir(data_dir, true)?;
Ok(vec![profile, lock_dir(conn, false)?])
}
}
}
fn run(data_dir: PathBuf, connection_dir: Option<PathBuf>) -> ExitCode {
let _locks = match lock_run(&data_dir, connection_dir.as_deref()) {
let _locks = match locks::lock_run(&data_dir, connection_dir.as_deref()) {
Ok(l) => l,
Err(e) => {
error!("{e}");
@@ -135,8 +75,8 @@ fn run(data_dir: PathBuf, connection_dir: Option<PathBuf>) -> ExitCode {
}
};
rt.block_on(async move {
let (out, out_rx) = Out::new();
let writer = tokio::spawn(stdio::run_writer(out_rx));
let (out, out_rx, playback_rx) = Out::new();
let writer = tokio::spawn(stdio::run_writer(out_rx, playback_rx));
let audio_in = Arc::new(AudioInQueue::new());
let (cmd_tx, cmd_rx) = mpsc::channel(64);
{
+16 -5
View File
@@ -41,7 +41,7 @@ pub enum Action {
SetChannelPermission { channel_id: u64, permission_id: u32, value: Option<i32> },
KickChannel { reason: String }, KickServer { reason: String }, Ban { reason: String, duration: u32 },
Volume { db: f32, muted: bool }, Avatar { data: String },
MoveToOwnChannel { #[serde(default)] password: Option<String> }, DeleteAvatar {},
MoveToOwnChannel { #[serde(default)] password: Option<String>, expected_channel_id: u64 }, DeleteAvatar {},
}
impl Action {
pub fn key(&self) -> &'static str { match self {
@@ -66,22 +66,28 @@ pub fn validate_target(t: &Target) -> Result<(), ErrorObj> {
pub fn parse_action(mut value: Value) -> Result<ActionRequest, ErrorObj> {
let obj=value.as_object_mut().ok_or_else(||bad("args must be an object"))?;
let target=serde_json::from_value::<Target>(json!({"client_id":obj.remove("client_id"),"uid":obj.remove("uid")})).map_err(|e|bad(e.to_string()))?;
validate_target(&target)?;
let generation=obj.remove("generation").and_then(|v|v.as_u64()).filter(|v|*v>0).ok_or_else(||bad("generation is required"))?;
if matches!(obj.get("action").and_then(Value::as_str),Some("set_client_permission"|"set_channel_permission")) && !obj.contains_key("value") { return Err(bad("value is required; use null explicitly to remove a permission")); }
let action:Action=serde_json::from_value(value).map_err(|e|bad(e.to_string()))?;
match &action {
Ok(ActionRequest { target, generation, action })
}
pub(crate) fn validate_action(request: &ActionRequest) -> Result<(), ErrorObj> {
validate_target(&request.target)?;
if request.generation == 0 { return Err(bad("generation is required")); }
match &request.action {
Action::Poke{message} if message.is_empty() || message.len()>1024 || message.chars().any(char::is_control) =>return Err(bad("poke message must be 1..1024 bytes without controls")),
Action::KickChannel{reason}|Action::KickServer{reason}|Action::Ban{reason,..} if reason.len()>1024 || reason.chars().any(char::is_control)=>return Err(bad("reason must be at most 1024 bytes without controls")),
Action::Volume{db,..} if !crate::voice_dsp::valid_modifier_db(*db)=>return Err(bad("volume must be -200..10 dB in 0.5 dB steps")),
Action::ServerGroup{group_id,..}|Action::ChannelGroup{group_id,..} if *group_id==0=>return Err(bad("group_id must be positive")),
Action::ChannelGroup{channel_id,..}|Action::ChannelPermissions{channel_id}|Action::SetChannelPermission{channel_id,..} if *channel_id==0=>return Err(bad("channel_id must be positive")),
Action::SetClientPermission{permission_id,..}|Action::SetChannelPermission{permission_id,..} if *permission_id==0=>return Err(bad("permission_id must be positive")),
Action::MoveToOwnChannel{password:Some(p)} if p.len()>1024 || p.chars().any(char::is_control)=>return Err(bad("invalid channel password")),
Action::MoveToOwnChannel{expected_channel_id:0,..}=>return Err(bad("expected_channel_id must be positive")),
Action::MoveToOwnChannel{password:Some(p),..} if p.len()>1024 || p.chars().any(char::is_control)=>return Err(bad("invalid channel password")),
Action::Avatar{data}=>{avatar_bytes(data)?;},
_=>{},
}
Ok(ActionRequest{target,generation,action})
Ok(())
}
pub fn avatar_bytes(data:&str)->Result<Vec<u8>,ErrorObj>{
if data.len()>174_764 { return Err(bad("avatar exceeds 128 KiB")); }
@@ -205,6 +211,11 @@ pub fn response_matches(row:&Row,response:&str,client_id:u16,dbid:u64,channel:Op
#[cfg(test)]
mod tests {
use super::*;
fn parse_action(value: Value) -> Result<ActionRequest, ErrorObj> {
let request = super::parse_action(value)?;
validate_action(&request)?;
Ok(request)
}
#[test] fn command_fixture_escapes_and_uses_real_protocol_fields(){
let action=Action::KickChannel{reason:"a b|c".into()};
let packet=action_command(&action,42,9).unwrap().into_packet();
+2 -1
View File
@@ -21,8 +21,9 @@ impl Session {
let client=&book.clients[&ClientId(request.target.client_id)];
let dbid=client.database_id.0;
match &request.action {
MenuAction::MoveToOwnChannel{password}=>{
MenuAction::MoveToOwnChannel{password,expected_channel_id}=>{
let own_channel=book.clients.get(&book.own_client).ok_or_else(||menu::bad("own channel unavailable"))?.channel;
if own_channel.0!=*expected_channel_id{return Err(ErrorObj::new(ErrorCode::TargetChanged,"own channel changed; reopen the move action"));}
if own_channel==client.channel{return Err(menu::bad("client is already in your channel"));}
let pw=password.as_ref().filter(|p|!p.is_empty()).map(|p|tsproto_types::crypto::encode_password(p.as_bytes())).unwrap_or_default();
let command=menu::command("clientmove",&[("clid",client.id.0.to_string()),("cid",own_channel.0.to_string()),("cpw",pw)]);
+152
View File
@@ -0,0 +1,152 @@
//! Transport-neutral control output and bounded native playback PCM.
use std::{collections::VecDeque, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}};
use serde::Serialize;
use serde_json::{json, Value};
use tokio::sync::{mpsc, Notify};
use crate::protocol::{ErrorObj, Frame};
const CONTROL_CAPACITY: usize = 1024;
const PCM_CAPACITY: usize = 10;
pub struct PlaybackFrame {
pub pcm: Frame,
pub speakers: Vec<u16>,
pub generation: u64,
pub emitted_at: std::time::Instant,
recycled: Arc<Mutex<Vec<Vec<u16>>>>,
}
impl Drop for PlaybackFrame {
fn drop(&mut self) {
let mut speakers = std::mem::take(&mut self.speakers);
speakers.clear();
self.recycled.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(speakers);
}
}
struct PlaybackInner {
frames: VecDeque<PlaybackFrame>,
closed: bool,
}
struct PlaybackShared {
inner: Mutex<PlaybackInner>,
ready: Notify,
recycled: Arc<Mutex<Vec<Vec<u16>>>>,
}
pub struct PlaybackReceiver { shared: Arc<PlaybackShared> }
impl PlaybackReceiver {
pub async fn recv(&mut self) -> Option<PlaybackFrame> {
loop {
let notified = self.shared.ready.notified();
{
let mut inner = self.shared.inner.lock().expect("playback queue poisoned");
if let Some(frame) = inner.frames.pop_front() { return Some(frame); }
if inner.closed { return None; }
}
notified.await;
}
}
}
impl Drop for PlaybackReceiver {
fn drop(&mut self) {
let mut inner = self.shared.inner.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
inner.closed = true;
inner.frames.clear();
}
}
struct OutputInner {
control: mpsc::Sender<Value>,
playback: Arc<PlaybackShared>,
generation: AtomicU64,
}
impl Drop for OutputInner {
fn drop(&mut self) {
self.playback.inner.lock().expect("playback queue poisoned").closed = true;
self.playback.ready.notify_one();
}
}
#[derive(Clone)]
pub struct Out { inner: Arc<OutputInner> }
impl Out {
pub fn new() -> (Self, mpsc::Receiver<Value>, PlaybackReceiver) {
let (control, receiver) = mpsc::channel(CONTROL_CAPACITY);
let playback = Arc::new(PlaybackShared {
inner: Mutex::new(PlaybackInner { frames: VecDeque::with_capacity(PCM_CAPACITY), closed: false }),
ready: Notify::new(),
recycled: Arc::new(Mutex::new((0..PCM_CAPACITY + 2).map(|_| Vec::with_capacity(16)).collect())),
});
(Self { inner: Arc::new(OutputInner { control, playback: playback.clone(), generation: AtomicU64::new(0) }) }, receiver, PlaybackReceiver { shared: playback })
}
pub fn set_generation(&self, generation: u64) { self.inner.generation.store(generation, Ordering::Release); }
pub async fn control(&self, mut value: Value) {
if let Some(object) = value.as_object_mut().filter(|o| o.contains_key("event")) {
object.insert("generation".into(), Value::from(self.inner.generation.load(Ordering::Acquire)));
}
let _ = self.inner.control.send(value).await;
}
pub async fn json<T: Serialize>(&self, value: &T) {
match serde_json::to_value(value) {
Ok(value) => self.control(value).await,
Err(error) => tracing::error!(%error, "could not construct core output"),
}
}
/// Drops oldest playback under congestion; never waits for an audio device.
pub fn playback(&self, pcm: &Frame, speakers: &[u16]) -> bool {
let mut inner = self.inner.playback.inner.lock().expect("playback queue poisoned");
if inner.closed { return false; }
let retained = inner.frames.len() < PCM_CAPACITY;
if !retained { inner.frames.pop_front(); }
let Some(mut speaker_buffer) = self.inner.playback.recycled.lock().expect("playback pool poisoned").pop() else { return false; };
speaker_buffer.extend_from_slice(speakers);
inner.frames.push_back(PlaybackFrame { pcm: *pcm, speakers: speaker_buffer, generation: self.inner.generation.load(Ordering::Acquire), emitted_at: std::time::Instant::now(), recycled: self.inner.playback.recycled.clone() });
drop(inner);
self.inner.playback.ready.notify_one();
retained
}
pub async fn ok(&self, id: &str, result: Value) {
self.control(json!({"id":id,"ok":true,"result":result})).await;
}
pub async fn err(&self, id: &str, error: ErrorObj) {
self.control(json!({"id":id,"ok":false,"error":error})).await;
}
pub async fn error_event(&self, error: ErrorObj) {
self.control(json!({"event":"error","error":error})).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "current_thread")]
async fn playback_discards_oldest_without_relabeling_reconnected_frames() {
let (out, _control, mut playback) = Out::new();
out.set_generation(7);
for value in 0..12 { out.playback(&[value; crate::protocol::FRAME_SAMPLES], &[4, 9]); }
out.set_generation(8);
for expected in 2..12 {
let frame = playback.recv().await.unwrap();
assert_eq!(frame.pcm[0], expected);
assert_eq!(frame.generation, 7);
assert_eq!(frame.speakers, [4, 9]);
}
assert!(out.playback(&[12; crate::protocol::FRAME_SAMPLES], &[2]));
let frame = playback.recv().await.unwrap();
assert_eq!(frame.generation, 8);
assert_eq!(frame.speakers, [2]);
drop(frame);
drop(out);
assert!(playback.recv().await.is_none());
}
#[test]
fn missing_playback_consumer_refuses_new_audio() {
let (out, _control, playback) = Out::new();
drop(playback);
assert!(!out.playback(&[1; crate::protocol::FRAME_SAMPLES], &[2]));
}
}
+193 -77
View File
@@ -1,4 +1,9 @@
//! Bridge protocol v1 (see `docs/bridge.md`): request parsing and error objects.
//! Bridge protocol v1 (see `docs/bridge.md`): transport shape parsing and shared typed validation.
//!
//! Both CLI parsing and embedded requests enter through `validate_command` before
//! becoming `Input::Request`. Family parsers decode only transport shapes; their
//! semantic validators are dispatched here. Live generation/identity/permission
//! checks remain in the session because argument validation cannot replace them.
use std::borrow::Cow;
@@ -27,7 +32,7 @@ const MAX_FIELD_CHARS: usize = 1024;
pub type Frame = [i16; FRAME_SAMPLES];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
BadRequest,
@@ -63,7 +68,7 @@ pub enum ErrorCode {
}
/// TeamSpeak server error attached to an [`ErrorObj`].
#[derive(Clone, Debug, PartialEq, Serialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TsErrorInfo {
/// Numeric TeamSpeak error id (e.g. 513 = nickname in use).
pub id: u32,
@@ -73,7 +78,7 @@ pub struct TsErrorInfo {
pub missing_permission: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorObj {
pub code: ErrorCode,
pub message: String,
@@ -125,7 +130,7 @@ pub enum Command {
SetPlaybackDsp { agc: bool },
StreamList { client_id: Option<u16> },
StreamJoin { stream_id: String, client_id: u16, message: Option<String> },
/// `json` is already compact-serialized and size checked.
/// JSON text; `validate_command` requires an object, compacts it and checks its byte size.
StreamSignal { stream_id: String, client_id: u16, json: String },
StreamLeave { stream_id: String, client_id: u16 },
StreamSetup(StreamPublishArgs),
@@ -184,6 +189,16 @@ impl Command {
}
}
/// A command whose transport-independent arguments have been checked and normalized.
/// Only the core can unwrap it; callers must use [`validate_command`].
#[derive(Clone, Debug, PartialEq)]
pub struct ValidatedCommand(Command);
impl ValidatedCommand {
pub fn name(&self) -> &'static str { self.0.name() }
pub(crate) fn into_inner(self) -> Command { self.0 }
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConnectArgs {
@@ -205,7 +220,7 @@ pub struct ConnectArgs {
/// One parsed stdin line.
#[derive(Debug)]
pub enum Input {
Request { id: String, cmd: Command },
Request { id: String, cmd: ValidatedCommand },
AudioFrame(TaggedFrame),
AudioEnd,
/// The line could not be turned into a command. `id` is set if it could be recovered.
@@ -462,7 +477,7 @@ pub fn parse_line(line: &str) -> Input {
}
None => return Input::Invalid { id: None, error: bad("missing id") },
};
match parse_command(&env.cmd, env.args) {
match parse_command(&env.cmd, env.args).and_then(validate_command) {
Ok(cmd) => Input::Request { id, cmd },
Err(error) => Input::Invalid { id: Some(id), error },
}
@@ -483,42 +498,18 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
"rename" => Command::Rename { nickname: args_owned::<NicknameArgs>(raw)?.nickname },
"connect" => {
let a: ConnectArgs = args_owned(raw)?;
check_text("address", &a.address, 255, false)?;
check_opt("server_password", &a.server_password)?;
check_opt("channel", &a.channel)?;
check_opt("channel_password", &a.channel_password)?;
check_opt("identity_id", &a.identity_id)?;
Command::Connect(a)
}
"disconnect" => {
let a: DisconnectArgs = args_owned(raw)?;
check_opt("message", &a.message)?;
Command::Disconnect { message: a.message }
}
"join_channel" => {
let a: JoinChannelArgs = args_owned(raw)?;
check_opt("password", &a.password)?;
Command::JoinChannel { channel_id: a.channel_id, password: a.password }
}
"send_text" => {
let a: SendTextArgs = args_owned(raw)?;
if a.message.is_empty() || a.message.len() > MAX_TEXT_BYTES {
return Err(bad(format!("message must be 1-{MAX_TEXT_BYTES} bytes")));
}
match (a.target, a.client_id) {
(TextTarget::Client, None) => return Err(bad("client_id is required for target client")),
(TextTarget::Channel | TextTarget::Server, Some(_)) => {
return Err(bad("client_id is only allowed for target client"));
}
_ => {}
}
if a.target == TextTarget::Client {
if a.client_id == Some(0) { return Err(bad("client_id must be positive")); }
let uid = a.expected_client_uid.as_deref().ok_or_else(|| bad("expected_client_uid is required for target client"))?;
check_text("expected_client_uid", uid, 128, false)?;
} else if a.expected_client_uid.is_some() {
return Err(bad("expected_client_uid is only allowed for target client"));
}
Command::SendText { target: a.target, client_id: a.client_id, expected_client_uid: a.expected_client_uid, message: a.message }
}
"set_audio" => {
@@ -531,69 +522,34 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
"stream_list" => Command::StreamList { client_id: args_owned::<StreamListArgs>(raw)?.client_id },
"stream_join" => {
let a: StreamJoinArgs = args_owned(raw)?;
check_stream_id(&a.stream_id)?;
check_opt("message", &a.message)?;
Command::StreamJoin { stream_id: a.stream_id, client_id: a.client_id, message: a.message }
}
"stream_signal" => {
let a: StreamSignalArgs = args(raw)?;
check_stream_id(&a.stream_id)?;
let value: Value = serde_json::from_str(a.json.get())
.map_err(|e| bad(format!("json is not valid JSON: {e}")))?;
if !value.is_object() {
return Err(bad("json must be an object"));
}
let json = serde_json::to_string(&value).map_err(|e| bad(format!("json: {e}")))?;
if json.len() > MAX_SIGNAL_JSON_BYTES {
return Err(bad(format!("json larger than {MAX_SIGNAL_JSON_BYTES} bytes")));
}
Command::StreamSignal { stream_id: a.stream_id, client_id: a.client_id, json }
Command::StreamSignal { stream_id: a.stream_id, client_id: a.client_id, json: a.json.get().to_owned() }
}
"stream_leave" => {
let a: StreamLeaveArgs = args_owned(raw)?;
check_stream_id(&a.stream_id)?;
Command::StreamLeave { stream_id: a.stream_id, client_id: a.client_id }
}
"stream_setup" | "stream_update" => {
let a: StreamPublishArgs = args_owned(raw)?;
if (cmd == "stream_update") != a.stream_id.is_some() {
return Err(bad("stream_id is required only for stream_update"));
}
if let Some(id) = &a.stream_id { check_stream_id(id)?; }
check_text("name", &a.name, 200, false)?;
if a.name.chars().any(char::is_control) || !(1..=3).contains(&a.stream_type)
|| !(1..=3).contains(&a.accessibility) || a.mode != 1 || !(100..=100000).contains(&a.bitrate) {
return Err(bad("invalid stream metadata (only P2P is supported)"));
}
if cmd == "stream_setup" { Command::StreamSetup(a) } else { Command::StreamUpdate(a) }
}
"stream_stop" => {
let a: StreamStopArgs = args_owned(raw)?;
check_stream_id(&a.stream_id)?;
Command::StreamStop { stream_id: a.stream_id }
}
"stream_respond" => {
let a: StreamRespondArgs = args_owned(raw)?;
check_stream_id(&a.stream_id)?;
check_text("message", &a.message, 200, true)?;
if a.client_id == 0 || a.decision == a.offer.is_empty() || a.offer.len() > 60000
|| a.offer.chars().any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t'))
|| a.message.chars().any(char::is_control) {
return Err(bad("invalid stream join response"));
}
Command::StreamRespond { stream_id: a.stream_id, client_id: a.client_id, decision: a.decision, offer: a.offer, message: a.message }
}
"stream_remove" => {
let a: StreamLeaveArgs = args_owned(raw)?;
check_stream_id(&a.stream_id)?;
if a.client_id == 0 { return Err(bad("client_id must be nonzero")); }
Command::StreamRemove { stream_id: a.stream_id, client_id: a.client_id }
}
"fetch_icon" => {
let a: FetchIconArgs = args_owned(raw)?;
if a.icon_id == 0 {
return Err(bad("icon_id 0 means no icon"));
}
Command::FetchIcon { icon_id: a.icon_id }
}
"fetch_avatar" => Command::FetchAvatar { client_id: args_owned::<FetchAvatarArgs>(raw)?.client_id },
@@ -604,7 +560,6 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
}
"client_context" => {
let target = args_owned(raw)?;
crate::menu::validate_target(&target)?;
Command::ClientContext(target)
},
"client_action" => Command::ClientAction(crate::menu::parse_action(args_owned(raw)?)?),
@@ -622,6 +577,81 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
})
}
/// Validate and normalize typed requests, without serializing commands to JSON.
/// Signaling JSON is itself a protocol payload and is compacted for both transports.
pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorObj> {
let update = matches!(&command, Command::StreamUpdate(_));
match &mut command {
Command::Connect(a) => {
check_text("address", &a.address, 255, false)?;
check_opt("server_password", &a.server_password)?;
check_opt("channel", &a.channel)?;
check_opt("channel_password", &a.channel_password)?;
check_opt("identity_id", &a.identity_id)?;
}
Command::Disconnect { message } => check_opt("message", message)?,
Command::JoinChannel { password, .. } => check_opt("password", password)?,
Command::SendText { target, client_id, expected_client_uid, message } => {
if message.is_empty() || message.len() > MAX_TEXT_BYTES { return Err(bad(format!("message must be 1-{MAX_TEXT_BYTES} bytes"))); }
match (*target, *client_id) {
(TextTarget::Client, None) => return Err(bad("client_id is required for target client")),
(TextTarget::Channel | TextTarget::Server, Some(_)) => return Err(bad("client_id is only allowed for target client")),
_ => {}
}
if *target == TextTarget::Client {
if *client_id == Some(0) { return Err(bad("client_id must be positive")); }
let uid = expected_client_uid.as_deref().ok_or_else(|| bad("expected_client_uid is required for target client"))?;
check_text("expected_client_uid", uid, 128, false)?;
} else if expected_client_uid.is_some() { return Err(bad("expected_client_uid is only allowed for target client")); }
}
Command::SetTransmit { vad } => crate::voice_dsp::validate_transmit(*vad)?,
Command::SetLocalVolumes(a) => crate::voice_dsp::validate_local_volumes(a)?,
Command::StreamJoin { stream_id, message, .. } => { check_stream_id(stream_id)?; check_opt("message", message)?; }
Command::StreamSignal { stream_id, json, .. } => {
check_stream_id(stream_id)?;
let value: Value = serde_json::from_str(json).map_err(|e| bad(format!("json is not valid JSON: {e}")))?;
if !value.is_object() { return Err(bad("json must be an object")); }
let compact = serde_json::to_string(&value).map_err(|e| bad(format!("json: {e}")))?;
if compact.len() > MAX_SIGNAL_JSON_BYTES { return Err(bad(format!("json larger than {MAX_SIGNAL_JSON_BYTES} bytes"))); }
*json = compact;
}
Command::StreamLeave { stream_id, .. } | Command::StreamStop { stream_id } => check_stream_id(stream_id)?,
Command::StreamSetup(a) | Command::StreamUpdate(a) => {
if update != a.stream_id.is_some() { return Err(bad("stream_id is required only for stream_update")); }
if let Some(id) = &a.stream_id { check_stream_id(id)?; }
check_text("name", &a.name, 200, false)?;
if a.name.chars().any(char::is_control) || !(1..=3).contains(&a.stream_type)
|| !(1..=3).contains(&a.accessibility) || a.mode != 1 || !(100..=100000).contains(&a.bitrate) {
return Err(bad("invalid stream metadata (only P2P is supported)"));
}
}
Command::StreamRespond { stream_id, client_id, decision, offer, message } => {
check_stream_id(stream_id)?;
check_text("message", message, 200, true)?;
if *client_id == 0 || *decision == offer.is_empty() || offer.len() > 60000
|| offer.chars().any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t')) || message.chars().any(char::is_control) {
return Err(bad("invalid stream join response"));
}
}
Command::StreamRemove { stream_id, client_id } => {
check_stream_id(stream_id)?;
if *client_id == 0 { return Err(bad("client_id must be nonzero")); }
}
Command::FetchIcon { icon_id: 0 } => return Err(bad("icon_id 0 means no icon")),
Command::ClientContext(a) => crate::menu::validate_target(a)?,
Command::ClientAction(a) => crate::menu::validate_action(a)?,
Command::Admin(a) => crate::admin::validate(a)?,
Command::Files(a) => crate::file_transfer::validate(a)?,
Command::Recording(a) => crate::recording::validate(a)?,
Command::Whisper(a) => crate::whisper::validate(a)?,
Command::ProfileGet | Command::ProfileCreate { .. } | Command::Rename { .. }
| Command::SetAudio { .. } | Command::SetPlaybackDsp { .. } | Command::StreamList { .. }
| Command::FetchIcon { .. } | Command::FetchAvatar { .. } | Command::FetchBanner { .. }
| Command::FetchServerBanner | Command::Shutdown => {}
}
Ok(ValidatedCommand(command))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -678,11 +708,11 @@ mod tests {
#[test]
fn set_transmit_modes_and_sensitivities() {
let parse = |args: &str| parse_line(&format!(r#"{{"id":"t","cmd":"set_transmit","args":{args}}}"#));
assert!(matches!(parse(r#"{"mode":"direct"}"#), Input::Request { cmd: Command::SetTransmit { vad: None }, .. }));
assert!(matches!(parse(r#"{"mode":"direct"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: None }), .. }));
use crate::vad::Sensitivity;
assert!(matches!(parse(r#"{"mode":"vad"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Normal)) }, .. }));
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"high"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::High)) }, .. }));
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"low"}"#), Input::Request { cmd: Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Low)) }, .. }));
assert!(matches!(parse(r#"{"mode":"vad"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Normal)) }), .. }));
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"high"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::High)) }), .. }));
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"low"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Low)) }), .. }));
for bad in [r#"{"mode":"open"}"#, r#"{"mode":"direct","sensitivity":"low"}"#, r#"{"mode":"vad","sensitivity":"max"}"#, r#"{"mode":"vad","threshold":0.1}"#, r#"{}"#] {
match parse(bad) {
Input::Invalid { error, .. } => assert_eq!(error.code, ErrorCode::BadRequest, "{bad}"),
@@ -695,7 +725,7 @@ mod tests {
fn requests_need_valid_id_and_known_args() {
assert!(matches!(
parse_line(r#"{"id":"a","cmd":"profile_get"}"#),
Input::Request { cmd: Command::ProfileGet, .. }
Input::Request { cmd: ValidatedCommand(Command::ProfileGet), .. }
));
match parse_line(r#"{"cmd":"profile_get"}"#) {
Input::Invalid { id: None, error } => assert_eq!(error.code, ErrorCode::BadRequest),
@@ -733,17 +763,17 @@ mod tests {
fn publisher_metadata_and_responses_are_strict() {
let metadata = serde_json::json!({"name":"QA | stream", "type":3,"accessibility":3,"mode":1,"bitrate":4500,"viewer_limit":0,"audio":false});
let parse = |cmd: &str, args: Value| parse_line(&serde_json::json!({"id":"p","cmd":cmd,"args":args}).to_string());
assert!(matches!(parse("stream_setup", metadata.clone()), Input::Request { cmd: Command::StreamSetup(_), .. }));
assert!(matches!(parse("stream_setup", metadata.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamSetup(_)), .. }));
assert!(matches!(parse("stream_update", metadata.clone()), Input::Invalid { .. }));
let mut updated = metadata.clone(); updated["stream_id"] = serde_json::json!("s1");
assert!(matches!(parse("stream_update", updated.clone()), Input::Request { cmd: Command::StreamUpdate(_), .. }));
assert!(matches!(parse("stream_update", updated.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamUpdate(_)), .. }));
assert!(matches!(parse("stream_setup", updated), Input::Invalid { .. }));
for (key, value) in [("type", 4), ("accessibility", 0), ("mode", 2), ("bitrate", 99), ("viewer_limit", -1)] {
let mut invalid = metadata.clone(); invalid[key] = serde_json::json!(value);
assert!(matches!(parse("stream_setup", invalid), Input::Invalid { .. }), "{key}");
}
let response = serde_json::json!({"stream_id":"s1","client_id":5,"decision":true,"offer":"v=0\r\n","message":""});
assert!(matches!(parse("stream_respond", response.clone()), Input::Request { cmd: Command::StreamRespond { decision:true, .. }, .. }));
assert!(matches!(parse("stream_respond", response.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamRespond { decision:true, .. }), .. }));
let mut invalid = response; invalid["offer"] = serde_json::json!("");
assert!(matches!(parse("stream_respond", invalid), Input::Invalid { .. }));
assert!(matches!(parse("stream_remove", serde_json::json!({"stream_id":"s1","client_id":0})), Input::Invalid { .. }));
@@ -754,7 +784,7 @@ mod tests {
fn stream_signal_json_is_compacted_object() {
let line = r#"{"id":"s","cmd":"stream_signal","args":{"stream_id":"7","client_id":5,"json":{ "cmd" : "answer", "args": {"answer":"v=0\r\no=- 1 2 IN IP4 0.0.0.0"} }}}"#;
match parse_line(line) {
Input::Request { cmd: Command::StreamSignal { json, client_id, .. }, .. } => {
Input::Request { cmd: ValidatedCommand(Command::StreamSignal { json, client_id, .. }), .. } => {
assert_eq!(client_id, 5);
assert_eq!(json, r#"{"cmd":"answer","args":{"answer":"v=0\r\no=- 1 2 IN IP4 0.0.0.0"}}"#);
}
@@ -763,4 +793,90 @@ mod tests {
let arr = r#"{"id":"s","cmd":"stream_signal","args":{"stream_id":"7","client_id":5,"json":[1]}}"#;
assert!(matches!(parse_line(arr), Input::Invalid { .. }));
}
fn assert_bad(command: Command) {
assert_eq!(validate_command(command).unwrap_err().code, ErrorCode::BadRequest);
}
#[test]
fn direct_private_text_requires_exact_target_and_uid() {
let private = |client_id, expected_client_uid| Command::SendText {
target: TextTarget::Client, client_id, expected_client_uid, message: "hello".into(),
};
assert_bad(private(None, Some("uid".into())));
assert_bad(private(Some(0), Some("uid".into())));
assert_bad(private(Some(7), None));
assert_bad(private(Some(7), Some(String::new())));
assert_bad(private(Some(7), Some("x".repeat(129))));
let valid = validate_command(private(Some(7), Some("uid".into()))).unwrap();
assert_eq!(valid.name(), "send_text");
assert_eq!(valid.into_inner(), private(Some(7), Some("uid".into())));
for target in [TextTarget::Channel, TextTarget::Server] {
assert_bad(Command::SendText { target, client_id: Some(7), expected_client_uid: None, message: "hello".into() });
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: Some("uid".into()), message: "hello".into() });
for message in [String::new(), "я".repeat(MAX_TEXT_BYTES / 2 + 1)] {
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: None, message });
}
}
let Input::Invalid { error, .. } = parse_line(r#"{"id":"t","cmd":"send_text","args":{"target":"client","client_id":7,"message":"hello"}}"#) else { panic!() };
assert_eq!(error, validate_command(private(Some(7), None)).unwrap_err());
}
#[test]
fn direct_signaling_checks_objects_and_compact_byte_limit() {
let signal = |json| Command::StreamSignal { stream_id: "s1".into(), client_id: 7, json };
for json in ["[]", "null", "42", "\"string\"", "{"] { assert_bad(signal(json.into())); }
let compact = format!(r#"{{"x":"{}"}}"#, "x".repeat(MAX_SIGNAL_JSON_BYTES - 8));
let padded = format!(" {compact}{}", " ".repeat(MAX_SIGNAL_JSON_BYTES));
assert_eq!(validate_command(signal(padded)).unwrap().into_inner(), signal(compact));
assert_bad(signal(format!(r#"{{"x":"{}"}}"#, "x".repeat(MAX_SIGNAL_JSON_BYTES - 7))));
assert_bad(Command::StreamSignal { stream_id: "bad\n".into(), client_id: 7, json: "{}".into() });
}
#[test]
fn direct_publisher_metadata_and_join_response_are_validated() {
let args = StreamPublishArgs { stream_id: None, name: "Screen".into(), stream_type: 3,
accessibility: 3, mode: 1, bitrate: 4500, viewer_limit: 0, audio: false };
assert!(validate_command(Command::StreamSetup(args.clone())).is_ok());
assert_bad(Command::StreamUpdate(args.clone()));
let mut update = args.clone(); update.stream_id = Some("s1".into());
assert!(validate_command(Command::StreamUpdate(update.clone())).is_ok());
assert_bad(Command::StreamSetup(update));
for invalid in [
StreamPublishArgs { mode: 2, ..args.clone() },
StreamPublishArgs { accessibility: 0, ..args.clone() },
StreamPublishArgs { stream_type: 4, ..args.clone() },
StreamPublishArgs { bitrate: 99, ..args.clone() },
StreamPublishArgs { bitrate: 100001, ..args.clone() },
StreamPublishArgs { name: "Screen\n".into(), ..args.clone() },
StreamPublishArgs { name: String::new(), ..args },
] { assert_bad(Command::StreamSetup(invalid)); }
for (client_id, decision, offer, message) in [(0, true, "v=0", ""), (7, true, "", ""),
(7, false, "v=0", ""), (7, true, "v=0\0", ""), (7, true, "v=0", "bad\n")] {
assert_bad(Command::StreamRespond { stream_id: "s1".into(), client_id, decision, offer: offer.into(), message: message.into() });
}
}
#[test]
fn direct_family_commands_cannot_bypass_semantic_checks() {
use crate::{admin, file_transfer as files, menu, recording, whisper};
let invalid = [
Command::Admin(admin::AdminCommand::ChannelMove { generation: 1, channel_id: 7, parent_id: 7, order: None }),
Command::Admin(admin::AdminCommand::BanAdd { generation: 1, ip: None, name: None, uid: None, duration_s: 0, reason: None }),
Command::Admin(admin::AdminCommand::TempPasswordAdd { generation: 1, password: "pw".into(), description: String::new(), duration_s: 0, channel_id: 0, channel_password: String::new() }),
Command::Admin(admin::AdminCommand::Extra(admin::extra::Command::ServerLog { lines: 0, reverse: false, instance: false, begin_pos: 0 })),
Command::ClientAction(menu::ActionRequest { target: menu::Target { client_id: 7, uid: "uid".into() }, generation: 1, action: menu::Action::Volume { db: f32::NAN, muted: false } }),
Command::Files(files::Request::Config { download_slots: usize::MAX, upload_slots: usize::MAX, download_limit: 0, upload_limit: 0 }),
Command::Files(files::Request::Mkdir { channel_id: 7, path: "/../bad".into(), password: String::new() }),
Command::Files(files::Request::List { channel_id: 0, path: "/private".into(), password: String::new() }),
Command::Files(files::Request::Upload { channel_id: 7, path: "/file".into(), password: String::new(), source: "relative".into(), overwrite: false }),
Command::Recording(recording::RecCommand::Start { directory: "relative".into(), mode: recording::Mode::Master, label: None }),
Command::Whisper(whisper::WhisperCommand::Stop { epoch: 0 }),
Command::SetTransmit { vad: Some(GateMode::VolumeGate { level_db: f32::NAN }) },
Command::SetLocalVolumes(LocalVolumesUpdate { replace: false, volumes: vec![(vec![1], f32::INFINITY)] }),
];
for command in invalid { assert_bad(command); }
let validated = validate_command(Command::Files(files::Request::List { channel_id: 7, path: "/folder".into(), password: String::new() })).unwrap();
assert_eq!(validated.into_inner(), Command::Files(files::Request::List { channel_id: 7, path: "/folder/".into(), password: String::new() }));
}
}
+16 -14
View File
@@ -139,22 +139,11 @@ fn valid_label(label: &str) -> bool {
}
pub fn parse(cmd: &str, raw: Option<&RawValue>) -> Result<RecCommand, ErrorObj> {
Ok(match cmd {
let command = match cmd {
"recording_start" => {
let a: StartArgs = parse_args(raw)?;
if a.directory.is_empty() || a.directory.len() > 1024 || a.directory.chars().any(char::is_control) {
return Err(bad("directory must be 1-1024 characters without control characters"));
}
let directory = PathBuf::from(&a.directory);
if !directory.is_absolute() {
return Err(bad("directory must be an absolute path"));
}
let directory = PathBuf::from(a.directory);
let mode = Mode::from_num(a.mode).ok_or_else(|| bad("mode must be 1 (multitrack), 2 (master) or 3 (both)"))?;
if let Some(l) = &a.label {
if !valid_label(l) {
return Err(bad("label must be YYYY-MM-DD_HH-MM-SS"));
}
}
RecCommand::Start { directory, mode, label: a.label }
}
"recording_waveform" => {
@@ -172,7 +161,20 @@ pub fn parse(cmd: &str, raw: Option<&RawValue>) -> Result<RecCommand, ErrorObj>
}
}
other => return Err(ErrorObj::new(ErrorCode::UnknownCommand, format!("unknown command {other:?}"))),
})
};
Ok(command)
}
pub(crate) fn validate(command: &RecCommand) -> Result<(), ErrorObj> {
if let RecCommand::Start { directory, label, .. } = command {
let text = directory.to_str().ok_or_else(|| bad("directory must be valid UTF-8"))?;
if text.is_empty() || text.len() > 1024 || text.chars().any(char::is_control) {
return Err(bad("directory must be 1-1024 characters without control characters"));
}
if !directory.is_absolute() { return Err(bad("directory must be an absolute path")); }
if label.as_deref().is_some_and(|l| !valid_label(l)) { return Err(bad("label must be YYYY-MM-DD_HH-MM-SS")); }
}
Ok(())
}
// ---------------------------------------------------------------- identity
+6
View File
@@ -12,6 +12,12 @@ use super::*;
use crate::audio::{Receiver as AudioReceiver, TxCodec, TxEncoder};
use crate::vad::tests::speech_frames;
fn parse(name: &str, raw: Option<&RawValue>) -> Result<RecCommand, ErrorObj> {
let command = super::parse(name, raw)?;
validate(&command)?;
Ok(command)
}
const ALICE_UID: &[u8] = b"alice-uid-0123456789";
const BOB_UID: &[u8] = b"bob-uid-0123456789ab";
const CAROL_UID: &[u8] = b"carol-uid-0123456789";
+170
View File
@@ -0,0 +1,170 @@
//! Embedded session lifetime. The host owns one handle per server; no stdio or UI loop is required.
use std::{collections::HashMap, path::PathBuf, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}, thread};
use serde_json::Value;
use tokio::sync::{mpsc, oneshot};
use crate::{audio::{AudioIn, AudioInQueue, CapturedFrame}, locks, output::{Out, PlaybackReceiver}, profile::Store, protocol::{validate_command, Command, ErrorCode, ErrorObj, Input}, session::Session};
pub struct CoreConfig { pub data_dir: PathBuf, pub connection_dir: PathBuf }
#[derive(Debug, thiserror::Error)]
#[error("core startup or shutdown failed: {0}")]
pub struct CoreStartError(pub String);
type Pending = Arc<Mutex<HashMap<String, oneshot::Sender<Result<Value, ErrorObj>>>>>;
pub struct CoreEvents {
pub control: mpsc::Receiver<Value>,
pub playback: PlaybackReceiver,
}
pub struct CoreHandle {
commands: Option<mpsc::Sender<Input>>,
pending: Pending,
next_request: AtomicU64,
audio: Arc<AudioInQueue>,
cancel: Option<oneshot::Sender<()>>,
finished: Option<oneshot::Receiver<()>>,
worker: Option<thread::JoinHandle<()>>,
}
fn stopped() -> ErrorObj { ErrorObj::new(ErrorCode::NotConnected, "core session stopped") }
fn fail_pending(pending: &Pending) {
let mut requests = pending.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for (_, reply) in requests.drain() { let _ = reply.send(Err(stopped())); }
}
struct WorkerCleanup(Pending);
impl Drop for WorkerCleanup {
fn drop(&mut self) { fail_pending(&self.0); }
}
struct PendingRequest { id: String, pending: Pending }
impl Drop for PendingRequest {
fn drop(&mut self) { self.pending.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&self.id); }
}
impl CoreHandle {
pub async fn request(&self, command: Command) -> Result<Value, ErrorObj> {
let command = validate_command(command)?;
let commands = self.commands.as_ref().ok_or_else(stopped)?;
let id = self.next_request.fetch_add(1, Ordering::Relaxed).to_string();
let (reply, receiver) = oneshot::channel();
self.pending.lock().expect("pending requests poisoned").insert(id.clone(), reply);
let _guard = PendingRequest { id: id.clone(), pending: self.pending.clone() };
commands.send(Input::Request { id, cmd: command }).await.map_err(|_| stopped())?;
receiver.await.unwrap_or_else(|_| Err(stopped()))
}
pub fn push_audio(&self, frame: CapturedFrame) -> bool { self.audio.try_push(frame) }
pub fn invalidate_audio(&self) -> u64 { self.audio.invalidate() }
pub fn audio_epoch(&self) -> u64 { self.audio.epoch() }
pub fn connection_generation(&self) -> u64 { self.audio.generation() }
pub fn end_audio(&self) { self.audio.push(AudioIn::End); }
pub async fn shutdown(mut self) -> Result<(), CoreStartError> {
self.audio.invalidate();
self.commands.take();
if let Some(cancel) = self.cancel.take() { let _ = cancel.send(()); }
if let Some(finished) = self.finished.take() { let _ = finished.await; }
if let Some(worker) = self.worker.take() {
worker.join().map_err(|_| CoreStartError("core worker panicked".into()))?;
}
Ok(())
}
}
impl Drop for CoreHandle {
fn drop(&mut self) {
self.audio.invalidate();
self.commands.take();
if let Some(cancel) = self.cancel.take() { let _ = cancel.send(()); }
fail_pending(&self.pending);
// Explicit shutdown awaits completion. Drop signals cancellation without blocking a UI thread.
}
}
pub fn spawn(config: CoreConfig) -> Result<(CoreHandle, CoreEvents), CoreStartError> {
if !config.data_dir.is_absolute() || !config.connection_dir.is_absolute() || config.data_dir == config.connection_dir {
return Err(CoreStartError("data and connection directories must be distinct absolute paths".into()));
}
let locks = locks::lock_run(&config.data_dir, Some(&config.connection_dir)).map_err(CoreStartError)?;
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| CoreStartError(e.to_string()))?;
let (commands, command_rx) = mpsc::channel(64);
let (cancel, cancel_rx) = oneshot::channel();
let (finished_tx, finished) = oneshot::channel();
let (events, control) = mpsc::channel(1024);
let (out, mut out_rx, playback) = Out::new();
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
let worker_pending = pending.clone();
let audio = Arc::new(AudioInQueue::new());
let worker_audio = audio.clone();
let worker = thread::Builder::new().name("teamspeach-core".into()).spawn(move || {
let _locks = locks;
let _cleanup = WorkerCleanup(worker_pending.clone());
runtime.block_on(async move {
let (failure_tx, failure_rx) = oneshot::channel::<()>();
let mut failure_tx = Some(failure_tx);
let cancel = async { tokio::select! { _ = cancel_rx => {}, _ = failure_rx => {} } };
let mut session = Box::pin(Session::new(Store::new(&config.data_dir), out, worker_audio).run_with_cancel(command_rx, cancel));
let mut session_finished = false;
loop {
tokio::select! {
_ = &mut session, if !session_finished => { session_finished = true; },
value = out_rx.recv() => {
let Some(value) = value else { break };
if let Some(id) = value.get("id").and_then(Value::as_str) {
let reply = worker_pending.lock().expect("pending requests poisoned").remove(id);
if let Some(reply) = reply {
let result = if value.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(value.get("result").cloned().unwrap_or(Value::Null))
} else {
Err(serde_json::from_value(value.get("error").cloned().unwrap_or(Value::Null))
.unwrap_or_else(|_| ErrorObj::new(ErrorCode::Internal, "invalid core error response")))
};
let _ = reply.send(result);
}
} else {
// A stalled/dead host cannot stall network polling or command replies.
if failure_tx.is_some() && events.try_send(value).is_err() {
if let Some(cancel) = failure_tx.take() { let _ = cancel.send(()); }
fail_pending(&worker_pending);
}
}
}
}
}
fail_pending(&worker_pending);
});
drop(runtime);
drop(_locks);
let _ = finished_tx.send(());
}).map_err(|e| CoreStartError(e.to_string()))?;
Ok((CoreHandle { commands: Some(commands), pending, next_request: AtomicU64::new(1), audio,
cancel: Some(cancel), finished: Some(finished), worker: Some(worker) }, CoreEvents { control, playback }))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn worker_unwind_completes_retained_requests_even_with_poisoned_map() {
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
let (reply, mut receiver) = oneshot::channel();
pending.lock().unwrap().insert("pending".into(), reply);
let captured = pending.clone();
let result = std::panic::catch_unwind(move || {
let _cleanup = WorkerCleanup(captured.clone());
let _held = captured.lock().unwrap();
panic!("controlled worker failure");
});
assert!(result.is_err());
assert_eq!(receiver.try_recv().unwrap().unwrap_err().code, ErrorCode::NotConnected);
assert!(pending.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_empty());
}
#[test]
fn cancelled_waiter_releases_its_pending_sender() {
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
let (reply, mut receiver) = oneshot::channel();
pending.lock().unwrap().insert("cancelled".into(), reply);
drop(PendingRequest { id: "cancelled".into(), pending: pending.clone() });
assert!(matches!(receiver.try_recv(), Err(oneshot::error::TryRecvError::Closed)));
assert!(pending.lock().unwrap().is_empty());
}
}
+67 -34
View File
@@ -1,6 +1,7 @@
//! The session: owns the tsclientlib connection and maps bridge commands/events onto it.
use std::collections::{HashMap, VecDeque};
use std::future::Future;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -26,7 +27,7 @@ use crate::menu::{self, Action as MenuAction, ActionRequest, Target};
use tokio::io::AsyncWriteExt;
use md5::{Digest, Md5};
use crate::profile::{store_error, validate_nickname, Store, StoreError, StoredIdentity};
use crate::protocol::{Command, ConnectArgs, ErrorCode, ErrorObj, Frame, Input, TextTarget, TsErrorInfo, FRAME_SAMPLES};
use crate::protocol::{Command, ConnectArgs, ErrorCode, ErrorObj, Input, TextTarget, TsErrorInfo, FRAME_SAMPLES};
use crate::admin;
#[path = "menu_session.rs"]
mod menu_session;
@@ -42,7 +43,8 @@ mod whisper_session;
mod voice_dsp_session;
use crate::rawcmd;
use crate::snapshot::{self, RawExtras};
use crate::stdio::Out;
use crate::output::Out;
use crate::audio::CapturedFrame;
const DEFAULT_PORT: u16 = 9987;
const SNAPSHOT_MIN_INTERVAL: Duration = Duration::from_millis(50);
@@ -242,7 +244,7 @@ pub struct Session {
whisper: crate::whisper::Whisper,
/// Persisted per-user volumes and playback DSP flags pushed by the app (outlive connections).
voice: crate::voice_dsp::VoiceSettings,
preroll_buf: Box<[Frame; MAX_PREROLL_FRAMES]>,
preroll_buf: Box<[Option<CapturedFrame>; MAX_PREROLL_FRAMES]>,
pcm: Box<[i16; FRAME_SAMPLES]>,
rev: u64,
exit: Exit,
@@ -279,7 +281,7 @@ impl Session {
vad: None,
whisper: Default::default(),
voice: Default::default(),
preroll_buf: Box::new([[0; FRAME_SAMPLES]; MAX_PREROLL_FRAMES]),
preroll_buf: Box::new(std::array::from_fn(|_| None)),
pcm: Box::new([0; FRAME_SAMPLES]),
rev: 0,
exit: Exit::Running,
@@ -295,14 +297,31 @@ impl Session {
}
}
pub async fn run(mut self, mut cmds: mpsc::Receiver<Input>) {
let mut tick = tokio::time::interval(Duration::from_millis(20));
loop {
pub async fn run(self, cmds: mpsc::Receiver<Input>) {
self.run_with_cancel(cmds, std::future::pending()).await;
}
pub async fn run_embedded(self, cmds: mpsc::Receiver<Input>, cancel: tokio::sync::oneshot::Receiver<()>) {
self.run_with_cancel(cmds, async { let _ = cancel.await; }).await;
}
pub(crate) async fn run_with_cancel(mut self, mut cmds: mpsc::Receiver<Input>, cancel: impl Future<Output = ()>) {
tokio::pin!(cancel);
let mut cancelled = false;
let mut tick = tokio::time::interval(Duration::from_millis(20));
loop {
self.check_exit().await;
if matches!(self.exit, Exit::Done) {
break;
}
tokio::select! {
_ = &mut cancel, if !cancelled => {
cancelled = true;
self.audio_in.invalidate();
self.stdin_closed = true;
cmds.close();
self.begin_exit(None).await;
},
ev = next_event(&mut self.conn) => self.on_conn_event(ev).await,
input = cmds.recv(), if !self.stdin_closed => match input {
Some(input) => self.on_input(input).await,
@@ -386,7 +405,7 @@ impl Session {
return;
}
debug!(cmd = cmd.name(), "request");
self.handle(id, cmd).await;
self.handle(id, cmd.into_inner()).await;
}
Input::Invalid { id: Some(id), error } => self.out.err(&id, error).await,
Input::Invalid { id: None, error } => self.out.error_event(error).await,
@@ -528,6 +547,8 @@ impl Session {
let con = options.connect().map_err(|e| lib_error(ErrorCode::ConnectFailed, &e))?;
info!(uid = %identity.uid, address = %args.address, "connecting");
self.generation += 1;
self.audio_in.set_generation(self.generation);
self.out.set_generation(self.generation);
self.conn = Some(Conn {
con,
address: args.address.clone(),
@@ -633,6 +654,7 @@ impl Session {
}
async fn set_audio(&mut self, id: &str, input_muted: Option<bool>, output_muted: Option<bool>) -> Result<Option<Value>, ErrorObj> {
if input_muted.is_some() || output_muted.is_some() { self.audio_in.invalidate(); }
if let Some(m) = input_muted {
self.flags.input_muted = m;
}
@@ -896,6 +918,7 @@ impl Session {
// ------------------------------------------------------------ exit
async fn begin_exit(&mut self, req: Option<String>) {
self.audio_in.invalidate();
if !matches!(self.exit, Exit::Running) {
if let Some(r) = req {
self.out.err(&r, ErrorObj::new(ErrorCode::BadRequest, "already shutting down")).await;
@@ -1041,6 +1064,8 @@ impl Session {
self.rx_reset().await;
if let Some(c) = &mut self.conn {
self.generation += 1;
self.audio_in.set_generation(self.generation);
self.out.set_generation(self.generation);
c.generation = self.generation;
c.permissions = menu::Permissions::default();
c.gains.clear();
@@ -1285,6 +1310,7 @@ impl Session {
/// Drop the connection and emit `state: disconnected`. `respond` answers a disconnect request.
async fn close_conn(&mut self, reason: Option<ErrorObj>, respond: Option<(String, Value)>) {
self.audio_in.invalidate();
self.recording_finish("disconnected", None).await;
self.fail_pending("connection closed before the server answered").await;
self.fail_media("connection closed before the download finished").await;
@@ -1370,8 +1396,7 @@ impl Session {
}
while let Some(item) = self.audio_in.pop() {
match item {
AudioIn::Frame(f) => self.tx_frame(&f, None).await,
AudioIn::Whisper(f, epoch) => self.tx_frame(&f, Some(epoch)).await,
AudioIn::Frame(f) => self.tx_frame(&f).await,
AudioIn::End => self.tx_end().await,
}
}
@@ -1424,13 +1449,15 @@ impl Session {
/// One captured frame. `whisper` is the epoch the renderer tagged it with while a whisper key was held:
/// such a frame goes only to that whisper route (or nowhere); an untagged frame is ordinary voice.
async fn tx_frame(&mut self, frame: &Frame, whisper: Option<u32>) {
async fn tx_frame(&mut self, frame: &CapturedFrame) {
if !self.audio_in.validate(frame) { return; }
let whisper = frame.whisper;
// Capture queued before push-to-whisper must not escape to the ordinary channel.
if whisper.is_none() && self.whisper.active_epoch().is_some() {
return;
}
self.tx.burst_open = true;
self.tx.last_frame = Some(Instant::now());
self.tx.last_frame = Some(frame.captured_at);
let Some(route) = self.tx_route().await else {
// Nothing may be sent now; forget what voice activation heard so it is never sent later.
self.vad_reset();
@@ -1457,13 +1484,15 @@ impl Session {
vad.gate.reset();
vad.route = Some(route);
}
let decision = vad.gate.push(frame);
let held = if decision == Decision::Start { vad.gate.take_preroll(&mut self.preroll_buf) } else { 0 };
let decision = vad.gate.push_captured(frame);
let held = if decision == Decision::Start { vad.gate.take_captured_preroll(&mut self.preroll_buf) } else { 0 };
match decision {
Decision::Hold => {}
Decision::Start => {
for i in 0..held {
let earlier = self.preroll_buf[i];
let Some(earlier) = self.preroll_buf[i].take() else { continue; };
if earlier.capture_epoch != self.audio_in.epoch() || earlier.connection_generation != self.audio_in.generation() { return; }
if !self.audio_in.validate(&earlier) { continue; }
if !self.tx_send(&earlier, tx_codec, quality, None).await {
return;
}
@@ -1483,7 +1512,8 @@ impl Session {
/// Encodes and sends one frame as ordinary voice (`whisper` = `None`) or to the whisper route of that
/// epoch; returns false if it could not be sent (reported once per burst; whisper drops are silent).
async fn tx_send(&mut self, frame: &Frame, tx_codec: TxCodec, quality: u8, whisper: Option<u32>) -> bool {
async fn tx_send(&mut self, frame: &CapturedFrame, tx_codec: TxCodec, quality: u8, whisper: Option<u32>) -> bool {
if !self.audio_in.validate(frame) { return false; }
if self.tx.transmitting && self.whisper.spurt() != whisper {
// The open transmission belongs to another route and ends there before this one starts.
self.end_spurt().await;
@@ -1524,19 +1554,22 @@ impl Session {
}
let encoder = self.tx.encoder.as_mut().expect("set above");
let route = whisper.and_then(|epoch| self.whisper.route_mut(epoch, generation));
let packet = match encoder.encode_to(frame, route) {
Ok(p) => p,
Err(e) => {
self.report_once(ErrorObj::new(ErrorCode::AudioCodec, format!("Opus encode failed: {e}"))).await;
return false;
}
};
if let Err(e) = c.con.send_audio(packet) {
self.report_once(lib_error(ErrorCode::Io, &e)).await;
return false;
}
let sent = self.audio_in.with_valid_frame(frame, || {
let packet = encoder.encode_to(&frame.pcm, route)
.map_err(|e| ErrorObj::new(ErrorCode::AudioCodec, format!("Opus encode failed: {e}")))?;
if !self.audio_in.validate(frame) { return Ok(false); }
let metadata = tsclientlib::AudioSendMetadata { captured_at: frame.captured_at,
connection_generation: frame.connection_generation, capture_epoch: frame.capture_epoch };
c.con.send_audio_guarded(packet, metadata, self.audio_in.clone()).map_err(|e| lib_error(ErrorCode::Io, &e))?;
Ok(true)
});
match sent {
Some(Ok(true)) => {},
Some(Err(error)) => { self.report_once(error).await; return false; },
_ => return false,
}
if let Some(r) = self.rec.as_mut() {
r.capture(frame);
r.capture(&frame.pcm);
}
if !self.tx.transmitting {
self.tx.transmitting = true;
@@ -1640,15 +1673,15 @@ impl Session {
None => c.rx.mix(&mut self.pcm, gain),
};
let stopped = mixed.stopped;
let line = (!mixed.speakers.is_empty() && !self.flags.output_muted)
.then(|| audio::audio_event_line(&self.pcm, mixed.speakers));
let playback = (!mixed.speakers.is_empty() && !self.flags.output_muted)
.then(|| self.out.playback(&self.pcm, mixed.speakers));
for cid in stopped {
self.out.json(&json!({ "event": "talking", "client_id": cid, "talking": false })).await;
}
if let Some(line) = line {
if !self.out.try_line(line) && self.audio_drop_warned.is_none_or(|t| now - t >= Duration::from_secs(5)) {
self.audio_drop_warned = Some(now);
warn!("stdout is congested, dropping playback audio");
if let Some(retained) = playback {
if !retained && self.audio_drop_warned.is_none_or(|t| now - t >= Duration::from_secs(5)) {
self.audio_drop_warned = Some(now);
warn!("playback consumer is congested, dropping oldest audio");
}
}
self.recording_after_mix().await;
+38 -65
View File
@@ -3,73 +3,41 @@
use std::io::{BufRead, BufReader, Read};
use std::sync::Arc;
use serde::Serialize;
use tokio::io::{AsyncWriteExt, BufWriter};
use tokio::sync::mpsc;
use tracing::{error, warn};
use crate::audio::{AudioIn, AudioInQueue};
use crate::audio::{AudioIn, AudioInQueue, CapturedFrame};
use crate::protocol::{self, ErrorCode, ErrorObj, Input, MAX_LINE_BYTES};
use crate::output::PlaybackReceiver;
/// Control lines (responses/events) are awaited; audio lines are dropped when the pipe is full.
const OUT_QUEUE: usize = 1024;
#[derive(Clone)]
pub struct Out {
tx: mpsc::Sender<String>,
}
impl Out {
pub fn new() -> (Self, mpsc::Receiver<String>) {
let (tx, rx) = mpsc::channel(OUT_QUEUE);
(Self { tx }, rx)
}
pub async fn line(&self, line: String) {
if self.tx.send(line).await.is_err() {
error!("stdout writer is gone");
}
}
pub async fn json<T: Serialize>(&self, value: &T) {
match serde_json::to_string(value) {
Ok(s) => self.line(s).await,
Err(e) => error!(%e, "failed to serialize output"),
}
}
/// Non-blocking send for high-rate audio. Returns false if dropped.
pub fn try_line(&self, line: String) -> bool { self.tx.try_send(line).is_ok() }
pub async fn ok(&self, id: &str, result: serde_json::Value) {
self.json(&serde_json::json!({ "id": id, "ok": true, "result": result })).await
}
pub async fn err(&self, id: &str, error: ErrorObj) {
self.json(&serde_json::json!({ "id": id, "ok": false, "error": error })).await
}
pub async fn error_event(&self, error: ErrorObj) {
self.json(&serde_json::json!({ "event": "error", "error": error })).await
}
}
pub async fn run_writer(mut rx: mpsc::Receiver<String>) {
let mut out = BufWriter::new(tokio::io::stdout());
while let Some(first) = rx.recv().await {
let mut line = Some(first);
while let Some(l) = line {
if out.write_all(l.as_bytes()).await.is_err() || out.write_all(b"\n").await.is_err() {
error!("stdout closed");
return;
}
line = rx.try_recv().ok();
}
if out.flush().await.is_err() {
error!("stdout closed");
return;
}
}
/// The diagnostic CLI alone serializes native events and PCM onto stdout.
pub async fn run_writer(mut rx: mpsc::Receiver<serde_json::Value>, mut playback: PlaybackReceiver) {
let mut out = BufWriter::new(tokio::io::stdout());
let mut control_open = true;
let mut audio_open = true;
while control_open || audio_open {
let line = tokio::select! {
biased;
value = rx.recv(), if control_open => match value {
Some(value) => match serde_json::to_string(&value) {
Ok(line) => Some(line),
Err(error) => { error!(%error, "cannot serialize CLI output"); None }
},
None => { control_open = false; None }
},
frame = playback.recv(), if audio_open => match frame {
Some(frame) => Some(crate::audio::audio_event_line(&frame.pcm, &frame.speakers)),
None => { audio_open = false; None }
},
};
if let Some(line) = line {
if out.write_all(line.as_bytes()).await.is_err() || out.write_all(b"\n").await.is_err() || out.flush().await.is_err() {
error!("stdout closed");
return;
}
}
}
}
/// Blocking stdin reader (runs on its own thread). Lines longer than [`MAX_LINE_BYTES`] are
@@ -131,10 +99,15 @@ pub fn run_reader(input: impl Read, cmds: mpsc::Sender<Input>, audio: Arc<AudioI
input
};
match input {
Input::AudioFrame(f) => audio.push(match f.whisper {
None => AudioIn::Frame(f.pcm),
Some(epoch) => AudioIn::Whisper(f.pcm, epoch),
}),
Input::AudioFrame(f) => {
audio.try_push(CapturedFrame {
pcm: *f.pcm,
captured_at: std::time::Instant::now(),
capture_epoch: audio.epoch(),
connection_generation: audio.generation(),
whisper: f.whisper,
});
},
Input::AudioEnd => audio.push(AudioIn::End),
other => {
if cmds.blocking_send(other).is_err() {
+167 -4
View File
@@ -18,6 +18,7 @@
use earshot::Detector;
use crate::audio::CapturedFrame;
use crate::protocol::{Frame, FRAME_SAMPLES};
/// Frames kept from before the onset so the start of a word is not cut off (5 × 20 ms = 100 ms).
@@ -36,11 +37,11 @@ pub const MAX_LEVEL_DB: f32 = 50.0;
pub const DEFAULT_LEVEL_DB: f32 = -30.0;
/// Frames after a reset during which the gate cannot open: a freshly reset network scores the first
/// ~150 ms of any input (noise, clicks) higher than it settles to. Nothing heard in that time is lost:
/// every frame since the reset is kept (see [`MAX_PREROLL_FRAMES`]) and sent if speech opens the gate.
/// ~150 ms of any input (noise, clicks) higher than it settles to. Startup audio is
/// held, but the capture-age limit still applies before network transmission.
pub const WARMUP_FRAMES: u32 = 10;
/// Frames held at most: the whole warm-up plus the normal preroll (300 ms). The first spurt after a
/// reset sends everything since the reset; later spurts send the last [`PREROLL_FRAMES`].
/// Frames held at most: the whole warm-up plus the normal preroll (300 ms).
/// The consumer must reject expired held frames, including this first spurt.
pub const MAX_PREROLL_FRAMES: usize = WARMUP_FRAMES as usize + PREROLL_FRAMES;
/// Detector input: 16 ms at 16 kHz.
const WINDOW: usize = 256;
@@ -187,6 +188,14 @@ impl Decimator {
}
}
#[derive(Clone, Copy)]
struct CaptureMetadata {
captured_at: std::time::Instant,
connection_generation: u64,
capture_epoch: u64,
whisper: Option<u32>,
}
pub struct VoiceGate {
detector: Box<Detector>,
decimator: Decimator,
@@ -200,6 +209,8 @@ pub struct VoiceGate {
/// Frames left before the spurt ends; 0 = idle.
hangover: u32,
preroll: [Frame; MAX_PREROLL_FRAMES],
preroll_metadata: [Option<CaptureMetadata>; MAX_PREROLL_FRAMES],
capture_context: Option<(u64, u64, Option<u32>)>,
preroll_start: usize,
preroll_len: usize,
/// Frames left in the post-reset warm-up.
@@ -222,6 +233,8 @@ impl VoiceGate {
voiced_run: 0,
hangover: 0,
preroll: [[0; FRAME_SAMPLES]; MAX_PREROLL_FRAMES],
preroll_metadata: [None; MAX_PREROLL_FRAMES],
capture_context: None,
preroll_start: 0,
preroll_len: 0,
warmup: WARMUP_FRAMES,
@@ -265,6 +278,8 @@ impl VoiceGate {
self.hangover = 0;
self.preroll_len = 0;
self.preroll_start = 0;
self.preroll_metadata.fill(None);
self.capture_context = None;
}
/// Runs the detector over one frame and returns whether any 16 ms window in it was voiced and
@@ -313,6 +328,32 @@ impl VoiceGate {
/// Classifies `frame`. On [`Decision::Start`], the caller sends [`VoiceGate::take_preroll`] and then
/// `frame`; the current frame is never part of the preroll.
pub fn push(&mut self, frame: &Frame) -> Decision {
// Raw PCM is for detector analysis, never a replacement for capture tags.
if self.capture_context.is_some() { self.reset(); }
self.classify(frame)
}
/// Classify captured PCM without losing its original timestamp or routing tags.
/// A new boundary resets detector state as well as its held frames. Validation
/// remains the consumer's responsibility, both here and before every actual send.
pub fn push_captured(&mut self, frame: &CapturedFrame) -> Decision {
let context = (frame.connection_generation, frame.capture_epoch, frame.whisper);
if self.capture_context != Some(context) { self.reset(); }
self.capture_context = Some(context);
let slot = (self.preroll_start + self.preroll_len) % MAX_PREROLL_FRAMES;
let decision = self.classify(&frame.pcm);
if decision == Decision::Hold {
self.preroll_metadata[slot] = Some(CaptureMetadata {
captured_at: frame.captured_at,
connection_generation: frame.connection_generation,
capture_epoch: frame.capture_epoch,
whisper: frame.whisper,
});
}
decision
}
fn classify(&mut self, frame: &Frame) -> Decision {
let (keep_level, open_level) = self.level(frame);
let (voiced, onset) = match self.mode {
GateMode::VolumeGate { .. } => (keep_level, open_level),
@@ -343,6 +384,7 @@ impl VoiceGate {
fn remember(&mut self, frame: &Frame) {
let slot = (self.preroll_start + self.preroll_len) % MAX_PREROLL_FRAMES;
self.preroll[slot] = *frame;
self.preroll_metadata[slot] = None;
if self.preroll_len < MAX_PREROLL_FRAMES {
self.preroll_len += 1;
} else {
@@ -361,15 +403,136 @@ impl VoiceGate {
}
self.preroll_start = 0;
self.preroll_len = 0;
self.preroll_metadata.fill(None);
self.since_reset = false;
keep
}
/// Drain original capture envelopes, oldest first, without per-frame allocation.
/// Output entries beyond the returned length are cleared. Even a valid current
/// frame does not authorize these frames: check each one's age/epoch/generation
/// with the input queue immediately before encoding and network enqueue.
pub fn take_captured_preroll(&mut self, out: &mut [Option<CapturedFrame>; MAX_PREROLL_FRAMES]) -> usize {
let keep = if self.since_reset { self.preroll_len } else { self.preroll_len.min(PREROLL_FRAMES) };
let skip = self.preroll_len - keep;
out.fill(None);
let mut written = 0;
for i in 0..keep {
let slot = (self.preroll_start + skip + i) % MAX_PREROLL_FRAMES;
if let Some(metadata) = self.preroll_metadata[slot].take() {
out[written] = Some(CapturedFrame {
pcm: self.preroll[slot],
captured_at: metadata.captured_at,
connection_generation: metadata.connection_generation,
capture_epoch: metadata.capture_epoch,
whisper: metadata.whisper,
});
written += 1;
}
}
self.preroll_start = 0;
self.preroll_len = 0;
self.preroll_metadata.fill(None);
self.since_reset = false;
written
}
}
#[cfg(test)]
pub mod tests {
use super::*;
fn captured_frame(queue: &crate::audio::AudioInQueue, sample: i16) -> CapturedFrame {
CapturedFrame {
pcm: [sample; FRAME_SAMPLES],
captured_at: std::time::Instant::now(),
connection_generation: queue.generation(),
capture_epoch: queue.epoch(),
whisper: None,
}
}
#[test]
fn captured_preroll_preserves_original_age_and_routing() {
let queue = crate::audio::AudioInQueue::new();
queue.set_generation(9);
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
let mut old = captured_frame(&queue, 1);
old.captured_at -= std::time::Duration::from_millis(600);
old.whisper = Some(7);
assert_eq!(gate.push_captured(&old), Decision::Hold);
let mut onset = captured_frame(&queue, 20_000);
onset.whisper = Some(7);
assert_eq!(gate.push_captured(&onset), Decision::Start);
let mut held = std::array::from_fn(|_| None);
assert_eq!(gate.take_captured_preroll(&mut held), 1);
let earlier = held[0].as_ref().unwrap();
assert_eq!(earlier.pcm, old.pcm);
assert_eq!(earlier.captured_at, old.captured_at);
assert_eq!(earlier.connection_generation, old.connection_generation);
assert_eq!(earlier.capture_epoch, old.capture_epoch);
assert_eq!(earlier.whisper, Some(7));
assert!(!queue.validate(earlier), "opening VAD cannot renew an expired capture");
assert!(held[1..].iter().all(Option::is_none));
assert_eq!(gate.take_captured_preroll(&mut held), 0);
assert!(held.iter().all(Option::is_none));
}
#[test]
fn captured_preroll_is_revoked_by_every_routing_boundary() {
let queue = crate::audio::AudioInQueue::new();
for boundary in 0..3 {
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
let old = captured_frame(&queue, 1);
assert_eq!(gate.push_captured(&old), Decision::Hold);
let mut next = captured_frame(&queue, 20_000);
match boundary {
0 => next.capture_epoch += 1,
1 => next.connection_generation += 1,
_ => next.whisper = Some(3),
}
assert_eq!(gate.push_captured(&next), Decision::Start);
let mut held = std::array::from_fn(|_| None);
assert_eq!(gate.take_captured_preroll(&mut held), 0);
gate.reset();
assert!(gate.capture_context.is_none());
assert!(gate.preroll_metadata.iter().all(Option::is_none));
}
}
#[test]
fn captured_preroll_ring_keeps_metadata_with_its_pcm() {
let queue = crate::audio::AudioInQueue::new();
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
let start = std::time::Instant::now();
for i in 0..MAX_PREROLL_FRAMES + 5 {
let mut frame = captured_frame(&queue, i as i16);
frame.captured_at = start + std::time::Duration::from_millis(i as u64 * 20);
assert_eq!(gate.push_captured(&frame), Decision::Hold);
}
assert_eq!(gate.push_captured(&captured_frame(&queue, 20_000)), Decision::Start);
let mut held = std::array::from_fn(|_| None);
assert_eq!(gate.take_captured_preroll(&mut held), MAX_PREROLL_FRAMES);
for (i, frame) in held.iter().enumerate() {
let frame = frame.as_ref().unwrap();
assert_eq!(frame.pcm[0], (i + 5) as i16);
assert_eq!(frame.captured_at, start + std::time::Duration::from_millis((i + 5) as u64 * 20));
}
queue.invalidate();
assert!(held.iter().all(|frame| !queue.validate(frame.as_ref().unwrap())));
}
#[test]
fn raw_analysis_frames_cannot_inherit_capture_authorization() {
let queue = crate::audio::AudioInQueue::new();
let mut gate = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
assert_eq!(gate.push_captured(&captured_frame(&queue, 1)), Decision::Hold);
assert_eq!(gate.push(&[2; FRAME_SAMPLES]), Decision::Hold);
assert_eq!(gate.push(&[20_000; FRAME_SAMPLES]), Decision::Start);
let mut held = std::array::from_fn(|_| None);
assert_eq!(gate.take_captured_preroll(&mut held), 0);
}
/// Real speech: 4 s of a public-domain LibriVox reading (see tests/fixtures/README.md), 48 kHz mono s16le WAV.
pub fn speech_frames() -> Vec<Frame> {
let wav = include_bytes!("../tests/fixtures/speech-librivox-48k.wav");
+52 -6
View File
@@ -94,8 +94,7 @@ pub fn parse_transmit(raw: Option<&RawValue>) -> Result<Option<GateMode>, ErrorO
Some(_) => return Err(bad("set_transmit: sensitivity must be 'high', 'normal' or 'low'")),
};
let level = || match a.level_db {
Some(l) if l.is_finite() && (MIN_LEVEL_DB..=MAX_LEVEL_DB).contains(&l) => Ok(l),
Some(_) => Err(bad("set_transmit: level_db must be between -50 and 50")),
Some(l) => Ok(l),
None => Err(bad("set_transmit: level_db is required for this detector")),
};
match a.detector.as_deref() {
@@ -116,6 +115,15 @@ pub fn parse_transmit(raw: Option<&RawValue>) -> Result<Option<GateMode>, ErrorO
}
}
pub(crate) fn validate_transmit(mode: Option<GateMode>) -> Result<(), ErrorObj> {
if let Some(GateMode::VolumeGate { level_db } | GateMode::Hybrid { level_db, .. }) = mode {
if !level_db.is_finite() || !(MIN_LEVEL_DB..=MAX_LEVEL_DB).contains(&level_db) {
return Err(bad("set_transmit: level_db must be between -50 and 50"));
}
}
Ok(())
}
/// The `set_transmit` answer for an applied mode.
pub fn transmit_result(mode: Option<GateMode>) -> Value {
match mode {
@@ -162,12 +170,22 @@ pub fn parse_local_volumes(raw: Option<&RawValue>) -> Result<LocalVolumesUpdate,
return Err(bad("set_local_volumes: uid must be 1..128 characters"));
}
let uid = BASE64_STANDARD.decode(&e.uid).map_err(|_| bad("set_local_volumes: uid is not base64"))?;
if !valid_modifier_db(e.db) {
return Err(bad("set_local_volumes: db must be -200..10 in 0.5 steps"));
}
volumes.push((uid, e.db));
}
Ok(LocalVolumesUpdate { replace: a.replace, volumes })
let update = LocalVolumesUpdate { replace: a.replace, volumes };
Ok(update)
}
pub(crate) fn validate_local_volumes(update: &LocalVolumesUpdate) -> Result<(), ErrorObj> {
if update.volumes.len() > MAX_LOCAL_VOLUMES {
return Err(bad(format!("set_local_volumes: at most {MAX_LOCAL_VOLUMES} entries")));
}
for (uid, db) in &update.volumes {
// The wire representation is a nonempty base64 string of at most 128 bytes.
if uid.is_empty() || uid.len() > 96 { return Err(bad("set_local_volumes: uid must be 1..128 characters")); }
if !valid_modifier_db(*db) { return Err(bad("set_local_volumes: db must be -200..10 in 0.5 steps")); }
}
Ok(())
}
impl VoiceSettings {
@@ -289,6 +307,34 @@ impl PlaybackDsp {
mod tests {
use super::*;
fn parse_transmit(raw: Option<&RawValue>) -> Result<Option<GateMode>, ErrorObj> {
let mode = super::parse_transmit(raw)?;
validate_transmit(mode)?;
Ok(mode)
}
fn parse_local_volumes(raw: Option<&RawValue>) -> Result<LocalVolumesUpdate, ErrorObj> {
let update = super::parse_local_volumes(raw)?;
validate_local_volumes(&update)?;
Ok(update)
}
#[test]
fn typed_dsp_commands_enforce_finite_levels_and_decoded_uid_limits() {
use crate::protocol::{validate_command, Command};
for level_db in [f32::NAN, f32::INFINITY, -51.0, 51.0] {
for mode in [GateMode::VolumeGate { level_db }, GateMode::Hybrid { sensitivity: Sensitivity::Normal, level_db }] {
assert_eq!(validate_command(Command::SetTransmit { vad: Some(mode) }).unwrap_err().code, ErrorCode::BadRequest);
}
}
for volumes in [vec![(vec![], 0.0)], vec![(vec![1; 97], 0.0)], vec![(vec![1], -3.25)],
vec![(vec![1], 0.0); MAX_LOCAL_VOLUMES + 1]] {
assert_eq!(validate_command(Command::SetLocalVolumes(LocalVolumesUpdate { replace: true, volumes })).unwrap_err().code, ErrorCode::BadRequest);
}
let valid = LocalVolumesUpdate { replace: true, volumes: vec![(vec![1; 96], -200.0), (vec![2], 10.0)] };
assert_eq!(validate_command(Command::SetLocalVolumes(valid.clone())).unwrap().into_inner(), Command::SetLocalVolumes(valid));
}
fn raw(s: &str) -> Box<RawValue> { RawValue::from_string(s.to_owned()).unwrap() }
#[test]
+2 -2
View File
@@ -16,14 +16,14 @@ impl Session {
let state = self.vad.as_mut().expect("checked above");
state.gate.set_mode(mode.expect("checked above"));
} else {
let discarded = self.audio_in.clear();
let epoch = self.audio_in.invalidate();
self.tx_end().await;
match (mode, self.vad.as_mut()) {
(None, _) => self.vad = None,
(Some(m), Some(state)) => state.gate.set_mode(m),
(Some(m), None) => self.vad = Some(Box::new(VadState { gate: VoiceGate::new(m), route: None })),
}
info!(discarded, "transmit queue discarded for a mode change");
info!(epoch, "transmit queue invalidated for a mode change");
}
let result = voice_dsp::transmit_result(mode);
info!(mode = %result["mode"], detector = %result["detector"], sensitivity = %result["sensitivity"], level_db = %result["level_db"], "transmit mode applied");
+59 -26
View File
@@ -205,25 +205,10 @@ fn parse_target(raw: &RawValue) -> Result<TargetSpec, ErrorObj> {
Ok(match kind.kind.as_str() {
"list" => {
let a: ListArgs = serde_json::from_str(text).map_err(invalid)?;
if a.entries.len() > MAX_ENTRIES {
return Err(bad(format!("at most {MAX_ENTRIES} whisper list entries")));
}
for e in &a.entries {
check_text("uuid", &e.uuid)?;
check_text("name", &e.name)?;
}
TargetSpec::List { entries: a.entries }
}
"group" => {
let a: GroupArgs = serde_json::from_str(text).map_err(invalid)?;
if a.group_type > GROUP_ALL_CLIENTS {
return Err(invalid_list(&format!("unknown whisper group type: {}", a.group_type)));
}
if a.target_mode > MAX_GROUP_TARGET_MODE {
return Err(invalid_list(&format!("unknown whisper group target mode: {}", a.target_mode)));
}
check_text("group_id", &a.group_id)?;
check_text("server_uuid", &a.server_uuid)?;
TargetSpec::Group {
group_type: a.group_type,
target_mode: a.target_mode,
@@ -233,14 +218,6 @@ fn parse_target(raw: &RawValue) -> Result<TargetSpec, ErrorObj> {
}
"ids" => {
let a: IdsArgs = serde_json::from_str(text).map_err(invalid)?;
if a.clients.len() > MAX_TARGETS || a.channel_ids.len() > MAX_TARGETS {
return Err(too_many_targets());
}
for c in &a.clients {
if let Some(uid) = &c.uid {
check_text("uid", uid)?;
}
}
TargetSpec::Ids { clients: a.clients, channel_ids: a.channel_ids }
}
other => return Err(bad(format!("target kind must be 'list', 'group' or 'ids', not {other:?}"))),
@@ -249,14 +226,14 @@ fn parse_target(raw: &RawValue) -> Result<TargetSpec, ErrorObj> {
/// Parses `whisper_start`, `whisper_stop` and `set_whisper_receive` arguments.
pub fn parse(name: &str, raw: Option<&RawValue>) -> Result<WhisperCommand, ErrorObj> {
match name {
let command = match name {
"whisper_start" => {
let a: StartArgs = args(raw)?;
Ok(WhisperCommand::Start { epoch: check_epoch(a.epoch)?, target: parse_target(&a.target)? })
Ok(WhisperCommand::Start { epoch: a.epoch, target: parse_target(&a.target)? })
}
"whisper_stop" => {
let a: StopArgs = args(raw)?;
Ok(WhisperCommand::Stop { epoch: check_epoch(a.epoch)? })
Ok(WhisperCommand::Stop { epoch: a.epoch })
}
"set_whisper_receive" => {
let a: ReceiveArgs = args(raw)?;
@@ -269,7 +246,35 @@ pub fn parse(name: &str, raw: Option<&RawValue>) -> Result<WhisperCommand, Error
}
}
other => Err(ErrorObj::new(ErrorCode::UnknownCommand, format!("unknown command {other:?}"))),
}?;
Ok(command)
}
pub(crate) fn validate(command: &WhisperCommand) -> Result<(), ErrorObj> {
match command {
WhisperCommand::Start { epoch, target } => {
check_epoch(*epoch)?;
match target {
TargetSpec::List { entries } => {
if entries.len() > MAX_ENTRIES { return Err(bad(format!("at most {MAX_ENTRIES} whisper list entries"))); }
for e in entries { check_text("uuid", &e.uuid)?; check_text("name", &e.name)?; }
}
TargetSpec::Group { group_type, target_mode, group_id, server_uuid } => {
if *group_type > GROUP_ALL_CLIENTS { return Err(invalid_list(&format!("unknown whisper group type: {group_type}"))); }
if *target_mode > MAX_GROUP_TARGET_MODE { return Err(invalid_list(&format!("unknown whisper group target mode: {target_mode}"))); }
check_text("group_id", group_id)?;
check_text("server_uuid", server_uuid)?;
}
TargetSpec::Ids { clients, channel_ids } => {
if clients.len() > MAX_TARGETS || channel_ids.len() > MAX_TARGETS { return Err(too_many_targets()); }
for c in clients { if let Some(uid) = &c.uid { check_text("uid", uid)?; } }
}
}
}
WhisperCommand::Stop { epoch } => { check_epoch(*epoch)?; }
WhisperCommand::SetReceive { .. } => {}
}
Ok(())
}
// ------------------------------------------------------------------------------------ view
@@ -616,6 +621,34 @@ impl Whisper {
#[cfg(test)]
mod tests {
use super::*;
fn parse(name: &str, raw: Option<&RawValue>) -> Result<WhisperCommand, ErrorObj> {
let command = super::parse(name, raw)?;
validate(&command)?;
Ok(command)
}
#[test]
fn direct_whisper_validation_preserves_limits_and_structured_errors() {
use crate::protocol::{validate_command, Command};
let oversized = WhisperCommand::Start { epoch: 1, target: TargetSpec::Ids {
clients: vec![ClientRef { id: 7, uid: None }; MAX_TARGETS + 1], channel_ids: vec![],
} };
assert_eq!(validate_command(Command::Whisper(oversized)).unwrap_err(), too_many_targets());
let group = WhisperCommand::Start { epoch: 1, target: TargetSpec::Group {
group_type: u8::MAX, target_mode: 0, group_id: "1".into(), server_uuid: "server".into(),
} };
assert_eq!(validate_command(Command::Whisper(group)).unwrap_err(), invalid_list("unknown whisper group type: 255"));
for entries in [
vec![Entry { kind: ENTRY_CLIENT, uuid: "uid".into(), name: String::new() }; MAX_ENTRIES + 1],
vec![Entry { kind: ENTRY_CLIENT, uuid: "x".repeat(MAX_TEXT_BYTES + 1), name: String::new() }],
] {
let command = WhisperCommand::Start { epoch: 1, target: TargetSpec::List { entries } };
assert_eq!(validate_command(Command::Whisper(command)).unwrap_err().code, ErrorCode::BadRequest);
}
let allowed = WhisperCommand::Start { epoch: 1, target: TargetSpec::Ids { clients: vec![], channel_ids: vec![7; MAX_TARGETS] } };
assert_eq!(validate_command(Command::Whisper(allowed.clone())).unwrap().into_inner(), Command::Whisper(allowed));
}
use tsproto_packets::packets::{Direction, Flags, InPacket, PacketType};
fn raw(text: &str) -> Box<RawValue> { RawValue::from_string(text.to_owned()).unwrap() }
+57
View File
@@ -0,0 +1,57 @@
use std::{path::PathBuf, sync::atomic::{AtomicU64, Ordering}};
use teamspeach_core::{protocol::Command, runtime::{spawn, CoreConfig}};
static NEXT: AtomicU64 = AtomicU64::new(0);
struct Profile(PathBuf);
impl Profile {
fn new() -> Self {
Self(std::env::temp_dir().join(format!("teamspeach-embedded-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))))
}
fn config(&self, slot: usize) -> CoreConfig {
CoreConfig { data_dir: self.0.join("core"), connection_dir: self.0.join("core/connections").join(slot.to_string()) }
}
}
impl Drop for Profile { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } }
#[tokio::test(flavor = "current_thread")]
async fn embedded_identity_survives_repeated_worker_lifetimes() {
let profile = Profile::new();
let (first, _events) = spawn(profile.config(1)).unwrap();
let created = first.request(Command::ProfileCreate { nickname: "Native owner".into() }).await.unwrap();
let uid = created["uid"].clone();
assert!(uid.as_str().is_some());
for _ in 0..100 {
let (other, _events) = spawn(profile.config(2)).unwrap();
let state = other.request(Command::ProfileGet).await.unwrap();
assert_eq!(state["uid"], uid);
other.shutdown().await.unwrap();
}
assert_eq!(first.request(Command::ProfileGet).await.unwrap()["uid"], uid);
first.shutdown().await.unwrap();
let (again, _events) = spawn(profile.config(1)).unwrap();
assert_eq!(again.request(Command::ProfileGet).await.unwrap()["uid"], uid);
again.shutdown().await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn native_requests_validate_before_session_dispatch() {
use teamspeach_core::protocol::{ErrorCode, TextTarget};
let profile = Profile::new();
let (core, _events) = spawn(profile.config(1)).unwrap();
let error = core.request(Command::SendText { target: TextTarget::Client, client_id: None,
expected_client_uid: None, message: "private".into() }).await.unwrap_err();
assert_eq!(error.code, ErrorCode::BadRequest);
let error = core.request(Command::StreamSignal { stream_id: "s1".into(), client_id: 1, json: "[]".into() }).await.unwrap_err();
assert_eq!(error.code, ErrorCode::BadRequest);
core.shutdown().await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn duplicate_connection_slot_is_refused_and_released_after_shutdown() {
let profile = Profile::new();
let (core, _events) = spawn(profile.config(1)).unwrap();
assert!(spawn(profile.config(1)).is_err());
core.shutdown().await.unwrap();
let (next, _events) = spawn(profile.config(1)).unwrap();
next.shutdown().await.unwrap();
}
+111
View File
@@ -0,0 +1,111 @@
use std::{future::{poll_fn, Future}, path::PathBuf, sync::atomic::{AtomicU64, Ordering}, task::Poll, time::Duration};
use teamspeach_core::{protocol::{Command, ErrorCode}, runtime::{spawn, CoreConfig, CoreEvents, CoreHandle}};
use tokio::time::timeout;
const DEADLINE: Duration = Duration::from_secs(20);
static NEXT: AtomicU64 = AtomicU64::new(0);
struct Profile(PathBuf);
impl Profile {
fn new() -> Self {
Self(std::env::temp_dir().join(format!("teamspeach-runtime-failures-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))))
}
fn config(&self) -> CoreConfig {
CoreConfig { data_dir: self.0.join("core"), connection_dir: self.0.join("core/connections/1") }
}
async fn start(&self) -> (CoreHandle, CoreEvents, serde_json::Value) {
let (core, mut events) = spawn(self.config()).unwrap();
let identity = core.request(Command::ProfileCreate { nickname: "Failure regression".into() }).await.unwrap();
assert!(identity["uid"].as_str().is_some_and(|uid| !uid.is_empty()));
// Consume the creation event before testing the exact host queue capacity.
let event = events.control.recv().await.expect("profile event");
assert_eq!(event["event"], "profile");
(core, events, identity["uid"].clone())
}
async fn assert_reusable(&self, uid: &serde_json::Value) {
let (core, _events) = spawn(self.config()).expect("terminated worker must release its slot");
assert_eq!(&core.request(Command::ProfileGet).await.unwrap()["uid"], uid);
core.shutdown().await.unwrap();
}
}
impl Drop for Profile {
fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); }
}
fn audio_state_request() -> Command {
// Offline SetAudio still emits one audio_state event, without opening any device or socket.
Command::SetAudio { input_muted: None, output_muted: None }
}
#[tokio::test(flavor = "current_thread")]
async fn dropped_control_consumer_terminates_requests_and_releases_slot() {
timeout(DEADLINE, async {
let profile = Profile::new();
let (core, events, uid) = profile.start().await;
let CoreEvents { control, mut playback } = events;
drop(control);
let error = core.request(audio_state_request()).await.unwrap_err();
assert_eq!(error.code, ErrorCode::NotConnected);
assert!(playback.recv().await.is_none(), "output owner must be dropped on host failure");
assert_eq!(core.request(Command::ProfileGet).await.unwrap_err().code, ErrorCode::NotConnected);
core.shutdown().await.unwrap();
profile.assert_reusable(&uid).await;
}).await.expect("dead host must not strand shutdown or pending requests");
}
#[tokio::test(flavor = "current_thread")]
async fn full_control_queue_ends_core_without_a_consumer_drain() {
timeout(DEADLINE, async {
let profile = Profile::new();
let (core, mut events, uid) = profile.start().await;
for _ in 0..1024 {
core.request(audio_state_request()).await.unwrap();
}
assert_eq!(events.control.len(), 1024);
let error = core.request(audio_state_request()).await.unwrap_err();
assert_eq!(error.code, ErrorCode::NotConnected);
// Do not drain the congested receiver to help the worker finish.
assert!(events.playback.recv().await.is_none());
assert_eq!(core.request(Command::ProfileGet).await.unwrap_err().code, ErrorCode::NotConnected);
core.shutdown().await.unwrap();
assert_eq!(events.control.len(), 1024);
assert!(events.control.is_closed());
profile.assert_reusable(&uid).await;
}).await.expect("control backpressure must terminate rather than deadlock the core");
}
#[tokio::test(flavor = "current_thread")]
async fn requests_queued_after_shutdown_complete_with_stopped_error() {
timeout(DEADLINE, async {
let profile = Profile::new();
let (core, _events, uid) = profile.start().await;
let mut shutdown = Box::pin(core.request(Command::Shutdown));
// Poll once to enqueue Shutdown before ProfileGet. It may already finish on the
// worker; retain that outcome instead of depending on a scheduling race.
let completed = poll_fn(|cx| Poll::Ready(shutdown.as_mut().poll(cx))).await;
assert_eq!(core.request(Command::ProfileGet).await.unwrap_err().code, ErrorCode::NotConnected);
match completed {
Poll::Ready(result) => { result.unwrap(); }
Poll::Pending => { shutdown.as_mut().await.unwrap(); }
}
drop(shutdown);
core.shutdown().await.unwrap();
profile.assert_reusable(&uid).await;
}).await.expect("shutdown must settle requests queued behind it");
}
#[tokio::test(flavor = "current_thread")]
async fn abandoning_a_request_preserves_subsequent_requests_and_shutdown() {
timeout(DEADLINE, async {
let profile = Profile::new();
let (core, _events, uid) = profile.start().await;
let mut abandoned = Box::pin(core.request(Command::ProfileGet));
// This exercises caller cancellation if still pending, and the equally valid
// already-completed race; deterministic pending-map cleanup needs an internal test.
let _ = poll_fn(|cx| Poll::Ready(abandoned.as_mut().poll(cx))).await;
drop(abandoned);
assert_eq!(core.request(Command::ProfileGet).await.unwrap()["uid"], uid);
core.shutdown().await.unwrap();
profile.assert_reusable(&uid).await;
}).await.expect("abandoning a caller must not strand the worker");
}
+19 -6
View File
@@ -7,14 +7,15 @@
- Authors: Flakebi and the ReSpeak contributors.
- License: dual MIT OR Apache-2.0 — see `tsclientlib/LICENSE-MIT` and
`tsclientlib/LICENSE-APACHE` (copied verbatim from the upstream repository root).
- Only the `tsclientlib` crate (`Cargo.toml`, `README.md`, `src/`) is vendored. Its sibling
crates (`tsproto`, `ts-bookkeeping`, `tsproto-packets`, `tsproto-types`) are used unmodified
as git dependencies pinned to the same revision.
- `tsclientlib` and `tsproto` are vendored from that revision. `ts-bookkeeping`,
`tsproto-packets` and `tsproto-types` remain pinned git dependencies. The root workspace
patch selects the local `tsproto` for every consumer.
### Local modifications
The complete diff against upstream is `tsclientlib.patch` (apply with `git apply -p1` inside
upstream's `tsclientlib/` crate directory at the revision above; it reproduces this tree):
`tsclientlib.patch` records the original protocol-discovery modifications (items 1–5 below).
The native capture-send extension in item 6 and `tsproto/` is maintained directly in the vendored tree;
the historical patch alone no longer reproduces the complete tree.
1. `Cargo.toml`: the workspace `path` dependencies are replaced by git dependencies pinned to
the same revision.
@@ -37,4 +38,16 @@ upstream's `tsclientlib/` crate directory at the revision above; it reproduces t
instead of spawning upstream's unbounded proof-of-work thread. The explicit identity CLI owns
bounded, cancellable work and durable checkpoints.
No other behaviour changes.
6. `src/lib.rs`: `AudioSendMetadata`, `AudioSendGuard` and `send_audio_guarded` forward
original capture time, connection generation and privacy epoch to the transport. Ordinary
`send_audio` remains for non-capture end markers and existing third-party callers.
## `tsproto/`
Same upstream revision and dual MIT OR Apache-2.0 license; license texts accompany the crate.
Sibling workspace dependencies are pinned to the revision above. Guarded voice packets retain
metadata plus a shared authorization guard through the deferred UDP queue. Before each actual
socket send attempt, including a retry after backpressure, the guard synchronizes against capture
invalidation and refuses expired or revoked packets. Guarded media is bounded separately from
unmodified acknowledgement/control/end-marker traffic. This prevents muted or previous-session
audio from escaping merely because it was encoded before a privacy boundary.
+24
View File
@@ -58,6 +58,7 @@ mod tests;
pub use ts_bookkeeping::messages::s2c::InMessage;
// TODO This is bad because it re-exports ConnectOptions
pub use ts_bookkeeping::*;
pub use tsproto::connection::{AudioSendGuard, AudioSendMetadata};
pub use tsproto::resend::{ConnectionStats, PacketStat};
pub use tsproto::Identity;
pub use tsproto_types::errors::Error as TsError;
@@ -970,6 +971,29 @@ impl Connection {
}
}
/// Send captured audio only while its timestamp, generation and epoch remain valid.
///
/// Unlike `send_audio`, the reusable guard wraps every actual socket poll,
/// including retries after backpressure. Keep empty End packets on `send_audio`
/// so revoking capture cannot suppress the end of the preceding burst.
pub fn send_audio_guarded(
&mut self, packet: OutPacket, metadata: AudioSendMetadata, guard: Arc<dyn AudioSendGuard>,
) -> Result<()> {
assert!(
matches!(packet.header().packet_type(), PacketType::Voice | PacketType::VoiceWhisper),
"Can only send audio packets with send_audio_guarded"
);
if let ConnectionState::Connected { con, book } = &mut self.state {
if !Self::intern_can_send_audio(book, &self.options) {
let span = self.span.clone();
warn!(parent: span, "Sending audio while muted");
}
con.client.send_audio_guarded(packet, metadata, guard).map_err(Error::SendPacket)
} else {
Err(Error::NotConnected)
}
}
/// Download a file from a channel of the connected TeamSpeak server.
///
/// Returns the size of the file and a tcp stream of the requested file.
+367 -1274
View File
File diff suppressed because it is too large. Load diff
+70
View File
@@ -0,0 +1,70 @@
[package]
name = "tsproto"
version = "0.2.0"
authors = ["Flakebi <flakebi@t-online.de>"]
description = "An implementation of the TeamSpeak3 protocol as a library for use in clients and bots."
repository = "https://github.com/ReSpeak/tsclientlib"
readme = "README.md"
keywords = ["teamspeak3", "ts3", "voip"]
categories = ["multimedia"]
license = "MIT OR Apache-2.0"
edition = "2018"
autobenches = false
include = [
"/Cargo.toml",
"/README.md",
"**/*.rs",
]
[dependencies]
aes = "0.8"
base64 = "0.22"
omnom = "3"
curve25519-dalek-ng = "4"
eax = "0.5"
futures = "0.3"
generic-array = "0.14"
git-testament = "0.2"
num-bigint = "0.4"
num-derive = "0.4"
num-traits = "0.2"
pin-project-lite = "0.2"
rand = "0.10"
rug = { version = "1", optional = true, default-features = false, features = ["integer"] }
serde = { version = "1", features = ["derive"] }
sha-1 = "0.10"
sha2 = "0.10"
thiserror = "2"
time = { version = "0.3", features = ["formatting"] }
tokio = { version = "1", features = ["macros", "net", "sync", "time"] }
tracing = "0.1"
tsproto-packets = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
tsproto-types = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
quicklz = "0.3"
[dev-dependencies]
anyhow = "1"
criterion = "0.8"
once_cell = "1"
clap = { version = "4", features = ["derive"] }
tokio = { version = "1", features = ["rt-multi-thread", "signal"] }
tracing-subscriber = "0.3"
[[bench]]
name = "modpow"
harness = false
[[bench]]
name = "connect"
harness = false
[[bench]]
name = "license"
harness = false
[[bench]]
name = "message"
harness = false
# Keep standalone transport regression tests out of the application's package set.
[workspace]
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017-2020 tsclientlib contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
# TsProto &emsp; [![docs.rs](https://docs.rs/tsproto/badge.svg)](https://docs.rs/tsproto)
This library implements the TeamSpeak3 protocol.
For a usable library to build clients and bots, you should take a look at
[`tsclientlib`](https://github.com/ReSpeak/tsclientlib), which provides a
convenient interface to this library.
If you are searching for a usable client, [Qint](https://github.com/ReSpeak/Qint)
is a cross-platform TeamSpeak client, which is using this library (more
correctly, it is using `tsclientlib`).
For more info on this project, take a look at the
[tsclientlib README](https://github.com/ReSpeak/tsclientlib).
## License
Licensed under either of
* [Apache License, Version 2.0](../LICENSE-APACHE)
* [MIT license](../LICENSE-MIT)
at your option.
+10
View File
@@ -0,0 +1,10 @@
# TsProto &emsp; [![docs.rs](https://docs.rs/tsproto/badge.svg)](https://docs.rs/tsproto)
{{readme}}
## License
Licensed under either of
* [Apache License, Version 2.0](../LICENSE-APACHE)
* [MIT license](../LICENSE-MIT)
at your option.
+77
View File
@@ -0,0 +1,77 @@
use anyhow::{Error, Result};
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
use once_cell::sync::Lazy;
use tracing::{info, warn};
use tsproto::client::Client;
use tsproto::connection::StreamItem;
use tsproto_packets::commands::CommandParser;
mod utils;
use crate::utils::*;
static TRACING: Lazy<()> = Lazy::new(|| tracing_subscriber::fmt().with_test_writer().init());
async fn wait_channellistfinished(con: &mut Client) -> Result<()> {
con.filter_items(|con, i| {
Ok(match i {
StreamItem::S2CInit(packet) => {
con.hand_back_buffer(packet.into_buffer());
None
}
StreamItem::C2SInit(packet) => {
con.hand_back_buffer(packet.into_buffer());
None
}
StreamItem::Command(packet) => {
let (name, _) = CommandParser::new(packet.data().packet().content());
if name == b"channellistfinished" { Some(()) } else { None }
}
StreamItem::Error(error) => {
warn!(%error, "Got connection error");
None
}
i => {
warn!(got = ?i, "Unexpected packet, waiting for channellistfinished");
None
}
})
})
.await?;
Ok(())
}
fn one_connect(b: &mut Bencher) {
Lazy::force(&TRACING);
let local_address = "127.0.0.1:0".parse().unwrap();
let address = "127.0.0.1:9987".parse().unwrap();
let rt = tokio::runtime::Runtime::new().unwrap();
b.iter(|| {
rt.block_on(async move {
// The TS server does not accept the 3rd reconnect from the same port
// so we create a new client for every connection.
let mut con = create_client(local_address, address, 0).await?;
connect(&mut con).await?;
info!("Connected");
// Wait until channellistfinished
wait_channellistfinished(&mut con).await?;
info!("Disconnecting");
disconnect(&mut con).await?;
Ok::<_, Error>(())
})
.unwrap();
});
}
fn bench_connect(c: &mut Criterion) { c.bench_function("connect", one_connect); }
criterion_group! {
name = benches;
config = Criterion::default().sample_size(20);
targets = bench_connect
}
criterion_main!(benches);
+58
View File
@@ -0,0 +1,58 @@
use base64::prelude::*;
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
use tsproto::license::Licenses;
use tsproto_types::crypto::EccKeyPubEd25519;
fn license_parse(b: &mut Bencher, license: Vec<u8>) {
b.iter(|| {
Licenses::parse_ignore_expired(license.clone()).unwrap();
});
}
fn license_derive_key(b: &mut Bencher, license: Vec<u8>) {
let licenses = Licenses::parse_ignore_expired(license).unwrap();
b.iter(|| {
let derived_key =
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(tsproto::ROOT_KEY)).unwrap();
derived_key.compress().0
});
}
const STANDARD_LICENSE: &str = "AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==";
const AAL_LICENSE: &str = "AQCvbHFTQDY/terPeilrp/ECU9xCH5U3xC92lY\
TNaY/0KQAJFueAazbsgAAAACVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAABhl9gwla/UJ\
p2Eszst9TRVXO/PeE6a6d+CTI6Pg7OEVgAJc5CrL4Nh8gAAACRUZWFtU3BlYWsgc3lz\
dGVtcyBHbWJIAACvTQIgpv6zmLZq3znh7ygmOSokGFkFjz4bTigrOnetrgIJdIIACdS\
/gAYAAAAAU29zc2VuU3lzdGVtcy5iaWQAADY7+uV1CQ1niOvYSdGzsu83kPTNWijovr\
3B78eHGeePIAm98vQJvpu0";
fn standard_license_parse(b: &mut Bencher) {
license_parse(b, BASE64_STANDARD.decode(STANDARD_LICENSE).unwrap());
}
fn aal_license_parse(b: &mut Bencher) {
license_parse(b, BASE64_STANDARD.decode(AAL_LICENSE).unwrap());
}
fn standard_license_derive_key(b: &mut Bencher) {
license_derive_key(b, BASE64_STANDARD.decode(STANDARD_LICENSE).unwrap());
}
fn aal_license_derive_key(b: &mut Bencher) {
license_derive_key(b, BASE64_STANDARD.decode(AAL_LICENSE).unwrap());
}
fn bench_license(c: &mut Criterion) {
c.bench_function("parse standard license", standard_license_parse);
c.bench_function("parse aal license", aal_license_parse);
c.bench_function("derive key standard license", standard_license_derive_key);
c.bench_function("derive key aal license", aal_license_derive_key);
}
criterion_group!(benches, bench_license);
criterion_main!(benches);
+69
View File
@@ -0,0 +1,69 @@
use anyhow::Error;
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
use tracing::info;
use tsproto_packets::packets::*;
mod utils;
use crate::utils::*;
fn send_messages(b: &mut Bencher) {
create_logger(false);
let local_address = "127.0.0.1:0".parse().unwrap();
let address = "127.0.0.1:9987".parse().unwrap();
let rt = tokio::runtime::Runtime::new().unwrap();
let mut con = rt
.block_on(async move {
let mut con = create_client(local_address, address, 0).await?;
info!("Connecting");
connect(&mut con).await?;
Ok::<_, Error>(con)
})
.unwrap();
let mut i = 0;
let mut last_id = None;
b.iter(|| {
let text = format!("Hello {}", i);
let mut packet =
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "sendtextmessage");
packet.write_arg("targetmode", &"3");
packet.write_arg("msg", &text);
i += 1;
rt.block_on(async {
con.wait_until_can_send().await.unwrap();
last_id = Some(con.send_packet(packet.into_packet()).unwrap());
});
});
rt.block_on(async move {
if let Some(id) = last_id {
info!("Waiting for {:?}", id);
con.wait_for_ack(id).await?;
}
tokio::select! {
_ = tokio::time::sleep(tokio::time::Duration::from_millis(50)) => {
}
_ = con.wait_disconnect() => {
anyhow::bail!("Disconnected");
}
};
info!("Disconnecting");
disconnect(&mut con).await
})
.unwrap();
}
fn bench_message(c: &mut Criterion) { c.bench_function("message", send_messages); }
criterion_group! {
name = benches;
config = Criterion::default().sample_size(200);
targets = bench_message
}
criterion_main!(benches);
+42
View File
@@ -0,0 +1,42 @@
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
use num_bigint::BigUint;
use num_traits::One;
#[cfg(feature = "rug")]
use rug::Integer;
fn num_modpow(b: &mut Bencher) {
let n = "9387019355706217197639129234358945126657617361248696932841794255538327365072557602175160199263073329488914880215590036563068284078359088114486271428098753";
let x = "2148617454765635492758175407769288127281667975788420713054995716016550287184632946544163990319181591625774561067011999700977775946073267145316355582522577";
let level = 10_000;
let n = n.parse().unwrap();
let x: BigUint = x.parse().unwrap();
let mut e = BigUint::one();
e <<= level as usize;
b.iter(|| x.modpow(&e, &n));
}
#[cfg(feature = "rug")]
fn gmp_modpow(b: &mut Bencher) {
let n = "9387019355706217197639129234358945126657617361248696932841794255538327365072557602175160199263073329488914880215590036563068284078359088114486271428098753";
let x = "2148617454765635492758175407769288127281667975788420713054995716016550287184632946544163990319181591625774561067011999700977775946073267145316355582522577";
let level = 10_000;
let n: Integer = n.parse().unwrap();
let x: Integer = x.parse().unwrap();
let mut e = Integer::new();
e.set_bit(level, true);
b.iter(|| x.pow_mod_ref(&e, &n).unwrap());
}
fn bench_modpow(c: &mut Criterion) {
c.bench_function("num bigint", num_modpow);
#[cfg(feature = "rug")]
{
c.bench_function("gmp", gmp_modpow);
}
}
criterion_group!(benches, bench_modpow);
criterion_main!(benches);
+112
View File
@@ -0,0 +1,112 @@
use std::net::SocketAddr;
use anyhow::Result;
use tokio::net::UdpSocket;
use tsproto::algorithms as algs;
use tsproto::client::Client;
use tsproto_packets::packets::*;
use tsproto_types::crypto::EccKeyPrivP256;
#[allow(dead_code)]
pub fn create_logger(to_file: bool) {
if to_file {
tracing_subscriber::fmt()
.with_writer(|| std::fs::OpenOptions::new().append(true).open("bench.log").unwrap())
.init();
} else {
tracing_subscriber::fmt::init();
}
}
pub async fn create_client(
local_address: SocketAddr, remote_address: SocketAddr, verbose: u8,
) -> Result<Client> {
// Get P-256 ECDH key
let private_key = EccKeyPrivP256::import_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let udp_socket = UdpSocket::bind(local_address).await?;
let mut con = Client::new(remote_address, Box::new(udp_socket), private_key);
if verbose >= 1 {
tsproto::log::add_logger(true, verbose > 1, verbose > 2, &mut con)
}
Ok(con)
}
/// Returns the `initserver` command.
pub async fn connect(con: &mut Client) -> Result<InCommandBuf> {
con.connect().await?;
// Send clientinit
let private_key = EccKeyPrivP256::import_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let private_key_as_pub = private_key.to_pub();
let offset = algs::hash_cash(&private_key_as_pub, 8);
// Create clientinit packet
let offset = offset.to_string();
let mut packet =
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientinit");
for (arg, val) in [
("client_nickname", "Bot"),
("client_version", "3.?.? [Build: 5680278000]"),
("client_platform", "Linux"),
("client_input_hardware", "1"),
("client_output_hardware", "1"),
("client_default_channel", ""),
("client_default_channel_password", ""),
("client_server_password", ""),
("client_meta_data", ""),
(
"client_version_sign",
"Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ==",
),
("client_nickname_phonetic", ""),
("client_key_offset", &offset),
("client_default_token", ""),
("client_badges", "Overwolf=0"),
(
"hwid",
"923f136fb1e22ae6ce95e60255529c00,\
d13231b1bc33edfecfb9169cc7a63bcc",
),
] {
packet.write_arg(arg, &val);
}
con.send_packet(packet.into_packet())?;
Ok(con
.filter_commands(|con, cmd| {
Ok(if cmd.data().packet().content().starts_with(b"initserver ") {
Some(cmd)
} else {
con.hand_back_buffer(cmd.into_buffer());
None
})
})
.await?)
}
pub async fn disconnect(con: &mut Client) -> Result<()> {
let mut packet =
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientdisconnect");
for (arg, val) in [
// Reason: Disconnect
("reasonid", "8"),
("reasonmsg", "Bye"),
] {
packet.write_arg(arg, &val);
}
con.send_packet(packet.into_packet())?;
con.wait_disconnect().await?;
Ok(())
}
+67
View File
@@ -0,0 +1,67 @@
use std::net::SocketAddr;
use anyhow::{bail, Result};
use clap::Parser;
use tokio::time::{self, Duration};
use tracing::info;
use tsproto_packets::packets::*;
mod utils;
use crate::utils::*;
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "127.0.0.1:9987")]
address: SocketAddr,
/// The listening address of the client
#[arg(long, default_value = "0.0.0.0:0")]
local_address: SocketAddr,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
// Parse command line options
let args = Args::parse();
create_logger();
let mut con = create_client(args.local_address, args.address, args.verbose).await?;
// Connect
connect(&mut con).await?;
info!("Connected");
// Wait some time
tokio::select! {
_ = time::sleep(Duration::from_secs(2)) => {}
_ = con.wait_disconnect() => {
bail!("Disconnected");
}
};
info!("Waited");
// Send packet
let mut cmd =
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "sendtextmessage");
cmd.write_arg("targetmode", &3);
cmd.write_arg("msg", &"Hello");
let id = con.send_packet(cmd.into_packet())?;
con.wait_for_ack(id).await?;
// Disconnect
disconnect(&mut con).await?;
info!("Disconnected");
Ok(())
}
+21
View File
@@ -0,0 +1,21 @@
use std::io::{Cursor, Write};
use clap::Parser;
use tsproto::utils;
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// Data (hex)
#[arg()]
data: String,
}
fn main() {
// Parse command line options
let args = Args::parse();
let data = utils::read_hex(&args.data).unwrap();
let data = quicklz::decompress(&mut Cursor::new(data), std::u32::MAX).unwrap();
std::io::stdout().write_all(&data).unwrap();
}
+71
View File
@@ -0,0 +1,71 @@
use std::net::SocketAddr;
use anyhow::Result;
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tracing::info;
mod utils;
use crate::utils::*;
#[derive(Parser, Clone, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "127.0.0.1:9987")]
address: SocketAddr,
/// The listening address of the client
#[arg(long, default_value = "0.0.0.0:0")]
local_address: SocketAddr,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
/// How many connections
#[arg()]
count: usize,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
// Parse command line options
let args = Args::parse();
create_logger();
stream::iter(0..args.count)
.for_each_concurrent(None, |_| {
let args = args.clone();
tokio::spawn(async move {
let mut con =
create_client(args.local_address, args.address, args.verbose).await.unwrap();
// Connect
connect(&mut con).await.unwrap();
info!("Connected");
// Wait some time
tokio::select! {
_ = time::sleep(Duration::from_secs(2)) => {}
_ = con.wait_disconnect() => {
panic!("Disconnected");
}
};
info!("Waited");
// Disconnect
let _ = disconnect(&mut con).await;
info!("Disconnected");
})
.map(|_| ())
})
.await;
Ok(())
}
+19
View File
@@ -0,0 +1,19 @@
use base64::prelude::*;
use clap::Parser;
use tsproto::license::*;
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The license data (base64)
#[arg()]
license: String,
}
fn main() {
// Parse command line options
let args = Args::parse();
let l = Licenses::parse(BASE64_STANDARD.decode(&args.license).unwrap()).unwrap();
println!("{:#?}", l);
}
+52
View File
@@ -0,0 +1,52 @@
use std::io::Write;
use clap::Parser;
use tsproto::algorithms as algs;
use tsproto::utils;
use tsproto_packets::packets::*;
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// Print backtrace
#[arg(short, long = "debug")]
debug: bool,
/// Server to client
#[arg(short, long = "client")]
c2s: bool,
/// Data (hex)
#[arg()]
data: String,
}
fn main() {
// Parse command line options
let args = Args::parse();
let dir = if args.c2s { Direction::C2S } else { Direction::S2C };
let data = utils::read_hex(&args.data).unwrap();
let packet = match InPacket::try_new(dir, &data) {
Ok(p) => p,
Err(e) => {
if args.debug {
println!("Failed to decode: {:?}", e);
} else {
println!("Failed to decode: {}", e);
}
return;
}
};
let decrypted = match algs::decrypt_fake(&packet) {
Ok(d) => d,
Err(e) => {
if args.debug {
println!("Failed to decrypt: {:?}", e);
} else {
println!("Failed to decrypt: {}", e);
}
return;
}
};
std::io::stdout().write_all(&decrypted).unwrap();
}
+39
View File
@@ -0,0 +1,39 @@
use base64::prelude::*;
use clap::Parser;
use curve25519_dalek_ng::edwards::CompressedEdwardsY;
use curve25519_dalek_ng::scalar::Scalar;
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// Public key
#[arg(short, long = "pub")]
pub_key: String,
/// Private key
#[arg(short, long = "priv")]
priv_key: String,
}
fn main() {
// Parse command line options
let args = Args::parse();
let pub_key = BASE64_STANDARD.decode(&args.pub_key).unwrap();
let priv_key = BASE64_STANDARD.decode(&args.priv_key).unwrap();
let mut pubk = [0; 32];
pubk.copy_from_slice(&pub_key);
let mut privk = [0; 32];
privk.copy_from_slice(&priv_key);
/*privk[0] &= 248;
privk[31] &= 63;
privk[31] |= 64;*/
let priv_scal = Scalar::from_bytes_mod_order(privk);
//let priv_scal = Scalar::from_bytes_mod_order(privk);
let pub_point_compr = CompressedEdwardsY(pubk);
let pub_point = -pub_point_compr.decompress().unwrap();
//let pub_point = curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
let res = (pub_point * priv_scal).compress();
println!("Result: {}", BASE64_STANDARD.encode(&res.0));
}
+35
View File
@@ -0,0 +1,35 @@
use base64::prelude::*;
use clap::Parser;
use tsproto_types::crypto::EccKeyPubP256;
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// Public key
#[arg(short, long)]
key: String,
/// Data (base64)
#[arg(short, long)]
data: String,
/// Signature (base64)
#[arg(short, long)]
signature: String,
}
fn main() {
// Parse command line options
let args = Args::parse();
// l → proof
// ek || beta → proof
let data = BASE64_STANDARD.decode(&args.data).unwrap();
let signature = BASE64_STANDARD.decode(&args.signature).unwrap();
let key = EccKeyPubP256::from_ts(&args.key).unwrap();
/*let keyts = tomcrypt::P256EccKey::import(&BASE64_STANDARD.decode(&args.key).unwrap())
.unwrap();
let res = keyts.verify_hash(&data, &signature).unwrap();
println!("Res: {:?}", res);*/
key.verify(&data, &signature).unwrap();
}
+101
View File
@@ -0,0 +1,101 @@
use std::net::SocketAddr;
use anyhow::Result;
use tokio::net::UdpSocket;
use tracing::{info, info_span};
use tsproto::algorithms as algs;
use tsproto::client::Client;
use tsproto_packets::packets::*;
use tsproto_types::crypto::EccKeyPrivP256;
pub fn create_logger() { tracing_subscriber::fmt::init(); }
pub async fn create_client(
local_address: SocketAddr, remote_address: SocketAddr, verbose: u8,
) -> Result<Client> {
// Get P-256 ECDH key
let private_key = EccKeyPrivP256::import_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let udp_socket = UdpSocket::bind(local_address).await?;
let mut con = Client::new(remote_address, Box::new(udp_socket), private_key);
if verbose >= 1 {
tsproto::log::add_logger_with_verbosity(verbose, &mut con)
}
Ok(con)
}
/// Returns the `initserver` command.
pub async fn connect(con: &mut Client) -> Result<InCommandBuf> {
con.connect().await?;
// Send clientinit
let private_key = EccKeyPrivP256::import_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50CIA8M5nm\
DBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
// Compute hash cash
let offset;
{
let _span = info_span!("Compute public key hash cash level").entered();
let private_key_as_pub = private_key.to_pub();
offset = algs::hash_cash(&private_key_as_pub, 8);
let omega = private_key_as_pub.to_ts();
info!(
level = algs::get_hash_cash_level(&omega, offset),
offset, "Computed hash cash level"
);
}
// Create clientinit packet
let offset = offset.to_string();
let mut cmd =
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientinit");
cmd.write_arg("client_nickname", &"Bot");
cmd.write_arg("client_version", &"3.?.? [Build: 5680278000]");
cmd.write_arg("client_platform", &"Linux");
cmd.write_arg("client_input_hardware", &"1");
cmd.write_arg("client_output_hardware", &"1");
cmd.write_arg("client_default_channel", &"");
cmd.write_arg("client_default_channel_password", &"");
cmd.write_arg("client_server_password", &"");
cmd.write_arg("client_meta_data", &"");
cmd.write_arg(
"client_version_sign",
&"Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ==",
);
cmd.write_arg("client_nickname_phonetic", &"");
cmd.write_arg("client_key_offset", &offset);
cmd.write_arg("client_default_token", &"");
cmd.write_arg("client_badges", &"Overwolf=0");
cmd.write_arg("hwid", &"923f136fb1e22ae6ce95e60255529c00,d13231b1bc33edfecfb9169cc7a63bcc");
con.send_packet(cmd.into_packet())?;
Ok(con
.filter_commands(|con, cmd| {
Ok(if cmd.data().packet().content().starts_with(b"initserver ") {
Some(cmd)
} else {
con.hand_back_buffer(cmd.into_buffer());
None
})
})
.await?)
}
pub async fn disconnect(con: &mut Client) -> Result<()> {
let mut cmd =
OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientdisconnect");
cmd.write_arg("reasonid", &8);
cmd.write_arg("reasonmsg", &"Bye");
con.send_packet(cmd.into_packet())?;
con.wait_disconnect().await?;
Ok(())
}
+452
View File
@@ -0,0 +1,452 @@
//! Handle packet splitting and cryptography
use curve25519_dalek_ng::edwards::EdwardsPoint;
use eax::aead::consts::{U16, U8};
use eax::{AeadInPlace, Eax, KeyInit};
use generic_array::GenericArray;
use num_bigint::BigUint;
use num_traits::ToPrimitive;
use omnom::WriteExt;
use quicklz::CompressionLevel;
use sha1::Sha1;
use sha2::{Digest, Sha256, Sha512};
use tsproto_types::crypto::{EccKeyPrivEd25519, EccKeyPubP256};
use crate::connection::CachedKey;
use crate::{Error, Result};
use tsproto_packets::packets::*;
pub fn must_encrypt(t: PacketType) -> bool {
match t {
PacketType::Command | PacketType::CommandLow => true,
PacketType::Voice
| PacketType::Ack
| PacketType::AckLow
| PacketType::VoiceWhisper
| PacketType::Ping
| PacketType::Pong
| PacketType::Init => false,
}
}
pub fn should_encrypt(t: PacketType, voice_encryption: bool) -> bool {
must_encrypt(t)
|| t == PacketType::Ack
|| t == PacketType::AckLow
|| (voice_encryption && t.is_voice())
}
/// Compresses and splits the packet data of a `Command` or `CommandLow` packet.
///
/// Returns the splitted packet data and their headers.
/// The headers have their type and the compressed and fragmented flag set
/// to the right value.
///
/// Returns an error if the packet is too large but cannot be splitted.
/// Only `Command` and `CommandLow` packets can be compressed and splitted.
pub fn compress_and_split(is_client: bool, packet: OutPacket) -> Vec<OutPacket> {
// Everything except whisper packets has to be less than 500 bytes
let header_size =
if is_client { tsproto_packets::C2S_HEADER_LEN } else { tsproto_packets::S2C_HEADER_LEN };
let data = packet.content();
// The maximum packet size (including header) is 500 bytes.
let max_size = 500 - header_size;
// Split the data if it is necessary.
let compressed;
let datas = if data.len() > max_size {
// Compress with QuickLZ
let cdata = ::quicklz::compress(data, CompressionLevel::Lvl1);
// Use only if it is efficient
let mut data = if cdata.len() > data.len() {
compressed = false;
data
} else {
compressed = true;
&cdata
};
// Ignore size limit for whisper packets
if data.len() <= max_size || packet.header().packet_type() == PacketType::VoiceWhisper {
let mut v = vec![0; header_size + data.len()];
v[header_size..].copy_from_slice(data);
vec![v]
} else {
// Split
let count = (data.len() + max_size - 1) / max_size;
let mut splitted = Vec::with_capacity(count);
while data.len() > max_size {
let (first, last) = data.split_at(max_size);
let mut v = vec![0; header_size + max_size];
v[header_size..].copy_from_slice(first);
splitted.push(v);
data = last;
}
// Rest
let mut v = vec![0; header_size + data.len()];
v[header_size..].copy_from_slice(data);
splitted.push(v);
splitted
}
} else {
return vec![packet];
};
let len = datas.len();
let fragmented = len > 1;
let orig_header = packet.header_bytes();
let dir = packet.direction();
let mut packets = Vec::with_capacity(datas.len());
for (i, mut d) in datas.into_iter().enumerate() {
d[..header_size].copy_from_slice(orig_header);
let mut packet = OutPacket::new_from_data(dir, d);
// Only set flags on first fragment
if i == 0 && compressed {
packet.flags(packet.header().flags() | Flags::COMPRESSED);
}
// Set fragmented flag on first and last part
if fragmented && (i == 0 || i == len - 1) {
packet.flags(packet.header().flags() | Flags::FRAGMENTED);
}
packets.push(packet);
}
packets
}
fn create_key_nonce(
p_type: PacketType, c_id: Option<u16>, p_id: u16, generation_id: u32, iv: &[u8; 64],
cache: &mut [[CachedKey; 2]; 8],
) -> (GenericArray<u8, U16>, GenericArray<u8, U16>) {
// Check if this generation is cached
let cache = &mut cache[p_type.to_usize().unwrap()][if c_id.is_some() { 1 } else { 0 }];
if cache.generation_id != generation_id {
// Update the cache
let mut temp = [0; 70];
if c_id.is_some() {
temp[0] = 0x31;
} else {
temp[0] = 0x30;
}
temp[1] = p_type.to_u8().unwrap();
(&mut temp[2..6]).write_be(generation_id).unwrap();
temp[6..].copy_from_slice(iv);
let keynonce = Sha256::digest(&temp[..]);
let keynonce = keynonce.as_slice();
cache.generation_id = generation_id;
cache.key.copy_from_slice(&keynonce[..16]);
cache.nonce.copy_from_slice(&keynonce[16..]);
}
// Use the cached version
let mut key = cache.key;
let nonce = cache.nonce;
key[0] ^= (p_id >> 8) as u8;
key[1] ^= (p_id & 0xff) as u8;
(key, nonce)
}
pub fn encrypt_key_nonce(
packet: &mut OutPacket, key: &GenericArray<u8, U16>, nonce: &GenericArray<u8, U16>,
) -> Result<()> {
let meta = packet.header().get_meta().to_vec();
let cipher = Eax::<aes::Aes128, U8>::new(key);
let mac = cipher
.encrypt_in_place_detached(nonce, &meta, packet.content_mut())
.map_err(|_| Error::MaxLengthExceeded("encryption data"))?;
packet.mac().copy_from_slice(mac.as_slice());
Ok(())
}
pub fn encrypt_fake(packet: &mut OutPacket) -> Result<()> {
encrypt_key_nonce(packet, &crate::FAKE_KEY.into(), &crate::FAKE_NONCE.into())
}
pub fn encrypt(
packet: &mut OutPacket, generation_id: u32, iv: &[u8; 64], cache: &mut [[CachedKey; 2]; 8],
) -> Result<()> {
let header = packet.header();
let (key, nonce) = create_key_nonce(
header.packet_type(),
header.client_id(),
header.packet_id(),
generation_id,
iv,
cache,
);
encrypt_key_nonce(packet, &key, &nonce)
}
pub fn decrypt_key_nonce(
packet: &InPacket, key: &GenericArray<u8, U16>, nonce: &GenericArray<u8, U16>,
) -> Result<Vec<u8>> {
let header = packet.header();
let meta = header.get_meta();
// TODO decrypt in-place in packet
let mut content = packet.content().to_vec();
let cipher = Eax::<aes::Aes128, U8>::new(key);
cipher
.decrypt_in_place_detached(nonce, meta, &mut content, header.mac().into())
.map(|()| content)
.map_err(|_| Error::WrongMac {
p_type: header.packet_type(),
generation_id: 0,
packet_id: header.packet_id(),
})
}
pub fn decrypt_fake(packet: &InPacket) -> Result<Vec<u8>> {
decrypt_key_nonce(packet, &crate::FAKE_KEY.into(), &crate::FAKE_NONCE.into())
}
pub fn decrypt(
packet: &InPacket, generation_id: u32, iv: &[u8; 64], cache: &mut [[CachedKey; 2]; 8],
) -> Result<Vec<u8>> {
let header = packet.header();
let (key, nonce) = create_key_nonce(
header.packet_type(),
header.client_id(),
header.packet_id(),
generation_id,
iv,
cache,
);
decrypt_key_nonce(packet, &key, &nonce).map_err(|e| {
if let Error::WrongMac { p_type, packet_id, .. } = e {
Error::WrongMac { p_type, generation_id, packet_id }
} else {
e
}
})
}
/// Compute shared iv and shared mac.
pub fn compute_iv_mac(
alpha: &[u8; 10], beta: &[u8; 54], our_key: &EccKeyPrivEd25519, other_key: &EdwardsPoint,
) -> ([u8; 64], [u8; 8]) {
let shared_secret = our_key.create_shared_secret(other_key);
let mut shared_iv = [0; 64];
shared_iv.copy_from_slice(Sha512::digest(shared_secret).as_slice());
for i in 0..10 {
shared_iv[i] ^= alpha[i];
}
for i in 0..54 {
shared_iv[i + 10] ^= beta[i];
}
let mut shared_mac = [0; 8];
shared_mac.copy_from_slice(&Sha1::digest(shared_iv).as_slice()[..8]);
(shared_iv, shared_mac)
}
pub fn hash_cash(key: &EccKeyPubP256, level: u8) -> u64 {
let omega = key.to_ts();
let mut offset = 0;
while offset < u64::MAX && get_hash_cash_level(&omega, offset) < level {
offset += 1;
}
offset
}
#[inline]
pub fn get_hash_cash_level(omega: &str, offset: u64) -> u8 {
let data = Sha1::digest(format!("{}{}", omega, offset).as_bytes());
let mut res = 0;
for &d in data.as_slice() {
if d == 0 {
res += 8;
} else {
res += d.trailing_zeros() as u8;
break;
}
}
res
}
pub fn biguint_to_array(i: &BigUint) -> [u8; 64] {
let mut v = i.to_bytes_le();
// Extend with zeroes until 64 bytes
let len = v.len();
v.append(&mut vec![0; 64 - len]);
v.reverse();
let mut a = [0; 64];
a.copy_from_slice(&v);
a
}
pub fn array_to_biguint(i: &[u8; 64]) -> BigUint { BigUint::from_bytes_be(i) }
#[cfg(test)]
mod tests {
use base64::prelude::*;
use super::*;
use crate::license::Licenses;
use crate::packets::PacketType;
use crate::utils;
use tsproto_types::crypto::EccKeyPubEd25519;
#[test]
fn test_fake_crypt() {
let data = (0..100).into_iter().collect::<Vec<_>>();
let mut packet = OutPacket::new_with_dir(Direction::C2S, Flags::empty(), PacketType::Ack);
packet.data_mut().extend_from_slice(&data);
encrypt_fake(&mut packet).unwrap();
let packet =
InPacket::try_new(Direction::C2S, packet.data_mut().as_slice().into()).unwrap();
let dec_data = decrypt_fake(&packet).unwrap();
assert_eq!(&data, &dec_data);
}
#[test]
fn test_fake_encrypt() {
let mut packet = OutAck::new(Direction::C2S, PacketType::Command, 0);
encrypt_fake(&mut packet).unwrap();
let real_res: &[u8] =
&[0xa4, 0x7b, 0x47, 0x94, 0xdb, 0xa9, 0x6a, 0xc5, 0, 0, 0, 0, 0x6, 0xfe, 0x18];
assert_eq!(real_res, packet.data_mut().as_slice());
}
#[test]
fn shared_iv31() {
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs\
0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC\
4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==")
.unwrap()).unwrap();
let derived_key =
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(crate::ROOT_KEY)).unwrap();
let client_ek = [
0xb0, 0x4e, 0xa1, 0xd9, 0x5c, 0x72, 0x64, 0xdf, 0x0d, 0xe8, 0xb3, 0x6b, 0xaa, 0x7c,
0xa1, 0x5f, 0x75, 0x71, 0xf5, 0x1f, 0xa0, 0x54, 0xb5, 0x51, 0x27, 0x08, 0x8e, 0xdd,
0x96, 0x3d, 0x6e, 0x79,
];
let priv_key = EccKeyPrivEd25519::from_bytes(client_ek);
let alpha_b64 = BASE64_STANDARD.decode("Jkxq1wIvvhzaCA==").unwrap();
let mut alpha = [0; 10];
alpha.copy_from_slice(&alpha_b64);
let beta_b64 = BASE64_STANDARD
.decode("wU5T/MM6toW6Wge9th7VlTlzVZ9JDWypw2P9migfc25pjGP2Tj7Hm6rJpmKeHRr08Ch7BEAR")
.unwrap();
let mut beta = [0; 54];
beta.copy_from_slice(&beta_b64);
let expected_shared_shared_iv: [u8; 64] = [
0x58, 0x78, 0xae, 0x08, 0x08, 0x72, 0x05, 0xb0, 0x13, 0x27, 0x10, 0xe9, 0x81, 0xb4,
0xaf, 0x14, 0x14, 0x71, 0xad, 0xcd, 0x82, 0x98, 0xf3, 0xd1, 0x1d, 0x07, 0x20, 0x72,
0x7e, 0xb2, 0x1b, 0x89, 0x47, 0x82, 0x1e, 0xfb, 0x02, 0x53, 0x5a, 0x8a, 0x52, 0x4d,
0x9a, 0x7a, 0x09, 0x2c, 0x1b, 0xe7, 0x1f, 0xd1, 0x9d, 0x2a, 0x9d, 0x4f, 0xbd, 0xe3,
0x22, 0x09, 0xe4, 0x86, 0x7d, 0x63, 0x49, 0x07,
];
let expected_xored_shared_shared_iv: [u8; 64] = [
0x7e, 0x34, 0xc4, 0xdf, 0x0a, 0x5d, 0xbb, 0xac, 0xc9, 0x2f, 0xd1, 0xa7, 0xd2, 0x48,
0x6c, 0x2e, 0xa2, 0xf4, 0x17, 0x97, 0x85, 0x25, 0x45, 0xcf, 0xc8, 0x92, 0x19, 0x01,
0x2b, 0x2d, 0x52, 0x84, 0x2b, 0x2b, 0xdd, 0x98, 0xff, 0xc9, 0x72, 0x95, 0x21, 0x23,
0xf3, 0xf6, 0x6a, 0xda, 0x55, 0xd9, 0xd8, 0x4a, 0x37, 0xe3, 0x3b, 0x2d, 0x23, 0xfe,
0x38, 0xfd, 0x14, 0xae, 0x06, 0x67, 0x09, 0x16,
];
let (mut shared_iv, _shared_mac) = compute_iv_mac(&alpha, &beta, &priv_key, &derived_key);
assert_eq!(&shared_iv as &[u8], &expected_xored_shared_shared_iv as &[u8]);
for i in 0..10 {
shared_iv[i] ^= alpha[i];
}
for i in 0..54 {
shared_iv[i + 10] ^= beta[i];
}
assert_eq!(&shared_iv as &[u8], &expected_shared_shared_iv as &[u8]);
let mut temp = [0; 70];
temp[0] = 0x31;
temp[1] = 0x2 & 0xf;
temp[6..].copy_from_slice(&expected_xored_shared_shared_iv);
let temporary: [u8; 70] = [
0x31, 0x02, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x34, 0xc4, 0xdf, 0x0a, 0x5d, 0xbb, 0xac,
0xc9, 0x2f, 0xd1, 0xa7, 0xd2, 0x48, 0x6c, 0x2e, 0xa2, 0xf4, 0x17, 0x97, 0x85, 0x25,
0x45, 0xcf, 0xc8, 0x92, 0x19, 0x01, 0x2b, 0x2d, 0x52, 0x84, 0x2b, 0x2b, 0xdd, 0x98,
0xff, 0xc9, 0x72, 0x95, 0x21, 0x23, 0xf3, 0xf6, 0x6a, 0xda, 0x55, 0xd9, 0xd8, 0x4a,
0x37, 0xe3, 0x3b, 0x2d, 0x23, 0xfe, 0x38, 0xfd, 0x14, 0xae, 0x06, 0x67, 0x09, 0x16,
];
assert!(&temp as &[u8] == &temporary as &[u8]);
let keynonce = Sha256::digest(&temp);
let expected_keynonce: [u8; 32] = [
0xf3, 0x70, 0xd3, 0x43, 0xe7, 0x78, 0x15, 0x70, 0x7a, 0xff, 0x60, 0x48, 0xfb, 0xd9,
0xac, 0x6b, 0xb6, 0x33, 0x35, 0x79, 0x31, 0x9b, 0x88, 0x0e, 0x2d, 0x25, 0xef, 0x9c,
0xe9, 0x9e, 0x77, 0x5c,
];
assert!(keynonce.as_slice() == &expected_keynonce as &[u8]);
}
#[test]
fn test_new_decrypt() {
let shared_iv = utils::read_hex(
"C2 45 6F CB FC 22 08 AE 44 2B 7D E7 3A 67 1B DA 93 09 B2 00 F2 CD 10 49 08 CD 3A B0 \
7B DD 58 AD",
)
.unwrap();
let mut shared_iv = Sha512::digest(&shared_iv).as_slice().to_vec();
assert_eq!(
utils::read_hex(
"4D 3F DA B7 D8 B0 2C 82 70 6A 39 3E 97 17 61 09 FA 03 AB 30 5C BB 78 7A 9A 82 D5 \
39 9A 60 FD A9 F6 7A D9 04 52 F2 AE 00 3E 35 E8 19 10 89 40 43 80 58 27 1F 0A E0 \
E0 3D E0 9C F0 A3 4D 15 6B F0"
)
.unwrap()
.as_slice(),
shared_iv.as_slice()
);
let alpha = [0; 10];
let beta = BASE64_STANDARD
.decode("I4onb0zMyAD6bd24QANDls40eOES7qmjonBFtt5wRWzAfIIQWTSxjEas6TGTZIJ8QSJNX+Pl")
.unwrap();
for i in 0..10 {
shared_iv[i] ^= alpha[i];
}
for i in 0..54 {
shared_iv[i + 10] ^= beta[i];
}
let mut temp = [0; 70];
temp[0] = 0x31;
temp[1] = 0x2 & 0xf;
temp[6..].copy_from_slice(&shared_iv);
let keynonce = Sha256::digest(&temp);
let keynonce = keynonce.as_slice();
let all = utils::read_hex("2b982443ab38be6b00020000329abf64d4572e1349897b5e1e96fbc4a763a4c4ce1f64f0c1e3febd0a5f04a82ab1f2bc2344bb374fd16181beb8233b5b06944280470e9b6893290a1da0776ffcd89f3beec2ce23b9694930c09efaaea0d88a6895a08ede4d5cbfea61291fc553ac651f1e2bc1d2bd277a8bd9ab5386415579a9e56fac46d8b6b119f454bebd99179cd317dec60af205341d11f274d02bbacdd7e9773f72a426358ca1d39016dd95bde2409cd81bf99b340887e997ea982370c6790cf4d23150460820224766838ea4ec4d71dd102ede701ea0001f392623aa410dd9ab0e45874da82e29e6e370515ec30a37dd73f5a364c233ff014384beab5f1708c9f48dfba33a520f8fcdcef055789c54693c3fe72c5bfaca7cb4ca1fed77b8624660b8abc882f4b95b1284cb6dc55019c6082dd6dd146fa50383662d7298bef04ababaf1af80e15cd4c1f81326f085788e2918e00324147dce39b23db71326abc3de4b94df10f1531e9cce202bba71fa3ebeefd77b21fa3260a62e92eeee2183421d384a8c48777e2f9efbc58d4f442c5f0529c7c0e27e81b2b6b1b05eb8fa19256886248d553582dfd24c7cfab3c3f7317a5cebc6504b53fa0e86fc8c1100fc1d506fcf96caa76a7c0b6a27e577f2efdecd4070e847a559bf37d75bfdbe9e814c702426ce696d8645bc300b5f28f9e7f1ce").unwrap();
let packet = InPacket::try_new(Direction::C2S, &all).unwrap();
println!("Packet: {:?}", packet);
let mut key = [0; 16];
let mut nonce = [0; 16];
key.copy_from_slice(&keynonce[..16]);
nonce.copy_from_slice(&keynonce[16..]);
let expected_key =
utils::read_hex("D2 42 75 71 9C EE 83 35 EF 8A CE E0 B7 28 40 B8").unwrap();
let expected_nonce =
utils::read_hex("9C D9 30 B7 58 FE 50 23 64 66 11 C5 36 0E A2 5F").unwrap();
assert_eq!(&expected_nonce, &nonce);
assert_eq!(&expected_key, &key);
key[1] ^= 2; // packet id
let dec = decrypt_key_nonce(&packet, &key.into(), &nonce.into()).unwrap();
println!("Decrypted: {:?}", String::from_utf8_lossy(&dec));
}
}
+1222
View File
File diff suppressed because it is too large. Load diff
+556
View File
@@ -0,0 +1,556 @@
use std::collections::VecDeque;
use std::io;
use std::mem;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Instant;
use futures::prelude::*;
use generic_array::GenericArray;
use generic_array::typenum::consts::U16;
use num_traits::ToPrimitive;
use tokio::io::ReadBuf;
use tokio::net::UdpSocket;
use tracing::{Span, info_span};
use tsproto_packets::packets::*;
use tsproto_types::crypto::EccKeyPubP256;
use crate::packet_codec::PacketCodec;
use crate::resend::{PacketId, PartialPacketId, Resender, ResenderState};
use crate::{Error, MAX_UDP_PACKET_LENGTH, Result, UDP_SINK_CAPACITY};
/// The needed functions, this can be used to abstract from the underlying
/// transport and allows simulation.
pub trait Socket {
fn poll_recv_from(&self, cx: &mut Context, buf: &mut ReadBuf) -> Poll<io::Result<SocketAddr>>;
fn poll_send_to(
&self, cx: &mut Context, buf: &[u8], target: SocketAddr,
) -> Poll<io::Result<usize>>;
fn local_addr(&self) -> io::Result<SocketAddr>;
}
/// Capture identity retained with encoded audio, without retaining or copying PCM.
#[derive(Clone, Copy, Debug)]
pub struct AudioSendMetadata {
pub captured_at: Instant,
pub connection_generation: u64,
pub capture_epoch: u64,
}
/// Reusable authorization boundary for the actual, nonblocking socket send.
///
/// Implementations must invoke `send` synchronously, at most once, and only while
/// the capture timestamp, generation and epoch remain valid. The authorization
/// check and callback must share the lock used by capture invalidation; checking
/// an atomic and releasing the boundary before invoking `send` is insufficient.
/// Do not retain the callback or invoke it after returning. Socket backpressure
/// causes a fresh authorization on every subsequent poll. This hook is not called
/// during enqueue, which may itself run under the same capture lock.
pub trait AudioSendGuard: Send + Sync {
fn with_valid_audio(&self, metadata: &AudioSendMetadata, send: &mut dyn FnMut());
}
struct AudioAuthorization {
metadata: AudioSendMetadata,
guard: Arc<dyn AudioSendGuard>,
}
struct PendingPacket {
packet: OutUdpPacket,
audio: Option<AudioAuthorization>,
}
/// Ten 20-ms audio packets; control packets and unguarded End markers are retained.
const GUARDED_AUDIO_CAPACITY: usize = 10;
/// A cache for the key and nonce for a generation id.
/// This has to be stored for each packet type.
#[derive(Debug)]
pub struct CachedKey {
pub generation_id: u32,
pub key: GenericArray<u8, U16>,
pub nonce: GenericArray<u8, U16>,
}
/// Data that has to be stored for a connection when it is connected.
pub struct ConnectedParams {
/// The client id of this connection.
pub c_id: u16,
/// If voice packets should be encrypted
pub voice_encryption: bool,
/// The public key of the other side.
pub public_key: EccKeyPubP256,
/// The iv used to encrypt and decrypt packets.
pub shared_iv: [u8; 64],
/// The mac used for unencrypted packets.
pub shared_mac: [u8; 8],
/// Cached key and nonce per packet type and for server to client (without
/// client id inside the packet) and client to server communication.
pub key_cache: [[CachedKey; 2]; 8],
}
/// An event that originates from a tsproto raw connection.
#[derive(Debug)]
pub enum Event<'a> {
ReceiveUdpPacket(&'a InUdpPacket<'a>),
ReceivePacket(&'a InPacket<'a>),
SendUdpPacket(&'a OutUdpPacket),
SendPacket(&'a OutPacket),
}
/// An item that originates from a tsproto raw event stream.
///
/// The disconnected event is signaled by returning `None` from the stream.
#[derive(Debug)]
pub enum StreamItem {
Command(InCommandBuf),
Audio(InAudioBuf),
C2SInit(InC2SInitBuf),
S2CInit(InS2CInitBuf),
/// All packets with an id less or equal to this id were acknowledged.
AckPacket(PacketId),
/// The network statistics were updated.
NetworkStatsUpdated,
Error(Error),
}
type EventListener = Box<dyn for<'a> Fn(&'a Event<'a>) + Send>;
/// Represents a currently alive connection.
pub struct Connection {
pub is_client: bool,
pub span: Span,
/// The parameters of this connection, if it is already established.
pub params: Option<ConnectedParams>,
/// The address of the other side, where packets are coming from and going
/// to.
pub address: SocketAddr,
pub resender: Resender,
pub codec: PacketCodec,
pub udp_socket: Box<dyn Socket + Send>,
udp_buffer: Vec<u8>,
/// A buffer of packets that should be returned from the stream.
///
/// If a new udp packet is received and we already received the following
/// ids, we can get multiple packets back at once. As we can only return one
/// from the stream, the rest is stored here.
pub(crate) stream_items: VecDeque<StreamItem>,
/// The queue of non-command packets that should be sent.
///
/// These packets are not influenced by congestion control.
/// If it gets too long, we don't poll from the `udp_socket` anymore.
acks_to_send: VecDeque<PendingPacket>,
guarded_audio_pending: usize,
pub event_listeners: Vec<EventListener>,
}
impl Socket for UdpSocket {
fn poll_recv_from(&self, cx: &mut Context, buf: &mut ReadBuf) -> Poll<io::Result<SocketAddr>> {
self.poll_recv_from(cx, buf)
}
fn poll_send_to(
&self, cx: &mut Context, buf: &[u8], target: SocketAddr,
) -> Poll<io::Result<usize>> {
self.poll_send_to(cx, buf, target)
}
fn local_addr(&self) -> io::Result<SocketAddr> { self.local_addr() }
}
impl Default for CachedKey {
fn default() -> Self {
CachedKey { generation_id: u32::MAX, key: [0; 16].into(), nonce: [0; 16].into() }
}
}
impl ConnectedParams {
/// Fills the parameters for a connection with their default state.
pub fn new(public_key: EccKeyPubP256, shared_iv: [u8; 64], shared_mac: [u8; 8]) -> Self {
Self {
c_id: 0,
voice_encryption: true,
public_key,
shared_iv,
shared_mac,
key_cache: Default::default(),
}
}
}
impl Connection {
pub fn new(is_client: bool, address: SocketAddr, udp_socket: Box<dyn Socket + Send>) -> Self {
let span = info_span!("connection", local_addr = %udp_socket.local_addr().unwrap(),
remote_addr = %address);
let mut res = Self {
is_client,
span,
params: None,
address,
resender: Default::default(),
codec: Default::default(),
udp_socket,
udp_buffer: Default::default(),
stream_items: Default::default(),
acks_to_send: VecDeque::with_capacity(UDP_SINK_CAPACITY),
guarded_audio_pending: 0,
event_listeners: Default::default(),
};
if is_client {
// The first command is sent as part of the C2SInit::Init4 packet
// so it does not get registered automatically.
res.codec.outgoing_p_ids[PacketType::Command.to_usize().unwrap()] =
PartialPacketId { generation_id: 0, packet_id: 1 };
} else {
res.codec.incoming_p_ids[PacketType::Command.to_usize().unwrap()] =
PartialPacketId { generation_id: 0, packet_id: 1 };
}
res
}
/// Check if a given id is in the receive window.
///
/// Returns
/// 1. If the packet id is inside the receive window
/// 1. The generation of the packet
/// 1. The minimum accepted packet id
/// 1. The maximum accepted packet id
pub(crate) fn in_receive_window(&self, p_type: PacketType, p_id: u16) -> (bool, u32, u16, u16) {
if p_type == PacketType::Init {
return (true, 0, 0, 0);
}
let type_i = p_type.to_usize().unwrap();
// Receive window is the next half of ids
let cur_next = self.codec.incoming_p_ids[type_i].packet_id;
let (limit, next_gen) = cur_next.overflowing_add(u16::MAX / 2);
let gen = self.codec.incoming_p_ids[type_i].generation_id;
let in_recv_win = (!next_gen && p_id >= cur_next && p_id < limit)
|| (next_gen && (p_id >= cur_next || p_id < limit));
let gen_id = if in_recv_win {
if next_gen && p_id < limit { gen + 1 } else { gen }
} else if p_id < cur_next {
gen
} else {
gen - 1
};
(in_recv_win, gen_id, cur_next, limit)
}
pub fn send_event(&self, event: &Event) {
for l in &self.event_listeners {
l(event)
}
}
pub fn hand_back_buffer(&mut self, buffer: Vec<u8>) {
if self.udp_buffer.capacity() < MAX_UDP_PACKET_LENGTH
&& buffer.capacity() >= MAX_UDP_PACKET_LENGTH
{
self.udp_buffer = buffer;
}
}
fn poll_send_acks(&mut self, cx: &mut Context) -> Result<()> {
while let Some(pending) = self.acks_to_send.front() {
match Self::poll_send_udp_packet_with_guard(
&*self.udp_socket,
self.address,
&self.event_listeners,
cx,
&pending.packet,
pending.audio.as_ref(),
) {
Some(Poll::Ready(Ok(()))) => {
self.resender.handle_loss_outgoing(&pending.packet);
}
Some(Poll::Ready(Err(e))) => return Err(e),
Some(Poll::Pending) => break,
// Revoked/expired audio is discarded without polling the socket.
None => {}
}
if pending.audio.is_some() {
self.guarded_audio_pending -= 1;
}
self.acks_to_send.pop_front();
}
Ok(())
}
fn poll_incoming_udp_packet(&mut self, cx: &mut Context) -> Poll<Result<StreamItem>> {
if self.acks_to_send.len() >= UDP_SINK_CAPACITY {
return Poll::Pending;
}
loop {
// Poll udp_socket
if self.udp_buffer.len() != MAX_UDP_PACKET_LENGTH {
self.udp_buffer.resize(MAX_UDP_PACKET_LENGTH, 0);
}
let mut read_buf = ReadBuf::new(&mut self.udp_buffer);
match self.udp_socket.poll_recv_from(cx, &mut read_buf) {
Poll::Ready(Ok(addr)) => {
let size = read_buf.filled().len();
let mut udp_buffer = mem::take(&mut self.udp_buffer);
udp_buffer.truncate(size);
match self.handle_udp_packet(cx, udp_buffer, addr) {
Ok(()) => {
if let Some(item) = self.stream_items.pop_front() {
return Poll::Ready(Ok(item));
}
}
Err(e) => {
return Poll::Ready(Err(e));
}
}
}
// Udp socket closed
Poll::Ready(Err(e)) => return Poll::Ready(Err(Error::Network(e))),
Poll::Pending => return Poll::Pending,
}
}
}
fn handle_udp_packet(
&mut self, cx: &mut Context, udp_buffer: Vec<u8>, addr: SocketAddr,
) -> Result<()> {
let _span = self.span.clone().entered();
if addr != self.address {
self.stream_items.push_back(StreamItem::Error(Error::WrongAddress));
return Ok(());
}
let dir = if self.is_client { Direction::S2C } else { Direction::C2S };
let packet = InUdpPacket(match InPacket::try_new(dir, &udp_buffer) {
Ok(r) => r,
Err(e) => {
self.stream_items.push_back(StreamItem::Error(Error::PacketParse("udp", e)));
return Ok(());
}
});
let event = Event::ReceiveUdpPacket(&packet);
self.send_event(&event);
self.resender.received_packet();
PacketCodec::handle_udp_packet(self, cx, udp_buffer)?;
Ok(())
}
/// Try to send an ack packet.
///
/// If it does not work, add it to the ack queue.
pub(crate) fn send_ack_packet(&mut self, cx: &mut Context, packet: OutPacket) -> Result<()> {
self.send_event(&Event::SendPacket(&packet));
let mut udp_packets = PacketCodec::encode_packet(self, packet)?;
assert_eq!(
udp_packets.len(),
1,
"Encoding an ack packet should only yield a single packet"
);
let packet = udp_packets.pop().unwrap();
match self.poll_send_udp_packet(cx, &packet) {
Poll::Ready(r) => {
if r.is_ok() {
self.resender.handle_loss_outgoing(&packet);
}
r
}
Poll::Pending => {
self.acks_to_send.push_back(PendingPacket { packet, audio: None });
Ok(())
}
}
}
/// Add a packet to the send queue.
///
/// This function buffers indefinitely, to prevent using a large amount of
/// memory, check `is_send_queue_full` first and only send a packet if this
/// function returns `false`.
///
/// When the `PacketId` which is returned by this function is acknowledged,
/// the packet was successfully received by the other side of the
/// connection.
pub fn send_packet(&mut self, packet: OutPacket) -> Result<PacketId> {
self.send_event(&Event::SendPacket(&packet));
let udp_packets = PacketCodec::encode_packet(self, packet)?;
let id = udp_packets.last().unwrap().into();
for p in udp_packets {
self.send_udp_packet(p);
}
Ok(id)
}
/// Queue audio whose authorization must still hold at the actual socket poll.
///
/// The guard is shared across frames; each packet retains only metadata and an
/// `Arc` reference. Pending guarded media is capped at ten packets, evicting the
/// oldest guarded packet without removing or reordering control/End packets.
/// Packet IDs and encryption are assigned once by the normal encoder and are
/// never changed when a packet is retried. Use `send_packet` for unguarded End.
pub fn send_audio_guarded(
&mut self, packet: OutPacket, metadata: AudioSendMetadata, guard: Arc<dyn AudioSendGuard>,
) -> Result<()> {
assert!(
matches!(packet.header().packet_type(), PacketType::Voice | PacketType::VoiceWhisper),
"Can only send audio packets with send_audio_guarded"
);
self.send_event(&Event::SendPacket(&packet));
let mut packets = PacketCodec::encode_packet(self, packet)?;
assert_eq!(packets.len(), 1, "Audio encoding must yield one UDP packet");
let packet = packets.pop().unwrap();
if self.guarded_audio_pending == GUARDED_AUDIO_CAPACITY {
let oldest = self.acks_to_send.iter().position(|p| p.audio.is_some()).unwrap();
self.acks_to_send.remove(oldest);
self.guarded_audio_pending -= 1;
}
self.acks_to_send.push_back(PendingPacket {
packet,
audio: Some(AudioAuthorization { metadata, guard }),
});
self.guarded_audio_pending += 1;
Ok(())
}
/// Add an udp packet to the send queue.
pub fn send_udp_packet(&mut self, packet: OutUdpPacket) {
let _span = self.span.clone().entered();
match packet.packet_type() {
PacketType::Init | PacketType::Command | PacketType::CommandLow => {
Resender::send_packet(self, packet);
}
_ => self.acks_to_send.push_back(PendingPacket { packet, audio: None }),
}
}
pub fn poll_send_udp_packet(
&self, cx: &mut Context, packet: &OutUdpPacket,
) -> Poll<Result<()>> {
Self::static_poll_send_udp_packet(
&*self.udp_socket,
self.address,
&self.event_listeners,
cx,
packet,
)
}
/// Remember to add the size of the sent packet to the stats in the resender.
pub fn static_poll_send_udp_packet(
udp_socket: &dyn Socket, address: SocketAddr, event_listeners: &[EventListener],
cx: &mut Context, packet: &OutUdpPacket,
) -> Poll<Result<()>> {
Self::poll_send_udp_packet_with_guard(
udp_socket, address, event_listeners, cx, packet, None,
).expect("unguarded socket poll is always attempted")
}
fn poll_send_udp_packet_with_guard(
udp_socket: &dyn Socket, address: SocketAddr, event_listeners: &[EventListener],
cx: &mut Context, packet: &OutUdpPacket, authorization: Option<&AudioAuthorization>,
) -> Option<Poll<Result<()>>> {
let data = packet.data().data();
let mut result = None;
let mut send = || {
// Even an incorrectly repeated callback cannot send a datagram twice.
if result.is_none() {
result = Some(udp_socket.poll_send_to(cx, data, address));
}
};
if let Some(audio) = authorization {
audio.guard.with_valid_audio(&audio.metadata, &mut send);
} else {
send();
}
// Listeners and statistics run after releasing the capture boundary.
Some(match result? {
Poll::Pending => Poll::Pending,
Poll::Ready(Err(e)) => Poll::Ready(Err(Error::Network(e))),
Poll::Ready(Ok(size)) => {
let event = Event::SendUdpPacket(packet);
for l in event_listeners {
l(&event)
}
if size != data.len() {
Poll::Ready(Err(Error::Network(std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to send whole udp packet",
))))
} else {
Poll::Ready(Ok(()))
}
}
})
}
pub fn is_send_queue_full(&self) -> bool { self.resender.is_full() }
pub fn is_send_queue_empty(&self) -> bool { self.resender.is_empty() }
}
/// Pull for events.
///
/// `Ok(StreamItem::Error)` is recoverable, `Err()` is not.
///
/// Polling does a few things in round robin fashion:
/// 1. Check for new udp packets
/// 2. Use the resender to resend packets if necessary
/// 3. Use the resender to send ping packets if necessary
impl Stream for Connection {
type Item = Result<StreamItem>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let _span = self.span.clone().entered();
if let Err(e) = self.poll_send_acks(cx) {
return Poll::Ready(Some(Err(e)));
}
if self.resender.get_state() == ResenderState::Disconnected {
// Send all ack packets and return `None` afterwards
if self.acks_to_send.is_empty() {
return Poll::Ready(None);
}
}
// Use the resender to resend packets
match Resender::poll_resend(&mut self, cx) {
Ok(()) => {}
Err(e) => return Poll::Ready(Some(Err(e))),
}
// Use the resender to send pings
match Resender::poll_ping(&mut self, cx) {
Ok(()) => {}
Err(e) => return Poll::Ready(Some(Err(e))),
}
// Return existing stream_items
if let Some(item) = self.stream_items.pop_front() {
return Poll::Ready(Some(Ok(item)));
}
// Check for new udp packets
match self.poll_incoming_udp_packet(cx) {
Poll::Ready(r) => return Poll::Ready(Some(r)),
Poll::Pending => {}
}
Poll::Pending
}
}
#[cfg(test)]
#[path = "connection_tests.rs"]
mod tests;
+238
View File
@@ -0,0 +1,238 @@
use std::sync::Mutex;
use std::task::Waker;
use std::time::Duration;
use futures::task::noop_waker;
use tsproto_types::crypto::EccKeyPrivP256;
use super::*;
struct GuardState {
now: Instant,
epoch: u64,
generation: u64,
checks: usize,
}
struct CaptureGuard(Mutex<GuardState>);
impl CaptureGuard {
fn metadata(&self) -> AudioSendMetadata {
let state = self.0.lock().unwrap();
AudioSendMetadata {
captured_at: state.now,
connection_generation: state.generation,
capture_epoch: state.epoch,
}
}
}
impl AudioSendGuard for CaptureGuard {
fn with_valid_audio(&self, metadata: &AudioSendMetadata, send: &mut dyn FnMut()) {
let mut state = self.0.lock().unwrap();
state.checks += 1;
if metadata.capture_epoch == state.epoch
&& metadata.connection_generation == state.generation
&& state.now.checked_duration_since(metadata.captured_at)
.is_some_and(|age| age <= Duration::from_millis(200))
{
send();
}
}
}
#[derive(Default)]
struct SocketState {
blocked: bool,
attempts: Vec<Vec<u8>>,
sent: Vec<Vec<u8>>,
waker: Option<Waker>,
}
struct BackpressureSocket {
state: Arc<Mutex<SocketState>>,
guard: Arc<CaptureGuard>,
}
impl Socket for BackpressureSocket {
fn poll_recv_from(&self, _: &mut Context, _: &mut ReadBuf) -> Poll<io::Result<SocketAddr>> {
Poll::Pending
}
fn poll_send_to(&self, cx: &mut Context, buf: &[u8], _: SocketAddr) -> Poll<io::Result<usize>> {
let packet = InPacket::new(Direction::C2S, buf);
if matches!(packet.header().packet_type(), PacketType::Voice | PacketType::VoiceWhisper)
&& packet.content().len() > 3
{
assert!(self.guard.0.try_lock().is_err(), "socket poll escaped capture boundary");
}
let mut state = self.state.lock().unwrap();
state.attempts.push(buf.to_vec());
if state.blocked {
state.waker = Some(cx.waker().clone());
Poll::Pending
} else {
state.sent.push(buf.to_vec());
Poll::Ready(Ok(buf.len()))
}
}
fn local_addr(&self) -> io::Result<SocketAddr> { Ok("127.0.0.1:0".parse().unwrap()) }
}
fn setup(encrypted: bool) -> (Connection, Arc<CaptureGuard>, Arc<Mutex<SocketState>>) {
let guard = Arc::new(CaptureGuard(Mutex::new(GuardState {
now: Instant::now(), epoch: 1, generation: 1, checks: 0,
})));
let state = Arc::new(Mutex::new(SocketState { blocked: true, ..Default::default() }));
let socket = BackpressureSocket { state: state.clone(), guard: guard.clone() };
let mut con = Connection::new(true, "127.0.0.1:1".parse().unwrap(), Box::new(socket));
let mut params = ConnectedParams::new(EccKeyPrivP256::create().to_pub(), [7; 64], [9; 8]);
params.voice_encryption = encrypted;
con.params = Some(params);
con.resender.set_state(ResenderState::Connected);
let listener_guard = guard.clone();
con.event_listeners.push(Box::new(move |event| {
if matches!(event, Event::SendUdpPacket(_)) {
assert!(listener_guard.0.try_lock().is_ok(), "listener ran under capture lock");
}
}));
(con, guard, state)
}
fn poll_pending(con: &mut Connection) {
let waker = noop_waker();
con.poll_send_acks(&mut Context::from_waker(&waker)).unwrap();
}
fn unblock(state: &Mutex<SocketState>) {
let waker = {
let mut state = state.lock().unwrap();
state.blocked = false;
state.waker.take()
};
if let Some(waker) = waker {
waker.wake();
}
}
fn voice(data: &[u8]) -> OutPacket {
OutAudio::new(&AudioData::C2S { id: 0, codec: CodecType::OpusVoice, data })
}
fn whisper(data: &[u8]) -> OutPacket {
OutAudio::new(&AudioData::C2SWhisper {
id: 0, codec: CodecType::OpusVoice, channels: vec![], clients: vec![1], data,
})
}
fn ping() -> OutPacket {
OutPacket::new_with_dir(Direction::C2S, Flags::UNENCRYPTED, PacketType::Ping)
}
#[tokio::test]
async fn guarded_audio_rechecks_revocation_after_socket_backpressure() {
for generation_change in [false, true] {
for packet in [voice(&[1, 2, 3]), whisper(&[1, 2, 3])] {
let (mut con, guard, socket) = setup(true);
con.send_audio_guarded(packet, guard.metadata(), guard.clone()).unwrap();
con.send_packet(voice(&[])).unwrap();
con.send_packet(ping()).unwrap();
assert_eq!(guard.0.lock().unwrap().checks, 0, "enqueue must not relock capture");
poll_pending(&mut con);
assert_eq!(socket.lock().unwrap().attempts.len(), 1);
assert!(socket.lock().unwrap().sent.is_empty());
{
let mut state = guard.0.lock().unwrap();
if generation_change { state.generation += 1; } else { state.epoch += 1; }
}
unblock(&socket);
poll_pending(&mut con);
let state = socket.lock().unwrap();
assert_eq!(state.attempts.len(), 3, "revoked media must not poll the socket again");
assert_eq!(state.sent.len(), 2, "End and control survive capture invalidation");
let end = InPacket::new(Direction::C2S, &state.sent[0]);
assert_eq!(end.header().packet_type(), PacketType::Voice);
assert_eq!(end.content().len(), 3);
assert_eq!(InPacket::new(Direction::C2S, &state.sent[1]).header().packet_type(), PacketType::Ping);
assert!(con.acks_to_send.is_empty());
assert_eq!(con.guarded_audio_pending, 0);
}
}
}
#[tokio::test]
async fn guarded_audio_expires_while_socket_is_pending() {
let (mut con, guard, socket) = setup(false);
con.send_audio_guarded(voice(&[1]), guard.metadata(), guard.clone()).unwrap();
poll_pending(&mut con);
guard.0.lock().unwrap().now += Duration::from_millis(600);
unblock(&socket);
poll_pending(&mut con);
assert_eq!(socket.lock().unwrap().attempts.len(), 1);
assert!(socket.lock().unwrap().sent.is_empty());
assert!(con.acks_to_send.is_empty());
assert_eq!(con.guarded_audio_pending, 0);
// Reject a future timestamp and a frame already stale before its first poll too.
for offset in [Duration::from_millis(600), Duration::from_millis(1)] {
let mut metadata = guard.metadata();
if offset.as_millis() == 600 { metadata.captured_at -= offset; }
else { metadata.captured_at += offset; }
con.send_audio_guarded(voice(&[2]), metadata, guard.clone()).unwrap();
poll_pending(&mut con);
}
assert_eq!(socket.lock().unwrap().attempts.len(), 1);
assert!(con.acks_to_send.is_empty());
}
#[tokio::test]
async fn guarded_audio_retries_identical_encrypted_packet_under_boundary() {
for packet in [voice(&[1, 2, 3]), whisper(&[4, 5, 6])] {
let (mut con, guard, socket) = setup(true);
con.send_audio_guarded(packet, guard.metadata(), guard.clone()).unwrap();
let expected = con.acks_to_send.front().unwrap().packet.data().data().to_vec();
assert!(!InPacket::new(Direction::C2S, &expected).header().flags().contains(Flags::UNENCRYPTED));
poll_pending(&mut con);
poll_pending(&mut con);
assert_eq!(con.guarded_audio_pending, 1);
unblock(&socket);
poll_pending(&mut con);
let state = socket.lock().unwrap();
assert_eq!(state.attempts, vec![expected.clone(), expected.clone(), expected.clone()]);
assert_eq!(state.sent, vec![expected]);
assert_eq!(guard.0.lock().unwrap().checks, 3);
assert!(con.acks_to_send.is_empty());
assert_eq!(con.guarded_audio_pending, 0);
}
}
#[tokio::test]
async fn guarded_audio_capacity_drops_oldest_without_reordering_end_or_control() {
let (mut con, guard, socket) = setup(false);
con.send_packet(voice(&[])).unwrap();
for value in 0..30u8 {
con.send_audio_guarded(voice(&[value]), guard.metadata(), guard.clone()).unwrap();
if value == 14 {
con.send_packet(ping()).unwrap();
con.send_packet(voice(&[])).unwrap();
}
poll_pending(&mut con);
assert!(con.guarded_audio_pending <= GUARDED_AUDIO_CAPACITY);
}
assert_eq!(con.guarded_audio_pending, GUARDED_AUDIO_CAPACITY);
assert_eq!(con.acks_to_send.len(), GUARDED_AUDIO_CAPACITY + 3);
unblock(&socket);
poll_pending(&mut con);
let state = socket.lock().unwrap();
assert_eq!(state.sent.len(), GUARDED_AUDIO_CAPACITY + 3);
let control_types: Vec<_> = state.sent[..3].iter()
.map(|data| InPacket::new(Direction::C2S, data).header().packet_type()).collect();
assert_eq!(control_types, vec![PacketType::Voice, PacketType::Ping, PacketType::Voice]);
for (data, expected) in state.sent[3..].iter().zip(20..30u8) {
let packet = InPacket::new(Direction::C2S, data);
assert_eq!(packet.header().packet_type(), PacketType::Voice);
assert_eq!(&packet.content()[3..], &[expected]);
}
assert!(con.acks_to_send.is_empty());
assert_eq!(con.guarded_audio_pending, 0);
}
+253
View File
@@ -0,0 +1,253 @@
//! This library implements the TeamSpeak3 protocol.
//!
//! For a usable library to build clients and bots, you should take a look at
//! [`tsclientlib`](https://github.com/ReSpeak/tsclientlib), which provides a
//! convenient interface to this library.
//!
//! If you are searching for a usable client, [Qint](https://github.com/ReSpeak/Qint)
//! is a cross-platform TeamSpeak client, which is using this library (more
//! correctly, it is using `tsclientlib`).
//!
//! For more info on this project, take a look at the
//! [tsclientlib README](https://github.com/ReSpeak/tsclientlib).
use std::fmt;
use std::num::ParseIntError;
use base64::prelude::*;
use serde::de::{Unexpected, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;
use tsproto_packets::packets;
use tsproto_types::crypto::EccKeyPrivP256;
pub mod algorithms;
pub mod client;
pub mod connection;
pub mod license;
pub mod log;
pub mod packet_codec;
pub mod resend;
pub mod utils;
use algorithms as algs;
// The build environment of tsproto.
git_testament::git_testament!(TESTAMENT);
#[doc(hidden)]
pub fn get_testament() -> &'static git_testament::GitTestament<'static> { &TESTAMENT }
type Result<T> = std::result::Result<T, Error>;
/// The maximum number of bytes for a fragmented packet.
///
/// The maximum packet size is 500 bytes, as used by
/// `algorithms::compress_and_split`.
/// We pick the ethernet MTU for possible future compatibility, it is unlikely
/// that a packet will get bigger.
pub const MAX_UDP_PACKET_LENGTH: usize = 1500;
/// The maximum number of bytes for a fragmented packet.
#[allow(clippy::unreadable_literal)]
const MAX_FRAGMENTS_LENGTH: usize = 40960;
/// The maximum number of packets which are stored, if they are received
/// out-of-order.
const MAX_QUEUE_LEN: u16 = 200;
/// The maximum decompressed size of a packet.
#[allow(clippy::unreadable_literal)]
/// On large servers with more than 2000 channels, the notifychannelsubscribed packet can be
/// 50 kB large (uncompressed). A maximum size to 2 MiB should allow for even larger servers.
const MAX_DECOMPRESSED_SIZE: u32 = 2 * 1024 * 1024;
const FAKE_KEY: [u8; 16] = *b"c:\\windows\\syste";
const FAKE_NONCE: [u8; 16] = *b"m\\firewall32.cpl";
/// The root key in the TeamSpeak license system.
pub const ROOT_KEY: [u8; 32] = [
0xcd, 0x0d, 0xe2, 0xae, 0xd4, 0x63, 0x45, 0x50, 0x9a, 0x7e, 0x3c, 0xfd, 0x8f, 0x68, 0xb3, 0xdc,
0x75, 0x55, 0xb2, 0x9d, 0xcc, 0xec, 0x73, 0xcd, 0x18, 0x75, 0x0f, 0x99, 0x38, 0x12, 0x40, 0x8a,
];
/// The maximum amount of ack pachets that a connection intermediately stores.
///
/// When this amount is stored, no new packets will be polled from the UDP
/// connection.
const UDP_SINK_CAPACITY: usize = 50;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error("Failed to create ack packet: {0}")]
CreateAck(#[source] tsproto_packets::Error),
#[error("Failed to decompress packet: {0}")]
DecompressPacket(#[source] quicklz::Error),
#[error(transparent)]
IdentityCrypto(tsproto_types::crypto::Error),
#[error("Failed to parse int: {0}")]
InvalidHex(#[source] ParseIntError),
#[error("Maximum length exceeded for {0}")]
MaxLengthExceeded(&'static str),
#[error("Network error: {0}")]
Network(#[source] std::io::Error),
#[error("Packet {id} not in receive window [{next};{limit}) for type {p_type:?}")]
NotInReceiveWindow { id: u16, next: u16, limit: u16, p_type: packets::PacketType },
#[error("Failed to parse {0} packet: {1}")]
PacketParse(&'static str, #[source] tsproto_packets::Error),
#[error("Connection timed out: {0}")]
Timeout(&'static str),
#[error("Got unallowed unencrypted packet")]
UnallowedUnencryptedPacket,
#[error("Got unexpected init packet")]
UnexpectedInitPacket,
#[error("Packet has wrong client id {0}")]
WrongClientId(u16),
#[error("Received udp packet from wrong address")]
WrongAddress,
#[error("{p_type:?} Packet {generation_id}:{packet_id} has a wrong mac")]
WrongMac { p_type: packets::PacketType, generation_id: u32, packet_id: u16 },
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Identity {
#[serde(serialize_with = "serialize_id_key", deserialize_with = "deserialize_id_key")]
key: EccKeyPrivP256,
/// The `client_key_offset`/counter for hash cash.
counter: u64,
/// The maximum counter that was tried, this is greater or equal to
/// `counter` but may yield a lower level.
max_counter: u64,
}
struct IdKeyVisitor;
impl<'de> Visitor<'de> for IdKeyVisitor {
type Value = EccKeyPrivP256;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "a P256 private ecc key")
}
fn visit_str<E: serde::de::Error>(self, s: &str) -> std::result::Result<Self::Value, E> {
EccKeyPrivP256::import_str(s)
.map_err(|_| serde::de::Error::invalid_value(Unexpected::Str(s), &self))
}
}
fn serialize_id_key<S: Serializer>(
key: &EccKeyPrivP256, s: S,
) -> std::result::Result<S::Ok, S::Error> {
s.serialize_str(&BASE64_STANDARD.encode(key.to_short()))
}
fn deserialize_id_key<'de, D: Deserializer<'de>>(
d: D,
) -> std::result::Result<EccKeyPrivP256, D::Error> {
d.deserialize_str(IdKeyVisitor)
}
impl Identity {
#[inline]
pub fn create() -> Self {
let mut res = Self::new(EccKeyPrivP256::create(), 0);
res.upgrade_level(8);
res
}
#[inline]
pub fn new(key: EccKeyPrivP256, counter: u64) -> Self {
Self::new_with_max_counter(key, counter, counter)
}
#[inline]
pub fn new_with_max_counter(key: EccKeyPrivP256, counter: u64, max_counter: u64) -> Self {
Self { key, counter, max_counter }
}
#[inline]
pub fn new_from_str(key: &str) -> Result<Self> {
if let Ok(identity) = Identity::new_from_ts_str(key) {
return Ok(identity);
}
let mut res = Self::new(EccKeyPrivP256::import_str(key).map_err(Error::IdentityCrypto)?, 0);
res.upgrade_level(8);
Ok(res)
}
pub fn new_from_ts_str(key: &str) -> Result<Self> {
let counter_separator = key
.find('V')
.ok_or(Error::IdentityCrypto(tsproto_types::crypto::Error::NoCounterBlock))?;
let counter = key[..counter_separator]
.parse::<u64>()
.map_err(|_| Error::IdentityCrypto(tsproto_types::crypto::Error::NoCounterBlock))?;
let ecc_key = EccKeyPrivP256::import_str(&key[(counter_separator + 1)..])
.map_err(Error::IdentityCrypto)?;
Ok(Self::new(ecc_key, counter))
}
#[inline]
pub fn new_from_bytes(key: &[u8]) -> Result<Self> {
let mut res = Self::new(EccKeyPrivP256::import(key).map_err(Error::IdentityCrypto)?, 0);
res.upgrade_level(8);
Ok(res)
}
#[inline]
pub fn key(&self) -> &EccKeyPrivP256 { &self.key }
#[inline]
pub fn counter(&self) -> u64 { self.counter }
#[inline]
pub fn max_counter(&self) -> u64 { self.max_counter }
#[inline]
pub fn set_key(&mut self, key: EccKeyPrivP256) { self.key = key }
#[inline]
pub fn set_counter(&mut self, counter: u64) { self.counter = counter; }
#[inline]
pub fn set_max_counter(&mut self, max_counter: u64) { self.max_counter = max_counter; }
/// Compute the current hash cash level.
#[inline]
pub fn level(&self) -> u8 {
let omega = self.key.to_pub().to_ts();
algs::get_hash_cash_level(&omega, self.counter)
}
/// Compute a better hash cash level.
pub fn upgrade_level(&mut self, target: u8) {
let omega = self.key.to_pub().to_ts();
let mut offset = self.max_counter;
while offset < u64::MAX && algs::get_hash_cash_level(&omega, offset) < target {
offset += 1;
}
self.counter = offset;
self.max_counter = offset;
}
}
#[cfg(test)]
mod identity_tests {
use super::*;
const TEST_PRIV_KEY: &str =
"MG8DAgeAAgEgAiEA6rtKxDn/o/Bo50rNtAE5Ph3h2RKLHQ0gbFkvm2yA79kCIQCrfzAZts/\
vHP+3MOetKLjNnpZXt4c6U3UB4gWLKR4H9AIgYTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=";
const TEST_UID: &str = "test/9PZ9vww/Bpf5vJxtJhpz80=";
#[test]
fn parse_ts_base64() {
let identity = Identity::new_from_str(TEST_PRIV_KEY).unwrap();
let uid = identity.key().to_pub().get_uid();
assert_eq!(TEST_UID, &uid);
}
#[test]
fn parse_ts_base64_with_offset() {
let ident_str = String::from("2792354V") + TEST_PRIV_KEY;
let identity = Identity::new_from_str(&ident_str).unwrap();
let uid = identity.key().to_pub().get_uid();
assert_eq!(TEST_UID, &uid);
assert_eq!(identity.level(), 21u8);
}
}
+932
View File
@@ -0,0 +1,932 @@
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::io::Cursor;
use std::str;
use curve25519_dalek_ng::edwards::EdwardsPoint;
use curve25519_dalek_ng::scalar::Scalar;
use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::{FromPrimitive as _, ToPrimitive as _};
use omnom::{ReadExt, WriteExt};
use sha2::{Digest, Sha512};
use thiserror::Error;
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use tracing::trace;
use tsproto_packets::HexSlice;
use tsproto_types::{
LicenseType,
crypto::{EccKeyPrivEd25519, EccKeyPubEd25519},
};
pub const TIMESTAMP_OFFSET: i64 = 0x50e2_2700;
const BLOCK_MIN_LEN: usize = 42;
const BLOCK_TYPE_OFFSET: usize = 33;
const BLOCK_NOT_VALID_BEFORE_OFFSET: usize = 34;
const BLOCK_NOT_VALID_AFTER_OFFSET: usize = 38;
type Result<T> = std::result::Result<T, Error>;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error(
"License must not exceed bounds {outer_start} - {outer_end} but has {inner_start} - \
{inner_end}"
)]
Bounds {
outer_start: OffsetDateTime,
outer_end: OffsetDateTime,
inner_start: OffsetDateTime,
inner_end: OffsetDateTime,
},
#[error("Failed to deserialize license: {0}")]
Deserialize(#[source] std::io::Error),
#[error("Failed to deserialize license: {0}")]
DeserializeString(#[source] std::str::Utf8Error),
#[error("Failed to deserialize date: {0}")]
DeserializeDate(#[source] time::error::ComponentRange),
#[error("License is only valid between {start} and {end}")]
Expired { start: OffsetDateTime, end: OffsetDateTime },
#[error("Cannot uncompress license public key")]
InvalidPublicKey,
#[error("Invalid data {0:#x} in intermediate license")]
IntermediateInvalidData(u32),
#[error("Invalid public root key for license")]
InvalidRootKey,
#[error("Non-null-terminated string")]
NonterminatedString,
#[error("License contains no private key")]
NoPrivateKey,
#[error("Too many license blocks: {0}")]
TooManyBlocks(usize),
#[error("License too short ({0}): {1}")]
TooShort(usize, &'static str),
#[error("Unknown license block type {0}")]
UnknownBlockType(u8),
#[error("Unknown license type {0}")]
UnknownLicenseType(u8),
#[error("Unsupported license version {0}")]
UnsupportedVersion(u8),
#[error("Wrong key kind {0} in license")]
WrongKeyKind(u8),
#[error("There is no {0} in this block")]
NoSuchProperty(&'static str),
#[error("Wrong property type for id {id}: Expected type {expected} but got type {actual}")]
WrongPropertyType { id: u8, expected: u8, actual: u8 },
#[error(
"Property with id {id} and type {typ} has wrong length: Expected length {expected} but \
got length {actual}"
)]
WrongPropertyLength { id: u8, typ: u8, expected: u8, actual: u8 },
}
/// A single block of a license
#[derive(Clone, Debug)]
pub struct License {
/// Length of the block
pub len: usize,
/// A private key for the block to derive a private key
pub private_key: Option<EccKeyPrivEd25519>,
pub inner: InnerLicense,
}
/// Helper struct to debug print a license block.
pub struct DebugLicense<'a>(&'a License, &'a [u8]);
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, FromPrimitive, ToPrimitive)]
pub enum LicenseBlockType {
Intermediate,
Website,
/// Ts3_Server
Server,
Code,
// Not existing in the license parameter:
// 4: Token, 5: License_Sign, 6: MyTsId_Sign, 7: Updater
/// Ts_Server_License
Ts5Server = 8,
/// 32, Ephemeral_Key
Ephemeral = 32,
}
#[derive(Debug, Clone)]
pub enum InnerLicense {
Ts5Server {
/// Properties from the license, offset from the start of properties for every field
properties: Vec<usize>,
},
Other,
}
/// A list of blocks, forming a complete license
#[derive(Clone)]
pub struct Licenses {
pub data: Vec<u8>,
pub blocks: Vec<License>,
}
#[derive(Clone, Debug)]
pub enum LicenseProperty<'a> {
/// Unknown property with id 1 and type 1
Unknown1(u32),
Issuer(&'a str),
MaxClients(u32),
Unknown {
id: u8,
typ: u8,
data: &'a [u8],
},
}
#[derive(Debug)]
pub struct LicenseBuilder<'a> {
licenses: &'a mut Licenses,
}
#[derive(Debug)]
pub struct LicenseBlockBuilder<'a, 'b> {
builder: &'b mut LicenseBuilder<'a>,
/// The start offset for the new block
offset: usize,
typ: LicenseBlockType,
}
type LicenseTimeBounds = (OffsetDateTime, OffsetDateTime);
impl Licenses {
pub fn new() -> Self { Self::default() }
/// Parse a license but ignore expired licenses.
///
/// This is useful for tests but should not be used otherwise.
pub fn parse_ignore_expired(data: Vec<u8>) -> Result<Self> { Self::parse_internal(data, false) }
pub fn parse(data: Vec<u8>) -> Result<Self> { Self::parse_internal(data, true) }
pub fn parse_internal(data: Vec<u8>, check_expired: bool) -> Result<Self> {
let version = data[0];
if version != 0 && version != 1 {
return Err(Error::UnsupportedVersion(version));
}
// Read licenses
let mut blocks = Vec::new();
let now = OffsetDateTime::now_utc();
let mut offset = 1;
let mut bounds = None;
while data.len() > offset {
if blocks.len() >= 8 {
// Accept only 8 blocks
return Err(Error::TooManyBlocks(blocks.len()));
}
// Read next license
let (license, b) = Self::parse_block(&data[offset..], check_expired, now, bounds)?;
offset += license.len;
bounds = Some(b);
blocks.push(license);
}
Ok(Licenses { data, blocks })
}
fn parse_block(
data: &[u8], check_expired: bool, now: OffsetDateTime, bounds: Option<LicenseTimeBounds>,
) -> Result<(License, LicenseTimeBounds)> {
let license = License::parse(data)?;
let license_data = &data[..license.len];
// Check if the certificate is valid
let new_bounds = (
license.get_not_valid_before(license_data)?,
license.get_not_valid_after(license_data)?,
);
if new_bounds.0 > now && check_expired {
return Err(Error::Expired { start: new_bounds.0, end: new_bounds.1 });
}
if new_bounds.1 < now && check_expired {
return Err(Error::Expired { start: new_bounds.0, end: new_bounds.1 });
}
if let Some((start, end)) = bounds {
// The inner license must not have wider bounds
if new_bounds.0 < start || new_bounds.1 > end {
return Err(Error::Bounds {
outer_start: start,
outer_end: end,
inner_start: new_bounds.0,
inner_end: new_bounds.1,
});
}
}
Ok((license, new_bounds))
}
pub fn derive_public_key(&self, root: EccKeyPubEd25519) -> Result<EdwardsPoint> {
let mut last_round = root.0.decompress().ok_or(Error::InvalidRootKey)?;
let mut offset = 1;
trace!("Deriving public key for license");
for l in &self.blocks {
trace!(current_key = %HexSlice((&last_round.compress().0) as &[u8]));
last_round = l.derive_public_key(&self.data[offset..offset + l.len], &last_round)?;
offset += l.len;
}
trace!(
final_key = %HexSlice((&last_round.compress().0) as &[u8]),
"Finished deriving public key"
);
Ok(last_round)
}
/// Derive the private key of this license, starting with a specific block.
///
/// The keys which are stored inside the licenses from the starting block on
/// have to be private keys.
///
/// # Arguments
///
/// `starting_block`: The index of the first block for the key computation.
/// `first_key`: The starting private key (the key of a parent block or the
/// root private key).
///
/// # Panics
///
/// Panics if `starting_block` is not a valid license block index.
pub fn derive_private_key(
&self, starting_block: usize, first_key: EccKeyPrivEd25519,
) -> Result<EccKeyPrivEd25519> {
let mut res = first_key;
let mut offset = 1;
for (i, l) in self.blocks.iter().enumerate() {
if i >= starting_block {
res = l.derive_private_key(&self.data[offset..offset + l.len], &res)?;
}
offset += l.len;
}
Ok(res)
}
pub fn build<F: FnOnce(LicenseBuilder)>(mut self, f: F) -> Result<Self> {
let len = self.data.len();
f(LicenseBuilder { licenses: &mut self });
// Parse new blocks
let now = OffsetDateTime::now_utc();
let mut offset = len;
let mut bounds = self
.blocks
.last()
.map(|b| {
let b_offset = len - b.len;
let b_data = &self.data[b_offset..len];
Ok((b.get_not_valid_before(b_data)?, b.get_not_valid_after(b_data)?))
})
.transpose()?;
while self.data.len() > offset {
if self.blocks.len() >= 8 {
// Accept only 8 blocks
return Err(Error::TooManyBlocks(self.blocks.len()));
}
// Read next license
let (license, b) = Self::parse_block(&self.data[offset..], false, now, bounds)?;
offset += license.len;
bounds = Some(b);
self.blocks.push(license);
}
Ok(self)
}
pub fn is_valid(&self) -> Result<()> {
let mut offset = 1;
for b in &self.blocks {
b.is_valid(&self.data[offset..offset + b.len])?;
offset += b.len;
}
Ok(())
}
}
impl Default for Licenses {
fn default() -> Self { Self { data: vec![1], blocks: Default::default() } }
}
impl fmt::Debug for Licenses {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Licenses ")?;
let mut offset = 1;
f.debug_list()
.entries(self.blocks.iter().map(|b| {
let o = offset;
offset += b.len;
DebugLicense(b, &self.data[o..o + b.len])
}))
.finish()?;
Ok(())
}
}
impl License {
/// Parse license and return read length.
pub fn parse(data: &[u8]) -> Result<Self> {
let len = data.len();
if data.len() < BLOCK_MIN_LEN {
return Err(Error::TooShort(len, "less than minimum block length"));
}
if data[0] != 0 {
return Err(Error::WrongKeyKind(data[0]));
}
let typ_i = data[BLOCK_TYPE_OFFSET];
let typ = LicenseBlockType::from_u8(typ_i).ok_or(Error::UnknownBlockType(typ_i))?;
let data = &data[BLOCK_MIN_LEN..];
let (inner, extra_len) = match typ {
LicenseBlockType::Intermediate => {
if data.len() < 5 {
return Err(Error::TooShort(
len,
"less than minimum length of intermediate license",
));
}
// 4 byte unknown
// Issuer string
let len = if let Some(len) = data[4..].iter().position(|&b| b == 0) {
len
} else {
return Err(Error::NonterminatedString);
};
(InnerLicense::Other, 5 + len)
}
LicenseBlockType::Server => {
if data.len() < 6 {
return Err(Error::TooShort(
len,
"less than minimum length of TS3 server license",
));
}
// 1 byte server license type
// 4 byte max clients
// Issuer string
let len = if let Some(len) = data[5..].iter().position(|&b| b == 0) {
len
} else {
return Err(Error::NonterminatedString);
};
(InnerLicense::Other, 6 + len)
}
LicenseBlockType::Ts5Server => {
if data.len() < 2 {
return Err(Error::TooShort(
len,
"less than minimum length of TS5 server license",
));
}
// 1 byte server license type
// Property count and properties
let property_count = data[1];
let mut pos = 2;
let properties = (0..property_count)
.map(|_| {
let p = pos - 2;
if pos >= data.len() {
return Err(Error::TooShort(len, "missing TS5 license property"));
}
let len = usize::from(data[pos]);
pos += 1;
if pos + len >= data.len() {
return Err(Error::TooShort(len, "cut off TS5 license property"));
}
pos += len;
Ok(p)
})
.collect::<Result<_>>()?;
(InnerLicense::Ts5Server { properties }, pos)
}
LicenseBlockType::Ephemeral => (InnerLicense::Other, 0),
_ => {
return Err(Error::UnknownBlockType(typ_i));
}
};
Ok(License { len: BLOCK_MIN_LEN + extra_len, private_key: None, inner })
}
pub fn get_type(&self, data: &[u8]) -> Result<LicenseBlockType> {
let typ_i = data[BLOCK_TYPE_OFFSET];
LicenseBlockType::from_u8(typ_i).ok_or(Error::UnknownBlockType(typ_i))
}
pub fn get_public_key(&self, data: &[u8]) -> Result<EdwardsPoint> {
let k = EccKeyPubEd25519::from_bytes(data[1..33].try_into().unwrap());
k.0.decompress().ok_or(Error::InvalidPublicKey)
}
fn get_timestamp(&self, data: &[u8], block_offset: usize) -> Result<OffsetDateTime> {
let num: u32 = (&data[block_offset..]).read_be().map_err(Error::Deserialize)?;
OffsetDateTime::from_unix_timestamp(i64::from(num) + TIMESTAMP_OFFSET)
.map_err(Error::DeserializeDate)
}
pub fn get_not_valid_before(&self, data: &[u8]) -> Result<OffsetDateTime> {
self.get_timestamp(data, BLOCK_NOT_VALID_BEFORE_OFFSET)
}
pub fn get_not_valid_after(&self, data: &[u8]) -> Result<OffsetDateTime> {
self.get_timestamp(data, BLOCK_NOT_VALID_AFTER_OFFSET)
}
pub fn get_license_type(&self, data: &[u8]) -> Result<LicenseType> {
if ![LicenseBlockType::Server, LicenseBlockType::Ts5Server].contains(&self.get_type(data)?)
{
return Err(Error::NoSuchProperty("license type"));
}
LicenseType::from_u8(data[BLOCK_MIN_LEN])
.ok_or(Error::UnknownLicenseType(data[BLOCK_MIN_LEN]))
}
pub fn get_issuer<'a>(&self, data: &'a [u8]) -> Result<&'a str> {
let typ = self.get_type(data)?;
if typ == LicenseBlockType::Ts5Server {
// Search in properties
let res = self
.get_properties(data)?
.find_map(|p| if let Ok(LicenseProperty::Issuer(i)) = p { Some(i) } else { None })
.ok_or(Error::NoSuchProperty("issuer"));
return res;
}
let offset = BLOCK_MIN_LEN
+ match typ {
LicenseBlockType::Intermediate => 4,
LicenseBlockType::Website | LicenseBlockType::Code => 0,
LicenseBlockType::Server => 5,
_ => return Err(Error::NoSuchProperty("issuer")),
};
let len = match typ {
LicenseBlockType::Intermediate
| LicenseBlockType::Website
| LicenseBlockType::Code
| LicenseBlockType::Server => self.len - offset - 1,
_ => return Err(Error::NoSuchProperty("issuer")),
};
str::from_utf8(&data[offset..offset + len]).map_err(Error::DeserializeString)
}
pub fn get_max_clients(&self, data: &[u8]) -> Result<u32> {
let typ = self.get_type(data)?;
if typ == LicenseBlockType::Ts5Server {
// Search in properties
let res = self
.get_properties(data)?
.find_map(
|p| if let Ok(LicenseProperty::MaxClients(i)) = p { Some(i) } else { None },
)
.ok_or(Error::NoSuchProperty("max clients"));
return res;
}
let offset = BLOCK_MIN_LEN
+ match typ {
LicenseBlockType::Intermediate => 0,
LicenseBlockType::Server => 1,
_ => return Err(Error::NoSuchProperty("max clients")),
};
(&data[offset..offset + 4]).read_be().map_err(Error::Deserialize)
}
pub fn get_properties<'a: 'b, 'b>(
&'b self, data: &'a [u8],
) -> Result<impl Iterator<Item = Result<LicenseProperty<'a>>> + 'b> {
if let InnerLicense::Ts5Server { properties } = &self.inner {
Ok(properties.iter().map(move |p| {
let o = BLOCK_MIN_LEN + 2 + p;
let len = data[o];
let len_usize = len as usize;
let id = data[o + 1];
let typ = data[o + 2];
// Check length
if let Some(expected) = match typ {
// String, check that it is null-terminated
0 => {
if data[o + len_usize] != 0 {
return Err(Error::NonterminatedString);
}
None
}
1 | 3 => Some(4),
2 | 4 => Some(8),
_ => None,
} {
if len != expected {
return Err(Error::WrongPropertyLength { id, typ, expected, actual: len });
}
}
match id {
1 => {
if typ != 1 {
return Err(Error::WrongPropertyType { id, expected: 1, actual: typ });
}
Ok(LicenseProperty::Unknown1(
(&data[o + 3..o + 3 + 4]).read_be().map_err(Error::Deserialize)?,
))
}
2 => {
if typ != 0 {
return Err(Error::WrongPropertyType { id, expected: 0, actual: typ });
}
let s = str::from_utf8(&data[o + 3..o + len_usize])
.map_err(Error::DeserializeString)?;
Ok(LicenseProperty::Issuer(s))
}
3 => {
if typ != 1 {
return Err(Error::WrongPropertyType { id, expected: 1, actual: typ });
}
Ok(LicenseProperty::MaxClients(
(&data[o + 3..o + 3 + 4]).read_be().map_err(Error::Deserialize)?,
))
}
_ => {
Ok(LicenseProperty::Unknown { id, typ, data: &data[o + 3..o + len_usize] })
}
}
}))
} else {
Err(Error::NoSuchProperty("properties"))
}
}
/// Get the private key from the hash of this license block.
pub fn get_hash_key(&self, data: &[u8]) -> Scalar {
// Make a valid private key from the hash
let mut hash_key = Sha512::digest(&data[1..]);
hash_key[0] &= 248;
hash_key[31] &= 63;
hash_key[31] |= 64;
Scalar::from_bytes_mod_order(hash_key.as_slice()[..32].try_into().unwrap())
}
pub fn derive_public_key(
&self, data: &[u8], parent_key: &EdwardsPoint,
) -> Result<EdwardsPoint> {
let pub_key = self.get_public_key(data)?;
let hash_key = self.get_hash_key(data);
Ok(pub_key * hash_key + parent_key)
}
/// Derive the private key of this license block.
///
/// The key which is stored inside this license has to be a private key.
///
/// # Arguments
///
/// `parent_key`: The resulting private key of the previous block.
pub fn derive_private_key(
&self, data: &[u8], parent_key: &EccKeyPrivEd25519,
) -> Result<EccKeyPrivEd25519> {
let priv_key = if let Some(k) = &self.private_key {
&k.0
} else {
return Err(Error::NoPrivateKey);
};
let hash_key = self.get_hash_key(data);
Ok(EccKeyPrivEd25519(priv_key * hash_key + parent_key.0))
}
/// Check if this is a valid license.
///
/// Does some sanity checking on fields. Does not need to be called for correctness.
pub fn is_valid(&self, data: &[u8]) -> Result<()> {
self.get_public_key(data)?;
self.get_not_valid_before(data)?;
self.get_not_valid_after(data)?;
if let Err(e) = self.get_license_type(data) {
if !matches!(e, Error::NoSuchProperty(_)) {
return Err(e);
}
}
if let Err(e) = self.get_issuer(data) {
if !matches!(e, Error::NoSuchProperty(_)) {
return Err(e);
}
}
match self.get_properties(data) {
Ok(ps) => {
for p in ps {
p?;
}
}
Err(e) => {
if !matches!(e, Error::NoSuchProperty(_)) {
return Err(e);
}
}
}
Ok(())
}
}
impl fmt::Debug for DebugLicense<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let from = self
.0
.get_not_valid_before(self.1)
.ok()
.and_then(|d| d.format(&Rfc3339).ok())
.unwrap_or_else(|| "error".to_string());
let to = self
.0
.get_not_valid_after(self.1)
.ok()
.and_then(|d| d.format(&Rfc3339).ok())
.unwrap_or_else(|| "error".to_string());
let mut d = f.debug_struct("License");
let typ = self.0.get_type(self.1).unwrap();
d.field("type", &typ);
if let Some(key) = &self.0.private_key {
d.field("private_key", key);
}
d.field("not_valid_before", &from).field("not_valid_after", &to);
match typ {
LicenseBlockType::Intermediate => {
if let Ok(num) = self.0.get_max_clients(self.1) {
d.field("data", &num);
} else {
d.field("data", &"error");
}
}
LicenseBlockType::Website | LicenseBlockType::Code => {
if let Ok(issuer) = self.0.get_issuer(self.1) {
d.field("issuer", &issuer);
} else {
d.field("issuer", &"error");
}
}
LicenseBlockType::Server => {
if let Ok(license_type) = self.0.get_license_type(self.1) {
d.field("license_type", &license_type);
} else {
d.field("license_type", &"error");
}
if let Ok(issuer) = self.0.get_issuer(self.1) {
d.field("issuer", &issuer);
} else {
d.field("issuer", &"error");
}
if let Ok(max_clients) = self.0.get_max_clients(self.1) {
d.field("max_clients", &max_clients);
} else {
d.field("max_clients", &"error");
}
}
LicenseBlockType::Ts5Server => {
if let Ok(props) =
self.0.get_properties(self.1).and_then(|ps| ps.collect::<Result<Vec<_>>>())
{
d.field("properties", &props);
} else {
d.field("properties", &"error");
}
}
LicenseBlockType::Ephemeral => {}
}
d.finish()?;
Ok(())
}
}
impl LicenseBlockType {
fn min_len(&self) -> usize {
BLOCK_MIN_LEN
+ match self {
Self::Intermediate => 5,
Self::Website | Self::Code => 1,
Self::Server => 6,
Self::Ts5Server => 2,
Self::Ephemeral => 0,
}
}
}
impl<'a> LicenseBuilder<'a> {
pub fn add_block<'b>(&'b mut self, typ: LicenseBlockType) -> LicenseBlockBuilder<'a, 'b> {
let len = self.licenses.data.len();
self.licenses.data.resize(len + typ.min_len(), 0);
self.licenses.data[len + BLOCK_TYPE_OFFSET] = typ.to_u8().unwrap();
LicenseBlockBuilder { builder: self, offset: len, typ }
}
}
impl LicenseBlockBuilder<'_, '_> {
pub fn public_key(&mut self, key: &EccKeyPubEd25519) -> &mut Self {
let o = self.offset + 1;
self.builder.licenses.data[o..o + 32].copy_from_slice(&key.0.0);
self
}
fn write_timestamp(&mut self, offset: usize, time: OffsetDateTime) -> &mut Self {
let o = self.offset + offset;
Cursor::new(&mut self.builder.licenses.data[o..o + 4])
.write_be((time.unix_timestamp() - TIMESTAMP_OFFSET) as u32)
.unwrap();
self
}
pub fn not_valid_before(&mut self, time: OffsetDateTime) -> &mut Self {
self.write_timestamp(BLOCK_NOT_VALID_BEFORE_OFFSET, time)
}
pub fn not_valid_after(&mut self, time: OffsetDateTime) -> &mut Self {
self.write_timestamp(BLOCK_NOT_VALID_AFTER_OFFSET, time)
}
/// Only valid for Server and Ts5Server license types
pub fn server_license_type(&mut self, typ: LicenseType) -> &mut Self {
if ![LicenseBlockType::Server, LicenseBlockType::Ts5Server].contains(&self.typ) {
panic!(
"Setting the license type is only allowed for Server and Ts5Server license types, \
but this is a {:?}",
self.typ
);
}
self.builder.licenses.data[self.offset + BLOCK_MIN_LEN] = typ.to_u8().unwrap();
self
}
/// Add a property in a TS5 license block.
///
/// `len` is the length of the content, excluding id, type and length field.
/// Return the byte offset to where the contents of the property starts.
fn ts5_add_property(&mut self, id: u8, typ: u8, len: usize) -> usize {
let o = self.builder.licenses.data.len();
self.builder.licenses.data.resize(o + len + 3, 0);
// Increment property count
self.builder.licenses.data[self.offset + BLOCK_MIN_LEN + 1] += 1;
self.builder.licenses.data[o] = u8::try_from(len).unwrap() + 2;
self.builder.licenses.data[o + 1] = id;
self.builder.licenses.data[o + 2] = typ;
o + 3
}
/// Only valid for Intermediate, Server and Ts5Server license types
pub fn max_clients(&mut self, max_clients: u32) -> &mut Self {
let o = if self.typ == LicenseBlockType::Ts5Server {
self.ts5_add_property(3, 1, 4)
} else {
self.offset
+ BLOCK_MIN_LEN
+ match self.typ {
LicenseBlockType::Intermediate => 0,
LicenseBlockType::Server => 1,
_ => panic!(
"Setting max clients is only allowed for Intermediate, Server and \
Ts5Server license types, but this is a {:?}",
self.typ
),
}
};
Cursor::new(&mut self.builder.licenses.data[o..o + 4]).write_be(max_clients).unwrap();
self
}
/// Only valid for Intermediate, Server and Ts5Server license types
pub fn issuer(&mut self, issuer: &str) -> &mut Self {
// Check that the issuer does not contain null bytes
assert!(
!issuer.contains('\0'),
"The issuer is written as a null-terminated string so it cannot contain null bytes"
);
let o = if self.typ == LicenseBlockType::Ts5Server {
self.ts5_add_property(2, 0, issuer.len() + 1)
} else {
if ![LicenseBlockType::Intermediate, LicenseBlockType::Server].contains(&self.typ) {
panic!(
"Setting the issuer is only allowed for Intermediate, Server and Ts5Server \
license types, but this is a {:?}",
self.typ
);
}
// Check that no issuer was written so far
assert!(
self.builder.licenses.data.len() - self.offset == self.typ.min_len(),
"Only a single issuer can be written into a license block"
);
let o = self.builder.licenses.data.len();
self.builder.licenses.data.resize(o + issuer.len(), 0);
o - 1
};
self.builder.licenses.data[o..o + issuer.len()].copy_from_slice(issuer.as_bytes());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use base64::prelude::*;
#[test]
fn parse_standard_license() {
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==").unwrap()).unwrap();
}
#[test]
fn parse_standard_license_expired() {
assert!(Licenses::parse(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0\
Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAACiIBip9hQaK6P3QhwOJs/BkPn0i\
oyIDPaNgzJ6M8x0kiAJf4hxCYAxMQ==").unwrap()).is_err());
}
#[test]
fn parse_aal_license() {
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQCvbHFTQDY/terPeilrp/ECU9xCH5U3xC92lY\
TNaY/0KQAJFueAazbsgAAAACVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAABhl9gwla/UJ\
p2Eszst9TRVXO/PeE6a6d+CTI6Pg7OEVgAJc5CrL4Nh8gAAACRUZWFtU3BlYWsgc3lz\
dGVtcyBHbWJIAACvTQIgpv6zmLZq3znh7ygmOSokGFkFjz4bTigrOnetrgIJdIIACdS\
/gAYAAAAAU29zc2VuU3lzdGVtcy5iaWQAADY7+uV1CQ1niOvYSdGzsu83kPTNWijovr\
3B78eHGeePIAm98vQJvpu0").unwrap()).unwrap();
}
#[test]
fn parse_ts5_server_license_long() {
// Slightly older format having a block with a Ts5 license block in it
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQDVsMGbcrMmGif1vSXPWWXNW2CB5\
Fe9oZ/2uxP29j1EXQAQSfiAazbsgAAAASVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAAALB6Qfbe\
JyN+9foJhe+/KPFwyU+i++4MAA0q1/WCnizwARRuEPN1aeBQAAASBUZWFtU3BlYWsgc3lzdGV\
tcyBHbWJIAADrhbI5gUR3thsS7FqKV5P5h7djnwMSJfF2vi58lm1VcwgRUFMAE0P7gAUCGQIA\
VGVhbVNwZWFrIFN5c3RlbXMgR21iSAAGAwEAAAAFAAf2KhQ7WLjOvwwY0Bi7LxAcWmQeT+LQt\
uaOzjhYoA+YIBGNq1kRjlQZ").unwrap()).unwrap();
}
#[test]
fn parse_ts5_server_license_long2() {
// Also slightly older, has 3 properties
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQDVsMGbcrMmGif1vSXPWWXNW2CB5\
Fe9oZ/2uxP29j1EXQAQSfiAazbsgAAAASVUZWFtU3BlYWsgU3lzdGVtcyBHbWJIAAAtXG5p2n\
iXlDfpVAGuD88w8hetKYL4vqHRkB5xB8ASRwAR2t/MN+ttjAAAASBUZWFtU3BlYWsgc3lzdGV\
tcyBHbWJIAAAdZYGtwkeZFhzqnoV1uk+Tcphe8GgcqiPVtELF9y4wOAgR4qmAF4jnAAkDGQIA\
VGVhbVNwZWFrIFN5c3RlbXMgR21iSAAGAwEAAAAFBgEBAAGGoADzyFvD+9G6uhIxmh0jK+Uo8\
z8fYGJVH81vWFULDS0l8yATKe4cEyqW3A==").unwrap()).unwrap();
}
#[test]
fn parse_ts5_server_license_single_block_with_issuer() {
Licenses::parse_ignore_expired(
BASE64_STANDARD
.decode(
"AQBgjAAqtcBUrw5futTtkl3+EM3OW4Lal6OTPlwuv4xV/\
gIRFlEAG0NlAAcAAAAgQW5vbnltb3VzAACKNY+/\
9qCbonCSxG18vBb7y7zPIgDdjTmcZoAHHclnJSATPa69Ez5XfQ==",
)
.unwrap(),
)
.unwrap();
}
#[test]
fn parse_ts5_server_license_single_block() {
// Only a single server block and the ephemeral block
Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQAuio9ZxThXKE+hmzQyzBRedysp9\
79JBTv2xP3s2oCkiAgQI70AE+YkAAcBBgMBAAAABQBoazM313063zaipPTH06zrXc91ch3huB\
YrUET9sEbz1CATKgK8EyqrfA==").unwrap()).unwrap();
}
#[test]
fn derive_public_key() {
let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==").unwrap()).unwrap();
let derived_key =
licenses.derive_public_key(EccKeyPubEd25519::from_bytes(crate::ROOT_KEY)).unwrap();
let expected_key = [
0x40, 0xe9, 0x50, 0xc4, 0x61, 0xba, 0x18, 0x3a, 0x1e, 0xb7, 0xcb, 0xb1, 0x9a, 0xc3,
0xd8, 0xd9, 0xc4, 0xd5, 0x24, 0xdb, 0x38, 0xf7, 0x2d, 0x3d, 0x66, 0x75, 0x77, 0x2a,
0xc5, 0x9c, 0xc5, 0xc6,
];
let derived_key = derived_key.compress().0;
assert_eq!(derived_key, expected_key);
}
}
+111
View File
@@ -0,0 +1,111 @@
use std::fmt::Debug;
use std::str;
use tracing::{debug, debug_span, Span};
use tsproto_packets::packets::{InUdpPacket, OutUdpPacket, PacketType};
use tsproto_packets::HexSlice;
use crate::connection::{Connection, Event};
fn prepare_span(is_client: bool, incoming: bool) -> Span {
let dir = if incoming {
if !cfg!(windows) { "\x1b[1;32mIN\x1b[0m" } else { "IN" }
} else if !cfg!(windows) {
"\x1b[1;31mOUT\x1b[0m"
} else {
"OUT"
};
let to = if is_client { "S" } else { "C" };
debug_span!("packet", to, %dir)
}
pub fn log_udp_packet(is_client: bool, incoming: bool, packet: &InUdpPacket) {
let _span = prepare_span(is_client, incoming).entered();
debug!(header = ?packet.0.header(), content = %HexSlice(packet.0.content()), "UdpPacket");
}
pub fn log_out_udp_packet(is_client: bool, incoming: bool, packet: &OutUdpPacket) {
let _span = prepare_span(is_client, incoming).entered();
debug!(
generation = packet.generation_id(),
header = ?packet.data().header(),
content = %HexSlice(packet.data().content()),
"UdpPacket"
);
}
pub fn log_packet<P: Debug>(is_client: bool, incoming: bool, packet: &P) {
// packet.header.c_id is not set for newly created packets so we cannot
// detect if a packet is incoming or not.
let _span = prepare_span(is_client, incoming).entered();
debug!(content = ?packet, "Packet");
}
pub fn log_command(is_client: bool, incoming: bool, p_type: PacketType, cmd: &str) {
// packet.header.c_id is not set for newly created packets so we cannot
// detect if a packet is incoming or not.
let _span = prepare_span(is_client, incoming).entered();
if p_type == PacketType::Command {
debug!(content = cmd, "Command");
} else {
debug!(content = cmd, "CommandLow");
}
}
/// Print the content of all packets
///
/// 0 - Print commands
/// 1 - Print packets
/// 2 - Print udp packets
pub fn add_logger_with_verbosity(verbosity: u8, con: &mut Connection) {
let log_commands = verbosity > 0;
let log_packets = verbosity > 1;
let log_udp_packets = verbosity > 2;
add_logger(log_commands, log_packets, log_udp_packets, con);
}
pub fn add_logger(
log_commands: bool, log_packets: bool, log_udp_packets: bool, con: &mut Connection,
) {
if log_commands || log_packets || log_udp_packets {
let is_client = con.is_client;
let listener = Box::new(move |event: &Event| match event {
Event::ReceiveUdpPacket(packet) => {
if log_udp_packets {
log_udp_packet(is_client, true, packet);
}
}
Event::ReceivePacket(packet) => {
if log_packets {
log_packet(is_client, true, packet);
} else if log_commands {
let p_type = packet.header().packet_type();
if p_type.is_command() {
if let Ok(s) = str::from_utf8(packet.content()) {
log_command(is_client, true, p_type, s);
}
}
}
}
Event::SendUdpPacket(packet) => {
if log_udp_packets {
log_out_udp_packet(is_client, false, packet);
}
}
Event::SendPacket(packet) => {
if log_packets {
log_packet(is_client, false, &packet.packet());
} else if log_commands {
let p_type = packet.header().packet_type();
if p_type.is_command() {
if let Ok(s) = str::from_utf8(packet.content()) {
log_command(is_client, false, p_type, s);
}
}
}
}
});
con.event_listeners.push(listener);
}
}
+461
View File
@@ -0,0 +1,461 @@
use std::io::Cursor;
use std::task::Context;
use num_traits::ToPrimitive;
use omnom::WriteExt;
use tracing::warn;
use tsproto_packets::packets::*;
use crate::algorithms as algs;
use crate::connection::{Connection, Event, StreamItem};
use crate::resend::{PartialPacketId, Resender};
use crate::{Error, Result, MAX_FRAGMENTS_LENGTH, MAX_QUEUE_LEN};
/// Encodes outgoing packets.
///
/// This part does the compression, encryption and fragmentation.
#[derive(Clone, Debug, Default)]
pub struct PacketCodec {
/// The next packet id that should be sent.
///
/// This list is indexed by the `PacketType`, `PacketType::Init` is an
/// invalid index.
pub outgoing_p_ids: [PartialPacketId; 8],
/// Used for incoming out-of-order packets.
///
/// Only used for `Command` and `CommandLow` packets.
pub receive_queue: [Vec<Vec<u8>>; 2],
/// Used for incoming fragmented packets.
///
/// Contains the accumulated data from fragmented packets, the header of the
/// first packet is at the beginning, all other headers are stripped away.
/// Only used for `Command` and `CommandLow` packets.
pub fragmented_queue: [Option<Vec<u8>>; 2],
/// The next packet id that is expected.
///
/// Works like the `outgoing_p_ids`.
pub incoming_p_ids: [PartialPacketId; 8],
}
impl PacketCodec {
/// Handle a packet for a specific connection.
///
/// This part does the defragmentation, decryption and decompression.
pub fn handle_udp_packet(
con: &mut Connection, cx: &mut Context, mut packet_data: Vec<u8>,
) -> Result<()> {
let mut ack = false;
let dir = if con.is_client { Direction::S2C } else { Direction::C2S };
let packet = InPacket::new(dir, &packet_data);
let p_type = packet.header().packet_type();
let type_i = p_type.to_usize().unwrap();
let id = packet.header().packet_id();
let (in_recv_win, gen_id, cur_next, limit) = con.in_receive_window(p_type, id);
con.resender.handle_loss_incoming(&packet, in_recv_win, cur_next);
if let Some(params) = &con.params {
if p_type == PacketType::Init {
con.stream_items.push_back(StreamItem::Error(Error::UnexpectedInitPacket));
return Ok(());
}
if !con.is_client {
let c_id = packet.header().client_id().unwrap();
// Accept any client id for the first few acks
let is_first_ack = gen_id == 0 && id <= 3 && p_type == PacketType::Ack;
if c_id != params.c_id && !is_first_ack {
con.stream_items.push_back(StreamItem::Error(Error::WrongClientId(c_id)));
return Ok(());
}
}
}
// Ignore range for acks and audio packets
if [PacketType::Ack, PacketType::AckLow, PacketType::Voice, PacketType::VoiceWhisper]
.contains(&p_type)
|| in_recv_win
{
if !packet.header().flags().contains(Flags::UNENCRYPTED) {
if p_type == PacketType::Ack && id == 1 && con.is_client {
// This is the ack packet for the clientinit, we take the
// initserver as ack instead.
return Ok(());
}
// If it is the first ack packet of a client, try to fake
// decrypt it.
let new_content = if (p_type == PacketType::Ack && id <= 1 && con.is_client)
|| con.params.is_none()
{
match algs::decrypt_fake(&packet).or_else(|_| {
if let Some(params) = &mut con.params {
// Decrypt the packet
algs::decrypt(&packet, gen_id, &params.shared_iv, &mut params.key_cache)
} else {
// Failed to fake decrypt the packet
Err(Error::WrongMac { p_type, generation_id: gen_id, packet_id: id })
}
}) {
Ok(r) => r,
Err(e) => {
con.stream_items.push_back(StreamItem::Error(e));
return Ok(());
}
}
} else if let Some(params) = &mut con.params {
// Decrypt the packet
match algs::decrypt(&packet, gen_id, &params.shared_iv, &mut params.key_cache) {
Ok(r) => r,
Err(e) => {
con.stream_items.push_back(StreamItem::Error(e));
return Ok(());
}
}
} else {
// Failed to fake decrypt the packet
con.stream_items.push_back(StreamItem::Error(Error::WrongMac {
p_type,
generation_id: gen_id,
packet_id: id,
}));
return Ok(());
};
let start = packet.header().data().len();
packet_data[start..].copy_from_slice(&new_content);
} else if algs::must_encrypt(p_type) {
// Check if it is ok for the packet to be unencrypted
con.stream_items.push_back(StreamItem::Error(Error::UnallowedUnencryptedPacket));
return Ok(());
}
let packet = InPacket::new(dir, &packet_data);
match p_type {
PacketType::Command | PacketType::CommandLow => {
ack = true;
let commands = Self::handle_command_packet(con, packet_data)?;
// Be careful with command packets, they are guaranteed to
// be in the right order now.
for c in commands {
// Send again
let packet = InPacket::new(dir, &c);
let event = Event::ReceivePacket(&packet);
con.send_event(&event);
let item = match InCommandBuf::try_new(dir, c) {
Ok(c) => {
// initivexpand2 is the ack for the last init packet
if con.is_client
&& c.data().packet().content().starts_with(b"initivexpand2 ")
{
Resender::ack_packet(con, cx, PacketType::Init, 4);
} else if con.is_client
&& c.data().packet().content().starts_with(b"initserver ")
{
// initserver acks clientinit
Resender::ack_packet(con, cx, PacketType::Command, 2);
} else if !con.is_client
&& c.data().packet().content().starts_with(b"clientek ")
{
// clientek acks initivexpand2
Resender::ack_packet(con, cx, PacketType::Command, 0);
}
StreamItem::Command(c)
}
Err(e) => return Err(Error::PacketParse("command", e)),
};
con.stream_items.push_back(item);
}
}
_ => {
if p_type == PacketType::Ping {
ack = true;
}
// Update packet ids
let in_ids = &mut con.codec.incoming_p_ids;
if p_type != PacketType::Init {
let (id, next_gen) = id.overflowing_add(1);
let generation_id = if next_gen { gen_id + 1 } else { gen_id };
in_ids[type_i] = PartialPacketId { generation_id, packet_id: id };
}
match packet.ack_packet() {
Ok(Some(ack_id)) => {
// Remove command packet from send queue if the fitting ack is received.
let p_type = if p_type == PacketType::Ack {
PacketType::Command
} else if p_type == PacketType::AckLow {
PacketType::CommandLow
} else if p_type == PacketType::Pong {
PacketType::Ping
} else {
p_type
};
Resender::ack_packet(con, cx, p_type, ack_id);
}
Ok(None) => {}
Err(e) => {
con.stream_items.push_back(StreamItem::Error(Error::CreateAck(e)));
return Ok(());
}
}
// Send event after handling acks
let event = Event::ReceivePacket(&packet);
con.send_event(&event);
if p_type.is_voice() {
con.stream_items.push_back(match InAudioBuf::try_new(dir, packet_data) {
Ok(r) => StreamItem::Audio(r),
Err(e) => StreamItem::Error(Error::PacketParse("audio", e)),
});
} else if p_type == PacketType::Init {
con.stream_items.push_back(if con.is_client {
match InS2CInitBuf::try_new(dir, packet_data) {
Ok(r) => StreamItem::S2CInit(r),
Err(e) => StreamItem::Error(Error::PacketParse("s2cinit", e)),
}
} else {
match InC2SInitBuf::try_new(dir, packet_data) {
Ok(r) => StreamItem::C2SInit(r),
Err(e) => StreamItem::Error(Error::PacketParse("c2sinit", e)),
}
});
}
}
}
} else {
// Send an ack for the case when it was lost
if p_type == PacketType::Command || p_type == PacketType::CommandLow {
ack = true;
con.resender.handle_loss_resend_ack();
}
con.stream_items.push_back(StreamItem::Error(Error::NotInReceiveWindow {
id,
next: cur_next,
limit,
p_type,
}));
}
// Send ack
if ack {
con.send_ack_packet(cx, OutAck::new(dir.reverse(), p_type, id))?;
}
Ok(())
}
/// Handle `Command` and `CommandLow` packets.
///
/// They have to be handled in the right order.
fn handle_command_packet(
con: &mut Connection, mut packet_data: Vec<u8>,
) -> Result<Vec<Vec<u8>>> {
let dir = if con.is_client { Direction::S2C } else { Direction::C2S };
let mut packet = InPacket::new(dir, &packet_data);
let header = packet.header();
let p_type = header.packet_type();
let mut id = header.packet_id();
let type_i = p_type.to_usize().unwrap();
let cmd_i = if p_type == PacketType::Command { 0 } else { 1 };
let r_queue = &mut con.codec.receive_queue[cmd_i];
let frag_queue = &mut con.codec.fragmented_queue[cmd_i];
let in_ids = &mut con.codec.incoming_p_ids[type_i];
let cur_next = in_ids.packet_id;
if cur_next == id {
// In order
let mut packets = Vec::new();
loop {
// Update next packet id
*in_ids = *in_ids + 1;
let flags = packet.header().flags();
let res_packet = if flags.contains(Flags::FRAGMENTED) {
if let Some(mut frag_queue) = frag_queue.take() {
// Last fragmented packet
frag_queue.extend_from_slice(packet.content());
let header = InPacket::new(dir, &frag_queue);
// Decompress
if header.header().flags().contains(Flags::COMPRESSED) {
let decompressed = quicklz::decompress(
&mut Cursor::new(header.content()),
crate::MAX_DECOMPRESSED_SIZE,
)
.map_err(Error::DecompressPacket)?;
let start = header.header().data().len();
frag_queue.truncate(start);
frag_queue.extend_from_slice(&decompressed);
}
Some(frag_queue)
} else {
// Enqueue
*frag_queue = Some(packet_data);
None
}
} else if let Some(frag_queue) = frag_queue {
// The packet is fragmented
if frag_queue.len() < MAX_FRAGMENTS_LENGTH {
frag_queue.extend_from_slice(packet.content());
None
} else {
return Err(Error::MaxLengthExceeded("fragment queue"));
}
} else {
// Decompress
if flags.contains(Flags::COMPRESSED) {
let decompressed = quicklz::decompress(
&mut Cursor::new(packet.content()),
crate::MAX_DECOMPRESSED_SIZE,
)
.map_err(Error::DecompressPacket)?;
let start = packet.header().data().len();
packet_data.truncate(start);
packet_data.extend_from_slice(&decompressed);
};
Some(packet_data)
};
if let Some(p) = res_packet {
packets.push(p);
}
// Check if there are following packets in the receive queue.
id = id.wrapping_add(1);
if let Some(pos) =
r_queue.iter().position(|p| InHeader::new(dir, p).packet_id() == id)
{
packet_data = r_queue.remove(pos);
packet = InPacket::new(dir, &packet_data);
} else {
break;
}
}
Ok(packets)
} else {
// Out of order
warn!(got = id, expected = cur_next, "Out of order command packet");
let (limit, next_gen) = cur_next.overflowing_add(MAX_QUEUE_LEN);
if (!next_gen && id >= cur_next && id < limit)
|| (next_gen && (id >= cur_next || id < limit))
{
r_queue.push(packet_data);
Ok(vec![])
} else {
Err(Error::MaxLengthExceeded("command queue"))
}
}
}
pub fn encode_packet(con: &mut Connection, mut packet: OutPacket) -> Result<Vec<OutUdpPacket>> {
let p_type = packet.header().packet_type();
let type_i = p_type.to_usize().unwrap();
// TODO Needed, commands should set their own flag?
if (p_type == PacketType::Command || p_type == PacketType::CommandLow) && con.is_client {
// Set newprotocol flag
packet.flags(packet.header().flags() | Flags::NEWPROTOCOL);
}
let p_id = if p_type == PacketType::Init {
PartialPacketId { generation_id: 0, packet_id: 0 }
} else {
con.codec.outgoing_p_ids[type_i]
};
// We fake encrypt the first command packet of the server (id 0) and the
// first command packet of the client (id 1, clientek).
let mut fake_encrypt = p_type == PacketType::Command
&& p_id.generation_id == 0
&& ((!con.is_client && p_id.packet_id == 0)
|| (con.is_client && p_id.packet_id == 1 && {
// Test if it is a clientek packet
packet.content().starts_with(b"clientek")
}));
// Also fake encrypt the first ack of the client, which is the response
// for the initivexpand2 packet.
fake_encrypt |= con.is_client
&& p_type == PacketType::Ack
&& p_id.generation_id == 0
&& p_id.packet_id == 0;
// Get values from parameters
let should_encrypt;
let c_id;
if let Some(params) = con.params.as_mut() {
should_encrypt = algs::should_encrypt(p_type, params.voice_encryption);
c_id = params.c_id;
} else {
should_encrypt = algs::should_encrypt(p_type, false);
if should_encrypt {
fake_encrypt = true;
}
c_id = 0;
}
// Client id for clients
if con.is_client {
packet.client_id(c_id);
}
if !should_encrypt && !fake_encrypt {
packet.flags(packet.header().flags() | Flags::UNENCRYPTED);
if let Some(params) = con.params.as_mut() {
packet.mac().copy_from_slice(&params.shared_mac);
}
}
// Compress and split packet
let packets = if p_type == PacketType::Command || p_type == PacketType::CommandLow {
algs::compress_and_split(con.is_client, packet)
} else {
// Set the inner packet id for voice packets
if con.is_client && (p_type == PacketType::Voice || p_type == PacketType::VoiceWhisper)
{
(&mut packet.content_mut()[..2])
.write_be(con.codec.outgoing_p_ids[type_i].packet_id)
.unwrap();
}
vec![packet]
};
let packets = packets
.into_iter()
.map(|mut packet| -> Result<_> {
// Get packet id
let p_id = if p_type == PacketType::Init {
PartialPacketId { generation_id: 0, packet_id: 0 }
} else {
packet.packet_id(con.codec.outgoing_p_ids[type_i].packet_id);
con.codec.outgoing_p_ids[type_i]
};
// Encrypt if necessary
if fake_encrypt {
algs::encrypt_fake(&mut packet)?;
} else if should_encrypt {
// The params are set
let params = con.params.as_mut().unwrap();
algs::encrypt(
&mut packet,
p_id.generation_id,
&params.shared_iv,
&mut params.key_cache,
)?;
}
// Increment outgoing_p_ids
let p_id = p_id + 1;
if p_type != PacketType::Init {
con.codec.outgoing_p_ids[type_i] = p_id;
}
Ok(OutUdpPacket::new(p_id.generation_id, packet))
})
.collect::<Result<Vec<_>>>()?;
Ok(packets)
}
}
+1067
View File
File diff suppressed because it is too large. Load diff
+47
View File
@@ -0,0 +1,47 @@
use std::net::IpAddr;
use crate::{Error, Result};
/// Try to approximate the not stabilized ip.is_global().
pub fn is_global_ip(ip: &IpAddr) -> bool {
if !ip.is_unspecified() && !ip.is_loopback() && !ip.is_multicast() {
match *ip {
IpAddr::V4(ref ip) => !ip.is_broadcast() && !ip.is_link_local() && !ip.is_private(),
IpAddr::V6(_) => true,
}
} else {
false
}
}
pub fn read_hex(s: &str) -> Result<Vec<u8>> {
// Detect hex format
if s.chars().nth(2) == Some(':') {
// Wireshark
Ok(s.split(':')
.map(|s| u8::from_str_radix(s, 16))
.collect::<::std::result::Result<Vec<_>, _>>()
.map_err(Error::InvalidHex)?)
} else if s.chars().nth(2) == Some(' ') {
// Wireshark
Ok(s.split(' ')
.map(|s| u8::from_str_radix(s, 16))
.collect::<::std::result::Result<Vec<_>, _>>()
.map_err(Error::InvalidHex)?)
} else if s.starts_with("0x") {
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
// Own dumps
Ok(s[2..]
.split(',')
.map(|s| u8::from_str_radix(s.trim_start_matches("0x"), 16))
.collect::<::std::result::Result<Vec<_>, _>>()
.map_err(Error::InvalidHex)?)
} else {
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
Ok(s.as_bytes()
.chunks(2)
.map(|s| u8::from_str_radix(::std::str::from_utf8(s).unwrap(), 16))
.collect::<::std::result::Result<Vec<_>, _>>()
.map_err(Error::InvalidHex)?)
}
}
+16 -2
View File
@@ -5,6 +5,20 @@ Contract between the Electron **main** process and the native protocol core
to the core directly: main forwards only the commands listed here, after checking
`cmd` against this allowlist and argument shapes.
The Rust library also exposes `runtime::spawn(CoreConfig)` for native hosts. It owns a dedicated
current-thread runtime per session; `CoreHandle::request(Command)` applies the same semantic validation
as this JSON adapter. The returned control events and bounded playback PCM are separate channels;
native capture uses `CapturedFrame` with original timestamp, generation and privacy epoch. Explicit
`shutdown()` joins the worker and releases profile/slot locks; Drop requests cancellation without
blocking the UI. Control-consumer loss/overflow ends the session rather than silently dropping state.
The desktop reference still uses this stdio protocol until the full native cutover is verified.
Capture invalidation also guards the actual deferred UDP socket send through the pinned vendored
transport. Old/expired frames cannot become valid merely by remaining in a transport retry queue.
Control events carry the emitting connection generation; playback carries it in its native envelope.
Standalone identity improvement, application-audio and hotkey APIs have explicit cancellation/ownership
boundaries; callers must not perform their blocking joins or capture work on the UI thread.
## 1. Process model
```
@@ -23,8 +37,8 @@ teamspeach-core --data-dir <ABSOLUTE_DIR> [--connection-dir <ABSOLUTE_DIR>]
`TEAMSPEACH_LOG` (`error|warn|info|debug|trace`, tracing filter syntax), default `info`.
- **stdin EOF** or `shutdown` command → graceful disconnect (if connected), then exit 0.
- Exit codes: `0` clean, `2` bad CLI arguments, `3` data dir locked/unusable, `1` fatal internal error.
- Windows dev binary: `core/target/release/teamspeach-core.exe`
(debug: `core/target/debug/teamspeach-core.exe`). Packaged: `resources/core/teamspeach-core[.exe]`.
- Windows dev binary: `target/release/teamspeach-core.exe`
(debug: `target/debug/teamspeach-core.exe`, or explicit `CARGO_TARGET_DIR`). Packaged: `resources/core/teamspeach-core[.exe]`.
The first stdout line is always:
-251
View File
@@ -1,251 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
dependencies = [
"bytemuck_derive",
]
[[package]]
name = "bytemuck_derive"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "derive_more"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
dependencies = [
"derive_more-impl",
]
[[package]]
name = "derive_more-impl"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"syn 2.0.119",
"unicode-xid",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "sonora"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250"
dependencies = [
"sonora-aec3",
"sonora-agc2",
"sonora-common-audio",
"sonora-ns",
"sonora-simd",
"tracing",
]
[[package]]
name = "sonora-aec3"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50280e31256d09f7838aff6715ed4b7640e514dc1092a1e14013c01e552380db"
dependencies = [
"sonora-common-audio",
"sonora-fft",
"sonora-simd",
]
[[package]]
name = "sonora-agc2"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a93a9fa8373a33e61a7fb441d8a9e725ac6024079d2c77a845cf6abe1790b9f"
dependencies = [
"bytemuck",
"derive_more",
"sonora-common-audio",
"sonora-fft",
"sonora-simd",
"tracing",
]
[[package]]
name = "sonora-common-audio"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc"
dependencies = [
"derive_more",
"sonora-simd",
]
[[package]]
name = "sonora-fft"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012"
[[package]]
name = "sonora-ns"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f"
dependencies = [
"sonora-fft",
]
[[package]]
name = "sonora-simd"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868"
dependencies = [
"cpufeatures",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "teamspeach-denoise"
version = "0.1.0"
dependencies = [
"sonora",
"sonora-ns",
]
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+5 -17
View File
@@ -1,34 +1,22 @@
# Microphone noise reduction for the renderer's AudioWorklet, compiled to a zero-import
# WebAssembly module (app/renderer/assets/audio/denoise.wasm) by scripts/build-denoise.mjs.
# Standalone package: not part of the core/ workspace and never linked into the native core.
# Workspace package; the root denoise profile preserves the shipped WASM build settings.
[package]
name = "teamspeach-denoise"
version = "0.1.0"
edition = "2024"
rust-version = "1.91"
publish = false
description = "TeamsPeach 48 kHz mono noise reduction (sonora WebRTC NS) as a WebAssembly module"
description = "TeamsPeach native capture DSP and reference WASM noise reduction"
[lib]
crate-type = ["cdylib"]
crate-type = ["rlib", "cdylib"]
path = "src/lib.rs"
# Exact pins: the shipped DSP must not change behind a lockfile refresh.
# sonora provides the public 48 kHz ThreeBandFilterBank (split/merge); sonora-ns the
# noise suppressor. Neither crate has cargo features; AEC3/AGC2 are compiled as sonora's
# dependencies but never constructed or called, so they are dead-stripped from the module.
# Native capture uses sonora AEC3, noise suppression and adaptive AGC2 together.
# The reference WASM exports retain the standalone sonora-ns filter-bank path.
[dependencies]
sonora = "=0.2.0"
sonora-ns = "=0.2.0"
[profile.release]
opt-level = 3
lto = true
codegen-units = 1
panic = "abort"
debug = false
strip = true
incremental = false
# Own workspace root so this crate is never absorbed into another workspace.
[workspace]
+221
View File
@@ -0,0 +1,221 @@
//! Direct, normalized 10 ms capture processing for the native audio worker.
//!
//! Sonora owns the split/filter/synthesis path. Never put `Denoiser`, another noise
//! suppressor, or OS/WebRTC AEC in front of this processor. The caller supplies the
//! actual post-gain playout mix, aligned to the capture clock, before capture processing.
//!
//! Sonora's integrated NS also enables its split-band high-pass filter. The legacy
//! noise-only `Denoiser` does not; waveform equivalence to that wrapper is not promised.
use std::{error::Error, fmt};
use sonora::{AudioProcessing, StreamConfig};
use sonora::config::{
AdaptiveDigital, Config, EchoCanceller, GainController2, NoiseSuppression,
MaxProcessingRate, NoiseSuppressionLevel, Pipeline,
};
use crate::FRAME_SAMPLES;
/// Independent processing switches; noise levels match the existing settings schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CaptureSettings {
pub echo_cancellation: bool,
/// `None` disables NS; `Some(0..=3)` means Low / Moderate / High / Very High.
pub noise_suppression: Option<u8>,
/// Enables adaptive digital AGC2, not hardware microphone-volume control.
pub automatic_gain_control: bool,
}
impl Default for CaptureSettings {
fn default() -> Self {
Self {
echo_cancellation: true,
noise_suppression: Some(1),
automatic_gain_control: true,
}
}
}
/// A rejected frame or configuration. No audio samples appear in error messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaptureError {
InvalidNoiseSuppressionLevel(u8),
/// Delay is outside Sonora's supported inclusive 0..=500 ms range.
InvalidDelay(i32),
NonFiniteInput,
NonFiniteOutput,
/// AEC capture is disallowed until the first reverse frame after creation/reset.
MissingRenderReference,
Sonora(sonora::Error),
}
impl fmt::Display for CaptureError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidNoiseSuppressionLevel(level) => {
write!(f, "invalid capture noise suppression level {level} (expected 0..=3)")
}
Self::InvalidDelay(delay) => {
write!(f, "invalid capture/render delay {delay} ms (expected 0..=500)")
}
Self::NonFiniteInput => f.write_str("capture processor rejected non-finite input"),
Self::NonFiniteOutput => f.write_str("capture processor produced non-finite output; reset required"),
Self::MissingRenderReference => f.write_str("capture processor requires a render reference"),
Self::Sonora(error) => fmt::Display::fmt(error, f),
}
}
}
impl Error for CaptureError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Sonora(error) => Some(error),
_ => None,
}
}
}
impl From<sonora::Error> for CaptureError {
fn from(error: sonora::Error) -> Self {
Self::Sonora(error)
}
}
fn configuration(settings: CaptureSettings) -> Result<Config, CaptureError> {
let noise_suppression = match settings.noise_suppression {
None => None,
Some(level) => Some(NoiseSuppression {
level: match level {
0 => NoiseSuppressionLevel::Low,
1 => NoiseSuppressionLevel::Moderate,
2 => NoiseSuppressionLevel::High,
3 => NoiseSuppressionLevel::VeryHigh,
other => return Err(CaptureError::InvalidNoiseSuppressionLevel(other)),
},
..NoiseSuppression::default()
}),
};
Ok(Config {
// Sonora defaults to 32 kHz internally; keep the fullband 48 kHz capture path.
pipeline: Pipeline {
maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz,
..Pipeline::default()
},
echo_canceller: settings.echo_cancellation.then(EchoCanceller::default),
noise_suppression,
gain_controller2: settings.automatic_gain_control.then(|| GainController2 {
// GainController2::default() alone does NOT enable adaptive gain.
adaptive_digital: Some(AdaptiveDigital::default()),
input_volume_controller: false,
..GainController2::default()
}),
..Config::default()
})
}
/// One stateful AEC3 -> NS -> adaptive AGC2 chain, with 48 kHz mono on both sides.
///
/// Construct/reset and process on the dedicated DSP worker, never in device callbacks.
/// The wrapper reuses its scratch buffers, but no allocation-free or lock-free claim
/// is made for Sonora's internal processing. Processing is not bit-identical to Chromium.
#[derive(Debug)]
pub struct CaptureProcessor {
processing: AudioProcessing,
settings: CaptureSettings,
input: [f32; FRAME_SAMPLES],
render_output: [f32; FRAME_SAMPLES],
render_ready: bool,
}
impl CaptureProcessor {
pub fn new(settings: CaptureSettings) -> Result<Self, CaptureError> {
let config = configuration(settings)?;
let stream = StreamConfig::new(48_000, 1);
Ok(Self {
processing: AudioProcessing::builder()
.config(config)
.capture_config(stream)
.render_config(stream)
.build(),
settings,
input: [0.0; FRAME_SAMPLES],
render_output: [0.0; FRAME_SAMPLES],
render_ready: false,
})
}
/// Analyze the actual post-gain playout mix; this never modifies the supplied PCM.
///
/// `delay_ms` includes hardware delay, queued samples and resampler latency. Reject
/// out-of-range delay rather than silently continuing with Sonora's clamped estimate.
/// A silent physical sink must still supply silent reference blocks while AEC runs.
/// This API does not infer timestamps or reference freshness; the engine owns those.
pub fn process_render(
&mut self,
samples: &[f32; FRAME_SAMPLES],
delay_ms: i32,
) -> Result<(), CaptureError> {
if !(0..=500).contains(&delay_ms) {
return Err(CaptureError::InvalidDelay(delay_ms));
}
self.copy_input(samples)?;
self.processing.set_stream_delay_ms(delay_ms)?;
self.processing.process_render_f32(
&[&self.input],
&mut [&mut self.render_output],
)?;
self.render_ready = true;
Ok(())
}
/// Process one normalized frame in place. Invalid input is zeroed before returning
/// an error, without entering Sonora; finite input/output is clamped to [-1, 1].
/// On any processing error the caller must discard the frame, not transmit bypass PCM.
pub fn process_capture(
&mut self,
samples: &mut [f32; FRAME_SAMPLES],
) -> Result<(), CaptureError> {
if let Err(error) = self.copy_input(samples) {
samples.fill(0.0);
return Err(error);
}
if self.settings.echo_cancellation && !self.render_ready {
samples.fill(0.0);
return Err(CaptureError::MissingRenderReference);
}
if let Err(error) = self.processing.process_capture_f32(&[&self.input], &mut [&mut samples[..]]) {
samples.fill(0.0);
return Err(error.into());
}
if samples.iter().any(|sample| !sample.is_finite()) {
samples.fill(0.0);
return Err(CaptureError::NonFiniteOutput);
}
for sample in samples {
*sample = sample.clamp(-1.0, 1.0);
}
Ok(())
}
/// Discard ALL signal history and pending reverse frames, e.g. on device/route change.
/// Rebuild AEC instead of using Sonora's no-op playout-device-change runtime setting.
/// An invalid setting leaves the existing processor intact.
pub fn reset(&mut self, settings: CaptureSettings) -> Result<(), CaptureError> {
*self = Self::new(settings)?;
Ok(())
}
fn copy_input(&mut self, samples: &[f32; FRAME_SAMPLES]) -> Result<(), CaptureError> {
if samples.iter().any(|sample| !sample.is_finite()) {
return Err(CaptureError::NonFiniteInput);
}
for (destination, sample) in self.input.iter_mut().zip(samples) {
*destination = sample.clamp(-1.0, 1.0);
}
Ok(())
}
}
#[cfg(test)]
mod tests;
+276
View File
@@ -0,0 +1,276 @@
use super::*;
const BYPASS: CaptureSettings = CaptureSettings {
echo_cancellation: false,
noise_suppression: None,
automatic_gain_control: false,
};
fn noise(seed: &mut u32, amplitude: f32) -> [f32; FRAME_SAMPLES] {
std::array::from_fn(|_| {
*seed ^= *seed << 13;
*seed ^= *seed >> 17;
*seed ^= *seed << 5;
(*seed as f32 / u32::MAX as f32 * 2.0 - 1.0) * amplitude
})
}
fn harmonic(frame: usize, amplitude: f32) -> [f32; FRAME_SAMPLES] {
std::array::from_fn(|sample| {
let time = (frame * FRAME_SAMPLES + sample) as f32 / 48_000.0;
(1..=8).map(|harmonic| {
let harmonic = harmonic as f32;
amplitude / harmonic * (std::f32::consts::TAU * 220.0 * harmonic * time).sin()
}).sum()
})
}
fn energy(samples: &[f32]) -> f64 {
samples.iter().map(|&sample| f64::from(sample).powi(2)).sum()
}
fn assert_normalized(samples: &[f32]) {
assert!(samples.iter().all(|sample| sample.is_finite() && (-1.0..=1.0).contains(sample)));
}
#[test]
fn disabled_stages_preserve_signal_without_filterbank_delay() {
let mut processor = CaptureProcessor::new(BYPASS).unwrap();
let mut seed = 0x1234_5678;
for _ in 0..100 {
let input = noise(&mut seed, 0.8);
let mut output = input;
processor.process_capture(&mut output).unwrap();
for (actual, expected) in output.iter().zip(input) {
assert!((actual - expected).abs() < 1.0 / 32768.0);
}
}
}
#[test]
fn all_noise_levels_attenuate_stationary_noise_in_order() {
let mut previous = 0.0;
for (level, minimum_db) in [3.0, 6.0, 10.0, 12.0].into_iter().enumerate() {
let mut processor = CaptureProcessor::new(CaptureSettings {
noise_suppression: Some(level as u8),
..BYPASS
}).unwrap();
let mut seed = 0x9e37_79b9;
let mut input_energy = 0.0;
let mut output_energy = 0.0;
for frame in 0..800 {
let mut samples = noise(&mut seed, 0.1);
if frame >= 500 {
input_energy += energy(&samples);
}
processor.process_capture(&mut samples).unwrap();
assert_normalized(&samples);
if frame >= 500 {
output_energy += energy(&samples);
}
}
let attenuation = 10.0 * (input_energy / output_energy).log10();
assert!(attenuation > minimum_db, "level {level}: only {attenuation:.2} dB attenuation");
assert!(attenuation > previous + 0.5, "level {level}: {attenuation:.2} vs {previous:.2} dB");
previous = attenuation;
}
}
#[test]
fn adaptive_agc_boosts_quiet_voiced_input_without_hardware_gain() {
let mut processor = CaptureProcessor::new(CaptureSettings {
automatic_gain_control: true,
..BYPASS
}).unwrap();
let mut input_energy = 0.0;
let mut output_energy = 0.0;
// Exercise initial adaptive gain (15 dB) and its bounded adaptation, not a fixed gain.
for frame in 0..30 {
let mut samples = harmonic(frame, 0.002);
input_energy += energy(&samples);
processor.process_capture(&mut samples).unwrap();
assert_normalized(&samples);
output_energy += energy(&samples);
}
let gain_db = 10.0 * (output_energy / input_energy).log10();
assert!(gain_db > 6.0, "adaptive digital gain was not applied: {gain_db:.2} dB");
let config = processor.processing.config().gain_controller2.as_ref().unwrap();
assert!(config.adaptive_digital.is_some());
assert!(!config.input_volume_controller);
assert_eq!(config.fixed_digital.gain_db, 0.0);
}
#[test]
fn reverse_reference_is_required_after_each_device_reset() {
let settings = CaptureSettings { echo_cancellation: true, ..BYPASS };
let mut processor = CaptureProcessor::new(settings).unwrap();
let mut samples = [0.25; FRAME_SAMPLES];
assert_eq!(processor.process_capture(&mut samples), Err(CaptureError::MissingRenderReference));
assert_eq!(samples, [0.0; FRAME_SAMPLES]);
processor.process_render(&[0.0; FRAME_SAMPLES], 30).unwrap();
processor.process_capture(&mut samples).unwrap();
processor.reset(settings).unwrap();
assert_eq!(processor.process_capture(&mut samples), Err(CaptureError::MissingRenderReference));
}
#[test]
fn delayed_echo_is_attenuated_by_the_actual_reverse_signal() {
let settings = CaptureSettings { echo_cancellation: true, ..BYPASS };
let mut matching = CaptureProcessor::new(settings).unwrap();
let mut silent_reference = CaptureProcessor::new(settings).unwrap();
let mut history = [[0.0; FRAME_SAMPLES]; 4];
let mut seed = 0x72ad_b643;
let mut matched_energy = 0.0;
let mut unmatched_energy = 0.0;
// A synthetic 40 ms linear echo path; not a speakerphone/double-talk acoustic gate.
for frame in 0..1200 {
let render = noise(&mut seed, 0.2);
let slot = frame % history.len();
let mut actual = history[slot].map(|sample| sample * 0.6);
let mut unmatched = actual;
history[slot] = render;
matching.process_render(&render, 40).unwrap();
silent_reference.process_render(&[0.0; FRAME_SAMPLES], 40).unwrap();
matching.process_capture(&mut actual).unwrap();
silent_reference.process_capture(&mut unmatched).unwrap();
assert_normalized(&actual);
if frame >= 800 {
matched_energy += energy(&actual);
unmatched_energy += energy(&unmatched);
}
}
assert!(unmatched_energy > 0.0);
let benefit_db = 10.0 * (unmatched_energy / matched_energy).log10();
assert!(benefit_db > 3.0, "render reference did not reduce synthetic echo: {benefit_db:.2} dB");
}
#[test]
fn combined_pipeline_matches_one_direct_sonora_instance() {
let mut processor = CaptureProcessor::new(CaptureSettings::default()).unwrap();
// Construct independently, so accidentally disabling adaptive AGC/NS/AEC in the wrapper
// or inserting another denoiser cannot silently redefine this expected signal.
let mut reference = AudioProcessing::builder()
.config(Config {
pipeline: Pipeline {
maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz,
..Pipeline::default()
},
echo_canceller: Some(EchoCanceller::default()),
noise_suppression: Some(NoiseSuppression::default()),
gain_controller2: Some(GainController2 {
adaptive_digital: Some(AdaptiveDigital::default()),
..GainController2::default()
}),
..Config::default()
})
.capture_config(StreamConfig::new(48_000, 1))
.render_config(StreamConfig::new(48_000, 1))
.build();
let mut seed = 71;
let mut render_output = [0.0; FRAME_SAMPLES];
for frame in 0..100 {
let render = noise(&mut seed, 0.1);
let original = render;
let input = harmonic(frame, 0.04);
let mut actual = input;
let mut expected = [0.0; FRAME_SAMPLES];
processor.process_render(&render, 25).unwrap();
reference.set_stream_delay_ms(25).unwrap();
reference.process_render_f32(&[&render], &mut [&mut render_output]).unwrap();
processor.process_capture(&mut actual).unwrap();
reference.process_capture_f32(&[&input], &mut [&mut expected]).unwrap();
assert_eq!(render, original, "reference analysis modified physical playout samples");
for (actual, expected) in actual.into_iter().zip(expected) {
assert_eq!(actual.to_bits(), expected.clamp(-1.0, 1.0).to_bits());
}
}
}
#[test]
fn finite_extremes_are_clamped_before_any_stage() {
let settings = CaptureSettings::default();
let mut probed = CaptureProcessor::new(settings).unwrap();
let mut twin = CaptureProcessor::new(settings).unwrap();
for frame in 0..50 {
let input = std::array::from_fn(|index| if (index + frame) % 2 == 0 { f32::MAX } else { -f32::MAX });
let clamped = input.map(|sample| sample.clamp(-1.0, 1.0));
probed.process_render(&input, 0).unwrap();
twin.process_render(&clamped, 0).unwrap();
let mut actual = input;
let mut expected = clamped;
probed.process_capture(&mut actual).unwrap();
twin.process_capture(&mut expected).unwrap();
assert_normalized(&actual);
assert_eq!(actual, expected);
}
}
#[test]
fn rejected_inputs_and_delays_do_not_change_processing_state() {
let settings = CaptureSettings::default();
let mut probed = CaptureProcessor::new(settings).unwrap();
let mut twin = CaptureProcessor::new(settings).unwrap();
let mut seed = 98;
for frame in 0..120 {
let render = noise(&mut seed, 0.1);
probed.process_render(&render, 20).unwrap();
twin.process_render(&render, 20).unwrap();
if frame == 60 {
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
let mut samples = render;
samples[123] = bad;
assert_eq!(probed.process_render(&samples, 20), Err(CaptureError::NonFiniteInput));
assert_eq!(probed.process_capture(&mut samples), Err(CaptureError::NonFiniteInput));
assert_eq!(samples, [0.0; FRAME_SAMPLES]);
}
for delay in [i32::MIN, -1, 501, i32::MAX] {
assert_eq!(probed.process_render(&render, delay), Err(CaptureError::InvalidDelay(delay)));
}
assert_eq!(probed.processing.stream_delay_ms(), 20);
assert_eq!(probed.reset(CaptureSettings { noise_suppression: Some(4), ..settings }), Err(CaptureError::InvalidNoiseSuppressionLevel(4)));
}
let mut actual = harmonic(frame, 0.03);
let mut expected = actual;
probed.process_capture(&mut actual).unwrap();
twin.process_capture(&mut expected).unwrap();
assert_eq!(actual, expected);
}
}
#[test]
fn reset_discards_echo_noise_gain_history_and_matches_a_fresh_device() {
let mut reused = CaptureProcessor::new(CaptureSettings::default()).unwrap();
let mut seed = 0x1111_1234;
for _ in 0..100 {
let render = noise(&mut seed, 0.2);
let mut capture = noise(&mut seed, 0.1);
reused.process_render(&render, 80).unwrap();
reused.process_capture(&mut capture).unwrap();
}
let settings = CaptureSettings { noise_suppression: Some(3), ..CaptureSettings::default() };
reused.reset(settings).unwrap();
let mut fresh = CaptureProcessor::new(settings).unwrap();
for frame in 0..100 {
let render = if frame < 10 { [0.0; FRAME_SAMPLES] } else { noise(&mut seed, 0.05) };
let input = if frame < 10 { [0.0; FRAME_SAMPLES] } else { harmonic(frame, 0.02) };
let mut actual = input;
let mut expected = input;
reused.process_render(&render, 10).unwrap();
fresh.process_render(&render, 10).unwrap();
reused.process_capture(&mut actual).unwrap();
fresh.process_capture(&mut expected).unwrap();
assert_eq!(actual, expected, "reset leaked signal history at frame {frame}");
assert_normalized(&actual);
}
}
#[test]
fn invalid_settings_never_construct_a_processor() {
for level in [4, 255] {
assert!(matches!(CaptureProcessor::new(CaptureSettings {
noise_suppression: Some(level),
..BYPASS
}), Err(CaptureError::InvalidNoiseSuppressionLevel(actual)) if actual == level));
}
}
+65 -45
View File
@@ -1,8 +1,11 @@
//! TeamsPeach microphone noise reduction, compiled to a zero-import WebAssembly module.
//! TeamsPeach 48 kHz mono capture processing.
//!
//! The renderer's capture AudioWorklet runs every 10 ms frame of 48 kHz mono microphone audio
//! through this module, both for live voice and for the settings record test, so both paths hear
//! exactly the same processing. Every architecture executes the same scalar WebAssembly code.
//! Native workers use [`CaptureProcessor`]: one Sonora APM for AEC3, noise suppression and
//! adaptive AGC2, with a separate render-reference input. No pointer ABI is used by native code.
//! Device callbacks must not run DSP; the processor belongs to the dedicated audio worker.
//!
//! The legacy [`Denoiser`] below remains the reference renderer's noise-only implementation.
//! Its WebAssembly exports exist only on `wasm32`; it is not chained into native processing.
//!
//! # Processing
//!
@@ -46,8 +49,12 @@
//!
//! Handles carry a generation counter, so a handle stays invalid after `dsp_free` even when its
//! slot is reused. `dsp_new` and `dsp_reset` allocate (and may grow `memory`, detaching typed-array
//! views); `dsp_process` never allocates.
//! views). Native processing has no end-to-end allocation guarantee; Sonora owns internal buffers.
mod capture;
pub use capture::{CaptureError, CaptureProcessor, CaptureSettings};
#[cfg(target_arch = "wasm32")]
use std::sync::{Mutex, MutexGuard, PoisonError};
use sonora::three_band_filter_bank::{
@@ -134,7 +141,7 @@ impl Denoiser {
&mut self.frame
}
/// Denoise the frame in place. Allocation-free.
/// Denoise the frame in place.
pub fn process(&mut self) -> Result<(), ProcessError> {
if self.frame.iter().any(|sample| !sample.is_finite()) {
self.frame.fill(0.0);
@@ -164,6 +171,13 @@ impl Denoiser {
// ── WebAssembly exports ─────────────────────────────────────────────────────────────────────
#[cfg(target_arch = "wasm32")]
pub use wasm_abi::{dsp_free, dsp_input, dsp_new, dsp_process, dsp_reset};
#[cfg(target_arch = "wasm32")]
mod wasm_abi {
use super::*;
const SLOT_BITS: u32 = 8;
const SLOT_MASK: u32 = (1 << SLOT_BITS) - 1;
const GENERATION_MASK: u32 = u32::MAX >> SLOT_BITS;
@@ -257,6 +271,51 @@ pub extern "C" fn dsp_free(handle: u32) {
}
}
#[cfg(test)]
mod tests {
use super::*;
/// All export-table checks in one test: the table is process-global state.
#[test]
fn exported_handle_lifecycle() {
assert_eq!(dsp_new(MAX_LEVEL + 1), 0);
for bogus in [0, 0x0000_00FF, u32::MAX, MAX_INSTANCES as u32 + 1] {
assert_eq!(dsp_input(bogus), 0);
assert_eq!(dsp_process(bogus), STATUS_INVALID_HANDLE);
assert_eq!(dsp_reset(bogus, 1), STATUS_INVALID_HANDLE);
dsp_free(bogus);
}
let handle = dsp_new(1);
assert_ne!(handle, 0);
assert_eq!(dsp_process(handle), STATUS_OK);
assert_eq!(dsp_reset(handle, MAX_LEVEL + 1), STATUS_INVALID_LEVEL);
assert_eq!(dsp_reset(handle, 3), STATUS_OK);
{
let mut table = slots();
let dsp = live_dsp(&mut table, handle).unwrap();
dsp.frame_mut()[0] = f32::NAN;
}
assert_eq!(dsp_process(handle), STATUS_NON_FINITE_INPUT);
assert_eq!(dsp_process(handle), STATUS_OK);
dsp_free(handle);
assert_eq!(dsp_process(handle), STATUS_INVALID_HANDLE);
dsp_free(handle);
// Fill the table; the freed slot is reused under a new generation.
let handles: Vec<u32> = (0..MAX_INSTANCES).map(|_| dsp_new(0)).collect();
assert!(handles.iter().all(|&h| h != 0 && h != handle));
assert_eq!(dsp_new(0), 0, "table should be full");
assert_eq!(dsp_process(handle), STATUS_INVALID_HANDLE, "stale handle revived");
for &h in &handles {
assert_eq!(dsp_process(h), STATUS_OK);
dsp_free(h);
assert_eq!(dsp_process(h), STATUS_INVALID_HANDLE);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -465,43 +524,4 @@ mod tests {
}
}
/// All export-table checks in one test: the table is process-global state.
#[test]
fn exported_handle_lifecycle() {
assert_eq!(dsp_new(MAX_LEVEL + 1), 0);
for bogus in [0, 0x0000_00FF, u32::MAX, MAX_INSTANCES as u32 + 1] {
assert_eq!(dsp_input(bogus), 0);
assert_eq!(dsp_process(bogus), STATUS_INVALID_HANDLE);
assert_eq!(dsp_reset(bogus, 1), STATUS_INVALID_HANDLE);
dsp_free(bogus);
}
let handle = dsp_new(1);
assert_ne!(handle, 0);
assert_eq!(dsp_process(handle), STATUS_OK);
assert_eq!(dsp_reset(handle, MAX_LEVEL + 1), STATUS_INVALID_LEVEL);
assert_eq!(dsp_reset(handle, 3), STATUS_OK);
{
let mut table = slots();
let dsp = live_dsp(&mut table, handle).unwrap();
dsp.frame_mut()[0] = f32::NAN;
}
assert_eq!(dsp_process(handle), STATUS_NON_FINITE_INPUT);
assert_eq!(dsp_process(handle), STATUS_OK);
dsp_free(handle);
assert_eq!(dsp_process(handle), STATUS_INVALID_HANDLE);
dsp_free(handle);
// Fill the table; the freed slot is reused under a new generation.
let handles: Vec<u32> = (0..MAX_INSTANCES).map(|_| dsp_new(0)).collect();
assert!(handles.iter().all(|&h| h != 0 && h != handle));
assert_eq!(dsp_new(0), 0, "table should be full");
assert_eq!(dsp_process(handle), STATUS_INVALID_HANDLE, "stale handle revived");
for &h in &handles {
assert_eq!(dsp_process(h), STATUS_OK);
dsp_free(h);
assert_eq!(dsp_process(h), STATUS_INVALID_HANDLE);
}
}
}
+29
View File
@@ -0,0 +1,29 @@
{
"schema": 1,
"upstream_revision": "a024d6ef8351add55be5e8b1d6cc35f555787660",
"packages": [
{
"name": "sonora",
"version": "0.2.0",
"registry": "https://crates.io",
"archive": "https://static.crates.io/crates/sonora/sonora-0.2.0.crate",
"sha256": "2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250",
"path_in_vcs": "crates/sonora",
"modified_sources": ["src/gain_controller2.rs"],
"patch": "Mono AGC2 noise analysis uses a stack channel descriptor. Adaptive gain, fixed gain and limiter borrow AudioBuffer::channel_mut(0), eliminating caller-side per-frame channel/sample Vec allocation and copy-back. Multichannel processing remains the upstream path. Includes mono-vs-identical-stereo signal equivalence test."
},
{
"name": "sonora-agc2",
"version": "0.2.0",
"registry": "https://crates.io",
"archive": "https://static.crates.io/crates/sonora-agc2/sonora-agc2-0.2.0.crate",
"sha256": "9a93a9fa8373a33e61a7fb441d8a9e725ac6024079d2c77a845cf6abe1790b9f",
"path_in_vcs": "crates/sonora-agc2",
"modified_sources": ["src/limiter.rs"],
"patch": "Mono limiter level estimation uses a stack immutable channel descriptor rather than collecting Vec<&[f32]>. Multichannel processing and numerical operations remain unchanged."
}
],
"scope": "This removes the inspected AGC2 mono channel-adapter allocations/copies; it is not an allocation-free guarantee for the complete Sonora APM or its other dependencies.",
"source": "Copied installed pinned registry sources, retaining upstream Cargo manifests, lockfiles, license, README and VCS metadata; registry .cargo-ok extraction markers omitted.",
"verification": "Tests added, not executed by delegated worker. Parent runs verification after integration."
}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "a024d6ef8351add55be5e8b1d6cc35f555787660"
},
"path_in_vcs": "crates/sonora-agc2"
}
+532
View File
@@ -0,0 +1,532 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bit-set"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bitflags"
version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
dependencies = [
"bytemuck_derive",
]
[[package]]
name = "bytemuck_derive"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cpufeatures"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
dependencies = [
"libc",
]
[[package]]
name = "derive-ex"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bba95f299f6b9cd47f68a847eca2ae9060a2713af532dc35c342065544845407"
dependencies = [
"proc-macro2",
"quote",
"structmeta",
"syn",
]
[[package]]
name = "derive_more"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
dependencies = [
"derive_more-impl",
]
[[package]]
name = "derive_more-impl"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"syn",
"unicode-xid",
]
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "getrandom"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"libc",
"r-efi 5.3.0",
"wasip2",
]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi 6.0.0",
]
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "proptest"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
dependencies = [
"bit-set",
"bit-vec",
"bitflags",
"num-traits",
"rand",
"rand_chacha",
"rand_xorshift",
"regex-syntax",
"rusty-fork",
"tempfile",
"unarray",
]
[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "rand_xorshift"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
dependencies = [
"rand_core",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "rusty-fork"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
dependencies = [
"fnv",
"quick-error",
"tempfile",
"wait-timeout",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "sonora-agc2"
version = "0.2.0"
dependencies = [
"bytemuck",
"derive_more",
"proptest",
"sonora-common-audio",
"sonora-fft",
"sonora-simd",
"test-strategy",
"tracing",
]
[[package]]
name = "sonora-common-audio"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc"
dependencies = [
"derive_more",
"sonora-simd",
]
[[package]]
name = "sonora-fft"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012"
[[package]]
name = "sonora-simd"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868"
dependencies = [
"cpufeatures",
]
[[package]]
name = "structmeta"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e1575d8d40908d70f6fd05537266b90ae71b15dbbe7a8b7dffa2b759306d329"
dependencies = [
"proc-macro2",
"quote",
"structmeta-derive",
"syn",
]
[[package]]
name = "structmeta-derive"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "test-strategy"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f7fd1eb9efb36942b85a290c4201d317980fe09bc88d34dd48aaaae03075c6a"
dependencies = [
"derive-ex",
"proc-macro2",
"quote",
"structmeta",
"syn",
]
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "unarray"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "wasip2"
version = "1.0.4+wasi-0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "zerocopy"
version = "0.8.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
+86
View File
@@ -0,0 +1,86 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.91"
name = "sonora-agc2"
version = "0.2.0"
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Automatic Gain Control 2 (AGC2) with RNN VAD for WebRTC Audio Processing"
readme = "README.md"
keywords = [
"webrtc",
"audio",
"agc",
"gain-control",
"vad",
]
categories = ["multimedia::audio"]
license = "BSD-3-Clause"
repository = "https://github.com/dignifiedquire/sonora"
[lib]
name = "sonora_agc2"
path = "src/lib.rs"
[dependencies.bytemuck]
version = "1"
features = ["derive"]
[dependencies.derive_more]
version = "2"
features = ["debug"]
[dependencies.sonora-common-audio]
version = "0.2.0"
[dependencies.sonora-fft]
version = "0.2.0"
[dependencies.sonora-simd]
version = "0.2.0"
[dependencies.tracing]
version = "0.1"
[dev-dependencies.proptest]
version = "1.11"
[dev-dependencies.test-strategy]
version = "0.4"
[lints.clippy]
absolute_paths = "warn"
allow_attributes_without_reason = "warn"
approx_constant = "allow"
excessive_precision = "allow"
manual_let_else = "warn"
mod_module_files = "deny"
or_fun_call = "warn"
unused_async = "warn"
use_self = "warn"
[lints.rust]
elided_lifetimes_in_paths = "warn"
missing_debug_implementations = "warn"
unnameable_types = "warn"
unreachable_pub = "warn"
[lints.rust.unexpected_cfgs]
level = "deny"
priority = 0
check-cfg = ["cfg(docsrs)"]
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "sonora-agc2"
version = "0.2.0"
description = "Automatic Gain Control 2 (AGC2) with RNN VAD for WebRTC Audio Processing"
keywords = ["webrtc", "audio", "agc", "gain-control", "vad"]
categories = ["multimedia::audio"]
readme = "README.md"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
sonora-common-audio = { workspace = true }
sonora-fft = { workspace = true }
sonora-simd = { workspace = true }
bytemuck = { workspace = true }
derive_more = { workspace = true }
tracing = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
test-strategy = { workspace = true }
+31
View File
@@ -0,0 +1,31 @@
Copyright (c) 2011, The WebRTC Project Authors. All rights reserved.
Copyright (c) 2016, Arun Raghavan and contributors. All rights reserved.
Copyright (c) 2026, dignifiedquire. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Google nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+33
View File
@@ -0,0 +1,33 @@
# sonora-agc2
[![crate][crate-image]][crate-link]
[![docs][docs-image]][docs-link]
![BSD-3-Clause licensed][license-image]
![Rust Version][rustc-image]
Pure Rust implementation of [Automatic Gain Control 2 (AGC2)][AGC2] from WebRTC.
RNN-based voice activity detection (VAD) drives an adaptive digital gain
controller with limiter and clipping predictor. Includes fixed digital gain,
speech level estimation, and input volume control.
Part of the [Sonora] audio processing library.
## License
BSD-3-Clause. See [LICENSE] for details.
[//]: # (badges)
[crate-image]: https://img.shields.io/crates/v/sonora-agc2.svg
[crate-link]: https://crates.io/crates/sonora-agc2
[docs-image]: https://docs.rs/sonora-agc2/badge.svg
[docs-link]: https://docs.rs/sonora-agc2/
[license-image]: https://img.shields.io/badge/license-BSD--3--Clause-blue.svg
[rustc-image]: https://img.shields.io/badge/rustc-1.91+-blue.svg
[//]: # (general links)
[AGC2]: https://webrtc.googlesource.com/src/+/refs/heads/main/modules/audio_processing/agc2/
[Sonora]: https://github.com/dignifiedquire/sonora#readme
[LICENSE]: https://github.com/dignifiedquire/sonora/blob/main/LICENSE
@@ -0,0 +1,538 @@
//! Adaptive digital gain controller.
//!
//! Selects the target digital gain, decides when and how quickly to adapt to
//! the target and applies the current gain to 10 ms frames.
//!
//! Ported from `webrtc/modules/audio_processing/agc2/adaptive_digital_gain_controller.h/.cc`.
use crate::common::{
FRAME_DURATION_MS, LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS, VAD_CONFIDENCE_THRESHOLD, db_to_ratio,
};
use crate::gain_applier::GainApplier;
use crate::speech_level_estimator::AdaptiveDigitalConfig;
/// Information about a frame to process.
#[derive(Debug)]
pub struct FrameInfo {
/// Probability of speech in the [0, 1] range.
pub speech_probability: f32,
/// Estimated speech level (dBFS).
pub speech_level_dbfs: f32,
/// True with reliable speech level estimation.
pub speech_level_reliable: bool,
/// Estimated noise RMS level (dBFS).
pub noise_rms_dbfs: f32,
/// Headroom (dB).
pub headroom_db: f32,
/// Envelope level from the limiter (dBFS).
pub limiter_envelope_dbfs: f32,
}
/// Computes the gain for `input_level_dbfs` to reach `-config.headroom_db`.
/// Clamps the gain in [0, `config.max_gain_db`].
fn compute_gain_db(input_level_dbfs: f32, config: &AdaptiveDigitalConfig) -> f32 {
// If the level is very low, apply the maximum gain.
if input_level_dbfs < -(config.headroom_db + config.max_gain_db) {
return config.max_gain_db;
}
// We expect to end up here most of the time: the level is below
// -headroom, but we can boost it to -headroom.
if input_level_dbfs < -config.headroom_db {
return -config.headroom_db - input_level_dbfs;
}
// The level is too high and we can't boost.
0.0
}
/// Returns `target_gain_db` if applying such a gain to `input_noise_level_dbfs`
/// does not exceed `max_output_noise_level_dbfs`. Otherwise lowers the gain.
fn limit_gain_by_noise(
target_gain_db: f32,
input_noise_level_dbfs: f32,
max_output_noise_level_dbfs: f32,
) -> f32 {
let max_allowed_gain_db = max_output_noise_level_dbfs - input_noise_level_dbfs;
target_gain_db.min(max_allowed_gain_db.max(0.0))
}
fn limit_gain_by_low_confidence(
target_gain_db: f32,
last_gain_db: f32,
limiter_audio_level_dbfs: f32,
estimate_is_confident: bool,
) -> f32 {
if estimate_is_confident || limiter_audio_level_dbfs <= LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS {
return target_gain_db;
}
let limiter_level_dbfs_before_gain = limiter_audio_level_dbfs - last_gain_db;
// Compute a new gain so that `limiter_level_dbfs_before_gain` +
// `new_target_gain_db` is not greater than the threshold.
let new_target_gain_db =
(LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS - limiter_level_dbfs_before_gain).max(0.0);
new_target_gain_db.min(target_gain_db)
}
/// Computes how the gain should change during this frame.
fn compute_gain_change_this_frame_db(
target_gain_db: f32,
last_gain_db: f32,
gain_increase_allowed: bool,
max_gain_decrease_db: f32,
max_gain_increase_db: f32,
) -> f32 {
debug_assert!(max_gain_decrease_db > 0.0);
debug_assert!(max_gain_increase_db > 0.0);
let mut target_gain_difference_db = target_gain_db - last_gain_db;
if !gain_increase_allowed {
target_gain_difference_db = target_gain_difference_db.min(0.0);
}
target_gain_difference_db.clamp(-max_gain_decrease_db, max_gain_increase_db)
}
/// Adaptive digital gain controller.
#[derive(Debug)]
pub struct AdaptiveDigitalGainController {
gain_applier: GainApplier,
config: AdaptiveDigitalConfig,
adjacent_speech_frames_threshold: i32,
max_gain_change_db_per_10ms: f32,
frames_to_gain_increase_allowed: i32,
last_gain_db: f32,
}
impl AdaptiveDigitalGainController {
/// Creates a new adaptive digital gain controller.
pub fn new(config: AdaptiveDigitalConfig, adjacent_speech_frames_threshold: i32) -> Self {
let max_gain_change_db_per_10ms =
config.max_gain_change_db_per_second * FRAME_DURATION_MS as f32 / 1000.0;
debug_assert!(max_gain_change_db_per_10ms > 0.0);
debug_assert!(adjacent_speech_frames_threshold >= 1);
debug_assert!(config.max_output_noise_level_dbfs >= -90.0);
debug_assert!(config.max_output_noise_level_dbfs <= 0.0);
Self {
gain_applier: GainApplier::new(false, db_to_ratio(config.initial_gain_db)),
config,
adjacent_speech_frames_threshold,
max_gain_change_db_per_10ms,
frames_to_gain_increase_allowed: adjacent_speech_frames_threshold,
last_gain_db: config.initial_gain_db,
}
}
/// Analyzes `info`, updates the digital gain and applies it to a 10 ms frame.
pub fn process(&mut self, info: &FrameInfo, frame: &mut [&mut [f32]]) {
debug_assert!(info.speech_level_dbfs >= -150.0);
debug_assert!(!frame.is_empty());
// Compute the input level used to select the desired gain.
debug_assert!(info.headroom_db > 0.0);
let input_level_dbfs = info.speech_level_dbfs + info.headroom_db;
let target_gain_db = limit_gain_by_low_confidence(
limit_gain_by_noise(
compute_gain_db(input_level_dbfs, &self.config),
info.noise_rms_dbfs,
self.config.max_output_noise_level_dbfs,
),
self.last_gain_db,
info.limiter_envelope_dbfs,
info.speech_level_reliable,
);
// Forbid increasing the gain until enough adjacent speech frames are
// observed.
let mut first_confident_speech_frame = false;
if info.speech_probability < VAD_CONFIDENCE_THRESHOLD {
self.frames_to_gain_increase_allowed = self.adjacent_speech_frames_threshold;
} else if self.frames_to_gain_increase_allowed > 0 {
self.frames_to_gain_increase_allowed -= 1;
first_confident_speech_frame = self.frames_to_gain_increase_allowed == 0;
}
let gain_increase_allowed = self.frames_to_gain_increase_allowed == 0;
let mut max_gain_increase_db = self.max_gain_change_db_per_10ms;
if first_confident_speech_frame {
// No gain increase happened while waiting for a long enough speech
// sequence. Therefore, temporarily allow a faster gain increase.
debug_assert!(gain_increase_allowed);
max_gain_increase_db *= self.adjacent_speech_frames_threshold as f32;
}
let gain_change_this_frame_db = compute_gain_change_this_frame_db(
target_gain_db,
self.last_gain_db,
gain_increase_allowed,
self.max_gain_change_db_per_10ms,
max_gain_increase_db,
);
// Optimization: avoid calling math functions if gain does not change.
if gain_change_this_frame_db != 0.0 {
self.gain_applier
.set_gain_factor(db_to_ratio(self.last_gain_db + gain_change_this_frame_db));
}
self.gain_applier.apply_gain(frame);
// Remember that the gain has changed for the next iteration.
self.last_gain_db += gain_change_this_frame_db;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::{
ADJACENT_SPEECH_FRAMES_THRESHOLD, FRAME_DURATION_MS, MIN_LEVEL_DBFS, db_to_ratio,
};
const MONO: usize = 1;
const STEREO: usize = 2;
const FRAME_LEN_10MS_8KHZ: usize = 80;
const FRAME_LEN_10MS_48KHZ: usize = 480;
const MAX_SPEECH_PROBABILITY: f32 = 1.0;
// Constants used in place of estimated noise levels.
const NO_NOISE_DBFS: f32 = MIN_LEVEL_DBFS;
const WITH_NOISE_DBFS: f32 = -20.0;
// Number of additional frames to process to ensure convergence.
const NUM_EXTRA_FRAMES: i32 = 10;
const fn get_max_gain_change_per_frame_db(max_gain_change_db_per_second: f32) -> f32 {
max_gain_change_db_per_second * FRAME_DURATION_MS as f32 / 1000.0
}
fn default_config() -> AdaptiveDigitalConfig {
AdaptiveDigitalConfig {
headroom_db: 5.0,
max_gain_db: 50.0,
initial_gain_db: 15.0,
max_gain_change_db_per_second: 6.0,
max_output_noise_level_dbfs: -50.0,
}
}
/// Returns a `FrameInfo` that should cause no gain adaptation.
fn get_frame_info_to_not_adapt(config: &AdaptiveDigitalConfig) -> FrameInfo {
FrameInfo {
speech_probability: MAX_SPEECH_PROBABILITY,
speech_level_dbfs: -config.initial_gain_db - config.headroom_db,
speech_level_reliable: true,
noise_rms_dbfs: NO_NOISE_DBFS,
headroom_db: config.headroom_db,
limiter_envelope_dbfs: -2.0,
}
}
fn make_frame(num_channels: usize, samples_per_channel: usize, value: f32) -> Vec<Vec<f32>> {
vec![vec![value; samples_per_channel]; num_channels]
}
fn as_mut_slices(frame: &mut [Vec<f32>]) -> Vec<&mut [f32]> {
frame.iter_mut().map(|ch| ch.as_mut_slice()).collect()
}
#[test]
fn gain_applier_should_not_crash() {
let config = default_config();
let mut controller =
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
let mut audio = make_frame(STEREO, FRAME_LEN_10MS_48KHZ, 10000.0);
let mut slices = as_mut_slices(&mut audio);
controller.process(&get_frame_info_to_not_adapt(&config), &mut slices);
}
#[test]
fn max_gain_applied() {
let config = default_config();
let num_frames_to_adapt = (config.max_gain_db
/ get_max_gain_change_per_frame_db(config.max_gain_change_db_per_second))
as i32
+ NUM_EXTRA_FRAMES;
let high_noise_config = AdaptiveDigitalConfig {
max_output_noise_level_dbfs: -40.0,
..config
};
let mut controller =
AdaptiveDigitalGainController::new(high_noise_config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
let mut info = get_frame_info_to_not_adapt(&high_noise_config);
info.speech_level_dbfs = -60.0;
let mut applied_gain = 0.0_f32;
for _ in 0..num_frames_to_adapt {
let mut audio = make_frame(MONO, FRAME_LEN_10MS_8KHZ, 1.0);
let mut slices = as_mut_slices(&mut audio);
controller.process(&info, &mut slices);
applied_gain = audio[0][0];
}
let applied_gain_db = 20.0 * applied_gain.log10();
assert!(
(applied_gain_db - config.max_gain_db).abs() < 0.1,
"applied_gain_db={applied_gain_db}, expected ~{}",
config.max_gain_db
);
}
#[test]
fn gain_does_not_change_fast() {
let config = default_config();
let mut controller =
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
let initial_level_dbfs = -25.0_f32;
let max_gain_change_db_per_frame =
get_max_gain_change_per_frame_db(config.max_gain_change_db_per_second);
let num_frames_to_adapt =
(initial_level_dbfs / max_gain_change_db_per_frame) as i32 + NUM_EXTRA_FRAMES;
let max_change_per_frame_linear = db_to_ratio(max_gain_change_db_per_frame);
let mut last_gain_linear = 1.0_f32;
for _ in 0..num_frames_to_adapt {
let mut audio = make_frame(MONO, FRAME_LEN_10MS_8KHZ, 1.0);
let mut slices = as_mut_slices(&mut audio);
let mut info = get_frame_info_to_not_adapt(&config);
info.speech_level_dbfs = initial_level_dbfs;
controller.process(&info, &mut slices);
let current_gain_linear = audio[0][0];
assert!(
(current_gain_linear - last_gain_linear).abs() <= max_change_per_frame_linear,
"gain change {} exceeds max {}",
(current_gain_linear - last_gain_linear).abs(),
max_change_per_frame_linear
);
last_gain_linear = current_gain_linear;
}
// Check that the same is true when gain decreases as well.
for _ in 0..num_frames_to_adapt {
let mut audio = make_frame(MONO, FRAME_LEN_10MS_8KHZ, 1.0);
let mut slices = as_mut_slices(&mut audio);
let mut info = get_frame_info_to_not_adapt(&config);
info.speech_level_dbfs = 0.0;
controller.process(&info, &mut slices);
let current_gain_linear = audio[0][0];
assert!(
(current_gain_linear - last_gain_linear).abs() <= max_change_per_frame_linear,
"gain change {} exceeds max {}",
(current_gain_linear - last_gain_linear).abs(),
max_change_per_frame_linear
);
last_gain_linear = current_gain_linear;
}
}
#[test]
fn gain_is_ramped_in_a_frame() {
let config = default_config();
let mut controller =
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
let initial_level_dbfs = -25.0_f32;
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
let mut slices = as_mut_slices(&mut audio);
let mut info = get_frame_info_to_not_adapt(&config);
info.speech_level_dbfs = initial_level_dbfs;
controller.process(&info, &mut slices);
let mut maximal_difference = 0.0_f32;
let mut current_value = 1.0 * db_to_ratio(config.initial_gain_db);
for &x in &audio[0] {
let difference = (x - current_value).abs();
maximal_difference = maximal_difference.max(difference);
current_value = x;
}
let max_change_per_frame_linear = db_to_ratio(get_max_gain_change_per_frame_db(
config.max_gain_change_db_per_second,
));
let max_change_per_sample = max_change_per_frame_linear / FRAME_LEN_10MS_48KHZ as f32;
assert!(
maximal_difference <= max_change_per_sample,
"maximal_difference {maximal_difference} > max_change_per_sample {max_change_per_sample}"
);
}
#[test]
fn noise_limits_gain() {
let config = default_config();
let mut controller =
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
let initial_level_dbfs = -25.0_f32;
let num_initial_frames = (config.initial_gain_db
/ get_max_gain_change_per_frame_db(config.max_gain_change_db_per_second))
as i32;
let num_frames = 50;
assert!(
WITH_NOISE_DBFS > config.max_output_noise_level_dbfs,
"WITH_NOISE_DBFS is too low"
);
for i in 0..num_initial_frames + num_frames {
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
let mut slices = as_mut_slices(&mut audio);
let mut info = get_frame_info_to_not_adapt(&config);
info.speech_level_dbfs = initial_level_dbfs;
info.noise_rms_dbfs = WITH_NOISE_DBFS;
controller.process(&info, &mut slices);
// Wait so that the adaptive gain applier has time to lower the gain.
if i > num_initial_frames {
let maximal_ratio = audio[0].iter().copied().reduce(f32::max).unwrap();
assert!(
(maximal_ratio - 1.0).abs() < 0.001,
"frame {i}: maximal_ratio={maximal_ratio}, expected ~1.0"
);
}
}
}
#[test]
fn can_handle_positive_speech_levels() {
let config = default_config();
let mut controller =
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
let mut audio = make_frame(STEREO, FRAME_LEN_10MS_48KHZ, 10000.0);
let mut slices = as_mut_slices(&mut audio);
let mut info = get_frame_info_to_not_adapt(&config);
info.speech_level_dbfs = 5.0;
controller.process(&info, &mut slices);
}
#[test]
fn audio_level_limits_gain() {
let config = default_config();
let mut controller =
AdaptiveDigitalGainController::new(config, ADJACENT_SPEECH_FRAMES_THRESHOLD);
let initial_level_dbfs = -25.0_f32;
let num_initial_frames = (config.initial_gain_db
/ get_max_gain_change_per_frame_db(config.max_gain_change_db_per_second))
as i32;
let num_frames = 50;
assert!(
WITH_NOISE_DBFS > config.max_output_noise_level_dbfs,
"WITH_NOISE_DBFS is too low"
);
for i in 0..num_initial_frames + num_frames {
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
let mut slices = as_mut_slices(&mut audio);
let mut info = get_frame_info_to_not_adapt(&config);
info.speech_level_dbfs = initial_level_dbfs;
info.limiter_envelope_dbfs = 1.0;
info.speech_level_reliable = false;
controller.process(&info, &mut slices);
// Wait so that the adaptive gain applier has time to lower the gain.
if i > num_initial_frames {
let maximal_ratio = audio[0].iter().copied().reduce(f32::max).unwrap();
assert!(
(maximal_ratio - 1.0).abs() < 0.001,
"frame {i}: maximal_ratio={maximal_ratio}, expected ~1.0"
);
}
}
}
// Parametrized tests for adjacent_speech_frames_threshold = 1, 7, 31, 12.
#[test]
fn do_not_increase_gain_with_too_few_speech_frames_1() {
do_not_increase_gain_with_too_few_speech_frames(1);
}
#[test]
fn do_not_increase_gain_with_too_few_speech_frames_7() {
do_not_increase_gain_with_too_few_speech_frames(7);
}
#[test]
fn do_not_increase_gain_with_too_few_speech_frames_31() {
do_not_increase_gain_with_too_few_speech_frames(31);
}
#[test]
fn do_not_increase_gain_with_too_few_speech_frames_default() {
do_not_increase_gain_with_too_few_speech_frames(ADJACENT_SPEECH_FRAMES_THRESHOLD);
}
fn do_not_increase_gain_with_too_few_speech_frames(threshold: i32) {
let config = default_config();
let mut controller = AdaptiveDigitalGainController::new(config, threshold);
// Lower the speech level so that the target gain will be increased.
let mut info = get_frame_info_to_not_adapt(&config);
info.speech_level_dbfs -= 12.0;
let mut prev_gain = 0.0_f32;
for i in 0..threshold {
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
let mut slices = as_mut_slices(&mut audio);
controller.process(&info, &mut slices);
let gain = audio[0][0];
if i > 0 {
assert_eq!(prev_gain, gain, "no gain increase expected at frame {i}");
}
prev_gain = gain;
}
}
#[test]
fn increase_gain_with_enough_speech_frames_1() {
increase_gain_with_enough_speech_frames(1);
}
#[test]
fn increase_gain_with_enough_speech_frames_7() {
increase_gain_with_enough_speech_frames(7);
}
#[test]
fn increase_gain_with_enough_speech_frames_31() {
increase_gain_with_enough_speech_frames(31);
}
#[test]
fn increase_gain_with_enough_speech_frames_default() {
increase_gain_with_enough_speech_frames(ADJACENT_SPEECH_FRAMES_THRESHOLD);
}
fn increase_gain_with_enough_speech_frames(threshold: i32) {
let config = default_config();
let mut controller = AdaptiveDigitalGainController::new(config, threshold);
// Lower the speech level so that the target gain will be increased.
let mut info = get_frame_info_to_not_adapt(&config);
info.speech_level_dbfs -= 12.0;
let mut prev_gain = 0.0_f32;
for _ in 0..threshold {
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
let mut slices = as_mut_slices(&mut audio);
controller.process(&info, &mut slices);
prev_gain = audio[0][0];
}
// Process one more speech frame.
let mut audio = make_frame(MONO, FRAME_LEN_10MS_48KHZ, 1.0);
let mut slices = as_mut_slices(&mut audio);
controller.process(&info, &mut slices);
// An increased gain has been applied.
assert!(
audio[0][0] > prev_gain,
"gain {} should be > prev_gain {}",
audio[0][0],
prev_gain
);
}
}
+273
View File
@@ -0,0 +1,273 @@
//! IIR biquad filter.
//!
//! Ported from `webrtc/modules/audio_processing/agc2/biquad_filter.h`.
/// Biquad filter coefficients.
#[derive(Debug, Clone, Copy)]
pub struct BiquadFilterConfig {
/// Feedforward coefficients `[b0, b1, b2]`.
pub b: [f32; 3],
/// Feedback coefficients `[a1, a2]`.
pub a: [f32; 2],
}
/// Second-order IIR (biquad) filter.
///
/// Transfer function: `H(z) = (b0 + b1*z^-1 + b2*z^-2) / (1 + a1*z^-1 + a2*z^-2)`
#[derive(Debug)]
pub struct BiquadFilter {
config: BiquadFilterConfig,
/// State: `[x[n-1], x[n-2], y[n-1], y[n-2]]`.
state: [f32; 4],
}
impl BiquadFilter {
/// Creates a new biquad filter with the given configuration.
pub fn new(config: BiquadFilterConfig) -> Self {
Self {
config,
state: [0.0; 4],
}
}
/// Resets the filter state to zero.
pub fn reset(&mut self) {
self.state = [0.0; 4];
}
/// Reconfigures the filter and resets state.
pub fn set_config(&mut self, config: BiquadFilterConfig) {
self.config = config;
self.reset();
}
/// Processes input samples `x` and writes filtered output to `y`.
///
/// `x` and `y` may be the same slice for in-place processing.
pub fn process(&mut self, x: &[f32], y: &mut [f32]) {
debug_assert_eq!(x.len(), y.len());
for k in 0..x.len() {
let tmp = x[k];
y[k] = self.config.b[0] * tmp
+ self.config.b[1] * self.state[0]
+ self.config.b[2] * self.state[1]
- self.config.a[0] * self.state[2]
- self.config.a[1] * self.state[3];
self.state[1] = self.state[0];
self.state[0] = tmp;
self.state[3] = self.state[2];
self.state[2] = y[k];
}
}
/// Processes samples in-place.
pub fn process_in_place(&mut self, samples: &mut [f32]) {
for sample in samples.iter_mut() {
let tmp = *sample;
*sample = self.config.b[0] * tmp
+ self.config.b[1] * self.state[0]
+ self.config.b[2] * self.state[1]
- self.config.a[0] * self.state[2]
- self.config.a[1] * self.state[3];
self.state[1] = self.state[0];
self.state[0] = tmp;
self.state[3] = self.state[2];
self.state[2] = *sample;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const FRAME_SIZE: usize = 8;
const NUM_FRAMES: usize = 4;
const BIQUAD_INPUT_SEQ: [[f32; FRAME_SIZE]; NUM_FRAMES] = [
[
-87.166_29, -8.029_022, 101.619_58, -0.294_296, -5.825_764, -8.890_625, 10.310_432,
54.845_333,
],
[
-64.647_644,
-6.883_945,
11.059_189,
-95.242_54,
-108.870_834,
11.024_944,
63.044_1,
-52.709_583,
],
[
-32.350_53,
-18.108_028,
-74.022_34,
-8.986_874,
-1.525_581,
103.705_51,
6.346_226,
-14.319_557,
],
[
22.645_832,
-64.597_15,
55.462_52,
-109.393_19,
10.117_825,
-40.019_64,
-98.612_23,
-8.330_326,
],
];
// Computed as `scipy.signal.butter(N=2, Wn=60/24000, btype='highpass')`.
const BIQUAD_CONFIG: BiquadFilterConfig = BiquadFilterConfig {
b: [0.994_461_8, -1.988_923_5, 0.994_461_8],
a: [-1.988_892_9, 0.988_954_25],
};
// Comparing to scipy. The expected output is generated as follows:
// zi = np.float32([0, 0])
// for i in range(4):
// yn, zi = scipy.signal.lfilter(B, A, x[i], zi=zi)
// print(yn)
const BIQUAD_OUTPUT_SEQ: [[f32; FRAME_SIZE]; NUM_FRAMES] = [
[
-86.683_55,
-7.021_753_5,
102.102_9,
-0.374_873_33,
-5.872_058_5,
-8.855_216,
10.337_726,
54.511_57,
],
[
-64.925_316,
-6.763_96,
11.155_345,
-94.680_73,
-107.181_78,
13.246_425,
64.842_89,
-50.978_226,
],
[
-30.157_965,
-15.648_509,
-71.066_63,
-5.588_323,
1.911_753_5,
106.557_2,
8.571_83,
-12.062_985,
],
[
24.842_866,
-62.180_94,
57.914_88,
-106.656_86,
13.387_601,
-36.603_67,
-94.448_8,
-3.599_203_5,
],
];
/// Checks that the relative error between expected and computed values
/// is within tolerance.
fn expect_near_relative(expected: &[f32], computed: &[f32], tolerance: f32) {
assert_eq!(expected.len(), computed.len());
for (i, (&exp, &comp)) in expected.iter().zip(computed.iter()).enumerate() {
let abs_diff = (exp - comp).abs();
if abs_diff == 0.0 {
continue;
}
let den = if exp == 0.0 { 1.0 } else { exp.abs() };
assert!(
abs_diff / den <= tolerance,
"index {i}: expected {exp}, computed {comp}, relative error {}",
abs_diff / den,
);
}
}
#[test]
fn filter_not_in_place() {
let mut filter = BiquadFilter::new(BIQUAD_CONFIG);
let mut samples = [0.0_f32; FRAME_SIZE];
for (input, expected) in BIQUAD_INPUT_SEQ.iter().zip(&BIQUAD_OUTPUT_SEQ) {
filter.process(input, &mut samples);
expect_near_relative(expected, &samples, 2e-4);
}
}
#[test]
fn filter_in_place() {
let mut filter = BiquadFilter::new(BIQUAD_CONFIG);
let mut samples = [0.0_f32; FRAME_SIZE];
for (input, expected) in BIQUAD_INPUT_SEQ.iter().zip(&BIQUAD_OUTPUT_SEQ) {
samples.copy_from_slice(input);
filter.process_in_place(&mut samples);
expect_near_relative(expected, &samples, 2e-4);
}
}
#[test]
fn set_config_different_output() {
let mut filter = BiquadFilter::new(BiquadFilterConfig {
b: [0.978_030_5, -1.956_061, 0.978_030_5],
a: [-1.955_578_2, 0.956_543_7],
});
let mut samples1 = [0.0_f32; FRAME_SIZE];
for input in &BIQUAD_INPUT_SEQ {
filter.process(input, &mut samples1);
}
filter.set_config(BiquadFilterConfig {
b: [0.097_631_07, 0.195_262_15, 0.097_631_07],
a: [-0.942_809_04, 0.333_333_33],
});
let mut samples2 = [0.0_f32; FRAME_SIZE];
for input in &BIQUAD_INPUT_SEQ {
filter.process(input, &mut samples2);
}
assert_ne!(samples1, samples2);
}
#[test]
fn set_config_resets_state() {
let mut filter = BiquadFilter::new(BIQUAD_CONFIG);
let mut samples1 = [0.0_f32; FRAME_SIZE];
for input in &BIQUAD_INPUT_SEQ {
filter.process(input, &mut samples1);
}
filter.set_config(BIQUAD_CONFIG);
let mut samples2 = [0.0_f32; FRAME_SIZE];
for input in &BIQUAD_INPUT_SEQ {
filter.process(input, &mut samples2);
}
assert_eq!(samples1, samples2);
}
#[test]
fn reset() {
let mut filter = BiquadFilter::new(BIQUAD_CONFIG);
let mut samples1 = [0.0_f32; FRAME_SIZE];
for input in &BIQUAD_INPUT_SEQ {
filter.process(input, &mut samples1);
}
filter.reset();
let mut samples2 = [0.0_f32; FRAME_SIZE];
for input in &BIQUAD_INPUT_SEQ {
filter.process(input, &mut samples2);
}
assert_eq!(samples1, samples2);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,350 @@
//! Circular buffer for frame-wise level metrics used by the clipping predictor.
//!
//! Ported from `webrtc/modules/audio_processing/agc2/clipping_predictor_level_buffer.h/cc`.
/// Recommended maximum capacity. It is possible to create a buffer with a
/// larger capacity, but the implementation is not optimized for large values.
pub const MAX_CAPACITY: usize = 100;
/// Frame-wise level metrics: average (mean squared) and max (peak).
#[derive(Debug, Clone, Copy)]
pub struct Level {
pub average: f32,
pub max: f32,
}
impl PartialEq for Level {
fn eq(&self, other: &Self) -> bool {
const EPSILON: f32 = 1e-6;
(self.average - other.average).abs() < EPSILON && (self.max - other.max).abs() < EPSILON
}
}
/// A circular buffer to store frame-wise [`Level`] items for clipping prediction.
/// The current implementation is not optimized for large buffer lengths.
#[derive(Debug)]
pub struct ClippingPredictorLevelBuffer {
tail: isize,
size: usize,
data: Vec<Level>,
}
impl ClippingPredictorLevelBuffer {
/// Creates a new buffer with the given capacity (minimum 1).
/// Logs a warning if capacity exceeds [`MAX_CAPACITY`].
pub fn new(capacity: i32) -> Self {
let capacity = capacity.max(1) as usize;
if capacity > MAX_CAPACITY {
tracing::warn!(
"[agc]: ClippingPredictorLevelBuffer exceeds the maximum allowed capacity. Capacity: {}",
capacity
);
}
Self {
tail: -1,
size: 0,
data: vec![
Level {
average: 0.0,
max: 0.0
};
capacity
],
}
}
/// Resets the buffer, discarding all stored items.
pub fn reset(&mut self) {
self.tail = -1;
self.size = 0;
}
/// Returns the number of items currently in the buffer.
pub fn size(&self) -> usize {
self.size
}
/// Returns the capacity of the buffer.
pub fn capacity(&self) -> usize {
self.data.len()
}
/// Pushes a [`Level`] item into the circular buffer. If the buffer is full,
/// the oldest item is replaced.
pub fn push(&mut self, level: Level) {
self.tail += 1;
if self.tail as usize == self.capacity() {
self.tail = 0;
}
if self.size < self.capacity() {
self.size += 1;
}
self.data[self.tail as usize] = level;
}
/// If at least `num_items + delay` items have been pushed, returns the
/// average and maximum value for the `num_items` most recently pushed items
/// starting from `delay` positions back (delay=0 is the most recent item).
pub fn compute_partial_metrics(&self, delay: usize, num_items: usize) -> Option<Level> {
debug_assert!(delay < self.capacity());
debug_assert!(num_items > 0);
debug_assert!(num_items <= self.capacity());
debug_assert!(delay + num_items <= self.capacity());
if delay + num_items > self.size {
return None;
}
let mut sum = 0.0_f32;
let mut max = 0.0_f32;
for i in 0..num_items.min(self.size) {
let mut idx = self.tail - delay as isize - i as isize;
if idx < 0 {
idx += self.capacity() as isize;
}
sum += self.data[idx as usize].average;
max = max.max(self.data[idx as usize].max);
}
Some(Level {
average: sum / num_items as f32,
max,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
// Parametrized test helper: checks empty buffer size for various capacities.
#[test]
fn check_empty_buffer_size() {
for &capacity in &[-1, 0, 1, 123] {
let buffer = ClippingPredictorLevelBuffer::new(capacity);
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
assert_eq!(buffer.size(), 0);
}
}
#[test]
fn check_half_empty_buffer_size() {
for &capacity in &[-1, 0, 1, 123] {
let mut buffer = ClippingPredictorLevelBuffer::new(capacity);
for _ in 0..buffer.capacity() / 2 {
buffer.push(Level {
average: 2.0,
max: 4.0,
});
}
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
assert_eq!(buffer.size(), capacity.max(1) as usize / 2);
}
}
#[test]
fn check_full_buffer_size() {
for &capacity in &[-1, 0, 1, 123] {
let mut buffer = ClippingPredictorLevelBuffer::new(capacity);
for _ in 0..buffer.capacity() {
buffer.push(Level {
average: 2.0,
max: 4.0,
});
}
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
assert_eq!(buffer.size(), capacity.max(1) as usize);
}
}
#[test]
fn check_large_buffer_size() {
for &capacity in &[-1, 0, 1, 123] {
let mut buffer = ClippingPredictorLevelBuffer::new(capacity);
for _ in 0..2 * buffer.capacity() {
buffer.push(Level {
average: 2.0,
max: 4.0,
});
}
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
assert_eq!(buffer.size(), capacity.max(1) as usize);
}
}
#[test]
fn check_size_after_reset() {
for &capacity in &[-1, 0, 1, 123] {
let mut buffer = ClippingPredictorLevelBuffer::new(capacity);
buffer.push(Level {
average: 1.0,
max: 1.0,
});
buffer.push(Level {
average: 1.0,
max: 1.0,
});
buffer.reset();
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
assert_eq!(buffer.size(), 0);
buffer.push(Level {
average: 1.0,
max: 1.0,
});
assert_eq!(buffer.capacity(), capacity.max(1) as usize);
assert_eq!(buffer.size(), 1);
}
}
#[test]
fn check_metrics_after_full_buffer() {
let mut buffer = ClippingPredictorLevelBuffer::new(2);
buffer.push(Level {
average: 1.0,
max: 2.0,
});
buffer.push(Level {
average: 3.0,
max: 6.0,
});
let m = buffer.compute_partial_metrics(0, 1).unwrap();
assert_eq!(
m,
Level {
average: 3.0,
max: 6.0
}
);
let m = buffer.compute_partial_metrics(1, 1).unwrap();
assert_eq!(
m,
Level {
average: 1.0,
max: 2.0
}
);
let m = buffer.compute_partial_metrics(0, 2).unwrap();
assert_eq!(
m,
Level {
average: 2.0,
max: 6.0
}
);
}
#[test]
fn check_metrics_after_push_beyond_capacity() {
let mut buffer = ClippingPredictorLevelBuffer::new(2);
buffer.push(Level {
average: 1.0,
max: 1.0,
});
buffer.push(Level {
average: 3.0,
max: 6.0,
});
buffer.push(Level {
average: 5.0,
max: 10.0,
});
buffer.push(Level {
average: 7.0,
max: 14.0,
});
buffer.push(Level {
average: 6.0,
max: 12.0,
});
let m = buffer.compute_partial_metrics(0, 1).unwrap();
assert_eq!(
m,
Level {
average: 6.0,
max: 12.0
}
);
let m = buffer.compute_partial_metrics(1, 1).unwrap();
assert_eq!(
m,
Level {
average: 7.0,
max: 14.0
}
);
let m = buffer.compute_partial_metrics(0, 2).unwrap();
assert_eq!(
m,
Level {
average: 6.5,
max: 14.0
}
);
}
#[test]
fn check_metrics_after_too_few_items() {
let mut buffer = ClippingPredictorLevelBuffer::new(4);
buffer.push(Level {
average: 1.0,
max: 2.0,
});
buffer.push(Level {
average: 3.0,
max: 6.0,
});
assert!(buffer.compute_partial_metrics(0, 3).is_none());
assert!(buffer.compute_partial_metrics(2, 1).is_none());
}
#[test]
fn check_metrics_after_reset() {
let mut buffer = ClippingPredictorLevelBuffer::new(2);
buffer.push(Level {
average: 1.0,
max: 2.0,
});
buffer.reset();
buffer.push(Level {
average: 5.0,
max: 10.0,
});
buffer.push(Level {
average: 7.0,
max: 14.0,
});
let m = buffer.compute_partial_metrics(0, 1).unwrap();
assert_eq!(
m,
Level {
average: 7.0,
max: 14.0
}
);
let m = buffer.compute_partial_metrics(0, 2).unwrap();
assert_eq!(
m,
Level {
average: 6.0,
max: 14.0
}
);
let m = buffer.compute_partial_metrics(1, 1).unwrap();
assert_eq!(
m,
Level {
average: 5.0,
max: 10.0
}
);
}
}
+104
View File
@@ -0,0 +1,104 @@
//! AGC2 common constants and audio utility functions.
//!
//! Ported from `webrtc/modules/audio_processing/agc2/agc2_common.h`
//! and `webrtc/common_audio/include/audio_util.h`.
/// Minimum value of a float-encoded S16 sample (`-32768.0`).
pub const MIN_FLOAT_S16_VALUE: f32 = -32768.0;
/// Maximum value of a float-encoded S16 sample (`32767.0`).
pub const MAX_FLOAT_S16_VALUE: f32 = 32767.0;
/// Absolute maximum magnitude of a float-encoded S16 sample (`32768.0`).
pub const MAX_ABS_FLOAT_S16_VALUE: f32 = 32768.0;
/// Minimum audio level in dBFS scale for S16 samples (`20 * log10(1/32768)`).
pub const MIN_LEVEL_DBFS: f32 = -90.309;
/// Duration of one audio frame in milliseconds.
pub const FRAME_DURATION_MS: i32 = 10;
/// Number of sub-frames per frame (used for gain interpolation).
pub const SUB_FRAMES_IN_FRAME: i32 = 20;
/// Maximum number of samples per channel in a single frame (48 kHz * 10 ms).
pub const MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL: usize = 480;
// Adaptive digital gain applier settings.
/// At what limiter levels should we start decreasing the adaptive digital gain.
pub const LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS: f32 = -1.0;
/// Number of milliseconds to wait to periodically reset the VAD.
pub const VAD_RESET_PERIOD_MS: i32 = 1500;
/// Speech probability threshold to detect speech activity.
pub const VAD_CONFIDENCE_THRESHOLD: f32 = 0.95;
/// Minimum number of adjacent speech frames having a sufficiently high speech
/// probability to reliably detect speech activity.
pub const ADJACENT_SPEECH_FRAMES_THRESHOLD: i32 = 12;
/// Number of milliseconds of speech frames to observe to make the estimator
/// confident.
pub const LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS: f32 = 400.0;
/// Exponential decay factor for the speech level estimator.
pub const LEVEL_ESTIMATOR_LEAK_FACTOR: f32 = 1.0 - 1.0 / LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS;
/// Initial headroom in dB for the saturation protector.
pub const SATURATION_PROTECTOR_INITIAL_HEADROOM_DB: f32 = 20.0;
/// Ring buffer size (in 10 ms frames) for the saturation protector.
pub const SATURATION_PROTECTOR_BUFFER_SIZE: usize = 4;
/// Number of interpolation points in the knee region of the limiter gain curve.
///
/// These values have been tuned to limit the interpolated gain curve error given
/// the limiter parameters and allowing a maximum error of +/- 32768^-1.
pub const INTERPOLATED_GAIN_CURVE_KNEE_POINTS: usize = 22;
/// Number of interpolation points beyond the knee region.
pub const INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS: usize = 10;
/// Total number of interpolation points in the limiter gain curve.
pub const INTERPOLATED_GAIN_CURVE_TOTAL_POINTS: usize =
INTERPOLATED_GAIN_CURVE_KNEE_POINTS + INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS;
/// Maximum input level in dBFS for the limiter.
pub const LIMITER_MAX_INPUT_LEVEL_DB_FS: f64 = 1.0;
/// Smoothness of the limiter knee transition in dB.
pub const LIMITER_KNEE_SMOOTHNESS_DB: f64 = 1.0;
/// Compression ratio applied above the limiter knee.
pub const LIMITER_COMPRESSION_RATIO: f64 = 5.0;
// Audio utility functions ported from common_audio/include/audio_util.h.
/// Converts a dB value to a linear ratio: `10^(v/20)`.
pub fn db_to_ratio(v: f32) -> f32 {
10.0_f32.powf(v / 20.0)
}
/// Converts a dBFS value to a float S16 linear value.
pub fn dbfs_to_float_s16(v: f32) -> f32 {
db_to_ratio(v) * MAX_ABS_FLOAT_S16_VALUE
}
/// Converts a float S16 linear value to dBFS.
pub fn float_s16_to_dbfs(v: f32) -> f32 {
debug_assert!(v >= 0.0);
// kMinDbfs is equal to -20.0 * log10(-limits_int16::min())
const MIN_DBFS: f32 = -90.309;
if v <= 1.0 {
return MIN_DBFS;
}
// Equal to 20 * log10(v / (-limits_int16::min()))
20.0 * v.log10() + MIN_DBFS
}
/// Converts a dBFS value to a float S16 linear value (f64 version).
pub fn dbfs_to_float_s16_f64(v: f64) -> f64 {
10.0_f64.powf(v / 20.0) * MAX_ABS_FLOAT_S16_VALUE as f64
}
/// Converts a float S16 linear value to dBFS (f64 version).
pub fn float_s16_to_dbfs_f64(v: f64) -> f64 {
debug_assert!(v >= 0.0);
const MIN_DBFS: f64 = -90.308_998_699_194_36;
if v <= 1.0 {
return MIN_DBFS;
}
20.0 * v.log10() + MIN_DBFS
}
@@ -0,0 +1,317 @@
//! Peak envelope level estimator with exponential smoothing.
//!
//! Ported from `webrtc/modules/audio_processing/agc2/fixed_digital_level_estimator.h/.cc`.
use crate::common::SUB_FRAMES_IN_FRAME;
/// Initial filter state level.
const INITIAL_FILTER_STATE_LEVEL: f32 = 0.0;
/// Instant attack.
const ATTACK_FILTER_CONSTANT: f32 = 0.0;
/// Limiter decay constant.
/// Computed as `10 ** (-1/20 * subframe_duration / decay_ms)` where:
/// - `subframe_duration` is `FRAME_DURATION_MS / SUB_FRAMES_IN_FRAME`;
/// - `decay_ms` is 20.0 (from `agc2_testing_common.h`).
const DECAY_FILTER_CONSTANT: f32 = 0.9971259;
/// Produces a smooth signal level estimate from an input audio stream.
/// The estimate smoothing is done through exponential filtering.
#[derive(Debug)]
pub struct FixedDigitalLevelEstimator {
filter_state_level: f32,
samples_in_frame: i32,
samples_in_sub_frame: i32,
}
impl FixedDigitalLevelEstimator {
/// Creates a new estimator.
///
/// `samples_per_channel` must be divisible by `SUB_FRAMES_IN_FRAME`.
pub fn new(samples_per_channel: usize) -> Self {
let mut est = Self {
filter_state_level: INITIAL_FILTER_STATE_LEVEL,
samples_in_frame: 0,
samples_in_sub_frame: 0,
};
est.set_samples_per_channel(samples_per_channel);
est.check_parameter_combination();
est
}
/// Computes the level envelope for a multi-channel frame.
///
/// The input is assumed to be in FloatS16 format. Returns `SUB_FRAMES_IN_FRAME`
/// level estimates, one per sub-frame.
pub fn compute_level(&mut self, frame: &[&[f32]]) -> [f32; SUB_FRAMES_IN_FRAME as usize] {
let num_channels = frame.len();
debug_assert!(num_channels > 0);
debug_assert_eq!(frame[0].len(), self.samples_in_frame as usize);
// Compute max envelope without smoothing.
let mut envelope = [0.0_f32; SUB_FRAMES_IN_FRAME as usize];
let sub_frame_len = self.samples_in_sub_frame as usize;
for channel in frame {
for (sub_frame, env) in envelope.iter_mut().enumerate() {
let sub_frame_samples =
&channel[sub_frame * sub_frame_len..(sub_frame + 1) * sub_frame_len];
for &sample in sub_frame_samples {
*env = env.max(sample.abs());
}
}
}
// Make sure envelope increases happen one step earlier so that the
// corresponding *gain decrease* doesn't miss a sudden signal
// increase due to interpolation.
for sub_frame in 0..SUB_FRAMES_IN_FRAME as usize - 1 {
if envelope[sub_frame] < envelope[sub_frame + 1] {
envelope[sub_frame] = envelope[sub_frame + 1];
}
}
// Add attack / decay smoothing.
for env in &mut envelope {
let envelope_value = *env;
if envelope_value > self.filter_state_level {
*env = envelope_value * (1.0 - ATTACK_FILTER_CONSTANT)
+ self.filter_state_level * ATTACK_FILTER_CONSTANT;
} else {
*env = envelope_value * (1.0 - DECAY_FILTER_CONSTANT)
+ self.filter_state_level * DECAY_FILTER_CONSTANT;
}
self.filter_state_level = *env;
}
envelope
}
/// Changes the sample rate (samples per channel for a 10ms frame).
pub fn set_samples_per_channel(&mut self, samples_per_channel: usize) {
self.samples_in_frame = samples_per_channel as i32;
self.samples_in_sub_frame = self.samples_in_frame / SUB_FRAMES_IN_FRAME;
self.check_parameter_combination();
}
/// Resets the level estimator internal state.
pub fn reset(&mut self) {
self.filter_state_level = INITIAL_FILTER_STATE_LEVEL;
}
/// Returns the last computed audio level.
pub fn last_audio_level(&self) -> f32 {
self.filter_state_level
}
fn check_parameter_combination(&self) {
debug_assert!(self.samples_in_frame > 0);
debug_assert!(SUB_FRAMES_IN_FRAME <= self.samples_in_frame);
debug_assert_eq!(self.samples_in_frame % SUB_FRAMES_IN_FRAME, 0);
debug_assert!(self.samples_in_sub_frame > 1);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::{FRAME_DURATION_MS, SUB_FRAMES_IN_FRAME, dbfs_to_float_s16};
const INPUT_LEVEL: f32 = 10000.0;
/// Decay time constant in ms (from agc2_testing_common.h).
const DECAY_MS: f32 = 20.0;
/// Returns `sample_rate / 100` (samples per channel for 10ms).
fn sample_rate_to_default_channel_size(sample_rate: usize) -> usize {
sample_rate / 100
}
/// Run audio at specified settings through the level estimator, and
/// verify that the output level falls within the bounds.
fn test_level_estimator(
samples_per_channel: usize,
num_channels: usize,
input_level_linear_scale: f32,
expected_min: f32,
expected_max: f32,
) {
let mut level_estimator = FixedDigitalLevelEstimator::new(samples_per_channel);
// Create constant-level frame.
let channel_data = vec![input_level_linear_scale; samples_per_channel];
let channels: Vec<&[f32]> = vec![channel_data.as_slice(); num_channels];
for i in 0..500 {
let level = level_estimator.compute_level(&channels);
// Give the estimator some time to ramp up.
if i < 50 {
continue;
}
for x in &level {
assert!(
expected_min <= *x,
"level {x} < expected_min {expected_min} at frame {i}"
);
assert!(
*x <= expected_max,
"level {x} > expected_max {expected_max} at frame {i}"
);
}
}
}
/// Returns time it takes for the level estimator to decrease its level
/// estimate by `level_reduction_db`.
fn time_ms_to_decrease_level(
samples_per_channel: usize,
num_channels: usize,
input_level_db: f32,
level_reduction_db: f32,
) -> f32 {
let input_level = dbfs_to_float_s16(input_level_db);
debug_assert!(level_reduction_db > 0.0);
let channel_data = vec![input_level; samples_per_channel];
let channels: Vec<&[f32]> = vec![channel_data.as_slice(); num_channels];
let mut level_estimator = FixedDigitalLevelEstimator::new(samples_per_channel);
// Give the LevelEstimator plenty of time to ramp up and stabilize.
let mut last_level = 0.0_f32;
for _ in 0..500 {
let level_envelope = level_estimator.compute_level(&channels);
last_level = *level_envelope.last().unwrap();
}
// Set input to 0.
let zero_channel_data = vec![0.0_f32; samples_per_channel];
let zero_channels: Vec<&[f32]> = vec![zero_channel_data.as_slice(); num_channels];
let reduced_level_linear = dbfs_to_float_s16(input_level_db - level_reduction_db);
let mut sub_frames_until_level_reduction = 0;
while last_level > reduced_level_linear {
let level_envelope = level_estimator.compute_level(&zero_channels);
for v in &level_envelope {
assert!(*v < last_level, "level should decrease monotonically");
sub_frames_until_level_reduction += 1;
last_level = *v;
if last_level <= reduced_level_linear {
break;
}
}
}
sub_frames_until_level_reduction as f32 * FRAME_DURATION_MS as f32
/ SUB_FRAMES_IN_FRAME as f32
}
#[test]
fn estimator_should_not_crash() {
test_level_estimator(
sample_rate_to_default_channel_size(8000),
1,
0.0,
f32::MIN,
f32::MAX,
);
}
#[test]
fn estimator_should_estimate_constant_level() {
test_level_estimator(
sample_rate_to_default_channel_size(10000),
1,
INPUT_LEVEL,
INPUT_LEVEL * 0.99,
INPUT_LEVEL * 1.01,
);
}
#[test]
fn estimator_should_estimate_constant_level_for_many_channels() {
let num_channels = 10;
test_level_estimator(
sample_rate_to_default_channel_size(20000),
num_channels,
INPUT_LEVEL,
INPUT_LEVEL * 0.99,
INPUT_LEVEL * 1.01,
);
}
#[test]
fn time_to_decrease_for_low_level() {
let level_reduction_db = 25.0;
let initial_low_level = -40.0;
let expected_time = level_reduction_db * DECAY_MS;
let time_to_decrease = time_ms_to_decrease_level(
sample_rate_to_default_channel_size(22000),
1,
initial_low_level,
level_reduction_db,
);
assert!(
expected_time * 0.9 <= time_to_decrease,
"time_to_decrease {time_to_decrease} < expected {}",
expected_time * 0.9
);
assert!(
time_to_decrease <= expected_time * 1.1,
"time_to_decrease {time_to_decrease} > expected {}",
expected_time * 1.1
);
}
#[test]
fn time_to_decrease_for_full_scale_level() {
let level_reduction_db = 25.0;
let expected_time = level_reduction_db * DECAY_MS;
let time_to_decrease = time_ms_to_decrease_level(
sample_rate_to_default_channel_size(26000),
1,
0.0,
level_reduction_db,
);
assert!(
expected_time * 0.9 <= time_to_decrease,
"time_to_decrease {time_to_decrease} < expected {}",
expected_time * 0.9
);
assert!(
time_to_decrease <= expected_time * 1.1,
"time_to_decrease {time_to_decrease} > expected {}",
expected_time * 1.1
);
}
#[test]
fn time_to_decrease_for_multiple_channels() {
let level_reduction_db = 25.0;
let expected_time = level_reduction_db * DECAY_MS;
let num_channels = 10;
let time_to_decrease = time_ms_to_decrease_level(
sample_rate_to_default_channel_size(28000),
num_channels,
0.0,
level_reduction_db,
);
assert!(
expected_time * 0.9 <= time_to_decrease,
"time_to_decrease {time_to_decrease} < expected {}",
expected_time * 0.9
);
assert!(
time_to_decrease <= expected_time * 1.1,
"time_to_decrease {time_to_decrease} > expected {}",
expected_time * 1.1
);
}
}
+231
View File
@@ -0,0 +1,231 @@
//! Per-sample gain application with linear ramping.
//!
//! Ported from `webrtc/modules/audio_processing/agc2/gain_applier.h/.cc`.
use crate::common::{MAX_FLOAT_S16_VALUE, MIN_FLOAT_S16_VALUE};
/// Returns true when the gain factor is so close to 1 that it would
/// not affect int16 samples.
fn gain_close_to_one(gain_factor: f32) -> bool {
let threshold = 1.0 / MAX_FLOAT_S16_VALUE;
(1.0 - threshold..=1.0 + threshold).contains(&gain_factor)
}
/// Clamps all samples in multi-channel signal to FloatS16 range.
fn clip_signal(signal: &mut [&mut [f32]]) {
for channel in signal.iter_mut() {
for sample in channel.iter_mut() {
*sample = sample.clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
}
}
}
/// Applies gain with linear ramping across the frame.
fn apply_gain_with_ramping(
last_gain: f32,
gain_at_end: f32,
inverse_samples_per_channel: f32,
signal: &mut [&mut [f32]],
) {
// Do not modify the signal.
if last_gain == gain_at_end && gain_close_to_one(gain_at_end) {
return;
}
// Gain is constant and different from 1.
if last_gain == gain_at_end {
for channel in signal.iter_mut() {
for sample in channel.iter_mut() {
*sample *= gain_at_end;
}
}
return;
}
// The gain changes. Ramp linearly to avoid discontinuities.
let increment = (gain_at_end - last_gain) * inverse_samples_per_channel;
for channel in signal.iter_mut() {
let mut gain = last_gain;
for sample in channel.iter_mut() {
*sample *= gain;
gain += increment;
}
}
}
/// Applies a gain factor to multi-channel audio with linear ramping between
/// frames and optional hard clipping.
#[derive(Debug)]
pub struct GainApplier {
hard_clip_samples: bool,
last_gain_factor: f32,
current_gain_factor: f32,
samples_per_channel: i32,
inverse_samples_per_channel: f32,
}
impl GainApplier {
/// Creates a new gain applier.
///
/// - `hard_clip_samples`: if true, output is clamped to `[-32768, 32767]`
/// - `initial_gain_factor`: starting linear gain factor
pub fn new(hard_clip_samples: bool, initial_gain_factor: f32) -> Self {
Self {
hard_clip_samples,
last_gain_factor: initial_gain_factor,
current_gain_factor: initial_gain_factor,
samples_per_channel: -1,
inverse_samples_per_channel: -1.0,
}
}
/// Applies gain to the signal with linear ramping between frames.
pub fn apply_gain(&mut self, signal: &mut [&mut [f32]]) {
let spc = signal.first().map_or(0, |ch| ch.len()) as i32;
if spc != self.samples_per_channel {
self.initialize(spc);
}
apply_gain_with_ramping(
self.last_gain_factor,
self.current_gain_factor,
self.inverse_samples_per_channel,
signal,
);
self.last_gain_factor = self.current_gain_factor;
if self.hard_clip_samples {
clip_signal(signal);
}
}
/// Sets the target gain factor for the next frame.
pub fn set_gain_factor(&mut self, gain_factor: f32) {
debug_assert!(gain_factor > 0.0);
self.current_gain_factor = gain_factor;
}
/// Returns the current gain factor.
pub fn get_gain_factor(&self) -> f32 {
self.current_gain_factor
}
fn initialize(&mut self, samples_per_channel: i32) {
debug_assert!(samples_per_channel > 0);
self.samples_per_channel = samples_per_channel;
self.inverse_samples_per_channel = 1.0 / samples_per_channel as f32;
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Creates a multi-channel audio frame filled with a constant value.
fn make_frame(num_channels: usize, samples_per_channel: usize, value: f32) -> Vec<Vec<f32>> {
vec![vec![value; samples_per_channel]; num_channels]
}
/// Converts `Vec<Vec<f32>>` to `&mut [&mut [f32]]` for the API.
fn as_mut_slices(frame: &mut [Vec<f32>]) -> Vec<&mut [f32]> {
frame.iter_mut().map(|ch| ch.as_mut_slice()).collect()
}
#[test]
fn initial_gain_is_respected() {
let initial_signal_level = 123.0_f32;
let gain_factor = 10.0_f32;
let mut frame = make_frame(1, 1, initial_signal_level);
let mut gain_applier = GainApplier::new(true, gain_factor);
let mut slices = as_mut_slices(&mut frame);
gain_applier.apply_gain(&mut slices);
assert!(
(frame[0][0] - initial_signal_level * gain_factor).abs() < 0.1,
"expected ~{}, got {}",
initial_signal_level * gain_factor,
frame[0][0]
);
}
#[test]
fn clipping_is_done() {
let initial_signal_level = 30000.0_f32;
let gain_factor = 10.0_f32;
let mut frame = make_frame(1, 1, initial_signal_level);
let mut gain_applier = GainApplier::new(true, gain_factor);
let mut slices = as_mut_slices(&mut frame);
gain_applier.apply_gain(&mut slices);
assert!(
(frame[0][0] - i16::MAX as f32).abs() < 0.1,
"expected ~{}, got {}",
i16::MAX,
frame[0][0]
);
}
#[test]
fn clipping_is_not_done() {
let initial_signal_level = 30000.0_f32;
let gain_factor = 10.0_f32;
let mut frame = make_frame(1, 1, initial_signal_level);
let mut gain_applier = GainApplier::new(false, gain_factor);
let mut slices = as_mut_slices(&mut frame);
gain_applier.apply_gain(&mut slices);
assert!(
(frame[0][0] - initial_signal_level * gain_factor).abs() < 0.1,
"expected ~{}, got {}",
initial_signal_level * gain_factor,
frame[0][0]
);
}
#[test]
fn ramping_is_done() {
let initial_signal_level = 30000.0_f32;
let initial_gain_factor = 1.0_f32;
let target_gain_factor = 0.5_f32;
let num_channels = 3;
let samples_per_channel = 4;
let mut frame = make_frame(num_channels, samples_per_channel, initial_signal_level);
let mut gain_applier = GainApplier::new(false, initial_gain_factor);
gain_applier.set_gain_factor(target_gain_factor);
let mut slices = as_mut_slices(&mut frame);
gain_applier.apply_gain(&mut slices);
// The maximal gain change should be close to linear interpolation.
for (channel, ch_data) in frame.iter().enumerate() {
let mut max_signal_change = 0.0_f32;
let mut last_signal_level = initial_signal_level;
for &sample in ch_data {
let current_change = (last_signal_level - sample).abs();
max_signal_change = max_signal_change.max(current_change);
last_signal_level = sample;
}
let total_gain_change =
((initial_gain_factor - target_gain_factor) * initial_signal_level).abs();
assert!(
(max_signal_change - total_gain_change / samples_per_channel as f32).abs() < 0.1,
"channel {channel}: max_change {max_signal_change}, expected ~{}",
total_gain_change / samples_per_channel as f32,
);
}
// Next frame should have the desired level.
let mut next_frame = make_frame(num_channels, samples_per_channel, initial_signal_level);
let mut slices = as_mut_slices(&mut next_frame);
gain_applier.apply_gain(&mut slices);
// The first sample should have the new gain (no ramping needed).
assert!(
(next_frame[0][0] - initial_signal_level * target_gain_factor).abs() < 0.1,
"expected ~{}, got {}",
initial_signal_level * target_gain_factor,
next_frame[0][0]
);
}
}
+581
View File
@@ -0,0 +1,581 @@
//! Interpolated gain curve using piecewise-linear under-approximation.
//!
//! Ported from `webrtc/modules/audio_processing/agc2/interpolated_gain_curve.h/.cc`.
use std::cmp::Ordering;
use crate::common::{INTERPOLATED_GAIN_CURVE_KNEE_POINTS, INTERPOLATED_GAIN_CURVE_TOTAL_POINTS};
/// Defined as `DbfsToLinear(kLimiterMaxInputLevelDbFs)`.
const MAX_INPUT_LEVEL_LINEAR: f32 = 36_766.3;
/// Region of the gain curve.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GainCurveRegion {
Identity = 0,
Knee = 1,
Limiter = 2,
Saturation = 3,
}
/// Statistics tracking for gain curve lookups.
#[derive(Debug, Clone)]
pub struct Stats {
pub look_ups_identity_region: usize,
pub look_ups_knee_region: usize,
pub look_ups_limiter_region: usize,
pub look_ups_saturation_region: usize,
pub available: bool,
pub region: GainCurveRegion,
pub region_duration_frames: i64,
}
impl Default for Stats {
fn default() -> Self {
Self {
look_ups_identity_region: 0,
look_ups_knee_region: 0,
look_ups_limiter_region: 0,
look_ups_saturation_region: 0,
available: false,
region: GainCurveRegion::Identity,
region_duration_frames: 0,
}
}
}
/// Interpolated gain curve using piecewise-linear under-approximation to avoid
/// saturation.
#[derive(Debug, Default)]
pub struct InterpolatedGainCurve {
pub stats: Stats,
}
// Pre-computed approximation parameters (x boundaries, slopes m, intercepts q).
// These are static constexpr in the C++ header.
const APPROXIMATION_PARAMS_X: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS] = [
30057.297, 30148.986, 30240.676, 30424.053, 30607.43, 30790.807, 30974.184, 31157.56, 31340.94,
31524.316, 31707.693, 31891.07, 32074.447, 32257.824, 32441.201, 32624.58, 32807.957,
32991.332, 33174.71, 33358.09, 33541.465, 33724.844, 33819.535, 34009.54, 34200.06, 34389.816,
34674.49, 35054.375, 35434.863, 35814.816, 36195.168, 36575.03,
];
const APPROXIMATION_PARAMS_M: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS] = [
-3.515_235_7e-07,
-1.050_251_6e-06,
-2.085_213_7e-06,
-3.443_004_7e-06,
-4.773_849_5e-06,
-6.077_376e-06,
-7.353_258e-6,
-8.601_22e-06,
-9.821_013e-06,
-1.101_243_4e-05,
-1.217_532_6e-05,
-1.330_956_9e-05,
-1.441_507_5e-05,
-1.549_179_3e-05,
-1.653_970_7e-05,
-1.755_882_8e-05,
-1.854_918_4e-05,
-1.951_086_8e-05,
-2.044_398e-05,
-2.134_862_7e-05,
-2.222_497e-5,
-2.265_374_7e-05,
-2.242_571e-5,
-2.220_122e-05,
-2.198_021e-05,
-2.176_260_2e-05,
-2.133_731_7e-05,
-2.092_482e-5,
-2.052_459_6e-05,
-2.013_615_4e-05,
-1.975_903e-5,
-1.939_277_9e-05,
];
const APPROXIMATION_PARAMS_Q: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS] = [
1.010_565_9,
1.031_631_8,
1.062_929_7,
1.104_239_2,
1.144_973,
1.185_109_6,
1.224_629,
1.263_512_5,
1.301_742,
1.339_300_6,
1.376_173_3,
1.412_345_5,
1.447_804,
1.482_536_6,
1.516_532_2,
1.549_780_6,
1.582_272_2,
1.613_999_4,
1.644_955,
1.675_132_4,
1.704_526_2,
1.718_986_6,
1.711_274_5,
1.703_639_7,
1.696_081_2,
1.688_597_7,
1.673_851_1,
1.659_391_3,
1.645_209_4,
1.631_297_5,
1.617_647_4,
1.604_251_7,
];
impl InterpolatedGainCurve {
/// Returns the statistics for gain curve region lookups.
pub fn get_stats(&self) -> &Stats {
&self.stats
}
/// Given a non-negative input level (linear scale), returns a scalar gain
/// factor to apply. Levels above `kLimiterMaxInputLevelDbFs` will be
/// reduced to 0 dBFS after applying this gain.
pub fn look_up_gain_to_apply(&mut self, input_level: f32) -> f32 {
self.update_stats(input_level);
if input_level <= APPROXIMATION_PARAMS_X[0] {
// Identity region.
return 1.0;
}
if input_level >= MAX_INPUT_LEVEL_LINEAR {
// Saturation region: clamp to clipping level.
return 32768.0 / input_level;
}
// Knee and limiter regions: find the linear piece index via binary search.
let index = match APPROXIMATION_PARAMS_X
.binary_search_by(|x| x.partial_cmp(&input_level).unwrap_or(Ordering::Equal))
{
Ok(i) => i.saturating_sub(1),
Err(i) => i.saturating_sub(1),
};
debug_assert!(index < APPROXIMATION_PARAMS_M.len());
debug_assert!(APPROXIMATION_PARAMS_X[index] <= input_level);
// Piecewise linear interpolation.
let gain = APPROXIMATION_PARAMS_M[index] * input_level + APPROXIMATION_PARAMS_Q[index];
debug_assert!(gain >= 0.0);
gain
}
fn update_stats(&mut self, input_level: f32) {
self.stats.available = true;
let region = if input_level < APPROXIMATION_PARAMS_X[0] {
self.stats.look_ups_identity_region += 1;
GainCurveRegion::Identity
} else if input_level < APPROXIMATION_PARAMS_X[INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1] {
self.stats.look_ups_knee_region += 1;
GainCurveRegion::Knee
} else if input_level < MAX_INPUT_LEVEL_LINEAR {
self.stats.look_ups_limiter_region += 1;
GainCurveRegion::Limiter
} else {
self.stats.look_ups_saturation_region += 1;
GainCurveRegion::Saturation
};
if region == self.stats.region {
self.stats.region_duration_frames += 1;
} else {
self.stats.region_duration_frames = 0;
self.stats.region = region;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::{MAX_ABS_FLOAT_S16_VALUE, dbfs_to_float_s16};
use crate::limiter_db_gain_curve::LimiterDbGainCurve;
const LEVEL_EPSILON: f64 = 1e-2 * MAX_ABS_FLOAT_S16_VALUE as f64;
const TOLERANCE: f32 = 1.0 / 32768.0;
/// Returns evenly spaced points over `[l, r]`.
fn lin_space(l: f64, r: f64, num_points: usize) -> Vec<f64> {
assert!(num_points >= 2);
let step = (r - l) / (num_points - 1) as f64;
let mut points = Vec::with_capacity(num_points);
points.push(l);
for i in 1..num_points - 1 {
points.push(l + i as f64 * step);
}
points.push(r);
points
}
#[test]
fn create_use() {
let mut igc = InterpolatedGainCurve::default();
let limiter = LimiterDbGainCurve::default();
let levels = lin_space(
LEVEL_EPSILON,
dbfs_to_float_s16(limiter.max_input_level_db() as f32 + 1.0) as f64,
500,
);
for level in levels {
assert!(igc.look_up_gain_to_apply(level as f32) >= 0.0);
}
}
#[test]
fn check_valid_output() {
let mut igc = InterpolatedGainCurve::default();
let limiter = LimiterDbGainCurve::default();
let levels = lin_space(LEVEL_EPSILON, limiter.max_input_level_linear() * 2.0, 500);
for level in levels {
let gain = igc.look_up_gain_to_apply(level as f32);
assert!(
(0.0..=1.0).contains(&gain),
"gain {gain} out of range at level {level}"
);
}
}
#[test]
fn check_monotonicity() {
let mut igc = InterpolatedGainCurve::default();
let limiter = LimiterDbGainCurve::default();
let levels = lin_space(
LEVEL_EPSILON,
limiter.max_input_level_linear() + LEVEL_EPSILON + 0.5,
500,
);
let mut prev_gain = igc.look_up_gain_to_apply(0.0);
for level in levels {
let gain = igc.look_up_gain_to_apply(level as f32);
assert!(
prev_gain >= gain,
"not monotone at level {level}: {prev_gain} < {gain}"
);
prev_gain = gain;
}
}
#[test]
fn check_approximation() {
let mut igc = InterpolatedGainCurve::default();
let limiter = LimiterDbGainCurve::default();
let levels = lin_space(
LEVEL_EPSILON,
limiter.max_input_level_linear() - LEVEL_EPSILON,
500,
);
for level in levels {
let diff = (limiter.get_gain_linear(level) as f32
- igc.look_up_gain_to_apply(level as f32))
.abs();
assert!(
diff < TOLERANCE,
"approximation error {diff} at level {level}"
);
}
}
#[test]
fn check_region_boundaries() {
let mut igc = InterpolatedGainCurve::default();
let limiter = LimiterDbGainCurve::default();
igc.look_up_gain_to_apply(LEVEL_EPSILON as f32);
igc.look_up_gain_to_apply((limiter.knee_start_linear() + LEVEL_EPSILON) as f32);
igc.look_up_gain_to_apply((limiter.limiter_start_linear() + LEVEL_EPSILON) as f32);
igc.look_up_gain_to_apply((limiter.max_input_level_linear() + LEVEL_EPSILON) as f32);
let stats = &igc.stats;
assert_eq!(1, stats.look_ups_identity_region);
assert_eq!(1, stats.look_ups_knee_region);
assert_eq!(1, stats.look_ups_limiter_region);
assert_eq!(1, stats.look_ups_saturation_region);
}
#[test]
fn check_identity_region() {
const NUM_STEPS: usize = 10;
let mut igc = InterpolatedGainCurve::default();
let limiter = LimiterDbGainCurve::default();
let levels = lin_space(LEVEL_EPSILON, limiter.knee_start_linear(), NUM_STEPS);
for level in &levels {
assert_eq!(1.0, igc.look_up_gain_to_apply(*level as f32));
}
let stats = &igc.stats;
assert_eq!(NUM_STEPS - 1, stats.look_ups_identity_region);
assert_eq!(1, stats.look_ups_knee_region);
assert_eq!(0, stats.look_ups_limiter_region);
assert_eq!(0, stats.look_ups_saturation_region);
}
#[test]
fn check_no_over_approximation_knee() {
const NUM_STEPS: usize = 10;
let mut igc = InterpolatedGainCurve::default();
let limiter = LimiterDbGainCurve::default();
let levels = lin_space(
limiter.knee_start_linear() + LEVEL_EPSILON,
limiter.limiter_start_linear(),
NUM_STEPS,
);
for level in &levels {
assert!(
igc.look_up_gain_to_apply(*level as f32)
<= limiter.get_gain_linear(*level) as f32 + 1e-7,
"over-approximation at level {level}"
);
}
let stats = &igc.stats;
assert_eq!(0, stats.look_ups_identity_region);
assert_eq!(NUM_STEPS - 1, stats.look_ups_knee_region);
assert_eq!(1, stats.look_ups_limiter_region);
assert_eq!(0, stats.look_ups_saturation_region);
}
#[test]
fn check_no_over_approximation_beyond_knee() {
const NUM_STEPS: usize = 10;
let mut igc = InterpolatedGainCurve::default();
let limiter = LimiterDbGainCurve::default();
let levels = lin_space(
limiter.limiter_start_linear() + LEVEL_EPSILON,
limiter.max_input_level_linear() - LEVEL_EPSILON,
NUM_STEPS,
);
for level in &levels {
assert!(
igc.look_up_gain_to_apply(*level as f32)
<= limiter.get_gain_linear(*level) as f32 + 1e-7,
"over-approximation at level {level}"
);
}
let stats = &igc.stats;
assert_eq!(0, stats.look_ups_identity_region);
assert_eq!(0, stats.look_ups_knee_region);
assert_eq!(NUM_STEPS, stats.look_ups_limiter_region);
assert_eq!(0, stats.look_ups_saturation_region);
}
#[test]
fn check_no_over_approximation_with_saturation() {
const NUM_STEPS: usize = 3;
let mut igc = InterpolatedGainCurve::default();
let limiter = LimiterDbGainCurve::default();
let levels = lin_space(
limiter.max_input_level_linear() + LEVEL_EPSILON,
limiter.max_input_level_linear() + LEVEL_EPSILON + 0.5,
NUM_STEPS,
);
for level in &levels {
assert!(
igc.look_up_gain_to_apply(*level as f32) <= limiter.get_gain_linear(*level) as f32,
"over-approximation at level {level}"
);
}
let stats = &igc.stats;
assert_eq!(0, stats.look_ups_identity_region);
assert_eq!(0, stats.look_ups_knee_region);
assert_eq!(0, stats.look_ups_limiter_region);
assert_eq!(NUM_STEPS, stats.look_ups_saturation_region);
}
#[test]
fn check_approximation_params() {
let params = compute_interpolated_gain_curve_approximation_params();
let igc = InterpolatedGainCurve::default();
for i in 0..INTERPOLATED_GAIN_CURVE_TOTAL_POINTS {
assert!(
(APPROXIMATION_PARAMS_X[i] - params.x[i]).abs() < 0.9,
"x[{i}]: {} vs {}",
APPROXIMATION_PARAMS_X[i],
params.x[i]
);
assert!(
(APPROXIMATION_PARAMS_M[i] - params.m[i]).abs() < 0.00001,
"m[{i}]: {} vs {}",
APPROXIMATION_PARAMS_M[i],
params.m[i]
);
assert!(
(APPROXIMATION_PARAMS_Q[i] - params.q[i]).abs() < 0.001,
"q[{i}]: {} vs {}",
APPROXIMATION_PARAMS_Q[i],
params.q[i]
);
}
// Silence unused variable warning.
let _ = igc;
}
/// Computed approximation parameters for verification.
struct InterpolatedParameters {
x: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
m: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
q: [f32; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
}
/// Recomputes the interpolated gain curve parameters from the analytical
/// `LimiterDbGainCurve`. Port of `compute_interpolated_gain_curve.cc`.
fn compute_interpolated_gain_curve_approximation_params() -> InterpolatedParameters {
use crate::common::{
INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS, INTERPOLATED_GAIN_CURVE_KNEE_POINTS,
};
let limiter = LimiterDbGainCurve::default();
let mut params = InterpolatedParameters {
x: [0.0; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
m: [0.0; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
q: [0.0; INTERPOLATED_GAIN_CURVE_TOTAL_POINTS],
};
// Knee region: equally spaced points with an extra point at the start.
let knee_points = lin_space(
limiter.knee_start_linear(),
limiter.limiter_start_linear(),
INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1,
);
params.x[0] = knee_points[0] as f32;
params.x[1] = ((knee_points[0] + knee_points[1]) / 2.0) as f32;
for (i, &kp) in knee_points.iter().enumerate().skip(1) {
params.x[i + 1] = kp as f32;
}
// Compute (m, q) for knee region linear pieces.
for i in 0..INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1 {
let x0 = params.x[i] as f64;
let x1 = params.x[i + 1] as f64;
let y0 = limiter.get_gain_linear(x0);
let y1 = limiter.get_gain_linear(x1);
params.m[i] = ((y1 - y0) / (x1 - x0)) as f32;
params.q[i] = (y0 - params.m[i] as f64 * x0) as f32;
}
// Beyond-knee region: sample using greedy error minimization.
let samples = sample_limiter_region(&limiter);
// First beyond-knee piece uses the last knee point as boundary.
let (m, q) = compute_linear_approximation_params(
&limiter,
params.x[INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1] as f64,
);
params.m[INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1] = m as f32;
params.q[INTERPOLATED_GAIN_CURVE_KNEE_POINTS - 1] = q as f32;
for (i, &sample) in samples.iter().enumerate() {
let (m, q) = compute_linear_approximation_params(&limiter, sample);
params.m[i + INTERPOLATED_GAIN_CURVE_KNEE_POINTS] = m as f32;
params.q[i + INTERPOLATED_GAIN_CURVE_KNEE_POINTS] = q as f32;
}
// Find intersection points between adjacent linear pieces.
for i in INTERPOLATED_GAIN_CURVE_KNEE_POINTS
..INTERPOLATED_GAIN_CURVE_KNEE_POINTS + INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS
{
params.x[i] = ((params.q[i - 1] as f64 - params.q[i] as f64)
/ (params.m[i] as f64 - params.m[i - 1] as f64)) as f32;
}
params
}
fn compute_linear_approximation_params(limiter: &LimiterDbGainCurve, x: f64) -> (f64, f64) {
let m = limiter.get_gain_first_derivative_linear(x);
let q = limiter.get_gain_linear(x) - m * x;
(m, q)
}
fn limiter_under_approximation_negative_error(
limiter: &LimiterDbGainCurve,
x0: f64,
x1: f64,
) -> f64 {
let area_limiter = limiter.get_gain_integral_linear(x0, x1);
let area_interpolated = compute_area_under_piecewise_linear_approximation(limiter, x0, x1);
area_limiter - area_interpolated
}
fn compute_area_under_piecewise_linear_approximation(
limiter: &LimiterDbGainCurve,
x0: f64,
x1: f64,
) -> f64 {
let (m0, q0) = compute_linear_approximation_params(limiter, x0);
let (m1, q1) = compute_linear_approximation_params(limiter, x1);
let x_split = (q0 - q1) / (m1 - m0);
let area =
|xl: f64, xr: f64, m: f64, q: f64| xr * (m * xr / 2.0 + q) - xl * (m * xl / 2.0 + q);
area(x0, x_split, m0, q0) + area(x_split, x1, m1, q1)
}
fn sample_limiter_region(limiter: &LimiterDbGainCurve) -> Vec<f64> {
use std::cmp::Ordering;
use std::collections::BinaryHeap;
#[derive(PartialEq)]
struct Interval {
x0: f64,
x1: f64,
error: f64,
}
impl Eq for Interval {}
impl PartialOrd for Interval {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Interval {
fn cmp(&self, other: &Self) -> Ordering {
self.error.total_cmp(&other.error)
}
}
let mut heap = BinaryHeap::new();
let start = limiter.limiter_start_linear();
let end = limiter.max_input_level_linear();
heap.push(Interval {
x0: start,
x1: end,
error: limiter_under_approximation_negative_error(limiter, start, end),
});
use crate::common::INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS;
while heap.len() < INTERPOLATED_GAIN_CURVE_BEYOND_KNEE_POINTS {
let interval = heap.pop().unwrap();
let x_split = (interval.x0 + interval.x1) / 2.0;
heap.push(Interval {
x0: interval.x0,
x1: x_split,
error: limiter_under_approximation_negative_error(limiter, interval.x0, x_split),
});
heap.push(Interval {
x0: x_split,
x1: interval.x1,
error: limiter_under_approximation_negative_error(limiter, x_split, interval.x1),
});
}
let mut samples: Vec<f64> = heap.into_iter().map(|i| i.x1).collect();
samples.sort_by(|a, b| a.partial_cmp(b).unwrap());
samples
}
}
+18
View File
@@ -0,0 +1,18 @@
#![doc = include_str!("../README.md")]
pub mod adaptive_digital_gain_controller;
pub mod biquad_filter;
pub mod clipping_predictor;
pub mod clipping_predictor_level_buffer;
pub mod common;
pub mod fixed_digital_level_estimator;
pub mod gain_applier;
pub mod interpolated_gain_curve;
pub mod limiter;
pub mod limiter_db_gain_curve;
pub mod noise_level_estimator;
pub(crate) mod rnn_vad;
pub mod saturation_protector;
pub mod saturation_protector_buffer;
pub mod speech_level_estimator;
pub mod vad_wrapper;
+180
View File
@@ -0,0 +1,180 @@
//! Output limiter with interpolated gain curve and per-sample scaling.
//!
//! Ported from `webrtc/modules/audio_processing/agc2/limiter.h/.cc`.
use crate::common::{
MAX_FLOAT_S16_VALUE, MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL, MIN_FLOAT_S16_VALUE,
SUB_FRAMES_IN_FRAME,
};
use crate::fixed_digital_level_estimator::FixedDigitalLevelEstimator;
use crate::interpolated_gain_curve::InterpolatedGainCurve;
/// Power used for interpolation of the first sub-frame during attack.
/// Reduces the chances of over-shooting (and hence saturation).
const ATTACK_FIRST_SUBFRAME_INTERPOLATION_POWER: f32 = 8.0;
fn interpolate_first_subframe(last_factor: f32, current_factor: f32, subframe: &mut [f32]) {
let n = subframe.len() as f32;
let p = ATTACK_FIRST_SUBFRAME_INTERPOLATION_POWER;
for (i, sample) in subframe.iter_mut().enumerate() {
let t = i as f32 / n;
*sample = (1.0 - t).powf(p) * (last_factor - current_factor) + current_factor;
}
}
fn compute_per_sample_subframe_factors(
scaling_factors: &[f32],
per_sample_scaling_factors: &mut [f32],
) {
let num_subframes = scaling_factors.len() - 1;
let subframe_size = per_sample_scaling_factors.len() / num_subframes;
debug_assert_eq!(per_sample_scaling_factors.len() % num_subframes, 0);
// Handle first sub-frame differently in case of attack.
let is_attack = scaling_factors[0] > scaling_factors[1];
if is_attack {
interpolate_first_subframe(
scaling_factors[0],
scaling_factors[1],
&mut per_sample_scaling_factors[..subframe_size],
);
}
let start = if is_attack { 1 } else { 0 };
for i in start..num_subframes {
let subframe_start = i * subframe_size;
let scaling_start = scaling_factors[i];
let scaling_end = scaling_factors[i + 1];
let scaling_diff = (scaling_end - scaling_start) / subframe_size as f32;
for j in 0..subframe_size {
per_sample_scaling_factors[subframe_start + j] =
scaling_start + scaling_diff * j as f32;
}
}
}
fn scale_samples(per_sample_scaling_factors: &[f32], signal: &mut [&mut [f32]]) {
let samples_per_channel = signal.first().map_or(0, |ch| ch.len());
debug_assert_eq!(samples_per_channel, per_sample_scaling_factors.len());
for channel in signal.iter_mut() {
for (sample, &factor) in channel.iter_mut().zip(per_sample_scaling_factors) {
*sample = (*sample * factor).clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
}
}
}
/// Output limiter that applies gain curve compression and hard clipping.
#[derive(Debug)]
pub struct Limiter {
interp_gain_curve: InterpolatedGainCurve,
level_estimator: FixedDigitalLevelEstimator,
scaling_factors: [f32; SUB_FRAMES_IN_FRAME as usize + 1],
per_sample_scaling_factors: [f32; MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL],
last_scaling_factor: f32,
}
impl Limiter {
/// Creates a new limiter.
///
/// `samples_per_channel` must be <= `MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL`
/// and divisible by `SUB_FRAMES_IN_FRAME`.
pub fn new(samples_per_channel: usize) -> Self {
debug_assert!(samples_per_channel <= MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL);
Self {
interp_gain_curve: InterpolatedGainCurve::default(),
level_estimator: FixedDigitalLevelEstimator::new(samples_per_channel),
scaling_factors: [0.0; SUB_FRAMES_IN_FRAME as usize + 1],
per_sample_scaling_factors: [0.0; MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL],
last_scaling_factor: 1.0,
}
}
/// Applies limiter and hard-clipping to the signal.
pub fn process(&mut self, signal: &mut [&mut [f32]]) {
let samples_per_channel = signal.first().map_or(0, |ch| ch.len());
debug_assert!(samples_per_channel <= MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL);
// Mono capture needs only a stack descriptor; keep the generic multichannel path.
let level_estimate = if signal.len() == 1 {
self.level_estimator.compute_level(&[&*signal[0]])
} else {
let signal_refs: Vec<&[f32]> = signal.iter().map(|ch| &**ch).collect();
self.level_estimator.compute_level(&signal_refs)
};
debug_assert_eq!(level_estimate.len() + 1, self.scaling_factors.len());
self.scaling_factors[0] = self.last_scaling_factor;
for (i, &level) in level_estimate.iter().enumerate() {
self.scaling_factors[i + 1] = self.interp_gain_curve.look_up_gain_to_apply(level);
}
compute_per_sample_subframe_factors(
&self.scaling_factors,
&mut self.per_sample_scaling_factors[..samples_per_channel],
);
scale_samples(
&self.per_sample_scaling_factors[..samples_per_channel],
signal,
);
self.last_scaling_factor = self.scaling_factors[SUB_FRAMES_IN_FRAME as usize];
}
/// Changes the sample rate.
pub fn set_samples_per_channel(&mut self, samples_per_channel: usize) {
debug_assert!(samples_per_channel <= MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL);
self.level_estimator
.set_samples_per_channel(samples_per_channel);
}
/// Resets the internal state.
pub fn reset(&mut self) {
self.level_estimator.reset();
}
/// Returns the last audio level from the level estimator.
pub fn last_audio_level(&self) -> f32 {
self.level_estimator.last_audio_level()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::{MAX_ABS_FLOAT_S16_VALUE, dbfs_to_float_s16};
#[test]
fn limiter_should_construct_and_run() {
let samples_per_channel = 480;
let mut limiter = Limiter::new(samples_per_channel);
let mut buffer = vec![MAX_ABS_FLOAT_S16_VALUE; samples_per_channel];
let mut channels: Vec<&mut [f32]> = vec![buffer.as_mut_slice()];
limiter.process(&mut channels);
}
#[test]
fn output_volume_above_threshold() {
let samples_per_channel = 480;
let input_level = (MAX_ABS_FLOAT_S16_VALUE + dbfs_to_float_s16(1.0)) / 2.0;
let mut limiter = Limiter::new(samples_per_channel);
// Give the level estimator time to adapt.
for _ in 0..5 {
let mut buffer = vec![input_level; samples_per_channel];
let mut channels: Vec<&mut [f32]> = vec![buffer.as_mut_slice()];
limiter.process(&mut channels);
}
let mut buffer = vec![input_level; samples_per_channel];
let mut channels: Vec<&mut [f32]> = vec![buffer.as_mut_slice()];
limiter.process(&mut channels);
for &sample in channels[0].iter() {
assert!(
0.9 * MAX_ABS_FLOAT_S16_VALUE < sample,
"sample {sample} should be above threshold {}",
0.9 * MAX_ABS_FLOAT_S16_VALUE
);
}
}
}
+236
View File
@@ -0,0 +1,236 @@
//! Limiter dB gain curve.
//!
//! Ported from `webrtc/modules/audio_processing/agc2/limiter_db_gain_curve.h/.cc`.
use crate::common::{
LIMITER_COMPRESSION_RATIO, LIMITER_KNEE_SMOOTHNESS_DB, LIMITER_MAX_INPUT_LEVEL_DB_FS,
MAX_ABS_FLOAT_S16_VALUE, dbfs_to_float_s16_f64, float_s16_to_dbfs_f64,
};
/// A limiter gain curve (in dB scale) with four regions:
/// identity (linear), knee (quadratic polynomial), compression (linear),
/// saturation (linear).
#[derive(Debug)]
pub struct LimiterDbGainCurve {
max_input_level_linear: f64,
knee_start_dbfs: f64,
knee_start_linear: f64,
limiter_start_dbfs: f64,
limiter_start_linear: f64,
/// Coefficients `[a, b, c]` of the knee region polynomial `ax^2 + bx + c`.
knee_region_polynomial: [f64; 3],
gain_curve_limiter_d1: f64,
gain_curve_limiter_d2: f64,
gain_curve_limiter_i1: f64,
gain_curve_limiter_i2: f64,
}
fn compute_knee_start(
max_input_level_db: f64,
knee_smoothness_db: f64,
compression_ratio: f64,
) -> f64 {
debug_assert!(
(compression_ratio - 1.0) * knee_smoothness_db / (2.0 * compression_ratio)
< max_input_level_db
);
-knee_smoothness_db / 2.0 - max_input_level_db / (compression_ratio - 1.0)
}
fn compute_knee_region_polynomial(
knee_start_dbfs: f64,
knee_smoothness_db: f64,
compression_ratio: f64,
) -> [f64; 3] {
let a = (1.0 - compression_ratio) / (2.0 * knee_smoothness_db * compression_ratio);
let b = 1.0 - 2.0 * a * knee_start_dbfs;
let c = a * knee_start_dbfs * knee_start_dbfs;
[a, b, c]
}
fn compute_limiter_d1(max_input_level_db: f64, compression_ratio: f64) -> f64 {
(10.0_f64.powf(-max_input_level_db / (20.0 * compression_ratio)) * (1.0 - compression_ratio)
/ compression_ratio)
/ MAX_ABS_FLOAT_S16_VALUE as f64
}
const fn compute_limiter_d2(compression_ratio: f64) -> f64 {
(1.0 - 2.0 * compression_ratio) / compression_ratio
}
fn compute_limiter_i2(
max_input_level_db: f64,
compression_ratio: f64,
gain_curve_limiter_i1: f64,
) -> f64 {
debug_assert!(gain_curve_limiter_i1 != 0.0);
10.0_f64.powf(-max_input_level_db / (20.0 * compression_ratio))
/ gain_curve_limiter_i1
/ (MAX_ABS_FLOAT_S16_VALUE as f64).powf(gain_curve_limiter_i1 - 1.0)
}
impl Default for LimiterDbGainCurve {
fn default() -> Self {
let max_input_level_db = LIMITER_MAX_INPUT_LEVEL_DB_FS;
let knee_smoothness_db = LIMITER_KNEE_SMOOTHNESS_DB;
let compression_ratio = LIMITER_COMPRESSION_RATIO;
let max_input_level_linear = dbfs_to_float_s16_f64(max_input_level_db);
let knee_start_dbfs =
compute_knee_start(max_input_level_db, knee_smoothness_db, compression_ratio);
let knee_start_linear = dbfs_to_float_s16_f64(knee_start_dbfs);
let limiter_start_dbfs = knee_start_dbfs + knee_smoothness_db;
let limiter_start_linear = dbfs_to_float_s16_f64(limiter_start_dbfs);
let knee_region_polynomial =
compute_knee_region_polynomial(knee_start_dbfs, knee_smoothness_db, compression_ratio);
let gain_curve_limiter_d1 = compute_limiter_d1(max_input_level_db, compression_ratio);
let gain_curve_limiter_d2 = compute_limiter_d2(compression_ratio);
let gain_curve_limiter_i1 = 1.0 / compression_ratio;
let gain_curve_limiter_i2 =
compute_limiter_i2(max_input_level_db, compression_ratio, gain_curve_limiter_i1);
debug_assert!(knee_smoothness_db > 0.0);
debug_assert!(compression_ratio > 1.0);
debug_assert!(max_input_level_db >= knee_start_dbfs + knee_smoothness_db);
Self {
max_input_level_linear,
knee_start_dbfs,
knee_start_linear,
limiter_start_dbfs,
limiter_start_linear,
knee_region_polynomial,
gain_curve_limiter_d1,
gain_curve_limiter_d2,
gain_curve_limiter_i1,
gain_curve_limiter_i2,
}
}
}
impl LimiterDbGainCurve {
pub fn max_input_level_db(&self) -> f64 {
LIMITER_MAX_INPUT_LEVEL_DB_FS
}
pub fn max_input_level_linear(&self) -> f64 {
self.max_input_level_linear
}
pub fn knee_start_linear(&self) -> f64 {
self.knee_start_linear
}
pub fn limiter_start_linear(&self) -> f64 {
self.limiter_start_linear
}
/// Returns the output level in dBFS given an input level in dBFS.
pub fn get_output_level_dbfs(&self, input_level_dbfs: f64) -> f64 {
if input_level_dbfs < self.knee_start_dbfs {
input_level_dbfs
} else if input_level_dbfs < self.limiter_start_dbfs {
self.get_knee_region_output_level_dbfs(input_level_dbfs)
} else {
self.get_compressor_region_output_level_dbfs(input_level_dbfs)
}
}
/// Returns the gain (linear scale) for a given input level (linear scale).
pub fn get_gain_linear(&self, input_level_linear: f64) -> f64 {
if input_level_linear < self.knee_start_linear {
return 1.0;
}
dbfs_to_float_s16_f64(self.get_output_level_dbfs(float_s16_to_dbfs_f64(input_level_linear)))
/ input_level_linear
}
/// Computes the first derivative of `get_gain_linear()` at `x`.
/// Beyond-knee region only.
pub fn get_gain_first_derivative_linear(&self, x: f64) -> f64 {
debug_assert!(x >= self.limiter_start_linear - 1e-7 * MAX_ABS_FLOAT_S16_VALUE as f64);
self.gain_curve_limiter_d1
* (x / MAX_ABS_FLOAT_S16_VALUE as f64).powf(self.gain_curve_limiter_d2)
}
/// Computes the integral of `get_gain_linear()` in the range `[x0, x1]`.
/// Beyond-knee region only.
pub fn get_gain_integral_linear(&self, x0: f64, x1: f64) -> f64 {
debug_assert!(x0 <= x1);
debug_assert!(x0 >= self.limiter_start_linear);
let limiter_integral =
|x: f64| self.gain_curve_limiter_i2 * x.powf(self.gain_curve_limiter_i1);
limiter_integral(x1) - limiter_integral(x0)
}
fn get_knee_region_output_level_dbfs(&self, input_level_dbfs: f64) -> f64 {
self.knee_region_polynomial[0] * input_level_dbfs * input_level_dbfs
+ self.knee_region_polynomial[1] * input_level_dbfs
+ self.knee_region_polynomial[2]
}
fn get_compressor_region_output_level_dbfs(&self, input_level_dbfs: f64) -> f64 {
(input_level_dbfs - LIMITER_MAX_INPUT_LEVEL_DB_FS) / LIMITER_COMPRESSION_RATIO
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn construct() {
let _l = LimiterDbGainCurve::default();
}
#[test]
fn gain_curve_should_be_monotone() {
let l = LimiterDbGainCurve::default();
let mut last_output_level = None;
let mut level = -90.0_f64;
while level <= l.max_input_level_db() {
let current_output_level = l.get_output_level_dbfs(level);
if let Some(last) = last_output_level {
assert!(
last <= current_output_level,
"not monotone at level {level}: {last} > {current_output_level}"
);
}
last_output_level = Some(current_output_level);
level += 0.5;
}
}
#[test]
fn gain_curve_should_be_continuous() {
let l = LimiterDbGainCurve::default();
let mut last_output_level = None;
const MAX_DELTA: f64 = 0.5;
let mut level = -90.0_f64;
while level <= l.max_input_level_db() {
let current_output_level = l.get_output_level_dbfs(level);
if let Some(last) = last_output_level {
assert!(
current_output_level <= last + MAX_DELTA,
"not continuous at level {level}"
);
}
last_output_level = Some(current_output_level);
level += 0.5;
}
}
#[test]
fn output_gain_should_be_less_than_full_scale() {
let l = LimiterDbGainCurve::default();
let mut level = -90.0_f64;
while level <= l.max_input_level_db() {
let current_output_level = l.get_output_level_dbfs(level);
assert!(
current_output_level <= 0.0,
"output {current_output_level} > 0 at level {level}"
);
level += 0.5;
}
}
}
+381
View File
@@ -0,0 +1,381 @@
//! Noise floor estimator based on minimum statistics.
//!
//! Ported from `webrtc/modules/audio_processing/agc2/noise_level_estimator.h/.cc`.
const FRAMES_PER_SECOND: i32 = 100;
/// Update the noise floor every 5 seconds.
const UPDATE_PERIOD_NUM_FRAMES: i32 = 500;
fn frame_energy(audio: &[&[f32]]) -> f32 {
let mut energy = 0.0_f32;
for channel in audio {
let channel_energy: f32 = channel.iter().map(|&s| s * s).sum();
energy = energy.max(channel_energy);
}
energy
}
fn energy_to_dbfs(signal_energy: f32, num_samples: i32) -> f32 {
use crate::common::MIN_LEVEL_DBFS;
debug_assert!(signal_energy >= 0.0);
let rms_square = signal_energy / num_samples as f32;
if rms_square <= 1.0 {
return MIN_LEVEL_DBFS;
}
10.0 * rms_square.log10() + MIN_LEVEL_DBFS
}
/// Updates the noise floor with instant decay and slow attack. This tuning is
/// specific for AGC2, so that (i) it can promptly increase the gain if the noise
/// floor drops (instant decay) and (ii) in case of music or fast speech, due to
/// which the noise floor can be overestimated, the gain reduction is slowed
/// down.
fn smooth_noise_floor_estimate(current_estimate: f32, new_estimate: f32) -> f32 {
const ATTACK: f32 = 0.5;
if current_estimate < new_estimate {
// Attack phase.
ATTACK * new_estimate + (1.0 - ATTACK) * current_estimate
} else {
// Instant decay.
new_estimate
}
}
/// Noise level estimator based on noise floor detection.
#[derive(Debug)]
pub struct NoiseLevelEstimator {
sample_rate_hz: i32,
min_noise_energy: f32,
first_period: bool,
preliminary_noise_energy_set: bool,
preliminary_noise_energy: f32,
noise_energy: f32,
counter: i32,
}
impl Default for NoiseLevelEstimator {
fn default() -> Self {
let mut est = Self {
sample_rate_hz: 0,
min_noise_energy: 0.0,
first_period: true,
preliminary_noise_energy_set: false,
preliminary_noise_energy: 0.0,
noise_energy: 0.0,
counter: 0,
};
// Initially assume that 48 kHz will be used. `analyze()` will detect the
// used sample rate and call `initialize()` again if needed.
est.initialize(48000);
est
}
}
impl NoiseLevelEstimator {
/// Analyzes a 10 ms frame, updates the noise level estimation and returns
/// the value for the latter in dBFS.
pub fn analyze(&mut self, frame: &[&[f32]]) -> f32 {
debug_assert!(!frame.is_empty());
let samples_per_channel = frame[0].len();
// Detect sample rate changes.
let sample_rate_hz = samples_per_channel as i32 * FRAMES_PER_SECOND;
if sample_rate_hz != self.sample_rate_hz {
self.initialize(sample_rate_hz);
}
let frame_energy = frame_energy(frame);
if frame_energy <= self.min_noise_energy {
// Ignore frames when muted or below the minimum measurable energy.
return energy_to_dbfs(self.noise_energy, samples_per_channel as i32);
}
if self.preliminary_noise_energy_set {
self.preliminary_noise_energy = self.preliminary_noise_energy.min(frame_energy);
} else {
self.preliminary_noise_energy = frame_energy;
self.preliminary_noise_energy_set = true;
}
if self.counter == 0 {
// Full period observed.
self.first_period = false;
// Update the estimated noise floor energy with the preliminary
// estimation.
self.noise_energy =
smooth_noise_floor_estimate(self.noise_energy, self.preliminary_noise_energy);
// Reset for a new observation period.
self.counter = UPDATE_PERIOD_NUM_FRAMES;
self.preliminary_noise_energy_set = false;
} else if self.first_period {
// While analyzing the signal during the initial period, continuously
// update the estimated noise energy, which is monotonic.
self.noise_energy = self.preliminary_noise_energy;
self.counter -= 1;
} else {
// During the observation period it's only allowed to lower the energy.
self.noise_energy = self.noise_energy.min(self.preliminary_noise_energy);
self.counter -= 1;
}
energy_to_dbfs(self.noise_energy, samples_per_channel as i32)
}
fn initialize(&mut self, sample_rate_hz: i32) {
self.sample_rate_hz = sample_rate_hz;
self.first_period = true;
self.preliminary_noise_energy_set = false;
// Initialize the minimum noise energy to -84 dBFS.
self.min_noise_energy = sample_rate_hz as f32 * 2.0 * 2.0 / FRAMES_PER_SECOND as f32;
self.preliminary_noise_energy = self.min_noise_energy;
self.noise_energy = self.min_noise_energy;
self.counter = UPDATE_PERIOD_NUM_FRAMES;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::f32::consts::PI;
const NUM_ITERATIONS: i32 = 200;
const MIN_S16: f32 = -32768.0;
const MAX_S16: f32 = 32767.0;
/// PRNG matching WebRTC's `Random` class (xorshift128+).
struct WebRtcRandom {
x: u64,
y: u64,
}
impl WebRtcRandom {
fn new(seed: u64) -> Self {
Self { x: seed, y: seed }
}
fn next_u64(&mut self) -> u64 {
let mut s1 = self.x;
let s0 = self.y;
self.x = s0;
s1 ^= s1 << 23;
s1 ^= s1 >> 17;
s1 ^= s0;
s1 ^= s0 >> 26;
self.y = s1;
self.x.wrapping_add(self.y)
}
fn rand_int(&mut self, low: i32, high: i32) -> i32 {
let range = (high as i64 - low as i64 + 1) as u64;
let val = self.next_u64() % range;
low + val as i32
}
}
/// Generates white noise.
struct WhiteNoiseGenerator {
rng: WebRtcRandom,
min_amplitude: i32,
max_amplitude: i32,
}
impl WhiteNoiseGenerator {
fn new(min_amplitude: i32, max_amplitude: i32) -> Self {
Self {
rng: WebRtcRandom::new(42),
min_amplitude,
max_amplitude,
}
}
fn generate(&mut self) -> f32 {
self.rng.rand_int(self.min_amplitude, self.max_amplitude) as f32
}
}
/// Generates a sine function.
struct SineGenerator {
amplitude: f32,
frequency_hz: f32,
sample_rate_hz: i32,
x_radians: f32,
}
impl SineGenerator {
fn new(amplitude: f32, frequency_hz: f32, sample_rate_hz: i32) -> Self {
Self {
amplitude,
frequency_hz,
sample_rate_hz,
x_radians: 0.0,
}
}
fn generate(&mut self) -> f32 {
self.x_radians += self.frequency_hz / self.sample_rate_hz as f32 * 2.0 * PI;
if self.x_radians >= 2.0 * PI {
self.x_radians -= 2.0 * PI;
}
self.amplitude * self.x_radians.sin()
}
}
/// Generates periodic pulses.
struct PulseGenerator {
pulse_amplitude: f32,
no_pulse_amplitude: f32,
samples_period: i32,
sample_counter: i32,
}
impl PulseGenerator {
fn new(
pulse_amplitude: f32,
no_pulse_amplitude: f32,
frequency_hz: f32,
sample_rate_hz: i32,
) -> Self {
Self {
pulse_amplitude,
no_pulse_amplitude,
samples_period: (sample_rate_hz as f32 / frequency_hz) as i32,
sample_counter: 0,
}
}
fn generate(&mut self) -> f32 {
self.sample_counter += 1;
if self.sample_counter >= self.samples_period {
self.sample_counter -= self.samples_period;
}
if self.sample_counter == 0 {
self.pulse_amplitude
} else {
self.no_pulse_amplitude
}
}
}
/// Runs the noise estimator on audio generated by `gen_fn`
/// for NUM_ITERATIONS. Returns the last noise level estimate.
fn run_estimator(
gen_fn: &mut dyn FnMut() -> f32,
estimator: &mut NoiseLevelEstimator,
sample_rate_hz: i32,
) -> f32 {
let samples_per_channel = sample_rate_hz / FRAMES_PER_SECOND;
let mut signal = vec![0.0_f32; samples_per_channel as usize];
for _ in 0..NUM_ITERATIONS {
for s in &mut signal {
*s = gen_fn();
}
let channels: [&[f32]; 1] = [&signal];
estimator.analyze(&channels);
}
// Final analysis.
for s in &mut signal {
*s = gen_fn();
}
let channels: [&[f32]; 1] = [&signal];
estimator.analyze(&channels)
}
#[test]
fn noise_floor_estimator_with_random_noise_8000() {
noise_floor_estimator_with_random_noise(8000);
}
#[test]
fn noise_floor_estimator_with_random_noise_16000() {
noise_floor_estimator_with_random_noise(16000);
}
#[test]
fn noise_floor_estimator_with_random_noise_32000() {
noise_floor_estimator_with_random_noise(32000);
}
#[test]
fn noise_floor_estimator_with_random_noise_48000() {
noise_floor_estimator_with_random_noise(48000);
}
fn noise_floor_estimator_with_random_noise(sample_rate_hz: i32) {
let mut estimator = NoiseLevelEstimator::default();
let mut noise_gen = WhiteNoiseGenerator::new(MIN_S16 as i32, MAX_S16 as i32);
let noise_level_dbfs =
run_estimator(&mut || noise_gen.generate(), &mut estimator, sample_rate_hz);
assert!(
(noise_level_dbfs - (-5.5)).abs() < 0.5,
"noise_level_dbfs={noise_level_dbfs} at {sample_rate_hz}Hz, expected ~-5.5"
);
}
#[test]
fn noise_floor_estimator_with_sine_tone_8000() {
noise_floor_estimator_with_sine_tone(8000);
}
#[test]
fn noise_floor_estimator_with_sine_tone_16000() {
noise_floor_estimator_with_sine_tone(16000);
}
#[test]
fn noise_floor_estimator_with_sine_tone_32000() {
noise_floor_estimator_with_sine_tone(32000);
}
#[test]
fn noise_floor_estimator_with_sine_tone_48000() {
noise_floor_estimator_with_sine_tone(48000);
}
fn noise_floor_estimator_with_sine_tone(sample_rate_hz: i32) {
let mut estimator = NoiseLevelEstimator::default();
let mut sine_gen = SineGenerator::new(MAX_S16, 600.0, sample_rate_hz);
let noise_level_dbfs =
run_estimator(&mut || sine_gen.generate(), &mut estimator, sample_rate_hz);
assert!(
(noise_level_dbfs - (-3.0)).abs() < 0.1,
"noise_level_dbfs={noise_level_dbfs} at {sample_rate_hz}Hz, expected ~-3.0"
);
}
#[test]
fn noise_floor_estimator_with_pulse_tone_8000() {
noise_floor_estimator_with_pulse_tone(8000);
}
#[test]
fn noise_floor_estimator_with_pulse_tone_16000() {
noise_floor_estimator_with_pulse_tone(16000);
}
#[test]
fn noise_floor_estimator_with_pulse_tone_32000() {
noise_floor_estimator_with_pulse_tone(32000);
}
#[test]
fn noise_floor_estimator_with_pulse_tone_48000() {
noise_floor_estimator_with_pulse_tone(48000);
}
fn noise_floor_estimator_with_pulse_tone(sample_rate_hz: i32) {
let mut estimator = NoiseLevelEstimator::default();
let no_pulse_amplitude = 10.0_f32;
let mut pulse_gen = PulseGenerator::new(MAX_S16, no_pulse_amplitude, 20.0, sample_rate_hz);
let noise_level_dbfs =
run_estimator(&mut || pulse_gen.generate(), &mut estimator, sample_rate_hz);
let expected_noise_floor_dbfs = 20.0 * (no_pulse_amplitude / MAX_S16).log10();
assert!(
(noise_level_dbfs - expected_noise_floor_dbfs).abs() < 0.5,
"noise_level_dbfs={noise_level_dbfs} at {sample_rate_hz}Hz, expected ~{expected_noise_floor_dbfs}"
);
}
}
Loaded 100 of 1303 files, more files were not shown because too many files have changed in this diff. Show more