Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
32318e3e3f | ||
|
|
3d2e76eddd | ||
|
|
cb1d682dfb | ||
|
|
82334f8a8b | ||
|
|
2ebeebab35 |
No files matched your search
@@ -1,3 +1,5 @@
|
||||
# Native dependency recipes verify exact source bytes on every build host.
|
||||
native/patches/** text eol=lf
|
||||
xtask/src/*.rs text eol=lf
|
||||
.gitea/*.sh text eol=lf
|
||||
platform/android/gradlew text eol=lf
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
# Called by android.yml once per variant so verified harness artifacts upload first.
|
||||
set -euo pipefail
|
||||
variant="$1"
|
||||
case "$variant" in
|
||||
harness) harness=true ;;
|
||||
production) harness=false ;;
|
||||
*) echo "Expected harness or production" >&2; exit 2 ;;
|
||||
esac
|
||||
out="dist/android/$variant"
|
||||
cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --test-harness "$harness"
|
||||
# Explicit online dependency resolution supports a fresh Gradle cache.
|
||||
# Bootstrap still requires the local checksum-pinned zip; SDK downloads stay disabled.
|
||||
cargo run --locked -p xtask -- package --target "$TARGET" --out "$out" --test-harness "$harness" --gradle-online true
|
||||
cargo run --locked -p xtask -- verify-package --target "$TARGET" --out "$out" --test-harness "$harness"
|
||||
cp "$CARGO_TARGET_DIR/$TARGET/release/native-build.json" "$out/$TARGET/native-build.json"
|
||||
cp native/native-deps.lock.json "$out/$TARGET/native-deps.lock.json"
|
||||
cp "target/native-deps/$TARGET/provenance.json" "$out/$TARGET/dependency-provenance.json"
|
||||
python3 - "$out" "$harness" <<'PY'
|
||||
import hashlib, json, os, pathlib, subprocess, sys
|
||||
out = pathlib.Path(sys.argv[1])
|
||||
harness = sys.argv[2] == 'true'
|
||||
target = os.environ['TARGET']
|
||||
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
|
||||
assert revision == os.environ['EXPECTED_REVISION'], 'checkout revision changed'
|
||||
receipt = json.loads((out / target / 'package-report.json').read_text())
|
||||
verification = json.loads((out / target / 'verification.json').read_text())
|
||||
assert receipt['testOnly'] == harness and receipt['sourceBuild']['testHarness'] == harness
|
||||
assert verification['passed'] is True
|
||||
assert {a['kind'] for a in receipt['artifacts']} == ({'apk'} if harness else {'apk', 'aab'})
|
||||
assert all(a['signing'] == ('android-debug-test' if harness else 'unsigned-not-installable') and not a['release_eligible'] for a in receipt['artifacts'])
|
||||
files = [out / a['name'] for a in receipt['artifacts']]
|
||||
files += [out / target / name for name in ('package-report.json', 'verification.json', 'native-build.json', 'native-deps.lock.json', 'dependency-provenance.json')]
|
||||
hashes = {}
|
||||
for path in files:
|
||||
with path.open('rb') as source:
|
||||
digest = hashlib.sha256()
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b''):
|
||||
digest.update(chunk)
|
||||
hashes[str(path.relative_to(out))] = digest.hexdigest()
|
||||
(out / 'build-info.json').write_text(json.dumps({'schema': 1, 'revision': revision, 'run_id': os.environ['CI_RUN_ID'], 'target': target, 'testHarness': harness, 'gradleOnline': True, 'deviceAcceptance': 'not exercised', 'publicationAuthorized': False, 'sha256': hashes}, indent=2) + '\n')
|
||||
PY
|
||||
+104
-41
@@ -1,9 +1,19 @@
|
||||
# Trusted manual runs only, on an administrator-provisioned Linux x64 runner.
|
||||
# This job never installs host tools, signs production packages, publishes, or uses a device.
|
||||
# Trusted manual runs only. Inventory uses the existing generic runner;
|
||||
# full builds require an administrator-provisioned Linux x64 Android runner.
|
||||
# Neither mode installs host tools, publishes, or uses a device.
|
||||
name: android-ci
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: Inventory only, or full Android build on the dedicated runner
|
||||
required: true
|
||||
default: inventory
|
||||
type: choice
|
||||
options:
|
||||
- inventory
|
||||
- build
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -14,7 +24,94 @@ defaults:
|
||||
working-directory: ${{ github.workspace }}/android-${{ github.run_id }}
|
||||
|
||||
jobs:
|
||||
runner-inventory:
|
||||
if: ${{ github.event.inputs.mode != 'build' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ${{ github.workspace }}
|
||||
env:
|
||||
CONFIG_ANDROID_SDK_ROOT: ${{ vars.ANDROID_SDK_ROOT }}
|
||||
CONFIG_ANDROID_JAVA_HOME: ${{ vars.ANDROID_JAVA_HOME }}
|
||||
CONFIG_NATIVE_LLVM_HOME: ${{ vars.NATIVE_LLVM_HOME }}
|
||||
CONFIG_NATIVE_LIBCLANG_PATH: ${{ vars.NATIVE_LIBCLANG_PATH }}
|
||||
CONFIG_NATIVE_SKIA_SOURCE_DIR: ${{ vars.NATIVE_SKIA_SOURCE_DIR }}
|
||||
CONFIG_ANDROID_GRADLE_DISTRIBUTION: ${{ vars.ANDROID_GRADLE_DISTRIBUTION }}
|
||||
CONFIG_ANDROID_BUNDLETOOL: ${{ vars.ANDROID_BUNDLETOOL }}
|
||||
steps:
|
||||
# No checkout, downloads, env dump, secret access, build or installation.
|
||||
- name: Inspect available runner resources and Android prerequisites
|
||||
run: |
|
||||
set -euo pipefail
|
||||
printf 'OS=%s ARCH=%s\n' "$(uname -s)" "$(uname -m)"
|
||||
printf 'CPU_COUNT=%s\n' "$(getconf _NPROCESSORS_ONLN)"
|
||||
df -Pk .
|
||||
if [ -r /proc/meminfo ]; then
|
||||
while IFS=: read -r key value; do
|
||||
case "$key" in
|
||||
MemTotal|MemAvailable|SwapTotal|SwapFree|CommitLimit|Committed_AS) printf '%s:%s\n' "$key" "$value" ;;
|
||||
esac
|
||||
done < /proc/meminfo
|
||||
fi
|
||||
for file in /sys/fs/cgroup/memory.max /sys/fs/cgroup/memory.current /sys/fs/cgroup/memory.swap.max /sys/fs/cgroup/cpu.max /sys/fs/cgroup/memory/memory.limit_in_bytes /sys/fs/cgroup/memory/memory.usage_in_bytes /sys/fs/cgroup/cpu/cpu.cfs_quota_us /sys/fs/cgroup/cpu/cpu.cfs_period_us; do
|
||||
if [ -r "$file" ]; then printf '%s=' "$file"; cat "$file"; fi
|
||||
done
|
||||
for tool in cargo rustc rustup git cmake ninja python3 pkg-config clang clang++ ar llvm-strip llvm-readelf java javac jar keytool jarsigner sh zipalign aapt2 apksigner sdkmanager node; do
|
||||
if command -v "$tool" >/dev/null 2>&1; then printf 'TOOL %s=present\n' "$tool"; else printf 'TOOL %s=missing-from-PATH\n' "$tool"; fi
|
||||
done
|
||||
for tool in java javac clang cmake ninja; do
|
||||
if command -v "$tool" >/dev/null 2>&1; then
|
||||
printf 'VERSION %s\n' "$tool"
|
||||
case "$tool" in java|javac) flag=-version ;; *) flag=--version ;; esac
|
||||
timeout 10s "$tool" "$flag" 2>&1 || printf 'VERSION %s=unavailable\n' "$tool"
|
||||
fi
|
||||
done
|
||||
# Never invoke rustup proxies: even --version can auto-install a toolchain.
|
||||
rust_home="${RUSTUP_HOME:-$HOME/.rustup}"
|
||||
rust_found=false
|
||||
for toolchain in "$rust_home"/toolchains/1.96.0-*; do
|
||||
if [ -x "$toolchain/bin/rustc" ]; then
|
||||
rust_found=true
|
||||
printf 'RUST_1_96_0=present\n'
|
||||
if [ -d "$toolchain/lib/rustlib/aarch64-linux-android/lib" ]; then printf 'RUST_ANDROID_TARGET=present\n'; else printf 'RUST_ANDROID_TARGET=missing\n'; fi
|
||||
fi
|
||||
done
|
||||
if [ "$rust_found" = false ]; then printf 'RUST_1_96_0=not-found-in-rustup-home\n'; fi
|
||||
for name in ANDROID_SDK_ROOT ANDROID_JAVA_HOME NATIVE_LLVM_HOME NATIVE_LIBCLANG_PATH NATIVE_SKIA_SOURCE_DIR ANDROID_GRADLE_DISTRIBUTION ANDROID_BUNDLETOOL; do
|
||||
key="CONFIG_$name"
|
||||
if [ -z "${!key:-}" ]; then
|
||||
printf 'VARIABLE %s=unset\n' "$name"
|
||||
elif [ -e "${!key}" ]; then
|
||||
printf 'VARIABLE %s=set,path-exists\n' "$name"
|
||||
else
|
||||
printf 'VARIABLE %s=set,path-missing\n' "$name"
|
||||
fi
|
||||
done
|
||||
# Inspect only explicitly configured or inherited tool roots, never home/profile contents.
|
||||
for name in ANDROID_HOME ANDROID_SDK_ROOT ANDROID_NDK_ROOT JAVA_HOME LLVM_HOME LIBCLANG_PATH SKIA_SOURCE_DIR; do
|
||||
if [ -n "${!name:-}" ]; then printf 'RUNNER_ENV %s=set\n' "$name"; else printf 'RUNNER_ENV %s=unset\n' "$name"; fi
|
||||
done
|
||||
sdk="${CONFIG_ANDROID_SDK_ROOT:-${ANDROID_SDK_ROOT:-${ANDROID_HOME:-}}}"
|
||||
if [ -n "$sdk" ]; then
|
||||
for relative in platforms/android-36/android.jar build-tools/36.0.0/aapt2 ndk/28.2.13676358/source.properties; do
|
||||
if [ -f "$sdk/$relative" ]; then printf 'SDK %s=present\n' "$relative"; else printf 'SDK %s=missing\n' "$relative"; fi
|
||||
done
|
||||
else
|
||||
printf 'SDK=unknown,no-configured-root\n'
|
||||
fi
|
||||
skia="${CONFIG_NATIVE_SKIA_SOURCE_DIR:-${SKIA_SOURCE_DIR:-}}"
|
||||
if [ -n "$skia" ]; then
|
||||
for relative in BUILD.gn bin/gn third_party/externals; do
|
||||
if [ -e "$skia/$relative" ]; then printf 'SKIA %s=present\n' "$relative"; else printf 'SKIA %s=missing\n' "$relative"; fi
|
||||
done
|
||||
else
|
||||
printf 'SKIA=unknown,no-configured-root\n'
|
||||
fi
|
||||
printf 'INVENTORY_ONLY: no build, installation, signing, publication or device access\n'
|
||||
|
||||
android-arm64:
|
||||
if: ${{ github.event.inputs.mode == 'build' }}
|
||||
runs-on: teamspeach-android-linux-x64
|
||||
env:
|
||||
CARGO_TERM_COLOR: never
|
||||
@@ -105,45 +202,8 @@ jobs:
|
||||
- name: Build pinned Android WebRTC from source on Linux
|
||||
run: cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME"
|
||||
|
||||
- name: Build and verify harness first, then unsigned production (full Skia + WebRTC)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for variant in harness production; do
|
||||
if [ "$variant" = harness ]; then harness=true; else harness=false; fi
|
||||
out="dist/android/$variant"
|
||||
cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --test-harness "$harness"
|
||||
# Explicit online dependency resolution supports a fresh Gradle cache.
|
||||
# Bootstrap still requires the local checksum-pinned zip; SDK downloads stay disabled.
|
||||
cargo run --locked -p xtask -- package --target "$TARGET" --out "$out" --test-harness "$harness" --gradle-online true
|
||||
cargo run --locked -p xtask -- verify-package --target "$TARGET" --out "$out" --test-harness "$harness"
|
||||
cp "$CARGO_TARGET_DIR/$TARGET/release/native-build.json" "$out/$TARGET/native-build.json"
|
||||
cp native/native-deps.lock.json "$out/$TARGET/native-deps.lock.json"
|
||||
cp "target/native-deps/$TARGET/provenance.json" "$out/$TARGET/dependency-provenance.json"
|
||||
python3 - "$out" "$harness" <<'PY'
|
||||
import hashlib, json, os, pathlib, subprocess, sys
|
||||
out = pathlib.Path(sys.argv[1])
|
||||
harness = sys.argv[2] == 'true'
|
||||
target = os.environ['TARGET']
|
||||
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
|
||||
assert revision == os.environ['EXPECTED_REVISION'], 'checkout revision changed'
|
||||
receipt = json.loads((out / target / 'package-report.json').read_text())
|
||||
verification = json.loads((out / target / 'verification.json').read_text())
|
||||
assert receipt['testOnly'] == harness and receipt['sourceBuild']['testHarness'] == harness
|
||||
assert verification['passed'] is True
|
||||
assert {a['kind'] for a in receipt['artifacts']} == ({'apk'} if harness else {'apk', 'aab'})
|
||||
assert all(a['signing'] == ('android-debug-test' if harness else 'unsigned-not-installable') and not a['release_eligible'] for a in receipt['artifacts'])
|
||||
files = [out / a['name'] for a in receipt['artifacts']]
|
||||
files += [out / target / name for name in ('package-report.json', 'verification.json', 'native-build.json', 'native-deps.lock.json', 'dependency-provenance.json')]
|
||||
hashes = {}
|
||||
for path in files:
|
||||
with path.open('rb') as source:
|
||||
digest = hashlib.sha256()
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b''):
|
||||
digest.update(chunk)
|
||||
hashes[str(path.relative_to(out))] = digest.hexdigest()
|
||||
(out / 'build-info.json').write_text(json.dumps({'schema': 1, 'revision': revision, 'run_id': os.environ['CI_RUN_ID'], 'target': target, 'testHarness': harness, 'gradleOnline': True, 'deviceAcceptance': 'not exercised', 'publicationAuthorized': False, 'sha256': hashes}, indent=2) + '\n')
|
||||
PY
|
||||
done
|
||||
- name: Build and verify harness (full Skia + WebRTC)
|
||||
run: bash .gitea/build-android-variant.sh harness
|
||||
|
||||
- name: Retain installable test-only ARM64 harness and exact receipts
|
||||
uses: actions/upload-artifact@v3
|
||||
@@ -155,6 +215,9 @@ jobs:
|
||||
android-${{ github.run_id }}/dist/android/harness/aarch64-linux-android/*.json
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Build and verify unsigned production (full Skia + WebRTC)
|
||||
run: bash .gitea/build-android-variant.sh production
|
||||
|
||||
- name: Retain unsigned production ARM64 APK and store AAB (not installable)
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
|
||||
+28
-345
@@ -2,352 +2,31 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- A release check now clears the old download progress when the offered package changes or disappears.
|
||||
- Built the first full Skia/WebRTC Android ARM64 test APK in authorized WSL2. Verified APK v2 signing,
|
||||
16-KiB alignment, native ISA/imports, resources and exported WebRTC JNI symbols; no device run claimed.
|
||||
- Fixed Android build integration: use the complete NDK r28c rather than Chromium's sysroot-only subset,
|
||||
copy the matching WebRTC jar to Cargo's actual output directory, retain JNI exports in the final cdylib,
|
||||
pin Gradle launcher LF/build-tools36, and use the public AppOps permission-change observer.
|
||||
Corrected the pinned Slint NonNull pointer conversion in Android accessibility.
|
||||
|
||||
- Implemented Android call-scoped audio recovery: focus/route changes revoke microphone authorization,
|
||||
restore receive-only playback when permitted, and reject stale lease/revision callbacks. Communication
|
||||
mode and Android 12+ communication-device notifications follow the active foreground call.
|
||||
- Android network capability refreshes no longer masquerade as network handoffs. Added the missing
|
||||
privacy-approved external-link adapter; SAF filename collisions offer a new destination, and identity
|
||||
exports use private staging and the provider commit/partial-cleanup contract rather than direct writes.
|
||||
- Adapted the Android phone shell: connection/tab actions, selected-target actions, compact detail
|
||||
navigation and settings Back; bounded menus/forms, IME-aware chat/settings, and hold/cancel PTT.
|
||||
Android APK, physical-device voice, Bluetooth/provider behavior and full parity remain unverified.
|
||||
- Android Activity pause now releases touch PTT/long-press state without ending foreground screen/camera
|
||||
capture. Pending playback recovery survives later microphone revocation; duplicate audio-focus gain
|
||||
no longer revokes an explicitly enabled microphone.
|
||||
- Android camera/projection consent remains visible until foreground handoff, pending Camera2 opens
|
||||
drain before shutdown, and resize ignores obsolete ImageReader callbacks. Permission launch failures
|
||||
complete requests; SAF grants validate access and close descriptors/capabilities on failed handoff.
|
||||
- Added receiver instructions for building the exact mobile revision on another developer's WSL2
|
||||
Linux machine, using the existing pinned-source recipe and returning the complete APK/receipt bundle.
|
||||
|
||||
- Switching update channels clears the previous channel's last-check time until the new channel is checked.
|
||||
|
||||
- Shortcut conflicts now appear only in the profile that owns the conflicting chord. The bookmark Move dialog now labels unnamed folders in both destination and ordering choices.
|
||||
|
||||
- Search the server client database by nickname or UID. Enter submits the query; typing still filters the file browser immediately.
|
||||
|
||||
- Deafening a second server tab or restoring its sound no longer interrupts microphone capture on the transmitting tab.
|
||||
|
||||
- Reading mute state with an empty set_audio request no longer interrupts voice capture. Partial updates preserve the omitted flag and reject explicit null values.
|
||||
|
||||
- Playback no longer treats a missing or malformed output mute flag as permission to play voice. The initial roster must also identify the local client.
|
||||
|
||||
- Turning off push-to-talk after releasing the key resumes the previously authorized microphone on the same connection. Turning push-to-talk back on stops continuous speech until the next hold.
|
||||
|
||||
- Audio settings now show the PTT key being recorded, a Cancel action, and an inline error if the chord is invalid or cannot be saved. The previous binding remains usable after cancellation.
|
||||
|
||||
- Holding Push to Mute while speaking with Push to Talk no longer reconfigures capture on key-down. Releasing mute resumes the voice route only when transmission is still requested.
|
||||
|
||||
- Pressing push-to-talk again after its release delay expires resumes the previously active, authorized microphone on the same connection. A focus or input route change clears that remembered state.
|
||||
|
||||
- Releasing the on-screen push-to-talk button keeps capture active while another PTT key is held or the configured release delay is running. Repeated releases no longer extend the delay.
|
||||
|
||||
- Local whisper shortcuts bind the acknowledged whisper route together with its capture permit. When a second shortcut replaces the first, releasing the first no longer silences the second.
|
||||
|
||||
- Switching a whisper list to a different server or channel group catalog clears the old group and resets its delivery scope. A picker opened for the previous group type cannot select a recipient in the new catalog.
|
||||
|
||||
- Server and channel group whispers reject zero IDs even when padded with zeroes. Positive decimal IDs with leading zeroes remain valid.
|
||||
|
||||
- Ending a whisper rechecks its recipients against the current roster, so a departed client's reused numeric ID does not receive the end marker.
|
||||
|
||||
- Rejected voice packets no longer create a whisper history event or interrupt an active whisper. Only packets admitted by the jitter buffer update the receiver's whisper state.
|
||||
|
||||
- Dialog checkboxes now show their edited state immediately. A second click before submission toggles the current value rather than repeating the previous edit.
|
||||
|
||||
- The diagnostic stdio bridge requires JSON objects for requests and their arguments. Positional arrays and explicit null arguments no longer dispatch commands; omitting arguments for a no-argument command still works.
|
||||
|
||||
- A delayed channel subscription refusal is no longer displayed on a different server tab or after reconnection.
|
||||
|
||||
- The stdio channel subscription commands now reject positional arrays. They require named fields, including an explicit boolean for subscribe or unsubscribe.
|
||||
|
||||
- Imported shortcut files now report skipped duplicate profile and binding IDs. The first entry is retained, including when a duplicate uses different UUID letter case.
|
||||
|
||||
- A pending channel information or description request now rejects a reply if the requested channel was deleted, even if a new channel has since used its numeric ID.
|
||||
|
||||
- Permission Groups shows only regular groups. Refreshing one group list preserves the other list and the creation actions. A late request to open the panel no longer replaces the current tab or reopens a closed panel.
|
||||
|
||||
- Server Log now waits for Load and accepts the requested line count, start position, order and instance flag. A refusal leaves the request editable; switching server tabs invalidates the old request.
|
||||
|
||||
- Server Info discards late replies from a closed panel or a previous connection. Empty, ambiguous and mismatched server-property replies no longer open an editor.
|
||||
|
||||
- The Move to Own Channel form checks the password's 1024-byte UTF-8 limit before submission and preserves leading and trailing spaces.
|
||||
|
||||
- A confirmed participant move no longer reports a changed target just because the roster already shows the participant in the destination channel. Replies from a replaced session are still rejected.
|
||||
|
||||
- Move to Own Channel is offered only for participants in another channel. Its confirmation stays bound to the original participant and destination, asks for a password only for a protected channel, and keeps server refusals visible.
|
||||
|
||||
- Group Rename opens with the selected group's current name. Blank and unchanged names close the editor without submitting; changed names are trimmed before submission.
|
||||
|
||||
- A late client database search or page response no longer replaces newer results or reopens a closed panel. Results and errors are bound to the original server and tab.
|
||||
|
||||
- Client database search accepts patterns up to 255 Unicode characters. Administrative client UID fields use the 128-character limit, independently of UTF-8 byte length.
|
||||
|
||||
- Server and channel group names use the same 128-character Unicode limit in the editor and core. Multibyte names no longer fail early because of their UTF-8 byte length.
|
||||
|
||||
- Administrative commands reject IDs, log offsets and editable numeric properties above the reference interface's safe-integer limit before connecting. Server quota, bandwidth and default-group fields enforce the same limit in the native editor.
|
||||
|
||||
- Desktop users can select multiple files in the channel upload dialog. Selections above 100 files are rejected as a batch; cancelling or reconnecting does not queue files in another session.
|
||||
|
||||
- The channel file Rename form opens with the current filename. Confirming the same name leaves the file unchanged without sending a rename command.
|
||||
|
||||
- Switching the microphone to another server tab no longer marks audio devices active before they start. If setup fails, neither tab retains a usable capture permit. Muted sessions no longer report an expected absence of a capture permit as a changed target.
|
||||
|
||||
- A successful server login remembers the address even if the selected playback device is unavailable. The playback error is still reported.
|
||||
|
||||
- The first empty server tab restores the last saved address in its Connect form after restart. Additional empty tabs do not inherit that address.
|
||||
|
||||
- Shortcut profile diagnostics now distinguish unsupported Block Incoming Whispers bindings from other invalid entries. Other valid bindings remain usable.
|
||||
|
||||
- Whisper history and notifications use the sender captured at receipt. A guest who later receives the same client number cannot inherit the original guest's reply action.
|
||||
- Reply Whisper addresses only the connection that sent the whisper, even when a second client is connected with the same UID. Saved whisper lists keep their existing multi-client behavior.
|
||||
|
||||
- Channel commanders have a separate indicator in the detailed tree. The compact tree uses the saved commander lamp setting. Only the user's own row offers a commander change, and its confirmation reflects the current server flag.
|
||||
|
||||
- Participant volume changes while dragging the fader; releasing it saves the gain by UID. Mute stays local to the connection. Reset removes the saved modifier and unmutes the participant.
|
||||
|
||||
- The participant menu reads the selected client's capabilities on opening. Late replies cannot change a closed or reopened menu, and unavailable server actions stay disabled.
|
||||
|
||||
- Poke accepts up to 1024 UTF-8 bytes locally. A server refusal keeps the message editable; submitting a draft after the recipient leaves cannot send it to a replacement participant.
|
||||
|
||||
- Participant Connection Info shows localized timing, packet loss and traffic metrics without rounding 64-bit counters. Old statistics cannot populate a replacement tab or participant.
|
||||
|
||||
- Participant Info retains previously returned fields when a later update omits them. Superseded replies and errors cannot populate the next tab or a new participant reusing the same client number.
|
||||
|
||||
- The participant menu offers Grant or Revoke according to the current talker flag. Manual grants no longer require a pending request. Queue grants still require the selected request in the moderator's current channel.
|
||||
|
||||
- Reject explicitly null away and talk-request messages. Omitting a message remains valid.
|
||||
|
||||
- Invalid connection requests no longer revoke the current microphone route or trigger a default identity lookup. The manager forwards validated commands to the embedded core without parsing them again.
|
||||
|
||||
- Validate connect and disconnect string lengths and selected identity IDs before dispatch. The JSON bridge rejects explicitly null fields instead of treating them as omitted.
|
||||
|
||||
- Partial snapshot imports now list acknowledged changes alongside failures. Property and permission rows identify the object and field without displaying its value. Reusing an existing icon does not count as an upload.
|
||||
|
||||
- Snapshot Apply and Cancel now refer to the exact previewed file, even when the next file has a catalog with the same ID.
|
||||
|
||||
- A saved partial snapshot now shows its filename alongside the warning and issue details.
|
||||
|
||||
- Cancelling a snapshot immediately after starting it now prevents the initial server query. A cancellation received during that query stops subsequent work.
|
||||
|
||||
- Snapshot progress and cancellation controls are tied to the job, session and window that opened the panel. Completed and planned counts now use the same units, including permission reads.
|
||||
|
||||
- Reject oversized regular snapshot files using their checked descriptor size before reading the payload. Unknown-size streams remain bounded during reading.
|
||||
|
||||
- Dismissing an idle snapshot import now revokes its token, so a late confirmation cannot apply a file that was cancelled.
|
||||
|
||||
- Snapshot export rejects incomplete channel trees and ambiguous sibling order before writing the snapshot.
|
||||
|
||||
- Snapshot export no longer attaches an unrelated channel's properties to a saved channel. Missing or ambiguous properties are reported as a partial export.
|
||||
|
||||
- Channel Info ignores superseded successes and errors after navigation or reconnect. It rejects an empty, ambiguous or mismatched reply instead of showing the wrong channel.
|
||||
|
||||
- Contacts offers Ignore or Unignore according to the selected UID's current state. A queued action from a deleted contact can no longer change the ignore list.
|
||||
|
||||
- Desktop transfer settings display and copy the explicitly selected default download folder. Using the system Downloads folder does not turn it into a saved preference.
|
||||
|
||||
- The channel file browser disables Move when the channel denies rename. Download Folder requires both browsing and downloading permission.
|
||||
|
||||
- Check the dimensions of inline channel images before allocating decoded pixels.
|
||||
|
||||
- Reject zero transfer IDs for pause, resume and cancel before dispatch.
|
||||
|
||||
- Reject channel IDs above the protocol's safe-integer limit in file operations before sending a request.
|
||||
|
||||
- Releasing a file chooser token no longer keeps an unused directory grant alive solely to suggest its path in a later dialog. An active download still retains its own grant until it finishes.
|
||||
|
||||
- Opening the recording panel reads the recorder status. Pause, Resume, Stop and Reveal stay bound to the selected take so delayed controls cannot affect the next recording in the same tab.
|
||||
|
||||
- A stale Preview, Start or Stop command no longer acts on a replacement source in the same tab. A broadcast is shown as live only after both the setup acknowledgement and the server-assigned stream ID arrive.
|
||||
|
||||
- Reject zero client IDs for targeted stream commands. After WebRTC renegotiation, match ICE candidates to the addressed media transport and attach receiver sinks only after the answer commits.
|
||||
|
||||
- Opening Streams now queries other participants in the connected client's current channel. A background refresh cannot cancel a pending request for a selected participant.
|
||||
|
||||
- Leaving a stream closes the selected viewer immediately. A repeated stop waits for the pending leave instead of sending another request, and delayed cleanup does not close a replacement viewer of the same stream.
|
||||
|
||||
- Broadcast admission and removal buttons name their viewer. Actions stay bound to the same viewer when the list order changes.
|
||||
|
||||
- Stop on an active broadcast tile now targets the registered stream and its publisher. Closing the capture no longer looks up a replacement publisher to stop after the wait.
|
||||
|
||||
- Active publications now have an Edit broadcast action for the title, video bitrate, viewer limit and admission policy. It edits the registered stream without selecting or restarting the capture source.
|
||||
|
||||
- A running publisher reports changed stream settings only after the server acknowledges the update. Tighter admission rules apply immediately; looser rules wait for acknowledgement. A late reply cannot replace the state of a disconnected publication.
|
||||
|
||||
- Stopping a publication sends the close reason required by TS6 beta14. Stream discovery now distinguishes a server refusal for the requested participant from a successful lookup with no streams.
|
||||
|
||||
- A server stop naming only the local publisher now releases its registered capture. Queued stream notifications stay with the publication that received them and cannot stop its replacement.
|
||||
|
||||
- Approving or denying a stream viewer request now checks the UID selected in the menu. An obsolete request cannot admit or block a different viewer who was assigned the same client number.
|
||||
|
||||
- Removing or blocking a viewer from a stream menu now uses the UID captured when the action was selected. A replacement viewer can keep watching if the server reuses that number.
|
||||
|
||||
- Automatic stream viewer removal rechecks the viewer's UID before sending. A replacement client does not inherit a queued eviction when publication privacy changes.
|
||||
|
||||
- When the server stops a stream by publisher ID alone, current viewers of that publisher close immediately. The stop does not replay against a newly opened viewer.
|
||||
|
||||
- The stream viewer ignores a join reply or signaling event with a malformed recipient ID instead of treating it as unaddressed. Omitted IDs and empty wire flags remain supported.
|
||||
|
||||
- A viewer now reports a rejected outgoing ICE candidate after sending its answer, closes that peer, and leaves the stream once. Previously the send failure was lost.
|
||||
|
||||
- The core rejects malformed outgoing stream negotiation messages before transmission. Stream join notes now enforce the original 200-unit single-line limit.
|
||||
|
||||
- Switching between 12- and 24-hour time now updates loaded chat messages immediately. Recent server events use localized day periods without changing their recorded timestamps.
|
||||
|
||||
- A rejected channel password now opens an empty retry field with a localized error. Cancelling the password prompt leaves the user in the original channel.
|
||||
|
||||
- The channel menu offers Subscribe or Unsubscribe according to the current snapshot. A command from a dismissed or replaced menu cannot act on a newly selected channel.
|
||||
- Joining channel zero now returns a local validation error through both the embedded and diagnostic APIs.
|
||||
|
||||
- Show Moderation Events now hides and restores channel events already in the chat view, including events received while hidden. Ordinary chat history is unchanged.
|
||||
- Incoming chat with no explicit sender UID now uses the matching roster entry for the ignore list, just as it does for authorship. Reusing a client number does not transfer another user's ignore status.
|
||||
|
||||
- Private whispers no longer target a participant by client number alone when their UID is unavailable. Whispering to an explicitly selected channel still works.
|
||||
|
||||
- Creating a privilege key no longer reports success with an empty or ambiguous key. A repeated notification for the same key is accepted.
|
||||
|
||||
- Client information requests recheck the participant's UID when the server acknowledges the request. A stale client number cannot return another participant's details.
|
||||
|
||||
- Client database ID lookup now checks the returned UID and rejects conflicting IDs instead of passing unrelated notification rows to callers.
|
||||
|
||||
- Group creation no longer returns an existing group or a same-name group of another type as the newly created group. Follow-up permissions require one matching new ID.
|
||||
|
||||
- Searching a channel directory filters the loaded file names locally. Refreshing the same folder keeps the filter; opening another folder clears it.
|
||||
|
||||
- Searching or paging the client database now refreshes permission hints just like opening the first page, without losing the query or page offset.
|
||||
|
||||
- Filter scoped administration lists row by row so a change of group or channel within a notification cannot mix permissions from different targets.
|
||||
|
||||
- The connected nickname editor starts with the current name and stays open on server refusal. It uses the core's nickname validation and closes after an acknowledged change.
|
||||
|
||||
- Channel disclosure now remembers hidden participants per server address after restart. Collapsing a channel leaves its subchannels visible.
|
||||
|
||||
- The Compact tree style now reduces participant row and icon sizes without shrinking channels. The selected style takes effect immediately and survives restart.
|
||||
|
||||
- Desktop settings now report taskbar hiding as enabled for On Minimize, On Close and Both. The microphone lock description no longer promises automatic unmuting.
|
||||
|
||||
- Starting a local recording no longer asks for a free-form name that the core would reject. The native client uses the local start timestamp for the take folder, or the core's UTC name when the local offset is unavailable.
|
||||
|
||||
- Releasing the stream volume slider or confirming its form saves the level for the next viewer. Dragging previews the selected stream without writing preferences for each movement.
|
||||
|
||||
- Stream volume controls now use the playback engine's 0–100% range. Clicking the middle of the slider sets the selected viewer to half gain.
|
||||
|
||||
- Streams announced in server-routed mode show the SFU limitation instead of offering P2P playback. Direct streams from the same publisher remain watchable.
|
||||
|
||||
- A server notification that a channel description changed now invalidates its cached text and any pending description read for that channel. A newly reported empty description remains distinct from an unknown one.
|
||||
|
||||
- Audio and notification device pickers identify unavailable saved devices after enumeration. The saved route remains selected, and its name returns when the device becomes available again.
|
||||
|
||||
- Chat recognizes copied server-file links with bracketed IPv6 addresses, including links inside BBCode.
|
||||
|
||||
- The native Create Channel dialog no longer sends untouched optional overrides that can make ordinary guest creation fail. Codec and voice encryption offer Server default; explicit choices still go to the server.
|
||||
|
||||
- Channel creation returns an ID only for a matching notification from the same client under the requested parent. An accepted creation without a unique ID asks the caller to reload the tree before applying further changes.
|
||||
|
||||
- When creating a channel, changing its parent clears the previous insertion point. The picker lists only children of the new parent; leaving the position unset lets the server choose it.
|
||||
Creating or editing now also checks the selected predecessor at submission and refuses the change if it moved to another parent or disappeared.
|
||||
|
||||
- Moving a channel to its current parent and explicit position returns an unchanged result without sending a server command.
|
||||
|
||||
- Move Channel opens at the channel's current position. Selecting a new parent offers First and that parent's children; the moving channel and its descendants are excluded from the destinations.
|
||||
The core also checks the destination against the current tree when the move is submitted, so a predecessor that has since moved or disappeared cannot silently redirect the operation.
|
||||
|
||||
- Channel information and lists now show the current parent and preceding sibling after a neighboring channel moves.
|
||||
|
||||
- The server view now names the legacy Speex or CELT codec of the joined channel when voice is unavailable. Browsing another channel does not change the warning. The native transmission gate requires a known Opus codec.
|
||||
|
||||
- Reapplying direct voice transmission no longer ends an active burst or invalidates captured frames. Switching between direct transmission and voice activation still invalidates the old capture epoch.
|
||||
|
||||
- Push-to-talk release delay can now be set from Audio settings. Off preserves the last duration and cancels a running delay. Changing shortcut profiles also cancels a pending release from the previous profile.
|
||||
|
||||
- A talk request can now be submitted without a message. Pokes still require text.
|
||||
Once a withdrawal is visible to the moderator, the old Grant action no longer gives that client talk power.
|
||||
|
||||
- The Away with Message shortcut prompts once for all connected sessions. If a tab reconnects before confirmation, its replacement stays untouched and the other original sessions still receive the message. Cancel leaves all statuses unchanged; the per-server menu still targets one session.
|
||||
|
||||
- The moderation queue shows the newest talk requests first. Grant Next still selects the oldest waiting peer in the current channel and skips withdrawn requests.
|
||||
|
||||
- Alt-clicking the speaker gain slider resets only the gain to 0 dB. The Reset button also clears local mute. Both changes take effect on confirmation.
|
||||
|
||||
- The peer volume dialog now has a tapered slider from -200 to +10 dB in 0.5 dB increments. Reset restores 0 dB and clears local mute in the draft; Cancel leaves the original settings untouched.
|
||||
|
||||
- An unreadable speaker UID in saved local volume preferences no longer prevents valid speaker gains from being restored. Loading reports the invalid entry and leaves the original file untouched.
|
||||
|
||||
- Returning to the server tab that already owns the live microphone no longer interrupts capture when automatic microphone switching is enabled.
|
||||
|
||||
- File transfers now recognize HTTPFT and S3 anywhere in the server's capability announcement. A new connection without an announcement no longer displays the previous server's features.
|
||||
|
||||
- Desktop Appearance can open the folder of an individual installed theme. The existing Open Extension Directory button still opens the parent folder.
|
||||
|
||||
- Advanced notification settings now have separate controls and Listen actions for moderator moves into and out of your channel, a kick into your channel, assignment and removal of a server group, and permission errors. Existing advanced choices still apply until a variant is edited.
|
||||
|
||||
- Clients crossing channel subscription boundaries are reported as moving when the server supplies the movement reason or both channels. Subscribing to a roster no longer announces those clients as connecting. Batched roster entries preserve the previous channel for subsequent moves.
|
||||
|
||||
- Identity Details lists bookmarks in folder order. Bookmarks with no assigned identity follow the current default without rewriting the bookmark.
|
||||
|
||||
- When a connection is refused because its identity security level is too low, the server tab offers to review that identity at the requested level. Opening the review does not start a search or reconnect.
|
||||
|
||||
- First-run setup now keeps the selected theme when resuming an initialized profile without an identity. A failed theme save can be retried before any identity is created.
|
||||
|
||||
- Identity import now reports how many distinct identities were added or already present. Reimporting a known key no longer fails when all 256 slots are occupied.
|
||||
|
||||
- Desktop identity export now saves `.ini` backups atomically. A write failure leaves the previous backup intact.
|
||||
|
||||
- Removing the selected identity clears its saved selection. Details and subsequent edits stay with the surviving identity.
|
||||
|
||||
- A tab with a failed core remains selectable for recovery. Selecting a stale tab after restart no longer exits the application or disrupts the other tabs.
|
||||
|
||||
- On a confirmed move to another channel, the core revokes already captured audio before publishing the new channel snapshot. Other users' moves do not interrupt capture.
|
||||
|
||||
- Hiding offline contacts also hides the grouping switch without resetting its saved value.
|
||||
|
||||
- Collapsed contact groups show the total unread private messages for their hidden contacts.
|
||||
|
||||
- Contacts now count unread private messages across all server tabs, including conversations that have no open chat tab.
|
||||
|
||||
- Online and offline contact groups can be expanded independently and remember their state across restarts.
|
||||
|
||||
- The desktop bookmark section can be collapsed from its header and remembers that choice across restarts.
|
||||
|
||||
- Desktop sidebar and server pane widths now survive restart, including sizes saved by earlier native builds. Dragging on an ultrawide display cannot exceed the supported 1600 px server pane width.
|
||||
|
||||
- Variants in a theme package are sorted by name in the picker, matching the TS6 desktop order.
|
||||
|
||||
- The theme picker groups installed variants by package and shows shared package links once.
|
||||
|
||||
- The theme picker shows only declared package links, labels documentation separately from email, and confirms each destination before opening it.
|
||||
|
||||
- External links from Settings now show the local malicious-domain warning before opening. Malformed DNS names are rejected before classification.
|
||||
|
||||
- Trusted sites now shows whether the phishing list is up to date, using a previous copy, or unavailable.
|
||||
|
||||
- Reloading themes now names a missing selected variant when restoring the stock theme.
|
||||
|
||||
- A failed recording finalization now leaves the incomplete WAV in staging. The recording panel reports the writer error and does not offer to export it.
|
||||
- Stopping a recording no longer releases its directory grant while the writer is still finalizing WAV files. A late completion from an older take does not release the new take's grant.
|
||||
- The recording panel shows “Finalizing recording” after Stop. A late status reply cannot restore Pause or Stop while the WAV writer finishes.
|
||||
- Recording export asks about all existing destination files before replacing any of them. Cancelling an overwrite prompt leaves the existing files unchanged and retains the recording in staging.
|
||||
- Recording waveforms now show silence for blocks lost to a full writer queue, matching the saved WAV.
|
||||
- The recording panel now shows a live waveform for each track. Late replies cannot reopen a dismissed panel, and an older take's completion cannot authorize the current export.
|
||||
- Server chat now identifies advertised Matrix rooms as unsupported without disabling ordinary text chat or asking for an account.
|
||||
- Cancelling a password prompt no longer lets an older application snapshot reopen it.
|
||||
- Startup connections follow the order shown in the bookmark sidebar, including bookmarks inside reordered folders.
|
||||
- Two connections using the same identity and server now keep independent chat drafts. An acknowledgement in one tab no longer clears or unblocks a send in the other.
|
||||
- Channel chat now checks the channel captured by the editor against the core's current channel before sending. A draft for a channel you have left is rejected instead of being sent to the new channel.
|
||||
- An incoming chat message no longer appears twice when it is already included in the history page being loaded.
|
||||
- Closing a background private chat keeps the selected conversation and its draft in view. Reopened chats retain their label when the peer is offline.
|
||||
- Deleting the selected inactive shortcut profile now returns the editor to the active profile and its bindings.
|
||||
- Switching shortcut profiles cancels a held push-to-talk key immediately; the configured release delay still applies to ordinary key-up.
|
||||
- Settings checkboxes now display the value acknowledged by the application instead of retaining a local toggle state.
|
||||
- Settings selectors now show the acknowledged value after a change. The whisper receive selector
|
||||
no longer displays its previous mode after saving the new one.
|
||||
- Restarting a tab's core from its menu now confirms which tab restarted. A failed restart is
|
||||
reported as a failure before the caller receives its result.
|
||||
- Closing or restarting a connection discards queued playback from that session without interrupting
|
||||
another tab's microphone. Refusing to close the last tab preserves held push-to-talk and whisper.
|
||||
- Whisper settings now explain read-only and damaged files. Failed list deletion preserves assigned
|
||||
shortcuts, and Settings action buttons retain a clickable width on desktop.
|
||||
- A delayed global shortcut release can no longer stop a newly held local push-to-talk or whisper
|
||||
binding, or fire a local release-triggered action after the binding profile changes.
|
||||
- Channel and server edit dialogs read current values before editing, retain drafts after rejection,
|
||||
and close only on the matching server acknowledgement. Passwords are never prefilled.
|
||||
- Added ordinary-channel S3 metadata browsing, taking precedence over HTTPFT when both are advertised.
|
||||
The core accepts underscore-bearing command names and requires both matching list data and successful
|
||||
status; malformed or timed-out replies are errors, not empty folders. An isolated official TS6 beta14
|
||||
server verified an empty root listing and refused an ordinary guest upload grant. S3 file bytes,
|
||||
remote mutations and the live-peer check remain unverified; HTTPFT stays blocked without legacy fallback.
|
||||
- Verified two-way synthetic voice through the core CLI with silent disposable profiles. This did not
|
||||
exercise official-client peers, physical microphones or speakers.
|
||||
- A transport loss during a requested disconnect now completes the request as unconfirmed and
|
||||
leaves the session disconnected. Unexpected connection loss still follows the reconnect path.
|
||||
- A rejected connection command no longer tears down incoming voice. An expired capture frame is
|
||||
dropped without stopping the microphone; a revoked session still cannot submit audio.
|
||||
- Updated the desktop toolchain to Rust 1.100.0, Slint 1.19.1 (Skia m157.2), LiveKit WebRTC
|
||||
bindings 0.4.2/0.3.55, Sonora 0.3.0 and Rubato 5.1.0. Local media and clipboard patches
|
||||
are retained; old SDK build receipts do not certify the new source versions.
|
||||
- Fixed native Windows build environment capture for non-ASCII values by selecting UTF-8 in the
|
||||
child MSVC activation shell; verified against real vcvarsall with a synthetic Cyrillic value.
|
||||
- Pinned LF checkout for native dependency patches and recipe sources so Windows line-ending
|
||||
@@ -356,6 +35,10 @@
|
||||
production APK/AAB bundles with source/build/dependency receipts. Windows developers do not need WSL.
|
||||
Android packaging keeps offline Gradle by default; CI opts into dependency resolution explicitly and
|
||||
isolates each package's Gradle outputs. CI runner provisioning and device acceptance remain unverified.
|
||||
- Android CI now uploads the verified harness APK and receipts before starting production packaging,
|
||||
so a later production failure does not prevent retaining the test APK. Both variants reuse one recipe.
|
||||
- Android CI defaults to a bounded read-only runner inventory; full Android builds require explicit
|
||||
manual selection and still use the dedicated Android runner label. Inventory never installs tools.
|
||||
- Removed the Electron application, npm manifests and browser-only test/build tooling. Rust/Slint
|
||||
is now the only application; native resources and versioning no longer depend on the removed tree.
|
||||
Retained native profile migration and diagnostic core CLI. This cutover is not mobile runtime acceptance.
|
||||
|
||||
Generated
+646
-998
File diff suppressed because it is too large.
Load diff
+11
-13
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["core", "dsp", "native", "xtask"]
|
||||
exclude = ["core/vendor/tsclientlib", "core/vendor/tsproto", "core/vendor/tsproto-packets", "dsp/vendor/sonora", "dsp/vendor/sonora-agc2", "native/vendor/libwebrtc-0.4.2", "native/vendor/webrtc-sys-0.3.55", "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.19.1"]
|
||||
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"
|
||||
@@ -10,19 +10,18 @@ rust-version = "1.96"
|
||||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
base16ct = { version = "1", features = ["alloc"] }
|
||||
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.19.1", default-features = false, features = ["std", "compat-1-18", "accessibility", "image-default-formats", "unstable-fontique-012"] }
|
||||
slint-build = "=1.19.1"
|
||||
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.1.0", default-features = false }
|
||||
sonora = "=0.3.0"
|
||||
sonora-ns = "=0.3.0"
|
||||
libwebrtc = "=0.4.2"
|
||||
webrtc-sys = "=0.3.55"
|
||||
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 }
|
||||
@@ -30,17 +29,16 @@ cssparser = "=0.38.0"
|
||||
|
||||
[patch."https://github.com/ReSpeak/tsclientlib"]
|
||||
tsproto = { path = "core/vendor/tsproto" }
|
||||
tsproto-packets = { path = "core/vendor/tsproto-packets" }
|
||||
|
||||
[patch.crates-io]
|
||||
sonora = { path = "dsp/vendor/sonora" }
|
||||
sonora-agc2 = { path = "dsp/vendor/sonora-agc2" }
|
||||
libwebrtc = { path = "native/vendor/libwebrtc-0.4.2" }
|
||||
webrtc-sys = { path = "native/vendor/webrtc-sys-0.3.55" }
|
||||
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.19.1" }
|
||||
i-slint-backend-android-activity = { path = "native/vendor/i-slint-backend-android-activity-1.18.1" }
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: TeamsPeach
|
||||
description: Native TeamsPeach's account-free visual contract, derived from TeamSpeak 6 reference evidence.
|
||||
description: The installed TeamSpeak 6 client's own visual system, reproduced from its source values.
|
||||
colors:
|
||||
tsv-bg-dark: "#2b3346"
|
||||
tsv-bg-light: "#f5f5f5"
|
||||
@@ -100,13 +100,10 @@ components:
|
||||
**North Star: "The official TeamSpeak 6 client, value for value."**
|
||||
|
||||
The owner asked for the installed TeamSpeak 6 client's design, without reinterpretation. Two earlier
|
||||
TeamsPeach worlds (flat warm-neutral, then the Liquid Glass approximation) are retired. The current
|
||||
desktop visual reference is **TeamSpeak 6.0.0.5232**; see the [visual source map](docs/evidence/official-parity/visual-source-map.md)
|
||||
for both manifest-checked bundle hashes, fixture scope, capture commands and comparison results.
|
||||
The retained design values below are historically derived from **6.0.0.5163** (`main.css` sha256
|
||||
`bc700401…`, `main.js` sha256 `9d6bea2e…`): webpack theme tokens (`main.js` @92422 dark, @201685 light),
|
||||
scale and component geometry (`main.css`) and layout constants (`main.js` window slots @1273206).
|
||||
Do not use those offsets as 5232 offsets. The extracted historical values
|
||||
TeamsPeach worlds (flat warm-neutral, then the Liquid Glass approximation) are retired. The target values
|
||||
come from installed client 6.0.0.5163 (`main.css` sha256 `bc700401…`, `main.js` sha256 `9d6bea2e…`): theme
|
||||
tokens from its webpack theme modules (`main.js` @92422 dark, @201685 light), scale tokens and component
|
||||
geometry from `main.css`, layout constants from `main.js` (window slots @1273206). The extracted values
|
||||
and source offsets are in `docs/evidence/official-parity/ts6spec-{shell,tree,chat,controls,settings}.md`.
|
||||
Native stock theme data retains the official `--tsv-*` names in
|
||||
`native/src/services/themes/stock.css`; `native/ui/` expresses the Slint geometry and presentation.
|
||||
@@ -249,18 +246,14 @@ notifications opaque; forced colours use system tokens.
|
||||
project links and installation details live on working subpages with back-focus restoration.
|
||||
About retains TeamsPeach branding and real metadata; Report Issue targets the verified project tracker.
|
||||
Content reporting, Terms and five source-position social tiles explicitly state their unavailable status.
|
||||
- The current 5232 desktop comparisons use synthetic state, not a user account. Both native runs
|
||||
completed all 20 scenes (dark/light × EN/RU at 1280×800), but neither passed a whole screen.
|
||||
The strict comparator does not mask branding, account-only slots or caption differences.
|
||||
The historical Electron 192-pair checkpoint passed 56; its subsequent four-panel 32-pair
|
||||
checkpoint failed every whole-screen comparison. Runtime workflow success is not pixel parity.
|
||||
See the [current visual source map](docs/evidence/official-parity/visual-source-map.md) and the
|
||||
[historical QA record](docs/evidence/official-parity/qa-parity-harness.md).
|
||||
- Whole-screen comparisons remain strict failures where state, content or geometry differs. The full
|
||||
192-pair checkpoint passed 56; the subsequent four-panel 32-pair checkpoint still failed all whole-screen
|
||||
comparisons. Runtime workflow success is not pixel parity. Build-specific evidence and residuals are in
|
||||
`docs/evidence/official-parity/qa-parity-harness.md`.
|
||||
|
||||
## Do's and Don'ts
|
||||
|
||||
- **Do** cite the source build and offset or measured scene for new values. Keep 5163 extractions
|
||||
separate from 5232 capture evidence.
|
||||
- **Do** take every new value from the installed client and cite its offset in the evidence specs.
|
||||
- **Do** keep native caption colors aligned with `--ts-new-header-bg` and `--tsv-font-color` where supported.
|
||||
- **Do** retain stock token names and the explicitly supported native theme-import subset; no DOM fallback.
|
||||
- **Don't** reinterpret, restyle or "improve" the official look; deviations above are product constraints.
|
||||
|
||||
+3
-397
@@ -1,397 +1,5 @@
|
||||
# TeamsPeach ↔ TeamSpeak 6 server features
|
||||
|
||||
## Current Windows account-free checkpoint (2026-11-26)
|
||||
|
||||
**Channel description at creation:** On private beta14 with b_channel_create_with_description granted to the disposable guest, the Windows Slint toolbar form retained an over-limit draft with an inline error and discarded a cancelled draft. Submitting a two-line description created a temporary root channel; a separate channel_description request for its roster ID and a newly opened Edit Channel form both returned the exact text. This covers the creation property, not other optional fields or the whole channel administration workflow.
|
||||
|
||||
**Withdrawn updates:** The loopback server first offered native 0.1.8 to a disposable 0.1.7 Windows installation. After download, the listing changed to only 0.1.6 and 0.1.7. A second check returned UpToDate, no offer, zero transferred bytes, an empty update cache and no installable package. No second package was requested. Six focused tests passed, including candidate selection and the About selector. Combined with the channel and integrity runs below, this covers checkForUpdates and updateChannel on this fixture, not an actual installer or a public-feed availability check.
|
||||
|
||||
**Explicit update download:** On the local Windows release fixture an active session deferred automatic download, while explicit download retrieved the offered package. A short response failed the size check and a changed payload failed SHA512. The short package left no cache entry, could not be installed and did not change the disposable executable. The fixture uses blocking reads on accepted connections. No installer was launched.
|
||||
|
||||
**Update channel:** The About selector changed Preview to Stable in a disposable Windows profile. Two restarts retained Stable in both the selector and updater. A failed attempt to save Preview left selection, service and file unchanged. With a loopback release fixture, switching channels cleared the previous offer and check time; a late Preview check or download did not publish into Stable. Nine focused tests passed, including checksum rejection and call-aware download deferral. The installed application was not replaced.
|
||||
|
||||
**Local profile persistence (Windows, 2026-11-28):** Nine focused Rust tests passed on disposable profiles. Slint kept duplicate-chord warnings in the correct profile when two profiles reused a binding ID. After restart the active profile's F9 push-to-mute worked and the previous profile's F8 did not start PTT. A 33rd profile was rejected without changing the saved file. Shortcut events were supplied at the native platform boundary; no system-wide registration or physical keyboard was exercised.
|
||||
|
||||
The offline folder editor covered generated IDs, unnamed labels, moving folders, depth and capacity limits, restart, failed saves and recovery of orphaned or cyclic parents. The Contacts Ignore and Chats Remove controls preserved UID-based filtering across restarts: a renamed blocked contact stayed blocked, but another UID with the same name and recycled client number was delivered. Incoming chat events were synthetic; live send and failed-send draft retention were not verified by these tests.
|
||||
|
||||
**Voice toolbar ownership (Windows beta14):** With the observer tab in view and the other tab owning input, the microphone button muted the input owner. The speaker button then restored and disabled that owner's output without unmuting its microphone. The toolbar and both server rosters agreed after each change; the observer kept both mute flags. No physical input or output was opened.
|
||||
|
||||
**Cross-tab deafen (Windows beta14):** While one tab transmitted continuous synthetic input, the native deafen action on the receiving tab stopped and then restored its talking indicator. Its microphone stayed muted. The sending tab retained its original capture permit, kept transmitting and kept producing fresh capture blocks through both changes. No physical devices were opened.
|
||||
|
||||
**Voice playback after UI detach (Windows beta14):** A receiver with a synthetic output rendered a tone from a second disposable core. The first burst drained to silence, the receiver released its UI attachment, and a fresh burst produced new non-silent output blocks without reattaching or replacing either session. Notifications and comfort noise were disabled. Separate mixer tests checked gain and isolation when closing a connection. No physical speaker or microphone was opened.
|
||||
|
||||
**Playback authorization:** On Windows, generated PCM stayed silent when the initial roster lacked a local client ID. An explicit boolean output_muted=false admitted the samples; a missing flag or the string "false" closed the route again. Separate mixer tests checked volume and the surviving connection's samples after another route retired. No physical speaker was opened.
|
||||
|
||||
**Native capture ingress on Windows:** The synthetic 48 kHz input passed through the capture worker, DSP and embedded core to another beta14 client. Separate tests checked the full 960-sample frame against the timestamp of its first half (200 ms inclusive), discarded stale frames without retiring a valid permit, and discarded partial frames on mute or rebind. During input handoff the old permit was unusable before the new core's acknowledgement; viewing a third tab did not transfer ownership. Generation changes invalidated the old capture epoch. These checks do not measure a physical microphone or speaker.
|
||||
|
||||
**Capture release during a 600 ms stall:** A core regression revoked the capture epoch with one frame queued, one dequeued, and one held by VAD. The transport guard rejected the dequeued frame immediately. After a 600 ms consumer stall, the queue contained only an end marker; the old dequeued and preroll frames could neither enter encoding nor pass the send guard. A fresh frame with the new epoch started a new VAD burst and passed the guard. No network or devices were used in this stall test; live PTT and whisper release were checked separately on beta14.
|
||||
|
||||
**PTT key on Windows:** The Audio recorder rejected Ctrl+F9 and a failed atomic save without replacing F8. Cancel restored the old binding. Saving F10 retained the new key across two restarts. On private beta14 with continuous synthetic input, the old F8 did not transmit; F10 started and ended speech at the receiver and respected the selected tail. This checks native local key events, not OS-wide registration.
|
||||
|
||||
**Overlapping PTT and Push to Mute (Windows beta14):** With F8 held and both peers reporting speech, F9 stopped transmission and cleared the receiver's talking indicator without changing the visible mute flags. Releasing F9 with F8 held restored speech; releasing F8 before F9 left both peers silent. A later F8 hold still transmitted. These were local native key events with a synthetic capture backend, not OS-wide shortcut registration.
|
||||
|
||||
**Local whisper keys on Windows beta14:** Two saved list shortcuts were driven through native platform key events with the receiver viewed and the sender owning input. F9 replaced F8; releasing F8 preserved the F9 route. Synthetic PCM sent through the current manager permit produced remote talking and a sender-matched entry in the receiver's whisper history. Releasing F9 revoked the permit and ended remote talking. Separate worker tests checked that capture blocks acquire the whisper epoch when bound and do not carry it into an ordinary rebind. No physical device or OS-wide shortcut registration was used.
|
||||
|
||||
**Group whisper delivery (Windows beta14):** Two disposable Rust cores shared the default Opus channel with receive policy set to Allow All. In current-channel mode, `duplex_qa --group-whisper` delivered tones and sender-matched whisper notifications for the receiver's server and channel groups. Between those deliveries, transmissions to an existing server group and channel group the receiver did not belong to produced no playback, talking start or whisper notification on that same connection. Both disconnects were confirmed. This does not exercise a Slint hotkey, a physical device or other channel scopes.
|
||||
|
||||
**Channel subscriptions across tabs (Windows beta14):** Two muted guests stayed in the lobby. From the first tab's tree menus, Unsubscribe All cleared both accessible test channels, Subscribe enabled only channel A, Unsubscribe cleared it, and Subscribe All enabled both. Each transition required a newer snapshot; the second tab retained its flags and menu actions. Subscription to a third channel with needed subscribe power 100 returned a visible PermissionsClientInsufficient; that channel remained unsubscribed on both tabs. Separate tests covered stale menu tokens, malformed stdio arguments and refusal ownership after a tab switch or replacement session. Reconnect during acknowledgement was not forced on the live server.
|
||||
|
||||
**Channel reads across deletion:** Protocol tests fed deletion of the requested channel, reuse of its ID and a replacement description before the pending acknowledgement. Both channel_info and channel_description rejected the original request; deleting an unrelated channel preserved the requested description. The Windows beta14 channel editor separately passed multiline and empty description readback. ID reuse was tested with protocol events, not by forcing reuse on beta14.
|
||||
|
||||
**Classic uploads on Windows (2026-11-27):** Two muted tabs restored a 1 MiB/s upload limit and two upload slots saved through Slint. Both 4 MiB uploads made simultaneous progress; the combined rate stayed within the configured ceiling plus 192 KiB sampling allowance. Lowering the slot count to one paused the newer same-tab upload while the older upload and the other tab finished. Explicit resume completed the paused upload. All five files were downloaded and compared byte for byte. The ignored test `two_connected_tabs_share_the_saved_upload_rate_and_slots` requires a disposable classic beta14 on `127.0.0.1:19987` with an empty channel named `TeamsPeach Upload QA` granting the two guests upload, browse and download rights in that channel. No HTTPFT or S3 result is implied.
|
||||
|
||||
**Permission Groups on Windows (2026-11-27):** On both tabs of a private beta14 fixture, the rendered rows matched the regular groups in independent server and channel group list replies. The row menus and creation actions retained the viewed connection and matched its permission hints. Separate model tests checked one-list replacement (including an empty reply), equal IDs across catalogs, invalid replies and late panel results. No group was created, renamed or deleted on the live server.
|
||||
|
||||
**Server Log on Windows:** On private beta14, granting only b_virtualserver_log_view allowed a guest to read the virtual server log. The displayed lines matched an independent forward read from position zero. The instance log remained inaccessible: the editor displayed PermissionsClientInsufficient and retained the submitted options. Cancelling or submitting invalid bounds did not open a log panel; switching tabs invalidated the old form. Separate tests covered literal text, order, metadata-only rows, empty and malformed replies. To reproduce the positive test, enable a private runtime log directory on the disposable fixture after bootstrap. No log contents were printed.
|
||||
|
||||
**Server Info on Windows:** Two muted beta14 guests opened the server tree row's menu in turn. The rendered name and welcome message matched a separate server_info response for each connection, and the edit action retained the viewed tab's session and server UID. Model tests rejected obsolete results after Back, a new connection generation or a different UID. No server settings were changed.
|
||||
|
||||
**Protected move destination:** On private beta14 the move confirmation opened with an empty secret field for a protected destination. An oversized multibyte password and a tab were rejected in the editor. Cancelling left the two guests in their original channels. A command-builder test checked that a 1024-byte password including surrounding spaces was preserved. This does not establish a successful server-authorized participant move.
|
||||
|
||||
**Move to Own Channel:** With two muted beta14 guests the action was absent in the same channel and available once the initiator entered a separate temporary channel. The unprotected destination had no password field. Cancellation and the server's permission refusal left both guests in place; submitting an open confirmation after the initiator changed channels reported a changed target. No successful privileged move was observed.
|
||||
|
||||
**Client database panel:** Without list permission the disposable beta14 guest saw PermissionsClientInsufficient and no database rows or active search target. With b_virtualserver_client_dblist and b_virtualserver_client_dbsearch, listing, nickname search and UID search returned the same roster nickname, UID and positive database ID in the same session. The Windows smoke located the rendered search selector and submitted each mode through the Slint callback; it did not drive the dropdown or Enter key. No database entry was edited or deleted. Separate tests covered page bounds, Unicode search limits and stale query results.
|
||||
|
||||
**Channel codec quality:** The create form rejected 11 and created a temporary channel at quality 5. The edit form restored 5, saved 7, and retained an invalid -1 with a field error. Cancelling a draft of 3 left quality 7 in both the server roster and a newly opened editor. The check exercised server properties, not encoded audio quality.
|
||||
|
||||
**Channel rename:** In the private beta14 channel editor, a 41-character name remained in the form with a validation error. Cancelling a replacement draft preserved the original name. A 40-character rename was acknowledged on the same channel ID in the roster, Slint tree and reopened editor; the topic and the lobby name stayed unchanged.
|
||||
|
||||
**Channel upload chooser on Windows:** The native multi-file dialog returned exact names and sizes for two regular files. Cancellation, a reconnect while the picker was open, and selection of 101 files produced no usable upload batch. The staging regression also verified that changing a source after selection dropped staged bytes and issued no tokens. Five focused checks passed. This covers selection and session ownership, not receipt of uploaded bytes by a server. Mobile pickers were not changed or tested.
|
||||
|
||||
**Download destinations across tabs:** With Always Ask saved, a restarted Windows runtime hid the default chooser but retained the approved folder. Cancelling a one-off picker queued nothing; a picker held across reconnect was rejected. The first tab downloaded into its one-off folder. With both guests connected, disabling Always Ask on the second tab restored the approved folder and published the same seeded bytes there. The first copy remained intact. No upload or mobile picker was exercised.
|
||||
|
||||
**Download slot reduction:** After restoring two download slots from disk, two guests on private classic beta14 ran three downloads: two on one tab and one on the other. Changing the limit to one in Slint paused the newer same-tab transfer without publishing its partial file. The older transfer and the independent tab finished; the paused transfer completed only after an explicit resume. All three 4 MiB files matched the source pattern. Upload slots were not exercised on the wire.
|
||||
|
||||
**Shared download rate:** After setting 1 MiB/s through Slint and restarting the runtime, two tabs downloaded separate copies of the same 4 MiB classic beta14 fixture. Both cores reported positive progress at the same time. From that sample to final publication, their remaining combined bytes fit the 1 MiB/s ceiling with 192 KiB of allowance for in-flight chunks and sampling. Both complete files matched the seeded pattern byte for byte. This covers limitDownload and downloadMiB, not a two-tab upload rate or a hard per-packet bandwidth limit.
|
||||
|
||||
**Channel file mutations on Windows (2026-11-27):** On private classic beta14, a guest opened the empty, non-default permanent channel named `TeamsPeach Directory QA` with directory creation, rename, delete and browse rights. The native browser created and renamed a folder; cancelling deletion preserved the renamed folder, and confirming deletion removed it. Independent root listings matched the browser after each operation. In a separate temporary channel, a permission refusal remained visible and the listing stayed empty. Cancelling a rename of a seeded file or submitting its original name also left it unchanged.
|
||||
|
||||
**Microphone handoff failure:** With two private beta14 guests, viewing the second tab left the first capture permit valid. Choosing Use Microphone for the second tab with an unavailable exact output endpoint reported the device error, revoked the original permit, left no usable new permit and started no devices. Notification output was configured as None. Seven focused Windows checks passed, including connect-form persistence and capture revocation. Successful PCM delivery across a live UI handoff was not tested here.
|
||||
|
||||
**Remembered connection address:** On private beta14, a Windows Connect form replaced the saved address only after the muted guest joined. With a missing exact WASAPI endpoint, the playback error remained visible, neither audio direction started, and a fresh runtime restored the new address without connecting. A separate offline Slint test covered cancellation, refusal and a blank second tab. These checks do not verify swapping microphone owners between live connections.
|
||||
|
||||
**Central Matrix exclusion:** The native server-chat test rendered a matrix: room URI as non-interactive text and a matrix.to HTTPS room link as an external-link confirmation. Cancelling that prompt preserved the exact server conversation and its unsent draft. Together with the empty offline Chats check, this covers the account-free boundary, not central or server-hosted Matrix transport. Neither a browser nor a Matrix server was contacted.
|
||||
|
||||
**Account and Remote Apps exclusions:** An isolated Slint window showed local identity settings, no Account or Remote Apps category, and a disabled account-only private-message setting with the account requirement. Attempting that setting and then sending from empty offline Chats left no conversation, tab, login dialog or active server connection. The ordinary server-chat Matrix notice was tested separately. This verifies the native UI boundary, not account interoperability or a network traffic audit. An empty chat alone does not establish what a stale central-room link does when another conversation is open.
|
||||
|
||||
**Block Incoming Whispers shortcut (excluded):** The reference declares ActivateBlock, DeactivateBlock and ToggleBlock without a demonstrated dispatcher. Importing those modes in a disposable version 2 shortcut profile produced an explicit diagnostic, no local down/up action, and no global registration candidates; the profile bytes and a working Reply Whisper chord were preserved. The supported receive-mode selector is separate. No OS global shortcut was registered.
|
||||
|
||||
**Whisper sender identity on Windows:** The native client records the UID and nickname captured by the receiving core. A later roster cannot turn an unknown sender or a recycled client number into a reply target. On private beta14, two diagnostic cores matched the receipt to the sender roster under Allow All, observed neither playback nor a receipt under Deny All, then received an identified whisper after re-enabling. The connected Slint receive selector persisted Deny All across profile reopen. Three core and four native regression checks passed separately. A physical Reply shortcut and live recipient-number reassignment were not exercised.
|
||||
|
||||
**Channel commander on Windows:** Slint rendering tests verified the compact lamp versus separate icon, the detailed-tree icon, and preference persistence in English/dark and Russian/light fixtures. On private beta14 the other guest's menu had no commander action. The server refused the self change with PermissionsClientInsufficient; both flags remained off and the old confirmation could not affect the replacement identity. Four native checks and two core checks passed. A successful authorized commander change on beta14 remains unverified.
|
||||
|
||||
**Participant volume:** On private beta14 the Slint fader applied -10 dB during the drag without saving it, then persisted it on release. Muting the peer did not change the listener's own gain. Reconnecting the listener restored -10 dB for the peer without restoring mute; Reset returned the gain to 0 dB and removed the stored modifier. Twelve native checks covered ordering, persistence and error handling. Three core tests covered two-speaker Opus mixing, stale queued audio and reused client numbers. No physical capture or playback device was used.
|
||||
|
||||
**Participant context on Windows:** On private beta14, two muted guests opened the self and peer menus on both tabs. Poke, volume, Connection Info and group availability matched independently queried capabilities for the selected client ID, UID and generation. The test inspected an eligible group choice without submitting it. Escape preserved selection and whisper targeting. A separate popup test verified one request per opening and rejection of stale responses after reopening. Five native and two core checks passed.
|
||||
|
||||
**Participant Poke on Windows:** Two muted guests used Slint's participant menu on private beta14. The server refused the long message with ParameterInvalidSize; the editor retained it and accepted a shorter correction. The destination recorded the exact literal message with the initiator's UID. Cancelled, locally oversized and stale drafts did not arrive. The replacement guest had the same display name but a different client ID; reused-ID rejection was tested separately. Five native checks and a real stdio byte-boundary test passed. No physical audio was used.
|
||||
|
||||
**Participant connection statistics:** The Windows Slint menu displayed the peer's server-assigned client ID and a numeric timing metric with units on private beta14. After changing tabs and reconnecting, the self panel used the new session. Escape dismissed the menu without changing selection or the whisper target. Separate tests checked English and Russian formatting, exact counters, empty and unscoped responses and client-number reuse. Seven native and three core checks passed; no physical audio was used.
|
||||
|
||||
**Participant Info on Windows:** On private beta14, two muted guests opened the rendered participant Info menus. The test compared displayed properties with targeted core reads, required nonempty version and platform for self, checked the peer result against the server's actual permission response, and verified tab-switch cleanup. A separate reconnect scenario checked the same tab with a new identity. Matching rows merge the last explicitly supplied value for each field; an empty field can clear it. An acknowledgement without a matching row fails. Ten native and two core tests passed. Physical devices were not used.
|
||||
|
||||
**Talk power on Windows:** On private beta14 the moderator granted and revoked talk power from a participant's Slint menu without a pending request. Both guests observed the new talker flag. A queue grant succeeded for a pending request, a withdrawn request was rejected locally, and an ordinary guest's manual grant was refused by the server without changing either roster. Four native checks and a stdio validation test passed. Queue identity checks occur before dispatch; the server remains authoritative. Both guests were muted.
|
||||
|
||||
**Away status and talk requests:** Two muted beta14 clients observed the submitted away message and return to online. Cancelling the Slint form left both rosters unchanged; reconnecting one recipient before submission prevented the old prompt from changing its replacement. In a temporary moderated channel, both clients observed talk requests with and without a message, grant and revocation, then withdrawal. The core stdio test verified Unicode length limits, rejected null and forbidden controls, and distinguished malformed requests from valid offline commands. No physical voice equipment was used.
|
||||
|
||||
**Disconnecting the viewed tab:** Two muted guests connected to private beta14. After the first tab reconnected, selecting it did not move the second tab's microphone ownership. Disconnect from the first tab's Slint menu removed only that guest from the surviving roster. A separate embedded-core test exercised capture revocation and handoff acknowledgement with generated PCM. The live test did not open physical audio devices or initiate its connections through the Slint Connect form.
|
||||
|
||||
**Partial snapshot import receipts:** Controlled apply tests verified retained acknowledgements after refusal or cancellation, failed icon transfers, reused icons, and renames followed by failed creation. The partial report lists the affected objects, fields and permissions without their values. A recycled transfer ID was not cancelled in the replacement session. On live beta14 the confirmed Skip run reported one skipped root, zero changes and an unchanged roster. The 32-test Windows run did not perform privileged live mutations.
|
||||
|
||||
**Applying the previewed snapshot:** The private beta14 Windows test opened two client snapshots with the same catalog ID. Stale Apply and Cancel actions could neither apply nor dismiss the replacement. Cancelling confirmation made no changes; an empty confirmation was rejected. Confirming the server UID with Skip reported one existing root skipped, zero changes and an unchanged channel roster. Service tests, not the live server, covered partial mutations, cancellation and reconnect. The focused run passed 29 tests.
|
||||
|
||||
**Snapshot export result:** Windows Save cancellation created no file. On classic desktop UI with a private beta14 server, selecting the channels section wrote a client JSON snapshot with one permanent channel; the partial report showed the saved filename and the channel-permission issue. Reopening that file displayed the expected catalog and server UID. Separate service tests covered all selected sections and variable substitution. A complete privileged export of groups and icons was not run on the live server.
|
||||
|
||||
**Snapshot cancellation:** Six focused tests verified early cancellation of export and apply, preservation of an acknowledged parent without creating its child, exact session ownership when a file-transfer number is reused, and presentation of a partial cancellation report. An export cancelled at job start created no output or core request. These cases used controlled service and UI-state tests; no live import modified a server.
|
||||
|
||||
**Snapshot progress:** On private beta14 the channels-only export finished with phase `channel`, 2 of 2 processed steps, one saved channel and one channel-permission issue. A completed count is not a claim that all steps succeeded. Separate tests checked stale jobs, connection and attachment changes, cancellation, and terminal report preservation. Twenty focused native tests passed. No snapshot changes were applied to the live server.
|
||||
|
||||
**Opening client snapshots:** The live Windows Open dialog showed the saved beta14 catalog and target server UID. Separate selection and codec tests rejected malformed JSON, server-side exports and oversized documents without creating import tokens. Reconnect invalidated the original selection. No import was applied to the live server.
|
||||
|
||||
**Channels-only snapshot on Windows:** A muted guest opened Export from the server menu on private beta14. Cancelling the real Save dialog created no file. A second export wrote the named JSON file with exactly the requested channels section. Its permanent channel hierarchy matched the current roster (one channel). The report was **partial**, with one channel-permission issue; progress was visible. Opening the saved file through the Windows Open dialog showed the matching catalog, metadata and target server UID in Slint. No snapshot was applied and no permissions were changed. This verifies the channel_list consumer, not a fully privileged export of every section.
|
||||
|
||||
**Channel Info on Windows:** On private beta14, a muted guest opened Channel Info from the temporary channel's Slint menu. The visible name, edited topic and multiline description matched the selected channel. Back cleared the details; selecting the lobby showed its own properties without joining it. Separate tests exercised out-of-order results, reconnection and invalid reply cardinality. A real stdio test rejected invalid arguments for channel_info, channel_description and channel_list before connection lookup. This verifies the Windows channel_info workflow, not all channel administration.
|
||||
|
||||
**Contact highlighting:** The Slint Appearance switch saved its disabled state across two restarts. Turning it back on marked the saved contact's tree row; a different UID reusing the same client number was not marked. This used isolated roster snapshots, not live presence or a screenshot comparison with the official client.
|
||||
|
||||
**Local contact editing on Windows:** The offline Slint test added a UID and name, rejected malformed and duplicate UIDs without changing memory or disk, set and cleared an alias, and restored the alias and ignore entry after restart. Ignoring stored the UID and original name, not the alias. Cancelling removal kept the contact; confirmed removal survived a second restart. A separate runtime test used ordered roster and chat events to distinguish UIDs even when the client number was reused. These checks cover the local contacts preference and its uid, name and alias fields, not cloud presence or live private chat interoperability.
|
||||
|
||||
**Copy download location on Windows:** Transfer Settings displays the saved path both immediately after selection and after restart. The copy action uses that setting, not the cached OS Downloads grant. A service test checked the empty and configured strings, and a Winit/Slint test activated Copy and observed os_actions_disabled in an isolated profile. The real Windows clipboard was neither read nor written. Two live download scenarios passed in the same revision; a third stopped at login with TS 3329 before its picker opened.
|
||||
|
||||
**Inline channel image on Windows:** A muted guest sent a ts3image link in the Slint channel chat on classic beta14. Activating it loaded the fixture PNG; its RGBA bytes matched the 2-by-1 red/green reference and the window painted red to the left of green. Reconnecting rejected a request from the retired session and stale asset results while accepting the replacement conversation's result. Three decoder checks covered size and format boundaries; a stdio check rejected invalid file_fetch_image requests. No HTTPFT, S3 or external image fetching was exercised.
|
||||
|
||||
**Pause, resume and cancel on Windows:** A muted guest downloaded `teamspeach-transfer-control.bin` from classic beta14 at a configured 1 MiB/s. The Slint row showed positive partial progress before Pause. Cancelling the paused transfer left the destination and staging empty. Resuming a second paused transfer published all 4 MiB, checked byte for byte. The fixture has 64 blocks of 65536 bytes: byte zero is the block index; other bytes at offset i are (i + (i >> 8)) modulo 256. One stdio test verified the ID bounds for all three commands, and four core loopback tests exercised resume offsets, cancellation and replaced partial files. This covers `command:file_pause`, `command:file_resume` and `command:file_cancel` on classic storage.
|
||||
|
||||
**Download failure and overwrite:** With classic beta14 the Slint file browser downloaded the selected file into the approved folder and reported 46 B / 46 B. Cancelling overwrite kept the existing bytes; confirming a one-off picker after reconnect did not enqueue a transfer. Three separate Windows tests verified that a partial staged write followed by StorageFull preserves the previous file, a cancelled copy leaves no partial replacement, and a replayed core event does not retry a failed export. The storage-full error was injected at the writer, not produced by filling a volume. This covers `preload:filesDownload` and `main-only-command:file_download` on classic storage.
|
||||
|
||||
**Transfer history on Windows:** After a real download from private beta14, the guest reopened the list from the file browser and saw 46 B / 46 B for the published file. Reconnecting on the same tab produced a fresh session key, an empty core transfer list and an empty Slint panel. Over stdio, an unexpected channel_id returned bad_request; empty arguments without a connection returned not_connected. This covers `command:file_transfers` on classic storage, not sustained transfer speed.
|
||||
|
||||
**Channel file list on Windows:** The guest opened the default channel's file browser from its Slint menu on private beta14. The listed filename and size matched the 46-byte fixture, and Download from that row produced the exact bytes. A separate live test rejected a stale picker after reconnect. The stdio test rejected invalid paths, unknown fields and out-of-range IDs before connection lookup; the largest valid channel ID reached the connection gate. This covers `command:file_list` on classic storage, not HTTPFT or S3.
|
||||
|
||||
**File chooser release:** The last-used directory hint retains only a path. Releasing an unused token drops the backing lease; attempting to download with the released token returns bad_request before dispatch and leaves existing bytes unchanged. A separately retained in-flight staging grant survives token release until the transfer reaches a terminal state. All 13 file-service tests passed. This verifies the native service equivalent of `preload:filesRelease`; the OS picker and reconnect case were verified separately.
|
||||
|
||||
**Transfer settings readback:** The Windows Slint controls saved 8 download slots, 2 upload slots and directional limits of 1.5 and 2.5 MiB/s. Restart restored all four fields, both limit switches, the prompt choice and the selected directory; a real beta14 guest download reached that directory. Four separate checks covered the numeric controls, divided rate configuration sent to two simulated core sessions, invalid or rejected changes, and persistence failure. This is UI and scheduler-command evidence, not a measured two-peer wire rate.
|
||||
|
||||
**One-off Windows download folder:** With Always Ask enabled, cancelling the system picker queued no transfer and created no output. Confirming a picker left open across a reconnect in the same tab returned `target_changed`. The replacement session downloaded the 46 fixture bytes only after a new selection, without changing the default folder. All three download-directory tests passed on private beta14 with classic file storage. This covers Windows `preload:filesChooseDownloadDir`.
|
||||
|
||||
**Windows default download folder:** Transfer Settings selected and cancelled through the system folder picker. After restart, a muted beta14 guest downloaded the fixture's 46 known bytes using classic file transfer into the selected folder. Cancelling an overwrite preserved the existing bytes without queuing a transfer. A separate restart test removed the selected folder and observed the restore error without recreating it or staging a download. To reproduce the positive test, provision `/teamspeach-download-smoke.bin` in the disposable server's default channel with `BYTES` from `native/src/smoke/download_folder_fixture.rs`; the guest needs list and read permission only. This covers Windows `preload:filesChooseDefaultDir`, not S3, uploads, or multi-tab limits.
|
||||
|
||||
**Recording destination on Windows:** Audio Settings opened the Windows folder picker. Selecting a disposable folder updated Settings; Cancel retained it, generic preferences could not replace it, and two fresh runtime launches restored it. Both beta14 recording exports landed in that folder. A separate service test rejected failed persistence and stale chooser results without granting access. This covers Windows `preload:pickRecordingFolder` and `preference:recordingFolder`, not Android or iOS document pickers.
|
||||
|
||||
**Recording commands on beta14:** The Slint panel started, paused, resumed and stopped a master take in a disposable destination. The track waveform, recorder status and info were checked against the silent PCM export and its timeline. Cancelling or submitting an invalid start left the destination untouched. During a second take, old buttons and a queued Stop could not pause or stop it; the first WAV remained byte-for-byte intact. Reconnection opened an idle recorder. Eleven native checks passed. A separate offline stdio test rejected malformed arguments for all seven recording commands with bad_request and preserved an existing file. No physical audio devices were opened.
|
||||
|
||||
**Publication consent and registration:** Old Slint callbacks and queued actions cannot start or stop a replacement capture even when the tab and source match. A registered Stop also checks the publication identity when the server stream ID and owner match. A delayed setup reply leaves a publisher in Starting after an early stream ID; a refusal releases its source and unregisters that ID. Eight Windows tests passed, including the beta14 generated-source publisher scenario. This did not exercise the OS picker, physical capture consent, or a real refusal displayed by the chooser workflow; `command:stream_setup` remains open.
|
||||
|
||||
**P2P signaling after an ICE restart:** `native_viewer_signaling_rollback_and_ice_restart` used two native Windows peers with host-only ICE. An early candidate waited for the remote offer, and the viewer sent its answer before local candidates. After rollback and renegotiation the viewer rejected a retired ICE username fragment and decoded a green frame on the new selected pair after decoding red on the original connection. Four focused regressions covered candidate routing and cancellation; 16 core protocol tests passed, including signaling object and byte limits. This verifies `command:stream_signal` with native peers, not official-client interoperability.
|
||||
|
||||
**Watching a closed P2P stream:** `slint_watch_admits_and_presents_generated_av_on_beta14` exercised Watch and Allow on the selected stream tiles. Before admission the viewer applied no offer and decoded no audio. After admission the viewer tile presented generated red pixels and its decoder received at least 30 matching blocks of a 1 kHz tone. A different observer cancelled before admission; using its stale action after disconnect did not start playback on the selected tab. This covers Windows `command:stream_join`, not physical devices or an official client.
|
||||
|
||||
**Channel-wide stream discovery:** On private beta14, `duplex_qa --stream-lifecycle` returned an empty list for a solitary client. After a second client connected, its untargeted request returned only the publisher and a matching P2P announcement. Targeted discovery returned the same stream. The observer's Slint Streams stage showed the registered ID, updated title and Watch action. Separate tests covered partial refusal, stale and overlapping requests, and an SFU announcement displayed without a P2P Watch action. The SFU case used fixture data, not a live SFU transport.
|
||||
|
||||
**Voluntary viewer leave on beta14:** With two viewers receiving generated video, the second left the stream. Its native peer was released, decoder statistics were no longer available and no decoded frame remained. The publisher retained only the first viewer, which received new magenta frames without rejoining. After a fresh join by the second viewer, stopping its old handle again did not interrupt the replacement. Separate tests covered one leave request across a delayed acknowledgement and rejected a stale UI close for the same stream ID. This verifies Windows `command:stream_leave`; physical audio and the official client were not exercised.
|
||||
|
||||
**Removing one of two active viewers:** In `approved_beta14_viewer_receives_generated_video`, the second viewer requested access again after refusal, was admitted, and decoded red and green frames. The publisher used that viewer's named Slint removal action. Only that viewer entered Removed, with no frame left to present. The publication remained live and the first viewer decoded three new blue frames before the publisher stopped it. Two separate publisher regressions verified that a reused client number does not transfer manual or queued removal to a replacement UID. This covers Windows `command:stream_remove` with generated video, not physical capture or an official peer.
|
||||
|
||||
**Stopping an active broadcast:** In the three-client Windows beta14 test, the publisher invoked Stop from the Slint tile for the registered stream while the admitted viewer was receiving video. The source rejected another frame, the publisher had no pending or admitted viewers, and the admitted viewer ended with no frame left to present. The refused viewer stayed declined. Fresh discovery from both viewers did not bring the stream back. This covers `command:stream_stop` for a generated source, not physical capture or an official client.
|
||||
|
||||
**Viewer admission and video on beta14:** In `approved_beta14_viewer_receives_generated_video` three muted native tabs connected to private beta14. From its Slint tile, the publisher admitted the first viewer to a closed publication. That viewer answered and decoded three red frames. The second viewer requested the same stream and received a refusal, sent no answer, and was not admitted. Only after the refusal did the source switch to green; the first viewer decoded three green frames without rejoining. Its departure emptied the publisher's viewer list. This covers Windows `command:stream_respond` with generated 64×48 video on the same host, not physical capture, audio delivery, or an official client.
|
||||
|
||||
**Viewer admission refusal on beta14:** In `duplex_qa --stream-lifecycle` the publisher received the observer's join request for its registered stream. The server acknowledged the negative response with an empty offer; the observer received the decline message for the same stream. A fresh targeted listing still returned the original publication, and its subsequent metadata update and stop were observed. Both disconnects were confirmed. No viewer was admitted and no media was sent in this run.
|
||||
|
||||
**Active publication editor:** On private beta14, `active_publisher_settings_cancel_and_update_on_beta14` opened the Slint editor from a registered publisher tile with a generated source. Cancelling kept the original title. Saving changed the tile title; the observer's fresh discovery returned the same stream ID and owner with the new title, 2700 Kbps and a viewer limit of 4. Editing does not grant or change the audio or video capture source. The separate core lifecycle check exercised audio metadata; this UI run did not change the audio flag or measure media delivery.
|
||||
|
||||
**Stream metadata updates on beta14:** In `duplex_qa --stream-lifecycle`, the observer requested the publisher's stream before the update and again after the server acknowledged it. The same stream ID and owner were returned with a new name, bitrate 2500 instead of 1000, viewer limit 3 instead of unlimited, and audio enabled instead of disabled. Both clients disconnected cleanly. Separate native publisher tests checked the last confirmed options before acknowledgement, admission during privacy changes, server refusal, and a late acknowledgement after disconnect. This measures advertised metadata, not encoded bitrate, actual audio delivery, or the rendered settings dialog.
|
||||
|
||||
**Stream registration on beta14:** Two muted disposable guests ran `duplex_qa --stream-lifecycle`. The publisher received its assigned ID in `notifystreamstarted`. The observer requested the publisher's stream list and received `notifystreaminfo` matching the ID, name and owner. Beta14 rejected an ID-only stop with TS 1542 (missing parameter). With `reason=1` it acknowledged the stop and the observer received `notifystreamstopped` for that exact stream ID. Both disconnects were confirmed. No viewer joined, and no audio or video was transmitted in this scenario.
|
||||
|
||||
**Audio and moving video on two local WebRTC peers:** The focused Windows test `decoded_tone_and_moving_video_on_local_peers` measured the generated 1 kHz tone in 43 of 46 decoded 10 ms audio blocks (22080 samples; normalized RMS 0.06233). A matching block requires more than 80% of its first-channel energy at 1 kHz and a minimum signal level. In the same run libvpx decoded 13 video frames and 12 increasing frame counters reached the display path. The source stop callback ran once. This verifies same-host audio and video transport before physical playback; it does not verify TeamSpeak signaling, an official client or a physical device.
|
||||
|
||||
**Two-colour WebRTC loopback:** The Windows `webrtc_smoke` example sent 14 generated 64×48 frames between two native PeerConnections. The software decoder reported libvpx and 14 decoded frames; the display path presented seven red frames followed by six green frames. The ended source rejected further input, its stop callback ran once, and the closed surface had no pending image. No physical audio device was started. Screenshots: `target/codec-fixtures/peer-loopback-red.png` and `peer-loopback-green.png` in the same directory. This tests local video transport, not audio delivery, TS6 server signaling, an official peer, AV1 or H264 High negotiation.
|
||||
|
||||
**Clock format:** On Windows, switching the Chats setting changed the time shown on an already loaded history row. After restart the saved format was restored; switching back updated the same row, and reopening the profile returned the original millisecond timestamp. Recent Server Events showed the same event in both clock formats in English and Russian, retaining its row ID and raw log. Seven focused tests passed using isolated profiles and fixture events.
|
||||
|
||||
**Server-target send on beta14:** In the extended Windows Slint send test, the two disposable guests exchanged the private and channel messages. Sending from the server conversation returned `PermissionsClientInsufficient`. The sender saw the refusal, with no own echo; revisiting that server conversation restored its unsent draft. No matching message was visible in the recipient's server conversation. This is evidence of server-target refusal, not successful broadcast. The live test and three focused core validation tests passed.
|
||||
|
||||
**Live private and channel text:** Two native tabs with different identities connected to private beta14. The Slint editor sent Unicode text to the exact private recipient and then to the joined temporary channel. In each case the sender saw one echo and its draft cleared after acknowledgement; the other tab displayed the exact text and sender UID in its own conversation. An 8193-byte draft was rejected locally and retained. This did not exercise server-target text, a denied send, or reassignment of a client number during delivery.
|
||||
|
||||
**Protected channel join:** On private beta14 two disposable guests used a temporary password-protected channel. Selecting the row and cancelling the join prompt both left the joiner in the lobby. An incorrect password opened an empty retry field with the localized refusal; the correct password moved the exact client to the protected channel on both rosters and both Slint trees. This covers the Windows `command:join_channel` workflow, not bookmark login or physical audio.
|
||||
|
||||
**Channel subscriptions:** On private beta14, `channel_admin_qa --channel-subscriptions` verified single and all-channel subscribe/unsubscribe through fresh snapshots of the original, non-own lobby after explicitly clearing the connect-time subscribe-all mode. The server expired the generated temporary channel and confirmed disconnect. There was no second non-own channel to verify isolation. Without the explicit initial reset, the lobby showed unsubscribed after leaving it; subscribe was acknowledged but snapshot revision stayed at 4. Do not infer a transition from that acknowledgement. A separate Slint menu test using fixture snapshots checked individual and bulk command arguments and rejected stale menu IDs. Live UI permission refusal and reconnect before acknowledgement remain open.
|
||||
|
||||
**Chat preferences (Windows, isolated control events):** Four native tests passed. For `preference:chatOpenIncoming` an incoming private conversation stayed hidden with auto-open off, appeared as an unread background tab when enabled, and retained both messages. Neither the viewed room's draft nor the input-owning session changed. For `preference:chatIgnoredUsers` the contact's Ignore/Unignore actions controlled chat delivery by exact UID: explicit sender identity took precedence over the roster, while an absent sender UID used the preceding roster. A different UID using the same nickname and number remained visible. For `preference:chatShowModerationEvents` the visible timeline hid existing events when disabled and restored events received both before and during suppression. Only the two ordinary texts appeared in persisted channel history. Server control events were supplied by the fixture; no official peer or network delivery was tested.
|
||||
|
||||
**Connected Whisper settings:** Two native tabs on private beta14 changed the receive policy through the Slint selector and kept their connections. With the same saved F9 receiver list and input owner, the sender transmitted 42 synthetic frames under each policy. Deny All produced no remote talking or new whisper notification; switching back to Allow All restored remote talking and exactly one sender-matched notification. The frames were paced independently of UI rendering. A separate restart check restored the saved Deny All selection. No physical audio devices or OS-wide key registration were involved.
|
||||
|
||||
**Audio PTT checkbox:** The rendered checkbox, key binding and dependent controls followed the saved mode across two restarts. A failed save left the old mode intact. On private beta14 with VAD disabled, turning PTT off after key release resumed an already authorized synthetic input without another key press. Turning PTT back on stopped transmission and cleared the remote talking indicator; the next hold transmitted again. No physical device or global shortcut was used.
|
||||
|
||||
**Whisper through reconnect (Windows, beta14):** In `duplex_qa --whisper`, the receiver identified a 1450 Hz whisper from the live sender before that sender disconnected without stopping its whisper. After the sender reconnected, frames carrying the old tag triggered neither local transmission nor playback or a whisper notification. The receiver then decoded 42 ordinary 1750 Hz frames without a whisper notification. All three disconnects were acknowledged. This covers two diagnostic cores on loopback, not a physical shortcut, an official peer, or reassignment of the recipient's number.
|
||||
|
||||
**Sidebar preferences:** The Windows offline workflow `bookmark_sidebar_and_local_contact_reopen_without_network` covers `preference:savedServers` and `preference:bookmarkOrder`. It reopens the saved identity, nickname, channel and startup flags, checks the mixed folder/bookmark order after restart and preserves both disk and memory on a failed save. Duplicate and incomplete order writes are rejected. This does not verify bookmarked network login or a system password store.
|
||||
|
||||
**Moving bookmark folders:** The same Windows sidebar workflow moved the populated Outer folder under Archive through its Move form. After restarting the runtime and cancelling Archive deletion, it navigated the moved hierarchy and found the original folder and deep bookmark IDs. Confirmed removal deleted the subtree but retained Outside. This adds the folder-move case for `preference:bookmarkFolders`; the workflow uses shell actions, not physical pointer input.
|
||||
|
||||
**Client information readback:** On private TS6 beta14, `channel_admin_qa --client-info` returned version and platform for the exact roster client and rejected a mismatched UID locally. In `participant_info_menu_rejects_a_previous_session_target`, the Slint participant menu displayed version and platform for the first identity, cleared the details on disconnect, rejected the previous target after reconnect with a visible `target_changed` error, and opened fresh details for the second identity. A core regression separately covered disappearance or reuse of a client number before acknowledgement. The live menu test did not force a disconnect while a reply was in flight.
|
||||
|
||||
**Database identity readback on beta14:** With guest database search permission, `channel_admin_qa --client-database-id` returned the same positive database ID, UID and nickname from UID lookup and nickname search. Disconnect, core shutdown and profile cleanup succeeded. This was a read-only CLI check. In the original unprivileged run the UID lookup succeeded but the nickname search was refused with TS 2568.
|
||||
|
||||
**Directory search:** The Slint file browser filters the current listing without issuing a database search or a new file-list request. The test `directory_filter_keeps_file_targets_and_resets_on_navigation` matched a mixed-case Cyrillic name, kept the parent entry, included a new match after refresh and verified the selected file's original channel, path and session. Opening another directory cleared the filter. Three focused Windows tests passed; this did not exercise a network file transfer.
|
||||
|
||||
**Client database search and pagination:** Initial, searched and paginated results use the same server-context projection. Windows test `database_pages_and_search_results_keep_permission_and_target` checked the captured session and database ID, retained search/offset and enabled/disabled delete action for explicit allow/deny hints. Three projection and validation tests passed. No live database enumeration or deletion was attempted in this run.
|
||||
|
||||
**Connected nickname change:** On private TS6 beta14, `nickname_refusal_keeps_draft_and_retry_updates_only_own_identity` opened the tab's rename form with the current nickname, rejected a two-character draft locally and kept a refused duplicate nickname editable. On retry, both clients saw the trimmed new name with the original server-reported UID and client ID. Reopening the temporary profile confirmed that only the initiating local identity's nickname changed. The test binds server UIDs to the acknowledged client IDs rather than assuming a server-reported UID equals a local profile UID.
|
||||
|
||||
**Channel member disclosure:** The tree stores collapsed channel IDs under the server address in `collapsedChannels`. Collapsing hides direct members only: child channels and their members remain visible. A Windows Slint test exercised disclosure, two restarts, a different address reusing channel 7, and re-expansion on the original address in EN/dark and RU/light. The preference test checked pruning, isolation, rejection of malformed entries and preservation of disk and memory after a failed save. Three focused tests passed with fixture rosters; no network channel move or subscription was involved.
|
||||
|
||||
**Participant order in the desktop tree:** The Slint appearance test measured a participant and a nested channel under the same parent. Changing tree density kept their order. Turning off Show clients before channels then placed the subchannel above the participant without changing either row height or the selected channel. The order persisted after restart in EN/dark and RU/light. This exercised the rendered tree with a fixture roster, not a server-side move.
|
||||
|
||||
**Desktop tree style:** The Appearance selector now changes the rendered client rows. Compact uses 28 px rows, 22 px icons and 15 px nicknames; Detailed uses 40 px rows, 33 px icons and 14 px nicknames, following the [TS6 tree specification](docs/evidence/official-parity/ts6spec-tree.md). The Windows Slint test `tree_style_resizes_only_client_rows_and_survives_restart` measured the visible client and channel hit areas before the change, after the change on the same session, and after restart. The channel stayed 44 px high and channel 7 remained selected. Covered EN/dark and RU/light with fixture rosters, not full screenshot or live-audio parity.
|
||||
|
||||
**Global shortcuts and OS settings:** The [installed settings review](docs/evidence/official-parity/ts6spec-settings.md) records TS6's Windows-specific OS page and shortcut registration feedback. TeamsPeach lists the OS page on other platforms too, with capability-specific availability. Global shortcuts use Windows, X11/portal or macOS Carbon backends; saving a binding is not proof of physical registration. Native taskbar status now uses the same hide-mode interpretation as the tray action. Windows test `taskbar_capability_tracks_the_selected_hide_mode` selected minimize, close, both and never: the capability flag followed all four settings. The lock-mute description now matches the handler: unlocking does not unmute the microphone. This test did not hide a window in the tray, lock the workstation or exercise physical shortcuts.
|
||||
|
||||
**Appearance and local privacy reference:** The [installed settings review](docs/evidence/official-parity/ts6spec-settings.md) describes theme, sizing, tree and chat styles, trusted sites and restoration of suppressed confirmations. Native display size, chat compactness, clients-before-channels and contact highlighting have rendering consumers. Tree style, sidebar icon mode, badge/flag/banner/background visibility and the commander lamp have stored controls but no corresponding tree rendering consumer was found in this inspection. Chat links pass through native URL classification and consent; remembered hosts are guarded by the flagged-site preference. The optional phishing-list refresh fetches the list, not the user's visited URLs. Reset Confirmations restores four preferences, but the inspected operation paths do not consult them; for example, clearing transfer history always prompts. These are static comparisons, not proof of native visual parity, OS effects or confirmation suppression.
|
||||
|
||||
**Chat formatting and unread badges:** The [TS6 chat specification](docs/evidence/official-parity/ts6spec-chat.md) describes line-based formatting, BBCode and toolbar controls. TeamsPeach parses bounded typed nodes in `native/src/services/chat/parse.rs`, falls back to literal text on complexity overflow, and renders styled Slint runs, not HTML. Inactive conversations and messages arriving while older history is open contribute to unread counts. Returning to the latest messages clears the relevant conversation. The installed-client matrix identifies `setBadgeText`; native Windows uses a taskbar overlay, macOS a Dock label, and Linux a launcher signal on supported desktops. This comparison does not verify identical rendered text or a visible badge on those platforms.
|
||||
|
||||
**Notifications reference (2026-11-27):** The [installed settings review](docs/evidence/official-parity/ts6spec-settings.md) identifies a separate output selector and fader, group enablement, Listen and advanced per-event overrides. The official English locale names talking while muted (`settings.notifications.warnings.talking_while_muted`). TeamsPeach has the setting, sound and recent-event mapping, but its runtime has no muted-speech detector feeding that event. In particular, a rejected muted audio frame does not establish speech. Windows Listen/policy coverage is recorded below; the warning's source, setting and group acceptance remain open. Microphone capture policy has not been changed for this comparison.
|
||||
|
||||
**Recording mode preference (Windows, TS6 beta14):** The Audio settings selector saved Master. An invalid mode (4) returned `bad_request` and left Master selected. The same temporary profile was reopened twice; on the third launch the recording form offered Master by default. Choosing Multitrack and cancelling created no output. Reopening and submitting without changing the mode produced a finalized mode-2 manifest and a master WAV whose size matched the recorded timeline. Verified by `recording_panel_exports_a_paused_and_resumed_master` with a preapproved destination; the OS directory picker was not exercised.
|
||||
|
||||
**Local recording (Windows, TS6 beta14):** The installed English locale (`server.recording.*`, lines 2979–3005) names Master, Multitrack and Both, pause/resume, output folder, tracks and disk-overrun warnings. In `recording_panel_exports_a_paused_and_resumed_master` a real Winit/Slint window on loopback opened the recording form, selected Master, displayed track waveform data, paused, resumed, stopped and published the take through the Windows document adapter. The exported manifest contained mode 2, one pause and a positive frame count; the WAV length was exactly 44 + 2 bytes per frame (44-byte header plus 16-bit mono PCM). The take directory matched the start timestamp. This used a temporary profile and a preapproved temporary folder, not the OS picker or a physical microphone. Multitrack content, overflow, failed finalization and overwrite cancellation have separate checks.
|
||||
|
||||
**Stream volume control (Windows):** Moving the Slint slider previews gain on the selected viewer; releasing it or submitting the volume form saves a whole percentage for future viewers. A midpoint click dispatched approximately 0.5 gain. A disposable profile reopened at 0%, 43% and 100% after saving gains of 0, 0.426 and 1. Four focused UI, profile, viewer and PCM mixer tests passed. These checks used an isolated mixer, not live WebRTC or a physical output device.
|
||||
|
||||
**SFU stream offers (2026-11-27):** A mode-2 announcement now produces a stream tile with the localized SFU limitation and no P2P Watch action. A later metadata update can change one tile without disabling P2P streams from the same publisher. The media hub checks the latest announcement before registering a viewer or issuing a join. Windows tests `server_routed_stream_tile_has_no_p2p_watch_action` and `announced_sfu_mode_never_starts_a_p2p_join` passed with headless Slint and a recording signalling fixture. This verifies the inventory's explicit unsupported behavior, not mode-2 negotiation or media delivery.
|
||||
|
||||
**Channel description (Windows beta14, 2026-11-27):** The guest was refused creation with a description, then created a plain temporary channel. In the Slint editor it saved two lines, read them back via both the editor and `channel_description`, retained an oversized draft with an error, and cancelled an edit without changing the server value. Clearing the description returned an explicit empty string on a fresh read. The live test uses the same five-second request spacing as `channel_admin_qa`; an earlier unpaced edit hit `ClientIsFlooding`. Four core tests separately cover invalidation, including a pending read and an unrelated channel. Positive create-with-description is still unverified.
|
||||
|
||||
**Matrix reference (2026-11-27):** The [official chat review](docs/evidence/official-parity/ts6spec-chat.md) distinguishes the account-gated central/homebase path from decentralized server rooms using server identity and `MATRIXCHAT`. Central Matrix is outside the account-free contract. Rust detects server advertisement and displays a limitation in the ordinary server conversation; it does not perform discovery, Matrix login, invitation handling or sync. A classic server-target text send is not a Matrix room send. Neither the source review nor a Matrix-negative server proves positive Matrix interoperability.
|
||||
|
||||
**Stream reference (2026-11-27):** The [official client notes](docs/evidence/ts6-official-client.md) distinguish P2P offer/answer, ICE and realignment from mode-2 SFU access and mediasoup negotiation. Native P2P has session-bound discovery, per-viewer peers, capture consent and preview, renegotiation, decoder checks and bounded frame delivery. Fullscreen and pop-out reuse the existing stream. Compared to the [official settings](docs/evidence/official-parity/ts6spec-settings.md), the native stage has a vertical tile list, no source-resolution preset and one selected application-audio source rather than All/Exclude scopes. Native status is not a full RTC throughput panel. Server publication explicitly rejects SFU; on the receive side the inspected Watch action and hub did not check an advertised mode 2 before a P2P join. No successful SFU endpoint or live official-peer negotiation is claimed.
|
||||
|
||||
**File transport comparison (2026-11-27):** The [official storage evidence](docs/evidence/ts6-filetransfer-native.json) distinguishes legacy file verbs, HTTPFT and S3. TeamsPeach implements legacy TCP transfers and mutations. For ordinary S3 channels the active core requests channel-wide listings and signed GET/PUT URLs, correlates notifications and acknowledgements, and awaits upload completion; it does not fall back to legacy on unsupported mutations. HTTPFT-only storage remains unsupported. The historical matrix's combined blocked status is not the current S3 implementation status. The recorded empty S3 listing is not proof of populated listings, successful TeamSpeak-signed transfers or overwrite behavior; see the [bridge contract](docs/bridge.md).
|
||||
|
||||
**Device recovery UI (2026-11-27, supersedes the display gap in the reference comparison below):** After the first device enumeration, Audio and Notifications settings identify an absent or unconfigurable saved route and suggest reconnecting the device or selecting another. Before enumeration no absence is claimed. When the saved endpoint returns, the warning clears and its name reappears without a route-selection request. Windows headless Slint exercised capture, playback and notification choices (`saved_audio_device_recovers_without_switching_routes`); two focused tests passed. Physical device removal and recovery of an active stream were not exercised.
|
||||
|
||||
**TS3 file links (2026-11-27):** The installed TS6 English locale (lines 160–164) names download progress, disconnected/error states and Open File. TeamsPeach creates server- and channel-scoped links in its file browser and enables a file card's download action only in a conversation on the matching server UID. An IPv6 literal in brackets previously prevented detection of the copied URL. Windows test `copied_ipv6_file_link_reopens_the_same_chat_attachment` checks the browser encoder through chat attachment extraction, both bare and inside BBCode, including a nondefault port, encoded UID, spaces, plus sign, ampersand and brackets in the path/name. Three focused tests passed. No server transfer, OS file opening or visual card-state parity was exercised.
|
||||
|
||||
**Voice DSP, devices and 3D reference (2026-11-27):** The installed TS6 locale (`en.json` lines 5–12, 1689–1701), [Audio settings specification](docs/evidence/official-parity/ts6spec-settings.md) and [observed profile fields](docs/evidence/voice-official-source-20261029.json) identify per-device DSP, test capture/playback and independent notification routing. Native Audio settings apply capture AEC3/NS/AGC2, per-speaker playback AGC, ducking and comfort noise. Native typing attenuation uses local text-input events; the inspected native profiles have no TS6 `AgcExperimentalMode` equivalent. Explicit missing CPAL device IDs fail instead of silently selecting another endpoint; the native status does not reproduce the TS6 device-recovery prompt. No acoustic equivalence or physical hot-plug result follows from source inspection. The [historical 3D finding](docs/evidence/official-parity/final-feature-matrix.json) records a no-op Sound3D category without a corresponding settings surface; the native inventory preserves this exclusion, not a successful spatial-audio operation.
|
||||
|
||||
**Whisper reference (2026-11-27):** Installed TS6 `locales/en.json` lines 1849–1864 and 2047–2108 name block/reply/list hotkeys, client/channel and group targets, preview, history, Allow All and Deny All. TeamsPeach constructs `C2SWhisper` or `C2SWhisperNew` packets (`core/src/whisper.rs`); held routes and frames are bound to the current generation and epoch, with no ordinary-channel fallback. Preview is presentation only. Receive policy is configured before connecting and on ready cores: Deny All discards incoming whisper packets before decode and clears queued whisper audio (`core/src/audio.rs`). The official JS hooks `SetWhisperReceiveMode` and `HandleIgnoredWhisperEvent` do not establish a server-side refusal. TS6 declares block-hotkey labels without a demonstrated dispatch path; TeamsPeach offers reply, quick and list hotkeys and Deny All in settings, not a block shortcut. Static comparison, not a live recipient or reconnect test.
|
||||
|
||||
**Windows channel form on beta14 (2026-11-27):** `smoke::tabs::channel_create_from_toolbar_and_edit_on_beta14` used the actual Slint toolbar callback and editor on a headless desktop backend, an isolated identity and a live loopback server. For `admin-property:channel_create.channel_name` and `channel_create.channel_topic`, a 41-character name and 256-character topic remained in the draft with inline errors; cancellation discarded a valid draft, and a new form created the temporary root channel with the same name. Its row appeared in the tree and its topic was read back in Edit Channel. For `admin-property:channel_edit.channel_topic`, the editor retained the oversized draft with an error, cancellation preserved the old topic on reopen, and submission displayed the acknowledged new topic on reopen. Untouched optional overrides previously caused a guest permission refusal; codec and encryption now offer Server default. Five additional non-network editor/property tests passed. No physical display comparison, in-flight reconnect, nested-channel placement or privileged position change is claimed.
|
||||
|
||||
**Legacy chat send and local history reference (2026-11-27):** The [TS6 chat specification](docs/evidence/official-parity/ts6spec-chat.md) identifies private, channel and server targets and the native local-history methods. [Channel transport evidence](docs/evidence/official-parity/channel-text-target-evidence.json) distinguishes the channel ID in the client API from the classic wire command: mode 2 has no channel target. TeamsPeach checks the sender's current channel for mode 2 and the recipient UID for private messages before sending (`core/src/session.rs`); it does not promise delivery to another channel. Observed text events populate a profile-owned, paged history keyed by own identity, server UID and conversation (`native/src/services/chat_history.rs`). The installed locale's chat-history setting describes sidebar grouping and notification placement, not whether to persist messages. TS6 file-format compatibility, Matrix transport and end-to-end delivery are not established by this source comparison.
|
||||
|
||||
**TS6 server administration reference (2026-11-27):** Installed `client_ui/locales/en.json` lines 1181–1235, 1253–1427 and 1447–1545 identify ban and client database lists, categorized server settings, log filtering, privilege keys, temporary passwords and snapshots. In TeamsPeach, `native/src/app/server_actions/projection.rs` exposes list, create and delete actions for bans, keys and passwords, raw log lines and database search/pagination. Differences: no ban edit or clear-all control (the core has `bandelall`), no copy control in those key/password lists, no password validity dates there, and no event-type or identity filter for server logs. Server Edit reads current properties and submits typed changes; its general/advanced form does not reproduce the official categories. Native snapshots support UID-bound import, conflict selection, cancellation and partial results, not the official per-element preview or revert control (see [snapshot comparison](docs/evidence/official-parity/ts6spec-snapshots.md)). This is a comparison of advertised controls and native source, not live administration acceptance.
|
||||
|
||||
**Channel creation reply (2026-11-27, `e6a8d2f`):** On an isolated TS6 beta14 server, `channel_admin_qa` received the new temporary root channel ID, read back its topic and codec quality, changed the topic without changing the name or quality, and read back both client and family limit edits. Invalid quality and stale generation were refused without changing properties. The guest could not place the channel under a parent (TS 2568); family inheritance and explicit sibling positioning remain unverified. Leaving the channel caused it to expire; disconnect, core exit and disposable-profile cleanup succeeded. This exercised core IPC, not the owning Slint dialog.
|
||||
|
||||
**Create Channel position:** The Windows Slint form dropped a previously selected root predecessor when the destination changed to channel 8. The resulting create commands distinguished no channel_order property, an explicit first position (0), and the second of two identically named siblings (13). Six focused create/move editor tests passed. No server mutation was attempted in this test.
|
||||
|
||||
**Channel CRUD reference comparison:** In the installed TS6 UI bundle (SHA-256 `352683c3eb1d674c6b0fe098ec8ba132b696739a33424080c9266b751de41537`), byte offsets 2199453, 1938146, 1936309, 1939071 and 1938521 identify create, property edit, move, delete and description calls respectively. The move wrapper compares parent and predecessor before calling native code; delete passes whether the channel contains clients or children. TeamsPeach uses explicit force and name confirmation on delete. The UI exposes a subscription permission hint; the underlying official subscription call was not established by this inspection. The native core supports subscribe/unsubscribe. The comparison does not establish a live move or delete on a server.
|
||||
|
||||
**Move Channel dialog:** A Windows Slint test opened the form at its current parent and predecessor, changed the parent, and selected the second of two identically named siblings. The resulting typed command targeted channel 42 with parent 8 and predecessor 13; the drag source and its subtree were not offered as destinations. Six focused editor tests passed. No channel move was sent to a server in this run.
|
||||
|
||||
**Channel order readback:** The core regression verified that channel properties retain their wire format while reporting the current parent and preceding sibling. The live check, `channel_admin_qa --channel-order`, requires a private beta14 fixture that permits creating a temporary channel at a specified position. The guest received TS 2568 on creation. Disconnect, core shutdown and profile cleanup succeeded, but neither relinking nor restoration was observed on the server.
|
||||
|
||||
**Legacy channel codecs:** The Windows Slint tab test observed the localized warning for Speex Narrowband, Wideband, Ultra-Wideband and CELT Mono in the visible interface. Selecting an adjacent Opus channel without joining it kept the warning. Viewing an Opus tab or joining an Opus channel cleared it. A separate core test checked that none of the four legacy codecs selects an encoder or produces decoded playback. On private beta14, WebQuery rejected channel creation for each legacy codec (0, 1, 2, 3) with TS 1538, while the same request for Opus Voice (4) succeeded and channelinfo confirmed the codec. The UI used fixture snapshots; a live legacy-channel join and outgoing packet count remain unverified.
|
||||
|
||||
**Voice transmission modes:** The installed TS6 settings distinguish continuous transmission, PTT, voice activation and PTT combined with voice activation. Its detector choices are Automatic, Volume Gate and Hybrid. Five Windows core tests exercised speech onset, level hysteresis and hangover, changes of detector, invalidation of buffered PCM and hybrid rejection of a loud non-speech tone. The native PTT configuration test separately verified that selecting PTT preserves the input device's VAD policy. This is a behavioral comparison, not a claim that TS6's internal detector thresholds match or that an official peer received the audio.
|
||||
|
||||
**PTT release delay (Windows beta14):** On repeated F8 holds with a continuous synthetic capture device, the sender stopped transmitting 127 ms after key-up at 100 ms, 523 ms at 500 ms, and 15 ms with delay off. The receiver's talking state ended after 158, 554 and 46 ms respectively. Focus loss during a 500 ms tail stopped the sender 15 ms after focus loss. These are observations from one loopback run, not audible speaker latency. Separate Slint and profile tests verified preset persistence across restart, rejection of 250 ms and cancellation on profile change.
|
||||
|
||||
**Talk request draft:** The isolated Windows Slint test rejected a 51-character message before emitting any action. With a valid 50-character draft, replacing the tab's session key made Submit show the changed-session notice without dispatching a request. Cancel retained the original target. The separate live reconnect run did not pass: beta14 returned ClientIsFlooding. This result covers the native editor, not a request in flight on the network.
|
||||
|
||||
**Withdrawn talk request:** On the private beta14 fixture, a moderator used a previously captured Grant action after both rosters had received the withdrawal. The native workflow reported target_changed with the pending-request error, and both rosters still showed no request and no talk power. A withdrawal racing with an already sent grant was not tested.
|
||||
|
||||
**Talk moderation on beta14:** Two muted Windows sessions joined a temporary channel with required talk power 50. Both rosters reported a positive timestamp for a request submitted without a message, then its withdrawal. A second request carried the entered text into the moderator's queue. Grant and revoke from that entry changed the requester's is_talker flag in both rosters. This exercised the native form and queue actions, not a physical hotkey, permission denial or reconnect during grant.
|
||||
|
||||
**Away with Message:** Two muted native sessions joined the same private loopback TS6 beta14 using different disposable identities. After cancelling the Slint form both rosters showed both clients online. After confirming a single message, both rosters reported both clients away with that message. The test injected a semantic shortcut event; it did not exercise OS chord registration or a physical keypress. No audio device was used.
|
||||
|
||||
With the next prompt open on the second tab, the first tab disconnected and reconnected. After confirmation, both live rosters showed the replacement online and the original second session away with the new message. The runtime reported the stale recipient rather than reporting complete success.
|
||||
|
||||
**Talk request queue:** The installed TS6 UI lists positive request timestamps in the local channel in descending order (bundle byte 4201898). The Windows native regression checked display order separately from the Grant Next shortcut: a withdrawn request disappears, an already granted peer or the local client is not chosen by the shortcut, and an unknown local channel yields no target. This verifies snapshot selection, not a live permission grant or a physical shortcut.
|
||||
|
||||
**Peer fader Alt-click:** The Windows software-rendered slider test pressed Alt before mouse-down and released Alt while dragging. The draft stayed at -12.5 dB until mouse-up, then returned to 0 dB with mute still enabled. No command was submitted by this gesture. The separate Reset action also cleared mute. This test did not use a live server or a physical output.
|
||||
|
||||
**Peer volume slider:** The Windows software-rendered Slint dialog accepted a pointer drag on the speaker slider without submitting an action. Cancel and reopen restored -12.5 dB. Reset submitted 0 dB and unmuted only after confirmation. The test checked all 421 half-decibel values against the inverse taper and the six official travel anchors. Three targeted dialog tests passed. This covered neither an installed live-peer context menu nor physical audio output.
|
||||
|
||||
**Local speaker volume:** The installed TS6 UI calls setClientVolumeModifier with server handler, client ID, dB and persistence flag (byte 1969424); its fader rounds to half-decibels over -200 to +10 dB (byte 3067840). The native store ignores an undecodable UID without losing other preferences or rewriting the profile on load. Five store tests and two core tests passed on Windows, including reused numeric IDs and decoded two-speaker mixing. This run did not exercise the desktop fader or physical audio output.
|
||||
|
||||
**Multiple connections and microphone ownership:** In the installed TS6 bundle, FindAudioInputServerConnectionHandler (byte 2517988) looks for an established handler with input hardware; automatic activation defaults off and restoration to the previous target defaults on. Three Windows native tests exercised acknowledged handoff, conditional restoration, and rejection of a late session reply. Returning to the already-active tab retained its permit and accepted the next PCM frame. These tests used embedded cores and simulated connected states, not live servers or a physical microphone.
|
||||
|
||||
**Server capability comparison:** The installed TS6 UI uses case-sensitive substring checks on capabilityExtensions (hasFeature, MATRIXCHAT at byte 2232606). The Windows core matched the snapshot and file backend across multi-row announcements, partial edits, explicit clearing and a fresh initserver without extensions. An S3 marker beyond the diagnostic display limit still selected S3. Six targeted core tests passed. No live server capture, transfer or two-tab microphone test was made in this check.
|
||||
|
||||
**Log directory (Windows):** Installation Details showed a missing-directory notice and no Open logs action on a fresh profile. With an empty logs directory in that same disposable profile, the action opened exactly that directory in Explorer. The isolated About regression also rejected a direct OpenLogs operation with os_actions_disabled while the directory existed and kept Diagnostics open. No log contents were inspected and no mobile export was tested.
|
||||
|
||||
**Theme folders (Windows):** From the native Appearance picker, Explorer confirmed the package-specific button opened the disposable profile's `extensions/org.fixture.folder` and the general button opened `extensions`. The isolated Slint regression invoked both actions and received `os_actions_disabled` before continuing through selection and restart. No mobile picker/share claim.
|
||||
|
||||
**Channel visibility transitions (2026-11-27):** Windows passed seven core event/snapshot tests, including a batched enter with a shared destination, a per-client override and a subsequent move with an explicit origin for an uncached client. Five native notification adapter tests passed: supervised moves into and out of the current channel and a kick into it selected the movement log and corresponding WAV file; subscription changes emitted no notification. These were packet and control fixtures, not a live server test, individual Listen preview, or physical playback.
|
||||
|
||||
**Reference comparison (2026-11-27):** The installed TS6 client UI bundle has SHA-256 `352683c3eb1d674c6b0fe098ec8ba132b696739a33424080c9266b751de41537`. Byte offsets here refer to that bundle, not the older matrix hash. At 4721953, Identity Details walks the bookmark tree and includes unassigned entries for the default identity. The Windows Slint reattachment test verified that a nested unassigned bookmark follows a change of default without acquiring an explicit UID. At 3920374 the official refusal dialog chooses the attempted identity before falling back to the default; at 3920620 it reconnects when the required quality is reached. The latter is **not verified** in TeamsPeach. At 2806802 the official theme step stores the selected theme; the offline username strings describe a local, unsynchronized name. The native account-free flow was verified separately below; this is not evidence of identical screen layout or a live official-client run.
|
||||
|
||||
**Identity security challenge:** A Windows client connected to an isolated TS6 beta14 server configured to require level 31. The server refused the nondefault level-9 identity. Windows UI Automation opened the resulting review button and observed the correct identity and target 31; both public identity records and the default were unchanged afterward. The native regression separately checked that restarting the tab invalidates the review action. This run did not attempt improvement to level 31 or a subsequent successful connection.
|
||||
|
||||
**Offline onboarding:** Both a fresh directory and an initialized empty profile persisted the light theme chosen in the Windows Slint form. A failed preferences write created no identity; retry succeeded, and restarting restored one UID and the selected appearance. This was exercised without network or physical audio.
|
||||
|
||||
**Identity list updates:** Windows Slint retained a nondefault UID and its related bookmark when replacing the window attachment, even with identical display names. Editing the nickname in the new window changed only that UID; switching to the default did not expose the other identity's bookmark. Two attachment tests passed. Creation, default selection, additive INI import and confirmed deletion were exercised in the separate identity workflows below.
|
||||
|
||||
**Identity improvement progress:** The Windows Slint regression for `preload:onIdentityProgress` ran two searches on the same disposable identity. A late cancellation for the first job did not stop the second or replace its displayed target and quality; the active Cancel stopped the correct job and its final search offset matched the persisted checkpoint.
|
||||
|
||||
**Identity export cancellation:** Windows UI Automation cancelled the private-key warning and confirmed no Save dialog opened. After accepting the warning, cancelling the native Save dialog left an existing backup unchanged and did not create a new INI. Together with the verified export/import UID round trip, this covers the Windows `preload:exportIdentity` contract.
|
||||
|
||||
**Identity import feedback:** The Windows picker accepted a generated TeamSpeak-format INI and reported one added UID. Importing it again reported one existing UID, and malformed input produced a visible error without changing the recipient's public vault or default. The core also accepted duplicates at full capacity and rejected an overflowing batch without partial writes.
|
||||
|
||||
**Identity backups (Windows):** A generated identity was exported from its selector context menu after the private-key warning and imported through the system file chooser into a second disposable profile. After restart, the public UID matched and the recipient's original default was unchanged. Five focused document/export tests passed, including preservation of the old backup after a partial write. These results do not establish mobile provider or power-loss guarantees.
|
||||
|
||||
**Theme ZIP import:** Windows opened the system file chooser from the native theme picker and installed the selected local archive. Reload retained the selected variant and its stylesheet hash; unsupported selectors produced a visible diagnostic. A second ZIP referencing an external stylesheet was refused before publication. Two focused tests also passed for external/escaping resources and archive confinement. This verifies the native supported subset, not arbitrary TS6 browser CSS or the mobile picker.
|
||||
|
||||
**Theme picker:** Windows UI Automation verified `preload:listThemes` after Reload: the package name and two variant names appeared together, and scrolling showed the diagnostic for a second invalid package. In an isolated native run, Preview applied the variant color, family and size while the stored selection remained null. ZIP installation is a separate contract.
|
||||
|
||||
**Theme links:** Windows UI Automation verified `preload:openThemeLink` against four local manifest entries (homepage, documentation, repository, email). Each action displayed its own destination, including trusted hosts and mail links, before cancellation. A second fixture without the optional web URLs did not expose their actions.
|
||||
|
||||
**Settings link verdict:** for `preload:privacyLinkThreat`, the same extension repository URL was opened up to the confirmation step in two disposable Windows profiles. A matching cached domain produced the malicious-site warning; no list produced the ordinary external-link warning. Both displayed the exact URL and were cancelled. Eight privacy service tests passed, including invalid-host rejection and cancellation without an open capability.
|
||||
|
||||
**Local phishing list:** `preload:privacyThreatStatus` was checked in the Windows trusted-sites view with no list and with an old cache from the expected source. The eight native privacy service tests also exercised fresh, failed-refresh and disabled states. The status says whether list data is available, not that an unlisted URL is safe.
|
||||
|
||||
**Theme selection:** Windows passed `selected_variant_survives_restart_and_restores_stock_on_removal` for `preload:selectTheme`. A locally installed variant kept its rendered background, font family and size across runtime restart. With the package withdrawn, Reload removed the saved selection, named the missing variant and restored stock colors and typography without changing its stylesheet.
|
||||
|
||||
The current visual reference is **TeamSpeak 6.0.0.5232**. The four reference manifests agree on the
|
||||
served `main.js` and `main.css` SHA-256 fingerprints in the [visual source map and capture recipe](docs/evidence/official-parity/visual-source-map.md).
|
||||
The 6.0.0.5163 extractions and earlier Electron results below are historical. The 5232 captures render
|
||||
the official frontend and native Slint against a shared synthetic fixture, not a signed-in account,
|
||||
user profile, or live connected session.
|
||||
|
||||
Scope is local and server functionality without a myTeamSpeak account: identity/bookmarks, server
|
||||
tree and voice controls, channel/private chat, settings and permission-gated server tools and files.
|
||||
Independent TeamsPeach branding, omitted myTeamSpeak/homebase account services and Remote Apps,
|
||||
and native window captions are deliberate differences, not waivers for other layout mismatches.
|
||||
Server-hosted Matrix chat and SFU streams are **not** account-only exclusions.
|
||||
|
||||
- **Visual:** `target/evidence/official-5232-pc/official/` contains five scenes in each of four
|
||||
theme/locale combinations at 1280×800. Native runs `native-5232-pc-02` and `native-5232-pc-03`
|
||||
each rendered 20/20. `compare-5232-pc-02/parity-report.json` and `compare-5232-pc-03/parity-report.json`
|
||||
each record **0 passed, 20 failed, 0 blocked**. The strict whole-frame comparison is unmasked;
|
||||
declared differences explain residuals but do not change the verdict.
|
||||
- **Offline function:** `target/evidence/pc5232-functional-04/result.json` records 8 passed checks
|
||||
and 28 captures: 12 settings categories, EN/RU and dark/light at widths 390/800/1280, rich chat,
|
||||
PTT text-focus, capture denial, draft retention, two profile restarts and stale-session rejection.
|
||||
No network, OS actions, physical capture or local peer transport was enabled. Separate focused
|
||||
Windows gates recorded 109 native audio/tree tests, five DSP regression filters, three
|
||||
`tsproto-packets` grammar tests and 44 core file/raw/session tests. These are scoped results,
|
||||
not promoted entries in `native/compatibility.json`.
|
||||
- **Server Matrix chat:** `current-contract:matrix-not-account` and the unsupported-state contract for `feature:chat.server_matrix` were exercised on Windows. `server_matrix_notice_tracks_advertisement_without_disabling_plain_chat` opens server chat in an isolated native window, flips the session's advertised chat capability and observes the notice appear and disappear while plain text input stays enabled without an account dialog. No Matrix room, login or transport was implemented or contacted.
|
||||
- **Profile import:** `current-contract:profile-import` passed on Windows with generated profiles. Eight service tests cover external-key vault/default/hashcash preservation, corrupt or changing input, destination collision, password markers and explicit per-role device mapping. `cancelling_imported_bookmark_password_keeps_session_offline_after_restart` cancelled the actual Slint prompt on three launches, preserved the source hashes, history, bookmark order and password marker, and observed no active connection or audio start.
|
||||
- **Bookmark sidebar and startup:** `schema-field:bookmarkOrder` and `current-contract:bookmarks-sidebar` passed the native `bookmark_sidebar_and_local_contact_reopen_without_network` workflow. For `preload:getStartupBookmarks`, Windows UI Automation observed the two password prompts in depth-first sidebar order in the running desktop executable even though their storage order was reversed. Both were cancelled before connecting.
|
||||
- **Deliberate settings differences, TS6 5232:** the installed `main.js` matching the hash in the visual source map references the Account page (byte 1130212), Remote Apps page (1132687), analytics modes (4773285) and `skipUIPermissionChecks` (1104295). Windows UI Automation showed the twelve TeamsPeach categories, without Account, Remote Apps or Developer Options. Pointer activation of Privacy → More Information showed the read-only diagnostics explanation and no selectable analytics mode. This compares the user-visible settings; it is not a network telemetry audit.
|
||||
- **Notifications and file settings:** Windows passed both core `disconnect_tests` (explicit
|
||||
disconnect vs. reconnect and terminal phase classification), 49 selected native library tests,
|
||||
and all four `notification_preferences` integration tests. The legacy `group_status` cue and its
|
||||
stored values are preserved; the Status category has an independent switch.
|
||||
`target/evidence/pc5232-notification-03/result.json` passed with 32 captures. Global Private Chat,
|
||||
Global Group Chat, Incoming call and Outgoing call were captured separately and stayed disabled
|
||||
on pointer and accessibility activation attempts. Persisted preferences and the existing
|
||||
disconnected tab were unchanged; there were zero active sessions and no physical audio.
|
||||
- **Sound coverage:** On 2026-11-27 the Windows Slint settings surface exposed six formerly missing advanced controls: moderator move in/out, kick in, server group assigned/revoked and permission error. Fifteen targeted Windows tests passed across the native library and notification preference integration tests. The PCM fixture exercises event and Listen output, repeats, the disabled sink and the silent fader for all 58 sounds; preference regressions cover legacy overrides, independent choices, hide/show and reopen. This brings 57 of 58 source cases through both individual Listen and sound policy with a supported trigger. Talking while muted has Listen and policy
|
||||
coverage against a fixture, but no genuine speech trigger. The native local Recent Server Events
|
||||
service and view projection were exercised with test inputs: 501 events with sound disabled,
|
||||
500 retained and the newest 200 projected. Switching and closing tabs showed no cross-session
|
||||
leakage; the local view is separate from the remote Server Log action.
|
||||
- **Files scope:** focused tests checked that numeric steppers and typed input share the same step
|
||||
and bounds, valid settings survive reopening, and invalid limits are rejected. This is not
|
||||
end-to-end file I/O acceptance or proof that real transfers obey these settings. These results
|
||||
do not establish installed-build or official-peer behavior or change any of the 718 pending
|
||||
requirements in `native/compatibility.json`.
|
||||
- **Direct whisper transport:** `cargo run --locked -p teamspeach-core --example duplex_qa -- --whisper`
|
||||
ran two disposable Rust CLI peers against the private beta14. Sender and receiver agreed on the
|
||||
recipient's live server UID. The receiver decoded 43 frames at 650 Hz with `whisper_received`;
|
||||
deny mode suppressed both playback and the event at 900 Hz. Restoring allow mode delivered
|
||||
40 frames at 1150 Hz. A stopped-epoch 1450 Hz tag produced no playback; subsequent ordinary
|
||||
1750 Hz voice delivered 42 frames without a whisper event. Both disconnects were confirmed.
|
||||
This checks core transport, not installed-client settings, official peers or physical audio.
|
||||
- **Generated voice transport:** two core CLI peers exchanged paced 500 Hz and 900 Hz test tones
|
||||
simultaneously through an isolated official TeamSpeak server beta 14 (100 sent frames per peer).
|
||||
Spectral and exact sender checks matched 99/101 decoded frames B→A and 100/101 A→B; both peers
|
||||
disconnected cleanly. No physical endpoint or official client peer was used.
|
||||
- **Duplex voice and stall regression:** `cargo run --locked -p teamspeach-core --example duplex_qa`
|
||||
exercised the actual QA core against the isolated localhost beta 14 server. A→B and B→A each
|
||||
received 45 frames, with onset latency 14 ms and 21 ms respectively and 864 ms of overlap.
|
||||
Release, mute, rejection while disconnected and a fresh reconnect were verified, with 3/3 clean
|
||||
leaves. Separately, 112 Windows `media::audio` tests passed, including capture delayed beyond
|
||||
200 ms during active playback and capture permit replacement. The reproducible tests confirm the
|
||||
stalled-worker code-path fix; the reported physical WASAPI scenario was not independently observed.
|
||||
- **S3 read-only listing:** against an isolated official TeamSpeak server beta 14, the core negotiated
|
||||
`s3`, observed empty `b64_json` with `return_code` then ACK `id=0`, returned an empty root
|
||||
(0 entries, 0 malformed, `read_only=true`, `list_supported=true`), and disconnected cleanly.
|
||||
A separate direct SigV4 store PUT/list/GET recovered the seeded bytes (SHA-256
|
||||
`c099147635c59787127aa7d9b9e247a5e0736f5e7a833bfb2732515e1ccdecae`). That is store evidence,
|
||||
not a populated listing, upload, download or mutation through the TeamSpeak channel.
|
||||
- **Open acceptance:** strict visual parity, populated S3 listings and positive signed transfers or
|
||||
mutations through TeamSpeak, HTTPFT, live server-hosted Matrix/SFU, official-peer two-way voice
|
||||
and physical audio, visible native captions/accessibility, installed desktop acceptance of this
|
||||
build, and mobile/Asahi device checks. Generated voice and stall-regression tests do not establish
|
||||
physical desktop voice acceptance or release readiness for this build.
|
||||
|
||||
## Native-only cutover and verification (2026-11-10)
|
||||
|
||||
The current product source is Rust/Slint with in-process Rust core services, native DSP, Skia and
|
||||
@@ -614,11 +222,9 @@ not a claim about every server configuration. Evidence: `docs/evidence/official-
|
||||
negotiation. `docs/evidence/official-parity/server-sfu-prerequisite.json` records a read-only check of the configured server's empty
|
||||
SFU endpoint; it does not prove absence of an advertised runtime capability. No controlled SFU endpoint
|
||||
has been exercised, so SFU remains blocked rather than falsely successful.
|
||||
- **Historical HTTPFT/S3 inspection (2026-11-01):** `docs/evidence/ts6-filetransfer-native.json` and
|
||||
`docs/evidence/ts6-filetransfer-native-continuation.json` recorded command arguments but not complete
|
||||
endpoint/base-URL binding, operation response envelopes, S3 payload mapping or required headers/verb
|
||||
values. No controlled newer-storage server fixture was available at that checkpoint; see the
|
||||
current checkpoint above for the separately observed empty S3 listing.
|
||||
- **HTTPFT/S3:** `docs/evidence/ts6-filetransfer-native.json` and `docs/evidence/ts6-filetransfer-native-continuation.json` record
|
||||
command arguments but not complete endpoint/base-URL binding, operation response envelopes, S3 payload
|
||||
mapping or required headers/verb values. No controlled newer-storage server fixture is available.
|
||||
- **macOS implementations:** selected-application audio capture is not implemented; a CoreAudio/TCC
|
||||
backend is still needed. Global shortcuts are explicitly unsupported by the non-Windows/non-Linux
|
||||
branch of `core/src/hotkeys.rs`. These are implementation gaps, not merely unexecuted tests.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+10
-16
@@ -7,27 +7,22 @@ chain according to the selected settings. There is no renderer WebAssembly ABI.
|
||||
The noise-only filter-bank implementation remains a Rust-test-only behavioral
|
||||
reference, not a second production capture stage.
|
||||
|
||||
Pinned Sonora packages include (all 0.3.0, BSD-3-Clause):
|
||||
Pinned Sonora packages include (all 0.2.0, BSD-3-Clause):
|
||||
sonora, sonora-aec3, sonora-agc2, sonora-common-audio,
|
||||
sonora-fft, sonora-ns, sonora-simd.
|
||||
|
||||
Source: https://github.com/dignifiedquire/sonora
|
||||
Commit: 1632d47c1e77d0857f9145bd175134b348541e11 (per the published crates'
|
||||
Commit: a024d6ef8351add55be5e8b1d6cc35f555787660 (per the published crates'
|
||||
.cargo_vcs_info.json)
|
||||
Registry: crates.io; package checksums (SHA-256 of the .crate files)
|
||||
sonora 0.3.0 d461e6c9ad112f8728919387a4bc5639fd28631f2070171efad38676e907edd8
|
||||
sonora-aec3 0.3.0 f2809c3fda13f71deac22d0ddb6c02c493f254d3da2afe59a7e256a8f15bcffe
|
||||
sonora-agc2 0.3.0 501b5dd3f8bdc8c983dc64a131cef22a429f3ff879d6f0007b8bfe46ec7b96aa
|
||||
sonora-common-audio 0.3.0 2c05dfa300c14dc8498751ce2c5b87aad2acf1892d4f9d66b92ae2f372a83410
|
||||
sonora-fft 0.3.0 ec3529f2cf748f1acc85d9403ffa08a3fe69dec6bf22383910b3bd21aca2fd26
|
||||
sonora-ns 0.3.0 31c0a62e78419a174dbf9c9c01943c1ecd8c298a68d15c4fb4906cb19f0428b9
|
||||
sonora-simd 0.3.0 f939d8e63a2a0baa7555294d7b09c5e3d382f28358755b920e13ad527658c8fa
|
||||
sonora 0.2.0 2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250
|
||||
sonora-ns 0.2.0 d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f
|
||||
sonora-fft 0.2.0 27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012
|
||||
|
||||
sonora is a pure Rust port of the WebRTC Native Code audio processing module
|
||||
(M145 plus later upstream fixes), via PulseAudio's webrtc-audio-processing
|
||||
extraction. TeamsPeach vendors sonora and sonora-agc2, retaining local mono AGC2
|
||||
borrowed-channel processing to avoid frame copies. Upstream 0.3.0's generic limiter
|
||||
subsumes the former local limiter descriptor-allocation patch. Exact modified files,
|
||||
extraction. TeamsPeach vendors sonora and sonora-agc2 with local mono AGC2 and
|
||||
limiter channel-adapter allocation/copy reductions. Exact modified files,
|
||||
upstream archive checksums and patch scope are in dsp/vendor/provenance.json;
|
||||
upstream license and copyright texts are retained in each vendored package.
|
||||
Other pinned Sonora packages use their registry sources. No end-to-end
|
||||
@@ -35,10 +30,9 @@ allocation-free guarantee or bit-identical behavior with TeamSpeak's proprietary
|
||||
DSP is claimed.
|
||||
|
||||
The native executable also uses the Rust standard library (core, alloc, std and
|
||||
its bundled allocator and math routines), licensed MIT OR Apache-2.0. Current
|
||||
resolved DSP dependency license texts are in denoise-THIRD-PARTY-NOTICES.txt;
|
||||
that file includes locked optional, build-time and target-specific dependencies
|
||||
and is not a complete inventory of the native executable's dependencies.
|
||||
its bundled allocator and math routines), licensed MIT OR Apache-2.0. Historical
|
||||
DSP dependency license texts are retained in denoise-THIRD-PARTY-NOTICES.txt;
|
||||
that file is not a complete inventory of the native executable's dependencies.
|
||||
|
||||
License of the Sonora packages (BSD-3-Clause, verbatim):
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ CI/release configuration is under `.gitea/workflows/`; an unexecuted configurati
|
||||
### Native CI and releases
|
||||
|
||||
The workflows require matching native runners labelled `teamspeach-native-linux-x64` and
|
||||
`teamspeach-native-linux-arm64`. Provision the Rust version from `rust-toolchain.toml`, Python 3, LLVM/libclang, CMake, Ninja,
|
||||
`teamspeach-native-linux-arm64`. Provision Rust 1.96.0, Python 3, LLVM/libclang, CMake, Ninja,
|
||||
Linux audio/window development libraries, Xvfb and D-Bus session tools before enabling them.
|
||||
Set repository variables `NATIVE_LLVM_HOME`, `NATIVE_LIBCLANG_PATH` and `NATIVE_SKIA_SOURCE_DIR`
|
||||
to existing tools and a dependency-synchronized Skia checkout containing `bin/gn`. Packaging also
|
||||
@@ -78,18 +78,18 @@ it refuses to overwrite an existing release. Manual dispatch builds/verifies wit
|
||||
The Python tests mock HTTP and never publish. Native compilation, UI smoke and device acceptance
|
||||
remain separate checks; removing the Electron updater harness does not establish native update E2E.
|
||||
|
||||
### Android development (Windows, Linux CI)
|
||||
### Android development (Windows, separate Linux build host)
|
||||
|
||||
The selected Android route is **develop on Windows → manually dispatch Gitea Actions → build and
|
||||
package entirely on Linux CI → download artifacts → install the test-only APK with Windows `adb`**.
|
||||
WSL, Docker and a local Linux installation are **not required on the developer PC**. Windows needs
|
||||
the editor/source checkout, a browser for Gitea and Android SDK Platform-Tools for device installation;
|
||||
the Android SDK/NDK, Java and heavy native build tools belong on the CI runner for this route.
|
||||
Develop the existing Rust/Slint Android client on Windows; build/package on a separately authorized
|
||||
Linux x64 machine. This can be the prepared Gitea workflow **or another developer's WSL2 Linux**.
|
||||
WSL, Docker and an Android build SDK are **not required on this developer PC**. Tool installation and
|
||||
resource limits belong to the chosen build machine; do not copy `mobile-build.local.md` or local
|
||||
Windows compiler overrides to it. CI provisioning is currently deferred in favor of application work.
|
||||
|
||||
Pinned WebRTC's [official Android source-build documentation](https://github.com/webrtc-sdk/webrtc/blob/9c3a1386f07e4348c28cd85c066821cebc3b56e4/docs/native-code/android/README.md)
|
||||
states “Android development is only supported on Linux.” This is a build-host requirement for CI,
|
||||
states “Android development is only supported on Linux.” This is a build-host requirement,
|
||||
not a requirement to run Linux locally. A Windows WebRTC Android source build is not a supported
|
||||
alternative. CI keeps the full **Skia + WebRTC** feature set and pinned-source/receipt checks.
|
||||
alternative. Keep the full **Skia + WebRTC** feature set and pinned-source/receipt checks.
|
||||
|
||||
#### CI administrator prerequisites
|
||||
|
||||
@@ -116,11 +116,77 @@ allows Gradle dependency resolution on CI; the ordinary packaging default remain
|
||||
Provision runner resources for the full native build; local developer-machine limits are not a CI policy.
|
||||
No production signing credentials are needed or used by this unsigned-artifact workflow.
|
||||
|
||||
#### Handoff to another developer's WSL2 machine
|
||||
|
||||
Use Linux x64 inside WSL2, with the source and caches in its Linux filesystem (for example
|
||||
`~/src/TeamsPeach`), not a shared Windows `target/`. No Android emulator is required to build an APK.
|
||||
The receiving developer must approve tool installation, storage and resource limits on **their** PC.
|
||||
This is the same Linux source-build route, not a separately tested WSL product configuration.
|
||||
|
||||
1. Receive a **committed and pushed** `feature/mobile-port` revision containing the Android changes.
|
||||
The sender supplies its full SHA; the receiver checks `git rev-parse HEAD` against it and begins
|
||||
from a clean worktree. `cb1d682` is only the earlier CI-inventory baseline, not the completed port.
|
||||
Do not build `main` or assume uncommitted sender changes were transferred. Build fixes need their
|
||||
own commits and a new recorded SHA, not an APK with undocumented source modifications.
|
||||
2. Provision the versions/tools in the table above, plus Rust 1.96.0 and its
|
||||
`aarch64-linux-android` standard library. Use matching Linux LLVM/libclang and dependency-synchronized
|
||||
Skia sources, not Windows caches. Cargo/WebRTC/CIPD/Gradle dependency resolution needs network access.
|
||||
The Android dependency receipt must be generated by `xtask deps`, never copied from Windows or forged.
|
||||
3. Set these variables to **existing absolute Linux paths**: `ANDROID_SDK_ROOT`, `JAVA_HOME`,
|
||||
`LLVM_HOME`, `LIBCLANG_PATH`, `SKIA_SOURCE_DIR`, `TEAMSPEACH_GRADLE_DISTRIBUTION`, and
|
||||
`TEAMSPEACH_BUNDLETOOL` (the same inputs as the CI table, mapped to the names consumed by tools).
|
||||
Do not provide production signing credentials for the test-only build. From the repository root:
|
||||
|
||||
```bash
|
||||
set -euo pipefail
|
||||
: "${ANDROID_SDK_ROOT:?}" "${JAVA_HOME:?}" "${LLVM_HOME:?}" "${LIBCLANG_PATH:?}"
|
||||
: "${SKIA_SOURCE_DIR:?}" "${TEAMSPEACH_GRADLE_DISTRIBUTION:?}" "${TEAMSPEACH_BUNDLETOOL:?}"
|
||||
export TARGET=aarch64-linux-android
|
||||
export EXPECTED_REVISION="$(git rev-parse HEAD)"
|
||||
export CI_RUN_ID="wsl2-$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
export CARGO_BUILD_JOBS=1
|
||||
export CARGO_TARGET_DIR="$PWD/target"
|
||||
export GRADLE_USER_HOME="$PWD/target/android-gradle-cache"
|
||||
export ANDROID_HOME="$ANDROID_SDK_ROOT"
|
||||
export ANDROID_NDK_ROOT="$ANDROID_SDK_ROOT/ndk/28.2.13676358"
|
||||
export ANDROID_NDK_HOME="$ANDROID_NDK_ROOT"
|
||||
export ANDROID_NDK="$ANDROID_NDK_ROOT" # rust-skia uses this alias
|
||||
export ANDROID_JAR="$ANDROID_SDK_ROOT/platforms/android-36/android.jar" # compile API, distinct from native minimum API26
|
||||
export SKIA_GN_COMMAND="$SKIA_SOURCE_DIR/bin/gn"
|
||||
export SKIA_NINJA_COMMAND="$(command -v ninja)"
|
||||
export PATH="$JAVA_HOME/bin:$LLVM_HOME/bin:$ANDROID_SDK_ROOT/build-tools/36.0.0:$PATH"
|
||||
cargo run --locked -p xtask -- check-version
|
||||
cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME" --jobs 1
|
||||
bash .gitea/build-android-variant.sh harness
|
||||
```
|
||||
|
||||
The helper uses the existing `xtask build`, `package` and `verify-package` commands and writes
|
||||
`dist/android/harness/build-info.json`. Its `CI_RUN_ID` is a local provenance label here, not a claim
|
||||
that Gitea ran the build. Package directories must be fresh; preserve failed results/caches and
|
||||
explicitly move aside an old `dist/android/harness` before retrying. Do not run `cargo clean`.
|
||||
One Cargo job is only build parallelism, not a complete memory guard; choose WSL/host memory limits
|
||||
with that PC's owner before starting heavy compilation.
|
||||
4. Return the **whole `dist/android/harness` bundle**, including `*-harness-test.apk`,
|
||||
`build-info.json`, `package-report.json`, `verification.json`, `native-build.json`,
|
||||
`native-deps.lock.json` and `dependency-provenance.json`. Return the exact source SHA and
|
||||
build errors/fixes separately; omit credentials, private signing material and app/user profiles.
|
||||
Verify `passed=true`, ARM64, test-only signing and APK SHA256 before delivery.
|
||||
5. Optional production build is a separate decision: the same helper with `production` creates
|
||||
unsigned APK/AAB, not an installable release. Do not publish, sign for production, install on a
|
||||
phone, access a microphone or connect to a server without the relevant owner's explicit approval.
|
||||
|
||||
The receiver's first build still needs to establish Rust/Java/JNI/Gradle integration. A build pass
|
||||
does not establish phone UI, permissions, audio routes, foreground behavior or two-way voice.
|
||||
|
||||
#### Dispatch, download and install from Windows
|
||||
|
||||
1. Deliver the source changes through the normal authorized repository process. In the repository's
|
||||
**Actions** page select **android-ci** (`android.yml`), choose the intended branch/ref and dispatch it
|
||||
manually. This workflow has no automatic push/tag trigger and does not publish releases.
|
||||
**Actions** page select **android-ci** (`android.yml`) and choose the intended branch/ref.
|
||||
The default **inventory** mode runs a read-only, five-minute resource/tool inventory on the existing
|
||||
`ubuntu-latest` runner, without checkout, downloads, builds or installation. It reports configured
|
||||
variable presence, not their values; an inventory pass does not mean Android build readiness.
|
||||
Select **build** explicitly only after provisioning the dedicated Android runner and variables above.
|
||||
This workflow has no automatic push/tag trigger and does not publish releases.
|
||||
2. Only after an actual successful run, download and extract **`android-harness-arm64`** and
|
||||
**`android-production-unsigned-arm64`**. Each bundle includes root `build-info.json` identifying
|
||||
the exact revision, package manifests/hashes and `aarch64-linux-android` package-verification,
|
||||
@@ -151,10 +217,12 @@ No production signing credentials are needed or used by this unsigned-artifact w
|
||||
The **unsigned production APK is not installable** until separately authorized production signing
|
||||
and signature verification are completed. **An AAB is not directly installable with `adb install`**;
|
||||
it requires the separate signing/store or APK-generation process. These bundles are not a release.
|
||||
The harness is for test-only/offline smoke scenarios, not production feature/device acceptance.
|
||||
Neither this workflow configuration nor installing a harness proves live voice, official-client
|
||||
interoperability, Bluetooth/background behavior or full mobile parity. No successful CI run, generated
|
||||
APK/AAB, device install or mobile acceptance is claimed here.
|
||||
The harness supports isolated offline smoke; a normal launch without smoke extras uses the ordinary
|
||||
runtime and must be confined to an authorized disposable test installation. It is not production
|
||||
feature/device acceptance. Neither configuration nor installation proves live voice, official-client
|
||||
interoperability, Bluetooth/background behavior or full mobile parity. The first local WSL2 ARM64
|
||||
harness build and APK signature/16-KiB/JNI/package verification passed on 2026-11-11 after the build
|
||||
integration fixes recorded in `docs/mobile-port-progress.md`. Phone execution remains unverified.
|
||||
|
||||
**iOS still requires macOS and Xcode/Apple SDKs**, either locally or on separately provisioned macOS
|
||||
CI, plus appropriate signing/provisioning for devices. Windows editing does not make iOS buildable
|
||||
@@ -250,12 +318,9 @@ native/platform acceptance case has passed. Consult FEATURE_COMPATIBILITY.md for
|
||||
universal cross-platform or official-client interoperability proof.
|
||||
9. Channel/server menus provide typed administration with explicit destructive confirmations and server
|
||||
errors. Snapshot import is non-atomic: completed server changes are not rolled back by cancellation.
|
||||
Channel files use legacy transfer on legacy servers. Ordinary channels can browse S3 metadata;
|
||||
S3 takes precedence for listing when both S3 and HTTPFT are advertised. HTTPFT remains blocked,
|
||||
with no fallback to legacy storage. S3 upload/download bytes and remote mutations have not been
|
||||
verified live through TeamSpeak. Native services require chooser grants for recording and file
|
||||
destinations and explicit confirmation for overwrite or destructive operations. Filesystem
|
||||
publication fails safely when required atomic/no-replace semantics are unavailable.
|
||||
General file browsing/transfers support the legacy server transport; HTTPFT/S3 remain explicit gaps
|
||||
with no speculative legacy fallback. Filesystem publication fails safely when required atomic/no-replace
|
||||
semantics are unavailable. Native services approve recording/transfer destinations through chooser grants.
|
||||
File Transfer settings retain an approved download folder or ask every time, and apply upload/download
|
||||
concurrency across all tabs (combined at most ten) plus shared directional rate limits. Limits apply to
|
||||
active file/snapshot work without restarting streams; they are conservative ceilings, not bandwidth guarantees.
|
||||
@@ -284,7 +349,7 @@ native/platform acceptance case has passed. Consult FEATURE_COMPATIBILITY.md for
|
||||
IPC, page or remote-button binding is included.
|
||||
- **Server icons:** the server administration pane lists, uploads, deletes and assigns icons through
|
||||
legacy TeamSpeak file transfer. The server's permissions remain authoritative. A reconnect invalidates
|
||||
the panel's mutation grant. Ordinary-channel S3 browsing does not enable S3 or HTTPFT server icons.
|
||||
the panel's mutation grant; HTTPFT/S3 storage is not silently treated as an empty icon collection.
|
||||
- **Noise reduction:** Settings → Audio has four levels saved per input device. The implementation is
|
||||
independent DSP; selected settings and generated-media checks do not prove microphone sound quality
|
||||
or bit-identical behavior with the official client.
|
||||
@@ -357,8 +422,8 @@ An absolute, normalized `TEAMSPEACH_PROFILE_DIR` selects a separate root; do not
|
||||
unreachable over SSH.
|
||||
- Packages are unsigned. Windows SmartScreen warns about unsigned builds; macOS Gatekeeper would also
|
||||
require attention for a future macOS build.
|
||||
- A two-way core CLI run verified synthetic voice with silent disposable profiles. It did not use real
|
||||
microphones or playback devices and does not prove official-client peer or Asahi interoperability.
|
||||
- The recorded two-way voice run used synthetic capture between two TeamsPeach clients. It does not
|
||||
prove live microphone interoperability with the official TS6 client or operation on Asahi hardware.
|
||||
|
||||
## Product and design
|
||||
|
||||
@@ -411,12 +476,6 @@ actions and are not release eligible. Generated media proves only its exercised
|
||||
path. Live official peers, physical capture/playback, visible native windows, OS accessibility,
|
||||
installed upgrades and Asahi/mobile hardware need separately authorized isolated checks.
|
||||
|
||||
The S3 result is scoped to an empty ordinary-channel listing on an isolated official TS6 beta14
|
||||
server. An ordinary guest upload grant was refused; neither that refusal nor a separate direct object-store
|
||||
readback proves TeamSpeak file transfers. The live-peer check is still pending; keep any separately
|
||||
authorized probes and sanitized evidence in disposable profiles, channels and storage, away from user
|
||||
credentials and files.
|
||||
|
||||
`native/compatibility.json` preserves 718 pending acceptance requirements, not pass marks. Historical
|
||||
captures in `docs/evidence/` remain exact records of their original builds; they do not prove native parity.
|
||||
Strict visual comparisons previously failed and are not converted to passes by the stack cutover.
|
||||
|
||||
+4
-9
@@ -16,19 +16,15 @@ tsclientlib = { path = "vendor/tsclientlib", default-features = false, features
|
||||
tsproto-packets = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
tsproto-types = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
|
||||
audiopus = "0.3.0-rc.0"
|
||||
base64 = "0.23.1"
|
||||
bytes = "1"
|
||||
chrono = { version = "0.4", default-features = false }
|
||||
base64 = "0.22"
|
||||
futures = "0.3"
|
||||
num-traits = "0.2"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls", "stream"] }
|
||||
# File identity (volume serial + index / dev + inode) for paused partial downloads; already in the lock.
|
||||
same-file = "1.0.6"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = { version = "1", features = ["raw_value", "preserve_order"] }
|
||||
sha1 = "0.11.0"
|
||||
md-5 = "0.11.0"
|
||||
base16ct.workspace = true
|
||||
sha-1 = "0.10"
|
||||
md-5 = "0.10"
|
||||
# Same DER decoder tsproto-types uses for keys (already in the lock through it).
|
||||
simple_asn1 = "0.6"
|
||||
# Voice activation detector (pure Rust, embedded model; MIT OR Apache-2.0). Pinned: newer releases change the API.
|
||||
@@ -39,7 +35,6 @@ tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# The #[implement] macro in app_audio_windows expands to absolute ::windows_core paths.
|
||||
windows-core = "0.62.2"
|
||||
windows = { version = "0.62.2", features = [
|
||||
"Win32_Foundation",
|
||||
@@ -63,5 +58,5 @@ windows-sys = { version = "0.61", features = [
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
dbus = { version = "0.9", features = ["vendored"] }
|
||||
x11rb = "0.14.0"
|
||||
x11rb = "0.13"
|
||||
|
||||
+328
-3651
File diff suppressed because it is too large.
Load diff
@@ -1,848 +0,0 @@
|
||||
//! Connected administration QA for an already running, private TS6 beta14 fixture.
|
||||
//! Set TEAMSPEACH_QA_CORE to an absolute path to a disposable teamspeach-core.exe,
|
||||
//! then run `cargo run --locked -p teamspeach-core --example channel_admin_qa`.
|
||||
//! The only endpoint is 127.0.0.1:19987. No credentials, devices or ServerQuery.
|
||||
//! Pass `--channel-order` to check sibling readback on insertion and expiry only.
|
||||
//! Pass `--client-database-id` to compare UID lookup and nickname search without modifying the server.
|
||||
//! Pass `--client-info` to read the guest's own variables and reject a mismatched UID.
|
||||
//! Pass `--channel-subscriptions` to check this guest's channel subscriptions.
|
||||
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, ExitCode, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const ENDPOINT: &str = "127.0.0.1:19987";
|
||||
const CONTROL: Duration = Duration::from_secs(5);
|
||||
const CONNECT: Duration = Duration::from_secs(12);
|
||||
const POLL: Duration = Duration::from_millis(50);
|
||||
// Leave a quiet window between ordinary server commands; do not retry flood refusals.
|
||||
const WIRE_SPACING: Duration = Duration::from_secs(5);
|
||||
const CLIENT_IS_FLOODING: u64 = 524;
|
||||
const PERMISSION_DENIED: u64 = 2568;
|
||||
const ORIGINAL_TOPIC: &str = "QA initial topic";
|
||||
const UPDATED_TOPIC: &str = "QA edited topic";
|
||||
const CODEC_QUALITY: u64 = 5;
|
||||
const FAMILY_INHERITED: &str = "channel_flag_maxfamilyclients_inherited";
|
||||
|
||||
type Result<T, E = String> = std::result::Result<T, E>;
|
||||
|
||||
enum Reply {
|
||||
Accepted(Value),
|
||||
Refused(Value),
|
||||
}
|
||||
|
||||
impl Reply {
|
||||
fn require(self, cmd: &str) -> Result<Value> {
|
||||
match self {
|
||||
Self::Accepted(result) => Ok(result),
|
||||
Self::Refused(refusal) => Err(rejection(cmd, &refusal)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rejection(cmd: &str, refusal: &Value) -> String {
|
||||
// IDs are diagnostic; the IPC error message/detail can contain real target data.
|
||||
if let Some(id) = refusal["ts_error"]["id"].as_u64() {
|
||||
if id == CLIENT_IS_FLOODING {
|
||||
return format!("{cmd}: server flood-limited this request (TS {id}); not retried");
|
||||
}
|
||||
return format!("{cmd}: server refused (TS {id})");
|
||||
}
|
||||
let kind = match refusal["code"].as_str() {
|
||||
Some("bad_request") => "bad_request",
|
||||
Some("not_connected") => "not_connected",
|
||||
Some("not_found") => "not_found",
|
||||
Some("server_error") => "server_error without a TeamSpeak result",
|
||||
_ => "unexpected IPC error",
|
||||
};
|
||||
format!("{cmd}: {kind}")
|
||||
}
|
||||
|
||||
struct Core {
|
||||
child: Child,
|
||||
input: Option<mpsc::SyncSender<String>>,
|
||||
written: mpsc::Receiver<bool>,
|
||||
output: mpsc::Receiver<Value>,
|
||||
sequence: u32,
|
||||
state: Option<&'static str>,
|
||||
snapshot: Value,
|
||||
last_wire: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
fn start(exe: &Path, root: &Path) -> Result<Self> {
|
||||
let mut child = Command::new(exe)
|
||||
.arg("--data-dir").arg(root.join("profile"))
|
||||
.current_dir(root)
|
||||
.env("TEAMSPEACH_LOG", "off")
|
||||
.env("TMP", root).env("TEMP", root).env("TMPDIR", root)
|
||||
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
|
||||
.spawn().map_err(|e| format!("could not start diagnostic core ({:?})", e.kind()))?;
|
||||
let mut stdin = child.stdin.take().expect("piped stdin");
|
||||
let stdout = child.stdout.take().expect("piped stdout");
|
||||
let (input, outgoing) = mpsc::sync_channel::<String>(1);
|
||||
let (ack, written) = mpsc::sync_channel(1);
|
||||
let (incoming, output) = mpsc::sync_channel(256);
|
||||
let reader = thread::Builder::new().spawn(move || {
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let Ok(value) = line.and_then(|text| serde_json::from_str(&text).map_err(std::io::Error::other)) else {
|
||||
break;
|
||||
};
|
||||
if incoming.try_send(value).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let writer = thread::Builder::new().spawn(move || {
|
||||
while let Ok(line) = outgoing.recv() {
|
||||
let ok = stdin.write_all(line.as_bytes()).is_ok();
|
||||
if ack.send(ok).is_err() || !ok {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let core = Self {
|
||||
child, input: Some(input), written, output, sequence: 0, state: None, snapshot: Value::Null,
|
||||
last_wire: None,
|
||||
};
|
||||
if reader.is_err() || writer.is_err() {
|
||||
return Err("could not start core pipe workers".into());
|
||||
}
|
||||
let ready = core.read(Instant::now() + CONTROL, "ready")?;
|
||||
ensure(ready["event"] == "ready" && ready["protocol"] == 1, "expected protocol 1 ready event")?;
|
||||
Ok(core)
|
||||
}
|
||||
|
||||
fn read(&self, deadline: Instant, stage: &str) -> Result<Value> {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return Err(format!("{stage}: deadline exceeded"));
|
||||
}
|
||||
self.output.recv_timeout(remaining).map_err(|e| format!("{stage}: core stdout {e}"))
|
||||
}
|
||||
|
||||
fn request(&mut self, cmd: &str, args: Value, deadline: Instant) -> Result<Reply> {
|
||||
self.sequence += 1;
|
||||
let id = self.sequence.to_string();
|
||||
let line = format!("{}\n", json!({"id": id, "cmd": cmd, "args": args}));
|
||||
if Instant::now() >= deadline
|
||||
|| self.input.as_ref().is_none_or(|input| input.try_send(line).is_err())
|
||||
|| self.written.recv_timeout(deadline.saturating_duration_since(Instant::now())) != Ok(true)
|
||||
{
|
||||
return Err(format!("{cmd}: core stdin write failed or timed out"));
|
||||
}
|
||||
loop {
|
||||
let value = self.read(deadline, cmd)?;
|
||||
if value["id"].as_str() == Some(id.as_str()) {
|
||||
return match value["ok"].as_bool() {
|
||||
Some(true) => Ok(Reply::Accepted(value["result"].clone())),
|
||||
Some(false) if value["error"].is_object() => Ok(Reply::Refused(value["error"].clone())),
|
||||
_ => Err(format!("{cmd}: malformed core reply")),
|
||||
};
|
||||
}
|
||||
self.observe(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn observe(&mut self, event: Value) {
|
||||
match event["event"].as_str() {
|
||||
Some("snapshot") => self.snapshot = event,
|
||||
Some("state") => self.state = match event["state"].as_str() {
|
||||
Some("connecting") => Some("connecting"),
|
||||
Some("connected") => Some("connected"),
|
||||
Some("disconnecting") => Some("disconnecting"),
|
||||
Some("disconnected") => Some("disconnected"),
|
||||
_ => None,
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, cmd: &str, args: Value) -> Result<Value> {
|
||||
self.request(cmd, args, Instant::now() + CONTROL)?.require(cmd)
|
||||
}
|
||||
|
||||
fn wait_wire_spacing(&self) {
|
||||
if let Some(last) = self.last_wire {
|
||||
thread::sleep((last + WIRE_SPACING).saturating_duration_since(Instant::now()));
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_request(&mut self, cmd: &str, args: Value, timeout: Duration) -> Result<Reply> {
|
||||
self.wait_wire_spacing();
|
||||
let reply = self.request(cmd, args, Instant::now() + timeout);
|
||||
self.last_wire = Some(Instant::now());
|
||||
reply
|
||||
}
|
||||
|
||||
fn wire_call(&mut self, cmd: &str, args: Value) -> Result<Value> {
|
||||
self.wire_request(cmd, args, CONTROL)?.require(cmd)
|
||||
}
|
||||
|
||||
fn wait_for(&mut self, stage: &str, ready: impl Fn(&Value) -> bool) -> Result<()> {
|
||||
let deadline = Instant::now() + CONTROL;
|
||||
while !ready(&self.snapshot) {
|
||||
let event = self.read(deadline, stage)?;
|
||||
self.observe(event);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn leave_and_close(&mut self) -> Result<()> {
|
||||
// A failed action can still leave us connected. Shutdown runs even if the
|
||||
// explicit disconnect failed; dropping stdin is the last graceful path.
|
||||
let leave = if self.state == Some("connected") {
|
||||
self.call("disconnect", json!({})).and_then(|result| {
|
||||
ensure(self.state == Some("disconnected") && result["clean"] == true,
|
||||
"disconnect did not receive server confirmation")
|
||||
}).map(|()| println!("disconnect: ok (server confirmed)"))
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
let close = self.call("shutdown", json!({})).and_then(|_| {
|
||||
match self.wait_exit(CONTROL)? {
|
||||
Some(status) if status.success() => {
|
||||
println!("shutdown: ok (core exited)");
|
||||
Ok(())
|
||||
}
|
||||
_ => Err("core did not exit cleanly by its deadline".into()),
|
||||
}
|
||||
});
|
||||
combine(leave, close)
|
||||
}
|
||||
|
||||
fn wait_exit(&mut self, limit: Duration) -> Result<Option<std::process::ExitStatus>> {
|
||||
let deadline = Instant::now() + limit;
|
||||
loop {
|
||||
let status = self.child.try_wait().map_err(|_| "could not query the diagnostic core process")?;
|
||||
if status.is_some() || Instant::now() >= deadline {
|
||||
return Ok(status);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Core {
|
||||
fn drop(&mut self) {
|
||||
drop(self.input.take());
|
||||
if !matches!(self.wait_exit(CONTROL), Ok(Some(_))) && self.child.kill().is_ok() {
|
||||
let _ = self.wait_exit(CONTROL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only constructed from this run's create result and a verified matching live
|
||||
// name. No caller-supplied channel ID can reach the edit path, and no delete
|
||||
// command is sent: the server expires the temporary channel after we leave it.
|
||||
struct RunChannel<'a> {
|
||||
id: u64,
|
||||
name: &'a str,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl RunChannel<'_> {
|
||||
fn row<'a>(&self, rows: &'a [Value]) -> Result<&'a Value> {
|
||||
let row = rows.iter().find(|row| wire_id(row) == Some(self.id));
|
||||
row.filter(|row| row["channel_name"].as_str() == Some(self.name))
|
||||
.ok_or_else(|| "the generated channel is not visible with its original name".into())
|
||||
}
|
||||
|
||||
fn listed(&self, core: &mut Core, deadline: Instant) -> Result<Value> {
|
||||
let list = core.request("channel_list", json!({}), deadline)?.require("channel_list")?;
|
||||
Ok(self.row(rows(&list)?)?.clone())
|
||||
}
|
||||
|
||||
fn edit(&self, core: &mut Core, generation: u64, properties: Value) -> Result<Reply> {
|
||||
let args = self.edit_args(core, generation, properties)?;
|
||||
core.wire_request("channel_edit", args, CONTROL)
|
||||
}
|
||||
|
||||
fn edit_args(&self, core: &mut Core, generation: u64, properties: Value) -> Result<Value> {
|
||||
self.listed(core, Instant::now() + CONTROL)?;
|
||||
self.check_live_generation(core)?;
|
||||
Ok(json!({"generation": generation, "channel_id": self.id, "properties": properties}))
|
||||
}
|
||||
|
||||
fn check_live_generation(&self, core: &Core) -> Result<()> {
|
||||
ensure(core.state == Some("connected") && core.snapshot["generation"].as_u64() == Some(self.generation),
|
||||
"live connection changed before mutating the generated channel")
|
||||
}
|
||||
|
||||
fn move_under(&self, core: &mut Core, parent_id: u64) -> Result<Reply> {
|
||||
self.listed(core, Instant::now() + CONTROL)?;
|
||||
self.check_live_generation(core)?;
|
||||
ensure(valid_parent(&core.snapshot, parent_id), "the original default channel is no longer a valid parent")?;
|
||||
core.wire_request("channel_move", json!({"generation": self.generation, "channel_id": self.id, "parent_id": parent_id}), CONTROL)
|
||||
}
|
||||
|
||||
fn info(&self, core: &mut Core) -> Result<Value> {
|
||||
let result = core.wire_call("channel_info", json!({"channel_id": self.id}))?;
|
||||
let rows = rows(&result)?;
|
||||
ensure(rows.len() == 1, "channel_info did not return exactly one row")?;
|
||||
Ok(self.row(rows)?.clone())
|
||||
}
|
||||
|
||||
fn observe_row(&self, core: &mut Core, matches: impl Fn(&Value) -> bool) -> Result<Value> {
|
||||
let deadline = Instant::now() + CONTROL;
|
||||
loop {
|
||||
let row = self.listed(core, deadline)?;
|
||||
if matches(&row) || deadline.saturating_duration_since(Instant::now()) <= POLL {
|
||||
return Ok(row);
|
||||
}
|
||||
thread::sleep(POLL);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_fields(&self, core: &mut Core, expected: &[(&str, &str)]) -> Result<Value> {
|
||||
let matches = |row: &Value| expected.iter().all(|(key, value)| row[*key].as_str() == Some(*value));
|
||||
let row = self.observe_row(core, matches)?;
|
||||
ensure(matches(&row), "server acknowledged edit but live properties did not match")?;
|
||||
Ok(row)
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure(condition: bool, message: &str) -> Result<()> {
|
||||
if condition { Ok(()) } else { Err(message.into()) }
|
||||
}
|
||||
|
||||
fn combine(first: Result<()>, second: Result<()>) -> Result<()> {
|
||||
match (first, second) {
|
||||
(Err(first), Err(second)) => Err(format!("{first}; {second}")),
|
||||
(first, second) => first.and(second),
|
||||
}
|
||||
}
|
||||
|
||||
fn rows(value: &Value) -> Result<&[Value]> {
|
||||
value["rows"].as_array().map(Vec::as_slice).ok_or_else(|| "missing row list".into())
|
||||
}
|
||||
|
||||
fn wire_id(row: &Value) -> Option<u64> {
|
||||
row["cid"].as_str()?.parse().ok()
|
||||
}
|
||||
|
||||
fn snapshot_channel(snapshot: &Value, id: u64) -> Option<&Value> {
|
||||
snapshot["channels"].as_array()?.iter().find(|row| row["id"].as_u64() == Some(id))
|
||||
}
|
||||
|
||||
fn own_channel(snapshot: &Value, own: u64) -> Option<u64> {
|
||||
if snapshot["own_client_id"].as_u64() != Some(own) {
|
||||
return None;
|
||||
}
|
||||
let channel = snapshot["own_channel_id"].as_u64().filter(|id| *id != 0)?;
|
||||
snapshot_channel(snapshot, channel)?;
|
||||
snapshot["clients"].as_array()?.iter()
|
||||
.any(|client| client["id"].as_u64() == Some(own) && client["channel_id"].as_u64() == Some(channel))
|
||||
.then_some(channel)
|
||||
}
|
||||
|
||||
fn check_topic(stage: &str, row: &Value, expected: &str) -> Result<()> {
|
||||
let field = row.get("channel_topic");
|
||||
let text = field.and_then(Value::as_str);
|
||||
if text == Some(expected) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("{stage}: channel row topic (present={}, string={}, matches=false)",
|
||||
field.is_some(), text.is_some()))
|
||||
}
|
||||
}
|
||||
|
||||
fn check_quality(stage: &str, snapshot: &Value, id: u64, row: &Value) -> Result<()> {
|
||||
let field = snapshot_channel(snapshot, id).and_then(|channel| channel.get("codec_quality"));
|
||||
let quality = field.and_then(Value::as_u64);
|
||||
if quality != Some(CODEC_QUALITY) {
|
||||
return Err(format!("{stage}: snapshot codec quality (reported={}, integer={}, matches=false)",
|
||||
field.is_some_and(|value| !value.is_null()), quality.is_some()));
|
||||
}
|
||||
// The raw row is sparse; require agreement only when the server reported it there.
|
||||
if let Some(wire) = row.get("channel_codec_quality") {
|
||||
let quality = wire.as_str().and_then(|text| text.parse::<u64>().ok());
|
||||
if quality != Some(CODEC_QUALITY) {
|
||||
return Err(format!("{stage}: channel row codec quality (present=true, wire_integer={}, matches=false)",
|
||||
quality.is_some()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_local_refusal(reply: Reply, message: &str, generation: Option<u64>) -> Result<()> {
|
||||
match reply {
|
||||
Reply::Refused(error) if error["code"] == "bad_request" && error.get("ts_error").is_none()
|
||||
&& error["message"] == message && error["detail"]["generation"].as_u64() == generation => Ok(()),
|
||||
Reply::Refused(error) => Err(rejection("expected local validation", &error)),
|
||||
Reply::Accepted(_) => Err("unexpected mutation acknowledgement".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn permission_probe(
|
||||
core: &mut Core, channel: &RunChannel<'_>, label: &str, props: Value, expected: &[(&str, &str)],
|
||||
) -> Result<Option<Value>> {
|
||||
let before = channel.listed(core, Instant::now() + CONTROL)?;
|
||||
match channel.edit(core, channel.generation, props)? {
|
||||
Reply::Accepted(_) => {
|
||||
let after = channel.wait_fields(core, expected).map_err(|err| format!("{label}: {err}"))?;
|
||||
ensure(after["channel_topic"] == before["channel_topic"], "limit edit changed the topic")?;
|
||||
let changed = expected.iter().any(|(key, _)| key.starts_with("channel_flag_") && before[*key] != after[*key]);
|
||||
ensure(changed, "limit edit did not exercise a flag change")?;
|
||||
println!("{label}: ok (server acknowledged, properties read back)");
|
||||
Ok(Some(after))
|
||||
}
|
||||
Reply::Refused(error) if permission_denied(&error) => {
|
||||
let after = channel.listed(core, Instant::now() + CONTROL)?;
|
||||
ensure(after == before, "permission refusal was followed by a property change")?;
|
||||
println!("{label}: refused (TS {PERMISSION_DENIED}; properties unchanged)");
|
||||
Ok(None)
|
||||
}
|
||||
Reply::Refused(error) => Err(rejection(label, &error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn permission_denied(error: &Value) -> bool {
|
||||
error["code"] == "server_error" && error["ts_error"]["id"].as_u64() == Some(PERMISSION_DENIED)
|
||||
}
|
||||
|
||||
fn report_inherited(label: &str, row: &Value, expected: &str) -> Result<()> {
|
||||
match row.get(FAMILY_INHERITED) {
|
||||
Some(value) if value.as_str() == Some(expected) => println!("{label}: ok (inherited flag read back)"),
|
||||
Some(value) => return Err(format!("{label}: wrong inherited flag (present=true, string={}, matches=false)",
|
||||
value.is_string())),
|
||||
None => println!("{label}: unreported (server acknowledged; inherited flag not returned)"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn valid_parent(snapshot: &Value, id: u64) -> bool {
|
||||
snapshot_channel(snapshot, id).is_some_and(|parent| parent["is_default"] == true && parent["channel_type"] == "permanent")
|
||||
}
|
||||
|
||||
fn probe_inherited(core: &mut Core, channel: &RunChannel<'_>, lobby: u64) -> Result<()> {
|
||||
const LABEL: &str = "family inheritance under a parent";
|
||||
if !valid_parent(&core.snapshot, lobby) {
|
||||
println!("{LABEL}: unverified (no valid default-channel parent)");
|
||||
return Ok(());
|
||||
}
|
||||
// Move only our temporary channel. The default lobby is a parent reference,
|
||||
// never the target of a write. Its properties and permissions stay untouched.
|
||||
let before_move = channel.listed(core, Instant::now() + CONTROL)?;
|
||||
match channel.move_under(core, lobby)? {
|
||||
Reply::Accepted(_) => core.wait_for("generated channel under the default parent", |s| {
|
||||
snapshot_channel(s, channel.id).is_some_and(|c| c["parent_id"].as_u64() == Some(lobby))
|
||||
})?,
|
||||
Reply::Refused(error) if permission_denied(&error) => {
|
||||
ensure(channel.listed(core, Instant::now() + CONTROL)? == before_move,
|
||||
"refused parent move changed the generated channel")?;
|
||||
println!("{LABEL}: unverified (parent placement refused, TS {PERMISSION_DENIED}; channel unchanged)");
|
||||
return Ok(());
|
||||
}
|
||||
Reply::Refused(error) => return Err(rejection("place generated channel under parent", &error)),
|
||||
}
|
||||
let before = channel.listed(core, Instant::now() + CONTROL)?;
|
||||
if before[FAMILY_INHERITED] == "1" {
|
||||
println!("{LABEL}: unverified (already inherited after placement; no explicit transition observed)");
|
||||
return Ok(());
|
||||
}
|
||||
let properties = json!({"channel_flag_maxfamilyclients_unlimited": false, "channel_flag_maxfamilyclients_inherited": true});
|
||||
match channel.edit(core, channel.generation, properties)? {
|
||||
Reply::Accepted(_) => {
|
||||
let after = channel.observe_row(core, |row| row[FAMILY_INHERITED] == "1")?;
|
||||
report_inherited(LABEL, &after, "1")
|
||||
}
|
||||
Reply::Refused(error) if permission_denied(&error) => {
|
||||
ensure(channel.listed(core, Instant::now() + CONTROL)? == before,
|
||||
"permission refusal was followed by a property change")?;
|
||||
println!("{LABEL}: refused (TS {PERMISSION_DENIED}; properties unchanged)");
|
||||
Ok(())
|
||||
}
|
||||
Reply::Refused(error) => Err(rejection(LABEL, &error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_first_sibling(core: &mut Core, sibling: u64, predecessor: u64) -> Result<()> {
|
||||
let list = core.call("channel_list", json!({}))?;
|
||||
let info = core.wire_call("channel_info", json!({"channel_id":sibling}))?;
|
||||
for response in [&list, &info] {
|
||||
let row = rows(response)?.iter().find(|row| wire_id(row) == Some(sibling)).ok_or("missing original sibling")?;
|
||||
ensure(row["cpid"] == "0" && row["channel_order"].as_str().and_then(|v| v.parse().ok()) == Some(predecessor),
|
||||
"channel property readback disagreed with the observed root sibling chain")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exercise_order(core: &mut Core, name: &str, lobby: u64, generation: u64, own: u64) -> Result<()> {
|
||||
let first = core.snapshot["channels"].as_array().and_then(|rows| rows.iter().find(|row|row["parent_id"]==0 && row["order"]==0))
|
||||
.and_then(|row|row["id"].as_u64()).ok_or("missing first root sibling")?;
|
||||
let created = core.wire_call("channel_create", json!({"generation":generation,"parent_id":0,
|
||||
"properties":{"channel_name":name,"channel_order":0}}))?;
|
||||
let id=created["channel_id"].as_u64().filter(|id|*id!=0 && *id!=first).ok_or("missing temporary channel ID")?;
|
||||
core.wait_for("first sibling relinked", |s| snapshot_channel(s,id).is_some_and(|r|r["channel_type"]=="temporary" && r["name"]==name && r["order"]==0)
|
||||
&& snapshot_channel(s,first).is_some_and(|r|r["order"]==id))?;
|
||||
check_first_sibling(core,first,id)?;
|
||||
if own_channel(&core.snapshot,own)!=Some(id) {
|
||||
core.wire_call("join_channel",json!({"channel_id":id}))?;
|
||||
core.wait_for("own temporary channel joined",|s|own_channel(s,own)==Some(id))?;
|
||||
}
|
||||
core.wire_call("join_channel",json!({"channel_id":lobby}))?;
|
||||
core.wait_for("temporary sibling expired",|s|own_channel(s,own)==Some(lobby) && snapshot_channel(s,id).is_none()
|
||||
&& snapshot_channel(s,first).is_some_and(|r|r["order"]==0))?;
|
||||
check_first_sibling(core,first,0)?;
|
||||
println!("channel_list + channel_info: original sibling linked to new first channel, then restored on expiry");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn subscription_step(
|
||||
core: &mut Core, label: &str, target: Option<u64>, subscribe: bool,
|
||||
matches: impl Fn(&Value) -> bool,
|
||||
) -> Result<()> {
|
||||
let (cmd, args) = match target {
|
||||
Some(id) => ("channel_subscribe", json!({"channel_id": id, "subscribe": subscribe})),
|
||||
None => ("channel_subscribe_all", json!({"subscribe": subscribe})),
|
||||
};
|
||||
let before = core.snapshot["rev"].as_u64().ok_or("missing snapshot revision")?;
|
||||
// Cleanup may already be at the expected state. Test transitions are not.
|
||||
let already_matches = matches(&core.snapshot);
|
||||
match core.wire_request(cmd, args, CONTROL)? {
|
||||
Reply::Accepted(_) => core.wait_for(label, |s| {
|
||||
(already_matches || s["rev"].as_u64().is_some_and(|rev| rev > before)) && matches(s)
|
||||
}).map_err(|error| {
|
||||
let flags: Vec<_> = core.snapshot["channels"].as_array().into_iter().flatten()
|
||||
.filter_map(|row| Some((row["id"].as_u64()?, row["subscribed"].as_bool()?))).collect();
|
||||
format!("{error}; command acknowledged; snapshot revision {before} -> {}, channel subscription flags {flags:?}", core.snapshot["rev"])
|
||||
}),
|
||||
Reply::Refused(error) if permission_denied(&error) => {
|
||||
Err(format!("{label}: unverified (server permission refusal, TS {PERMISSION_DENIED})"))
|
||||
}
|
||||
Reply::Refused(error) => Err(rejection(label, &error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn exercise_subscriptions(core: &mut Core, name: &str, lobby: u64, generation: u64, own: u64) -> Result<()> {
|
||||
ensure(valid_parent(&core.snapshot, lobby), "subscription target must be the original permanent lobby")?;
|
||||
let lobby_name = snapshot_channel(&core.snapshot, lobby).and_then(|row| row["name"].as_str())
|
||||
.ok_or("original lobby name missing")?.to_owned();
|
||||
let list = core.call("channel_list", json!({}))?;
|
||||
let existing = rows(&list)?;
|
||||
ensure(existing.iter().any(|row| wire_id(row) == Some(lobby) && row["channel_name"] == lobby_name.as_str())
|
||||
&& existing.iter().all(|row| wire_id(row).is_some() && row["channel_name"] != name),
|
||||
"channel list did not verify the original lobby and unique temporary name")?;
|
||||
let created = core.wire_call("channel_create", json!({"generation": generation, "parent_id": 0,
|
||||
"properties": {"channel_name": name}}))?;
|
||||
let id = created["channel_id"].as_u64().filter(|id| *id != 0 && existing.iter().all(|row| wire_id(row) != Some(*id)))
|
||||
.ok_or("create did not return a new temporary channel ID")?;
|
||||
let same_session = |s: &Value| s["generation"].as_u64() == Some(generation);
|
||||
let temporary = |s: &Value| same_session(s) && snapshot_channel(s, id).is_some_and(|row| {
|
||||
row["channel_type"] == "temporary" && row["name"] == name && row["parent_id"] == 0
|
||||
});
|
||||
core.wait_for("generated temporary channel", temporary)?;
|
||||
if own_channel(&core.snapshot, own) != Some(id) {
|
||||
core.wire_call("join_channel", json!({"channel_id": id}))?;
|
||||
core.wait_for("enter generated temporary channel", |s| temporary(s) && own_channel(s, own) == Some(id))?;
|
||||
}
|
||||
// Let the connect-time subscribe-all and the move's book events settle
|
||||
// before taking the baseline. The local read drains queued snapshots.
|
||||
core.wait_wire_spacing();
|
||||
core.call("channel_list", json!({}))?;
|
||||
// The only client in the lobby at connect was us. Hold the temporary
|
||||
// channel open while probing the now non-own lobby. Do not edit the lobby.
|
||||
let in_scope = |s: &Value| temporary(s) && own_channel(s, own) == Some(id) && valid_parent(s, lobby)
|
||||
&& snapshot_channel(s, lobby).is_some_and(|row| row["name"] == lobby_name.as_str())
|
||||
&& s["clients"].as_array().is_some_and(|clients| clients.iter().all(|c| c["id"].as_u64() == Some(own)));
|
||||
ensure(in_scope(&core.snapshot), "subscription target was not the empty original lobby in the same session")?;
|
||||
let baseline: Vec<_> = core.snapshot["channels"].as_array().ok_or("missing snapshot channels")?.iter()
|
||||
.filter(|row| row["id"].as_u64() != Some(id))
|
||||
.map(|row| Ok((row["id"].as_u64().ok_or("missing channel ID")?,
|
||||
row["subscribed"].as_bool().ok_or("missing channel subscription state")?)))
|
||||
.collect::<Result<_>>()?;
|
||||
let lobby_subscribed = baseline.iter().find(|(cid, _)| *cid == lobby).map(|(_, subscribed)| *subscribed)
|
||||
.ok_or("subscription baseline did not include the original lobby")?;
|
||||
let matches = |s: &Value, target: Option<u64>, value: bool| in_scope(s)
|
||||
&& s["channels"].as_array().is_some_and(|channels| {
|
||||
// Compare the stable ordered channel list; disappearance or a new
|
||||
// channel makes this snapshot unsuitable as readback.
|
||||
let others = channels.iter().filter(|row| row["id"].as_u64() != Some(id));
|
||||
channels.len() == baseline.len() + 1 && others.zip(&baseline).all(|(row, &(cid, initial))| {
|
||||
let expected = if target.is_none_or(|target| target == cid) { value } else { initial };
|
||||
row["id"].as_u64() == Some(cid) && row["subscribed"].as_bool() == Some(expected)
|
||||
})
|
||||
});
|
||||
let mut automatic = true; // The disposable core sends subscribe-all on connect.
|
||||
let cases = (|| {
|
||||
// Leaving the initially occupied lobby can leave a false book flag even while
|
||||
// subscribe-all is active. Establish the starting server mode explicitly.
|
||||
if !lobby_subscribed {
|
||||
automatic = false;
|
||||
subscription_step(core, "establish unsubscribed lobby", None, false, |s| matches(s, None, false))?;
|
||||
for &(cid, subscribed) in &baseline {
|
||||
if subscribed {
|
||||
subscription_step(core, "restore other baseline subscription", Some(cid), true, |s| in_scope(s)
|
||||
&& snapshot_channel(s, cid).is_some_and(|row| row["subscribed"] == true))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
for subscribe in [!lobby_subscribed, lobby_subscribed] {
|
||||
let label = if subscribe { "channelsubscribe" } else { "channelunsubscribe" };
|
||||
let expected = |s: &Value| matches(s, Some(lobby), subscribe);
|
||||
ensure(in_scope(&core.snapshot) && !expected(&core.snapshot), "no valid single-channel transition to observe")?;
|
||||
subscription_step(core, label, Some(lobby), subscribe, expected)?;
|
||||
println!("{label}: original non-own lobby subscribed={subscribe} in a new snapshot");
|
||||
}
|
||||
if baseline.len() > 1 {
|
||||
println!("single-channel scope: {} other non-own channel(s) retained their initial flags", baseline.len() - 1);
|
||||
} else {
|
||||
println!("single-channel scope: isolation unverified (no second non-own channel)");
|
||||
}
|
||||
// Start with a direction that must change at least one visible channel.
|
||||
let first_all = !baseline.iter().any(|&(_, subscribed)| subscribed);
|
||||
for subscribe in [first_all, !first_all] {
|
||||
let label = if subscribe { "channelsubscribeall" } else { "channelunsubscribeall" };
|
||||
let expected = |s: &Value| matches(s, None, subscribe);
|
||||
ensure(in_scope(&core.snapshot) && !expected(&core.snapshot), "no valid all-channel transition to observe")?;
|
||||
automatic = subscribe;
|
||||
subscription_step(core, label, None, subscribe, expected)?;
|
||||
println!("{label}: subscribed={subscribe} for all {} observed non-own channel(s) in a new snapshot", baseline.len());
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let restore = (|| {
|
||||
if cases.is_err() && core.state == Some("connected") {
|
||||
core.wait_wire_spacing();
|
||||
core.call("channel_list", json!({}))?;
|
||||
}
|
||||
ensure(core.state == Some("connected") && in_scope(&core.snapshot), "cannot restore subscriptions: fixture scope changed")?;
|
||||
if !automatic {
|
||||
subscription_step(core, "restore automatic subscriptions", None, true, |s| matches(s, None, true))?;
|
||||
}
|
||||
for &(cid, initial) in &baseline {
|
||||
let expected = |s: &Value| in_scope(s) && snapshot_channel(s, cid).is_some_and(|row| row["subscribed"].as_bool() == Some(initial));
|
||||
if !expected(&core.snapshot) {
|
||||
subscription_step(core, "restore initial channel subscription", Some(cid), initial, expected)?;
|
||||
}
|
||||
}
|
||||
ensure(matches(&core.snapshot, Some(lobby), lobby_subscribed), "initial non-own subscriptions were not restored")?;
|
||||
println!("subscription cleanup: initial non-own flags restored");
|
||||
Ok(())
|
||||
})();
|
||||
let leave = (|| {
|
||||
ensure(core.state == Some("connected") && same_session(&core.snapshot) && valid_parent(&core.snapshot, lobby)
|
||||
&& snapshot_channel(&core.snapshot, lobby).is_some_and(|row| row["name"] == lobby_name.as_str()),
|
||||
"cannot return to the original lobby: fixture scope changed")?;
|
||||
core.wire_call("join_channel", json!({"channel_id": lobby}))?;
|
||||
core.wait_for("return to original lobby and observe temporary expiry", |s| {
|
||||
same_session(s) && own_channel(s, own) == Some(lobby) && snapshot_channel(s, id).is_none()
|
||||
})?;
|
||||
println!("temporary channel cleanup: ok (left channel; server expired it)");
|
||||
Ok(())
|
||||
})();
|
||||
combine(combine(cases, restore), leave)
|
||||
}
|
||||
|
||||
enum Scenario { ChannelAdmin, ChannelOrder, ChannelSubscriptions, DatabaseId, ClientInfo }
|
||||
|
||||
fn exercise_client_info(core: &mut Core, own: u64, uid: &str) -> Result<()> {
|
||||
let info = core.wire_call("client_info", json!({"client_id":own,"uid":uid}))?;
|
||||
let fields = rows(&info)?;
|
||||
ensure(!fields.is_empty() && fields.iter().all(|r| r["clid"].as_str().and_then(|v| v.parse::<u64>().ok()) == Some(own)),
|
||||
"client info did not return rows scoped to the own client")?;
|
||||
for key in ["client_version", "client_platform"] {
|
||||
ensure(fields.iter().any(|r| r[key].as_str().is_some_and(|v| !v.is_empty())), "client info missing version or platform")?;
|
||||
}
|
||||
match core.request("client_info", json!({"client_id":own,"uid":"different-fixture-identity"}), Instant::now()+CONTROL)? {
|
||||
Reply::Refused(error) if error["code"]=="target_changed" && error["ts_error"].is_null() => {},
|
||||
_ => return Err("mismatched client UID did not return local target_changed".into()),
|
||||
}
|
||||
println!("client_info: own client version and platform received; mismatched UID refused locally");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exercise_database_id(core: &mut Core, name: &str, uid: &str) -> Result<()> {
|
||||
let lookup = core.wire_call("client_database_id", json!({"uid":uid}))?;
|
||||
let [row] = rows(&lookup)? else { return Err("UID lookup did not return one row".into()) };
|
||||
ensure(row["cluid"].as_str() == Some(uid), "lookup returned a different UID")?;
|
||||
let dbid = row["cldbid"].as_str().and_then(|v| v.parse::<u64>().ok()).filter(|id| *id > 0)
|
||||
.ok_or("lookup did not return a positive database ID")?;
|
||||
println!("client_database_id: exact roster UID and positive database ID");
|
||||
let search = core.wire_call("client_database_find", json!({"pattern":name,"uid":false}))?;
|
||||
let [found] = rows(&search)? else { return Err("unique test nickname did not return one row".into()) };
|
||||
ensure(found["client_unique_identifier"].as_str() == Some(uid) && found["client_nickname"].as_str() == Some(name)
|
||||
&& found["cldbid"].as_str().and_then(|v|v.parse::<u64>().ok()) == Some(dbid), "nickname search disagreed with UID lookup")?;
|
||||
println!("client_database_find: nickname, UID and database ID agree");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exercise(core: &mut Core, name: &str, scenario: Scenario) -> Result<()> {
|
||||
let profile = core.call("profile_get", json!({}))?;
|
||||
ensure(profile["exists"] == false, "expected an empty disposable profile")?;
|
||||
core.call("profile_create", json!({"nickname": name}))?;
|
||||
let mute = core.call("set_audio", json!({"input_muted": true, "output_muted": true}))?;
|
||||
ensure(mute["input_muted"] == true && mute["output_muted"] == true, "both mutes must be active before connect")?;
|
||||
let connect = core.wire_request("connect", json!({"address": ENDPOINT}), CONNECT)?.require("connect")?;
|
||||
let own = connect["own_client_id"].as_u64().filter(|id| *id != 0).ok_or("connect did not return an own client ID")?;
|
||||
ensure(core.state == Some("connected"), "core did not reach connected state")?;
|
||||
// Connect can be acknowledged before the own client and channel enter the book.
|
||||
core.wait_for("initial channel and own-client roster", |s| own_channel(s, own).is_some())?;
|
||||
let snapshot = &core.snapshot;
|
||||
let generation = snapshot["generation"].as_u64().filter(|g| *g != 0).ok_or("connected snapshot has no generation")?;
|
||||
let lobby = own_channel(snapshot, own).ok_or("missing initial channel")?;
|
||||
let beta14 = snapshot["server"]["version"].as_str().is_some_and(|s| {
|
||||
s.starts_with("6.") && s.split(|c: char| !c.is_ascii_alphanumeric()).any(|part| part.eq_ignore_ascii_case("beta14"))
|
||||
});
|
||||
ensure(beta14, "loopback endpoint did not report TS6 beta14")?;
|
||||
ensure(snapshot_channel(snapshot, lobby).is_some_and(|c| c["is_default"] == true), "session did not start in the fixture's default channel")?;
|
||||
ensure(snapshot["clients"].as_array().is_some_and(|clients| {
|
||||
clients.len() == 1 && clients[0]["id"].as_u64() == Some(own)
|
||||
&& clients[0]["client_type"] == "normal" && clients[0]["input_muted"] == true && clients[0]["output_muted"] == true
|
||||
}), "connected snapshot did not show only the muted fixture client")?;
|
||||
println!("connect: ok (loopback beta14; disposable guest; both mutes active)");
|
||||
match scenario {
|
||||
Scenario::ClientInfo => {
|
||||
let uid = snapshot["clients"][0]["uid"].as_str().filter(|s|!s.is_empty()).ok_or("own roster UID missing")?.to_owned();
|
||||
return exercise_client_info(core, own, &uid);
|
||||
}
|
||||
Scenario::ChannelOrder => return exercise_order(core, name, lobby, generation, own),
|
||||
Scenario::ChannelSubscriptions => return exercise_subscriptions(core, name, lobby, generation, own),
|
||||
Scenario::DatabaseId => {
|
||||
let uid = snapshot["clients"][0]["uid"].as_str().filter(|s|!s.is_empty()).ok_or("own roster UID missing")?.to_owned();
|
||||
return exercise_database_id(core, name, &uid);
|
||||
}
|
||||
Scenario::ChannelAdmin => {}
|
||||
}
|
||||
|
||||
let server = core.wire_call("server_info", json!({}))?;
|
||||
let server_rows = rows(&server)?;
|
||||
ensure(server_rows.len() == 1 && server_rows[0].as_object().is_some_and(|row| !row.is_empty()),
|
||||
"server_info did not return observed server properties")?;
|
||||
println!("server_info: ok (read only)");
|
||||
|
||||
let list = core.call("channel_list", json!({}))?;
|
||||
let existing = rows(&list)?;
|
||||
ensure(existing.iter().any(|row| wire_id(row) == Some(lobby))
|
||||
&& existing.iter().all(|row| wire_id(row).is_some() && row["channel_name"].as_str() != Some(name)),
|
||||
"initial channel list cannot establish a unique writable target")?;
|
||||
println!("channel_list: ok (baseline read only)");
|
||||
|
||||
let create = core.wire_call("channel_create", json!({"generation": generation, "parent_id": 0, "properties": {
|
||||
"channel_name": name, "channel_topic": ORIGINAL_TOPIC, "channel_codec_quality": CODEC_QUALITY,
|
||||
}}))?;
|
||||
let id = create["channel_id"].as_u64().filter(|id| *id != 0 && existing.iter().all(|row| wire_id(row) != Some(*id)))
|
||||
.ok_or("create did not return a newly generated channel ID")?;
|
||||
let channel = RunChannel { id, name, generation };
|
||||
core.wait_for("temporary channel and own-client roster", |s| {
|
||||
snapshot_channel(s, id).is_some() && own_channel(s, own).is_some()
|
||||
})?;
|
||||
ensure(snapshot_channel(&core.snapshot, id).is_some_and(|c| c["channel_type"] == "temporary" && c["parent_id"] == 0
|
||||
&& c["name"].as_str() == Some(name)), "created channel was not the generated root temporary channel")?;
|
||||
if own_channel(&core.snapshot, own) != Some(id) {
|
||||
core.wire_call("join_channel", json!({"channel_id": id}))?;
|
||||
core.wait_for("enter generated channel", |s| own_channel(s, own) == Some(id))?;
|
||||
}
|
||||
let original = channel.info(core)?;
|
||||
check_topic("create", &original, ORIGINAL_TOPIC)?;
|
||||
check_quality("create", &core.snapshot, id, &original)?;
|
||||
println!("channel_create + channel_info: ok (own root temporary channel, topic and codec quality read back)");
|
||||
|
||||
channel.edit(core, generation, json!({"channel_topic": UPDATED_TOPIC}))?.require("sparse channel_edit")?;
|
||||
let edited = channel.wait_fields(core, &[("channel_topic", UPDATED_TOPIC)])?;
|
||||
core.wait_for("edited channel snapshot", |s| snapshot_channel(s, id).is_some_and(|c| c["topic"] == UPDATED_TOPIC))?;
|
||||
check_topic("sparse edit", &edited, UPDATED_TOPIC)?;
|
||||
check_quality("sparse edit", &core.snapshot, id, &edited)?;
|
||||
println!("sparse channel_edit: ok (topic changed; name and codec quality preserved)");
|
||||
|
||||
for (label, attempt, props, message, live_generation) in [
|
||||
("invalid codec quality", generation, json!({"channel_topic": "invalid quality marker", "channel_codec_quality": 11}),
|
||||
"channel_codec_quality must be an integer 0..=10", None),
|
||||
("stale generation", generation.checked_add(1).ok_or("connection generation exhausted")?,
|
||||
json!({"channel_topic": "stale generation marker"}), "connection changed; reload and confirm again", Some(generation)),
|
||||
] {
|
||||
// These two requests must be rejected locally without reaching the server.
|
||||
let args = channel.edit_args(core, attempt, props)?;
|
||||
check_local_refusal(core.request("channel_edit", args, Instant::now() + CONTROL)?, message, live_generation)
|
||||
.map_err(|err| format!("{label}: {err}"))?;
|
||||
let after = channel.listed(core, Instant::now() + CONTROL)?;
|
||||
ensure(after == edited, "rejected edit changed live channel properties")?;
|
||||
check_quality(label, &core.snapshot, id, &after)?;
|
||||
println!("{label}: rejected (local bad_request; properties unchanged)");
|
||||
}
|
||||
|
||||
let finite_clients = [("channel_maxclients", "3"), ("channel_flag_maxclients_unlimited", "0")];
|
||||
let unlimited_clients = [("channel_maxclients", "-1"), ("channel_flag_maxclients_unlimited", "1")];
|
||||
let (props, expected) = if edited["channel_flag_maxclients_unlimited"] == "0" {
|
||||
(json!({"channel_maxclients": -1, "channel_flag_maxclients_unlimited": true}), &unlimited_clients)
|
||||
} else {
|
||||
(json!({"channel_maxclients": 3, "channel_flag_maxclients_unlimited": false}), &finite_clients)
|
||||
};
|
||||
let max_clients = permission_probe(core, &channel, "maximum clients / unlimited flag", props, expected)?;
|
||||
let (family_limit, unlimited, wire_limit, wire_unlimited) = if edited["channel_flag_maxfamilyclients_unlimited"] == "0"
|
||||
&& edited["channel_flag_maxfamilyclients_inherited"] == "0" {
|
||||
(-1, true, "-1", "1")
|
||||
} else {
|
||||
(4, false, "4", "0")
|
||||
};
|
||||
let family = permission_probe(core, &channel, "family limit / unlimited flag",
|
||||
json!({"channel_maxfamilyclients": family_limit, "channel_flag_maxfamilyclients_unlimited": unlimited,
|
||||
"channel_flag_maxfamilyclients_inherited": false}),
|
||||
&[("channel_maxfamilyclients", wire_limit), ("channel_flag_maxfamilyclients_unlimited", wire_unlimited)])?;
|
||||
let written = max_clients.is_some() as usize + family.is_some() as usize;
|
||||
println!("limit flag cases: {written} written and read back, {} refused", 2 - written);
|
||||
if let Some(row) = family {
|
||||
report_inherited("root family inheritance disabled", &row, "0")?;
|
||||
probe_inherited(core, &channel, lobby)?;
|
||||
} else {
|
||||
println!("family inheritance: unverified (family-limit baseline refused)");
|
||||
}
|
||||
|
||||
// Join the original default as this same client; never edit it or issue a
|
||||
// delete verb. Only the generated temporary channel is expected to expire.
|
||||
core.wire_call("join_channel", json!({"channel_id": lobby}))?;
|
||||
core.wait_for("leave generated channel and observe its expiry", |s| {
|
||||
own_channel(s, own) == Some(lobby) && snapshot_channel(s, id).is_none()
|
||||
})?;
|
||||
println!("temporary channel cleanup: ok (left channel; server expired it)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let scenario = match (args.next(),args.next()) {
|
||||
(None,None)=>Scenario::ChannelAdmin,
|
||||
(Some(arg),None) if arg=="--channel-order"=>Scenario::ChannelOrder,
|
||||
(Some(arg),None) if arg=="--channel-subscriptions"=>Scenario::ChannelSubscriptions,
|
||||
(Some(arg),None) if arg=="--client-database-id"=>Scenario::DatabaseId,
|
||||
(Some(arg),None) if arg=="--client-info"=>Scenario::ClientInfo,
|
||||
_=>return Err("usage: channel_admin_qa [--channel-order | --channel-subscriptions | --client-database-id | --client-info]".into()),
|
||||
};
|
||||
let exe = std::env::var_os("TEAMSPEACH_QA_CORE").map(PathBuf::from)
|
||||
.filter(|path| path.is_absolute() && path.is_file() && path.file_name().and_then(|n| n.to_str())
|
||||
.is_some_and(|n| n.eq_ignore_ascii_case("teamspeach-core.exe")))
|
||||
.ok_or("set TEAMSPEACH_QA_CORE to the absolute path of a disposable teamspeach-core.exe")?;
|
||||
let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| "invalid system clock")?.as_nanos();
|
||||
let name = format!("PeachQA-{:x}-{stamp:x}", std::process::id());
|
||||
let root = std::env::temp_dir().join(&name);
|
||||
ensure(root.is_absolute(), "system temporary directory must be absolute")?;
|
||||
fs::create_dir(&root).map_err(|_| "could not create unique scratch directory")?;
|
||||
let result = (|| {
|
||||
let mut core = Core::start(&exe, &root)?;
|
||||
let cases = exercise(&mut core, &name, scenario);
|
||||
let cleanup = core.leave_and_close();
|
||||
combine(cases, cleanup)
|
||||
})();
|
||||
let profile = fs::remove_dir_all(&root).map_err(|_| "could not remove scratch profile".into());
|
||||
if profile.is_ok() {
|
||||
println!("scratch profile cleanup: ok");
|
||||
}
|
||||
combine(result, profile)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
eprintln!("channel admin QA failed: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+58
-279
@@ -24,10 +24,6 @@ pub mod extra;
|
||||
|
||||
/// Upper bound for rows collected for one list request.
|
||||
pub const MAX_ROWS: usize = 10_000;
|
||||
/// Maximum number of Unicode scalar values in a server or channel group name.
|
||||
pub const MAX_GROUP_NAME_CHARS: usize = 128;
|
||||
/// Inclusive limit for integer arguments shared with the reference command interface.
|
||||
pub const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
|
||||
const MAX_TEXT: usize = 8192;
|
||||
const MAX_SHORT: usize = 1024;
|
||||
|
||||
@@ -93,7 +89,7 @@ const CHANNEL_CREATE: &[(&str, Kind)] = &[
|
||||
("channel_codec_quality", Kind::Uint(10)),
|
||||
("channel_maxclients", Kind::Int(-1, i32::MAX as i64)),
|
||||
("channel_maxfamilyclients", Kind::Int(-1, i32::MAX as i64)),
|
||||
("channel_order", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("channel_order", Kind::Uint(u64::MAX)),
|
||||
("channel_codec_is_unencrypted", Kind::Bool),
|
||||
("channel_delete_delay", Kind::Uint(u32::MAX as u64)),
|
||||
("channel_flag_maxclients_unlimited", Kind::Bool),
|
||||
@@ -106,7 +102,7 @@ const CHANNEL_CREATE: &[(&str, Kind)] = &[
|
||||
];
|
||||
/// Fields of `channeledit` (`ChannelEdit` declaration, minus `cid`).
|
||||
const CHANNEL_EDIT: &[(&str, Kind)] = &[
|
||||
("channel_order", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("channel_order", Kind::Uint(u64::MAX)),
|
||||
("channel_name", CHANNEL_NAME),
|
||||
("channel_topic", Kind::Str(255)),
|
||||
("channel_flag_default", Kind::Bool),
|
||||
@@ -151,18 +147,18 @@ const SERVER_EDIT: &[(&str, Kind)] = &[
|
||||
("virtualserver_reserved_slots", Kind::Uint(u16::MAX as u64)),
|
||||
("virtualserver_hostbanner_mode", Kind::Uint(2)),
|
||||
("virtualserver_nickname", Kind::Str(MAX_SHORT)),
|
||||
("virtualserver_max_download_total_bandwidth", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("virtualserver_max_upload_total_bandwidth", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("virtualserver_download_quota", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("virtualserver_upload_quota", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("virtualserver_max_download_total_bandwidth", Kind::Uint(u64::MAX)),
|
||||
("virtualserver_max_upload_total_bandwidth", Kind::Uint(u64::MAX)),
|
||||
("virtualserver_download_quota", Kind::Uint(u64::MAX)),
|
||||
("virtualserver_upload_quota", Kind::Uint(u64::MAX)),
|
||||
("virtualserver_antiflood_points_tick_reduce", Kind::Uint(u32::MAX as u64)),
|
||||
("virtualserver_antiflood_points_needed_command_block", Kind::Uint(u32::MAX as u64)),
|
||||
("virtualserver_antiflood_points_needed_ip_block", Kind::Uint(u32::MAX as u64)),
|
||||
("virtualserver_codec_encryption_mode", Kind::Uint(2)),
|
||||
("virtualserver_needed_identity_security_level", Kind::Uint(u8::MAX as u64)),
|
||||
("virtualserver_default_server_group", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("virtualserver_default_channel_group", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("virtualserver_default_channel_admin_group", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("virtualserver_default_server_group", Kind::Uint(u64::MAX)),
|
||||
("virtualserver_default_channel_group", Kind::Uint(u64::MAX)),
|
||||
("virtualserver_default_channel_admin_group", Kind::Uint(u64::MAX)),
|
||||
("virtualserver_complain_autoban_count", Kind::Uint(u32::MAX as u64)),
|
||||
("virtualserver_complain_autoban_time", Kind::Uint(u32::MAX as u64)),
|
||||
("virtualserver_complain_remove_time", Kind::Uint(u32::MAX as u64)),
|
||||
@@ -357,18 +353,11 @@ fn check_opt(field: &str, value: &Option<String>, max: usize) -> Result<(), Erro
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn nonnegative(field: &str, v: u64) -> Result<(), ErrorObj> {
|
||||
if v > MAX_SAFE_INTEGER { Err(bad(format!("{field} exceeds the maximum safe integer"))) } else { Ok(()) }
|
||||
fn positive(field: &str, v: u64) -> Result<u64, ErrorObj> {
|
||||
if v == 0 { Err(bad(format!("{field} must be positive"))) } else { Ok(v) }
|
||||
}
|
||||
|
||||
fn positive(field: &str, v: u64) -> Result<(), ErrorObj> {
|
||||
if v == 0 { Err(bad(format!("{field} must be positive"))) } else { nonnegative(field, v) }
|
||||
}
|
||||
|
||||
pub(crate) fn generation(v: u64) -> Result<u64, ErrorObj> {
|
||||
if !(1..=MAX_SAFE_INTEGER).contains(&v) { return Err(bad("generation must be a positive safe integer")); }
|
||||
Ok(v)
|
||||
}
|
||||
fn generation(v: u64) -> Result<u64, ErrorObj> { positive("generation", v) }
|
||||
|
||||
/// Validates a property object against an allowlist and renders wire values.
|
||||
fn properties(value: Map<String, Value>, allowed: &[(&'static str, Kind)]) -> Result<Vec<(&'static str, String)>, ErrorObj> {
|
||||
@@ -453,11 +442,11 @@ struct GroupArgs { group_id: u64 }
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct AwayArgs { away: bool, #[serde(default, deserialize_with = "crate::protocol::present_string")] message: Option<String> }
|
||||
struct AwayArgs { away: bool, #[serde(default)] message: Option<String> }
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TalkRequestArgs { request: bool, #[serde(default, deserialize_with = "crate::protocol::present_string")] message: Option<String> }
|
||||
struct TalkRequestArgs { request: bool, #[serde(default)] message: Option<String> }
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -623,20 +612,14 @@ pub(crate) fn validate(command: &AdminCommand) -> Result<(), ErrorObj> {
|
||||
if let C::Extra(c) = command { return c.validate(); }
|
||||
if let Some(g) = command.generation() { generation(g)?; }
|
||||
match command {
|
||||
C::ChannelCreate { properties, parent_id, .. } => {
|
||||
properties.check_scope(PropertyScope::ChannelCreate)?;
|
||||
nonnegative("parent_id", *parent_id)?;
|
||||
}
|
||||
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, order, .. } => {
|
||||
nonnegative("parent_id", *parent_id)?;
|
||||
if let Some(order) = order { nonnegative("order", *order)?; }
|
||||
C::ChannelMove { channel_id, parent_id, .. } => {
|
||||
if parent_id == channel_id { return Err(bad("a channel cannot be its own parent")); }
|
||||
if order.as_ref() == Some(channel_id) { return Err(bad("a channel cannot precede itself")); }
|
||||
positive("channel_id", *channel_id)?;
|
||||
}
|
||||
C::ChannelDelete { channel_id, .. } | C::ChannelSubscribe { channel_id, .. }
|
||||
@@ -670,7 +653,6 @@ pub(crate) fn validate(command: &AdminCommand) -> Result<(), ErrorObj> {
|
||||
}
|
||||
C::PrivilegeKeyDelete { token, .. } | C::PrivilegeKeyUse { token, .. } => check_str("token", token, 255, false)?,
|
||||
C::TempPasswordAdd { password, description, duration_s, channel_id, channel_password, .. } => {
|
||||
nonnegative("channel_id", *channel_id)?;
|
||||
check_str("password", password, 255, false)?;
|
||||
check_str("description", description, 255, true)?;
|
||||
check_str("channel_password", channel_password, 255, true)?;
|
||||
@@ -687,62 +669,21 @@ pub(crate) fn validate(command: &AdminCommand) -> Result<(), ErrorObj> {
|
||||
|
||||
// ------------------------------------------------------------ replies
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ClientInfoReply {
|
||||
pub(crate) client_id: u16,
|
||||
uid: String,
|
||||
rows: Result<Vec<Row>, ErrorObj>,
|
||||
}
|
||||
|
||||
impl ClientInfoReply {
|
||||
pub(crate) fn new(client_id: u16, uid: String) -> Self {
|
||||
Self { client_id, uid, rows: Ok(Vec::new()) }
|
||||
}
|
||||
|
||||
fn collect(&mut self, raw: &RawNotification) {
|
||||
let Ok(rows) = &mut self.rows else { return };
|
||||
for row in &raw.items {
|
||||
if row.get("clid").and_then(|v| v.parse::<u16>().ok()) != Some(self.client_id) { continue; }
|
||||
if row.get("client_unique_identifier").is_some_and(|uid| uid != &self.uid) {
|
||||
self.rows = Err(Self::target_changed());
|
||||
return;
|
||||
}
|
||||
if rows.len() >= MAX_ROWS {
|
||||
self.rows = Err(ErrorObj::new(ErrorCode::ServerError, "client information exceeds the row limit"));
|
||||
return;
|
||||
}
|
||||
rows.push(row.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn target_changed() -> ErrorObj { ErrorObj::new(ErrorCode::TargetChanged, "client identity changed; reopen information") }
|
||||
|
||||
pub(crate) fn finish(self, current_uid: Option<&str>) -> Result<Value, ErrorObj> {
|
||||
if current_uid != Some(self.uid.as_str()) { return Err(Self::target_changed()); }
|
||||
let rows = self.rows?;
|
||||
if rows.is_empty() { return Err(ErrorObj::new(ErrorCode::ServerError,"The server returned no information for the requested client")); }
|
||||
Ok(json!({"rows": rows}))
|
||||
}
|
||||
}
|
||||
|
||||
/// How the answer to an admin command is assembled.
|
||||
#[derive(Debug)]
|
||||
pub enum Reply {
|
||||
Ack,
|
||||
/// Rows without an explicit scope inherit the last scope in this reply.
|
||||
/// Rows of `notify` collected until the command result; `key` filters rows by the first
|
||||
/// entry's id (list notifications carry it there only).
|
||||
Rows { notify: &'static str, key: Option<(&'static str, String)>, rows: Vec<Row>, overflow: bool, accept: bool },
|
||||
/// Only an unambiguous creation by our client under the requested parent identifies the new channel.
|
||||
Created { name: String, parent: u64, invoker: u16, channel_id: Option<u64>, ambiguous: bool },
|
||||
/// `channelcreate`: the id comes from our own `notifychannelcreated` with that name.
|
||||
Created { name: String, invoker: u16, channel_id: Option<u64> },
|
||||
/// `tokenadd`: the key comes from `notifytokenadd`.
|
||||
Token { token: Option<String>, ambiguous: bool },
|
||||
GroupCreated { notify: &'static str, key: &'static str, name: String, group_type: u8, existing: std::collections::HashSet<u64>, group_id: Option<u64>, ambiguous: bool },
|
||||
Token { token: Option<String> },
|
||||
GroupCreated { notify: &'static str, key: &'static str, name: String, group_id: Option<u64>, ambiguous: bool },
|
||||
/// `channelgetdescription`: the description comes from `notifychanneledited`.
|
||||
Description { channel_id: u64, description: Option<String> },
|
||||
ChannelInfo { channel_id: u64 },
|
||||
/// Keep the pending notification slot until the command result arrives.
|
||||
ChannelReadDeleted,
|
||||
ClientInfo(ClientInfoReply),
|
||||
DatabaseId { uid: String, id: Option<u64>, ambiguous: bool },
|
||||
/// `permissionlist` refresh before answering `admin_context`.
|
||||
Context,
|
||||
}
|
||||
@@ -758,9 +699,7 @@ impl Reply {
|
||||
Reply::Rows { notify, .. } => Some(notify),
|
||||
Reply::Token { .. } => Some("notifytokenadd"),
|
||||
Reply::GroupCreated { notify, .. } => Some(notify),
|
||||
Reply::DatabaseId { .. } => Some("notifyclientdbidfromuid"),
|
||||
Reply::ClientInfo(_) => Some("notifyclientupdated"),
|
||||
Reply::ChannelInfo { .. } | Reply::Description { .. } | Reply::ChannelReadDeleted => Some("notifychanneledited"),
|
||||
Reply::ChannelInfo { .. } | Reply::Description { .. } => Some("notifychanneledited"),
|
||||
Reply::Created { .. } => Some("notifychannelcreated"),
|
||||
_ => None,
|
||||
}
|
||||
@@ -769,66 +708,47 @@ impl Reply {
|
||||
/// Feed a tapped notification.
|
||||
pub fn collect(&mut self, raw: &RawNotification) {
|
||||
match self {
|
||||
Reply::Description { channel_id, .. } | Reply::ChannelInfo { channel_id }
|
||||
if raw.name == "notifychanneldeleted" && raw.items.iter().any(|row| row.get("cid").and_then(|id| id.parse::<u64>().ok()) == Some(*channel_id)) => {
|
||||
*self = Reply::ChannelReadDeleted;
|
||||
}
|
||||
Reply::ClientInfo(info) if raw.name == "notifyclientupdated" => info.collect(raw),
|
||||
Reply::Rows { notify, key, rows, overflow, accept } if *notify == raw.name => {
|
||||
for row in &raw.items {
|
||||
if let Some((k, v)) = key {
|
||||
if let Some(id) = row.get(*k) { *accept = id == v; }
|
||||
if !*accept { continue; }
|
||||
// A continuation without the id belongs to the previous accepted notification.
|
||||
if let Some((k, v)) = key {
|
||||
match raw.items.first().and_then(|i| i.get(*k)) {
|
||||
Some(id) => *accept = id == v,
|
||||
None => {}
|
||||
}
|
||||
} else {
|
||||
*accept = true;
|
||||
}
|
||||
if !*accept { return; }
|
||||
for row in &raw.items {
|
||||
if rows.len() >= MAX_ROWS { *overflow = true; return; }
|
||||
rows.push(row.clone());
|
||||
}
|
||||
}
|
||||
Reply::Created { name, parent, invoker, channel_id, ambiguous } if raw.name == "notifychannelcreated" => {
|
||||
Reply::Created { name, invoker, channel_id } if raw.name == "notifychannelcreated" && channel_id.is_none() => {
|
||||
for row in &raw.items {
|
||||
let mine = row.get("invokerid").and_then(|v| v.parse::<u16>().ok()) == Some(*invoker);
|
||||
if mine && row.get("channel_name") == Some(name) && row.get("cpid").and_then(|v| v.parse::<u64>().ok()) == Some(*parent) {
|
||||
if let Some(id) = row.get("cid").and_then(|v| v.parse::<u64>().ok()).filter(|id| *id != 0) {
|
||||
if channel_id.is_some_and(|old| old != id) { *ambiguous = true; }
|
||||
*channel_id = Some(id);
|
||||
}
|
||||
if mine && row.get("channel_name").map(String::as_str) == Some(name.as_str()) {
|
||||
*channel_id = row.get("cid").and_then(|v| v.parse().ok());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reply::GroupCreated { notify, key, name, group_type, existing, group_id, ambiguous } if *notify == raw.name => {
|
||||
Reply::GroupCreated { notify, key, name, group_id, ambiguous } if *notify == raw.name => {
|
||||
for row in &raw.items {
|
||||
if row.get("name") == Some(name) && row.get("type").and_then(|v| v.parse::<u8>().ok()) == Some(*group_type) {
|
||||
if let Some(id) = row.get(*key).and_then(|v| v.parse::<u64>().ok()).filter(|id| *id != 0 && !existing.contains(id)) {
|
||||
if row.get("name") == Some(name) {
|
||||
if let Some(id) = row.get(*key).and_then(|v| v.parse::<u64>().ok()) {
|
||||
if group_id.is_some_and(|old| old != id) { *ambiguous = true; }
|
||||
*group_id = Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Reply::DatabaseId { uid, id, ambiguous } if raw.name == "notifyclientdbidfromuid" => {
|
||||
for row in &raw.items {
|
||||
if row.get("cluid") != Some(uid) { continue; }
|
||||
if let Some(found) = row.get("cldbid").and_then(|s| s.parse::<u64>().ok()).filter(|n| *n > 0) {
|
||||
if id.is_some_and(|previous| previous != found) { *ambiguous = true; }
|
||||
*id = Some(found);
|
||||
}
|
||||
}
|
||||
Reply::Token { token } if raw.name == "notifytokenadd" => {
|
||||
*token = raw.items.first().and_then(|i| i.get("token")).cloned();
|
||||
}
|
||||
Reply::Token { token, ambiguous } if raw.name == "notifytokenadd" && !*ambiguous => {
|
||||
for value in raw.items.iter().filter_map(|row| row.get("token")) {
|
||||
if value.trim().is_empty() || value.chars().count() > 255 || value.chars().any(char::is_control) { continue; }
|
||||
match token {
|
||||
Some(previous) if previous != value => { *ambiguous = true; break; }
|
||||
None => *token = Some(value.clone()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reply::Description { channel_id, description } if matches!(raw.name.as_str(), "notifychanneledited" | "notifychanneldescriptionchanged") => {
|
||||
Reply::Description { channel_id, description } if raw.name == "notifychanneledited" => {
|
||||
for row in &raw.items {
|
||||
if row.get("cid").and_then(|v| v.parse::<u64>().ok()) == Some(*channel_id) {
|
||||
if raw.name == "notifychanneldescriptionchanged" { *description = None; }
|
||||
else if let Some(d) = row.get("channel_description") { *description = Some(d.clone()); }
|
||||
if let Some(d) = row.get("channel_description") { *description = Some(d.clone()); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -851,18 +771,14 @@ pub fn finish(reply: Reply) -> Result<Value, ErrorObj> {
|
||||
format!("the server returned more than {MAX_ROWS} rows; the list is not complete"),
|
||||
)),
|
||||
Reply::Rows { rows, .. } => Ok(json!({ "rows": rows })),
|
||||
Reply::DatabaseId { uid, id: Some(id), ambiguous: false } => Ok(json!({"rows":[{"cluid":uid,"cldbid":id.to_string()}]})),
|
||||
Reply::DatabaseId { .. } => Err(ErrorObj::new(ErrorCode::ServerError, "server did not return a unique database ID for the requested UID")),
|
||||
Reply::GroupCreated { group_id: Some(id), ambiguous: false, .. } => Ok(json!({ "group_id": id })),
|
||||
Reply::GroupCreated { .. } => Err(ErrorObj::new(ErrorCode::ServerError, "group was accepted but its ID was not uniquely returned; reload groups before continuing").with_detail(json!({"created": true}))),
|
||||
Reply::ChannelInfo { .. } | Reply::ClientInfo(_) => Err(ErrorObj::new(ErrorCode::Internal, "target information is answered by the session")),
|
||||
Reply::ChannelReadDeleted => Err(ErrorObj::new(ErrorCode::TargetChanged, "channel was deleted while its properties were being read")),
|
||||
Reply::Created { channel_id: Some(id), ambiguous: false, .. } => Ok(json!({ "channel_id": id })),
|
||||
Reply::Created { .. } => Err(ErrorObj::new(ErrorCode::ServerError, "channel was accepted but its ID was not uniquely returned; reload channels before continuing").with_detail(json!({"created": true}))),
|
||||
Reply::Token { token: Some(token), ambiguous: false } => Ok(json!({ "token": token })),
|
||||
Reply::Token { .. } => Err(ErrorObj::new(
|
||||
Reply::ChannelInfo { .. } => Err(ErrorObj::new(ErrorCode::Internal, "channel info is answered by the session")),
|
||||
Reply::Created { channel_id, .. } => Ok(json!({ "channel_id": channel_id })),
|
||||
Reply::Token { token: Some(token) } => Ok(json!({ "token": token })),
|
||||
Reply::Token { token: None } => Err(ErrorObj::new(
|
||||
ErrorCode::ServerError,
|
||||
"the server accepted the privilege key but did not return one unique key; reload the list",
|
||||
"the server accepted the privilege key but did not send it; reload the list",
|
||||
)
|
||||
.with_detail(json!({ "created": true }))),
|
||||
Reply::Description { description, .. } => Ok(json!({ "description": description })),
|
||||
@@ -877,7 +793,6 @@ pub struct Live<'a> {
|
||||
pub own_client: u16,
|
||||
pub server_uid: &'a str,
|
||||
pub channel: &'a dyn Fn(u64) -> Option<String>,
|
||||
pub group_ids: &'a dyn Fn(extra::GroupKind) -> std::collections::HashSet<u64>,
|
||||
}
|
||||
|
||||
/// Checks the destructive-action confirmation against the live target.
|
||||
@@ -906,7 +821,7 @@ pub fn build(cmd: &AdminCommand, live: &Live) -> Result<(OutCommand, Reply), Err
|
||||
let mut a = vec![("cpid", s(*parent_id))];
|
||||
a.extend(properties.iter().map(|(k, v)| (*k, v.clone())));
|
||||
let name = properties.iter().find(|(k, _)| *k == "channel_name").map(|(_, v)| v.clone()).unwrap_or_default();
|
||||
(menu::command("channelcreate", &a), Reply::Created { name, parent: *parent_id, invoker: live.own_client, channel_id: None, ambiguous: false })
|
||||
(menu::command("channelcreate", &a), Reply::Created { name, invoker: live.own_client, channel_id: None })
|
||||
}
|
||||
C::ChannelEdit { channel_id, properties, .. } => {
|
||||
channel_exists(live, *channel_id, "channel")?;
|
||||
@@ -970,7 +885,7 @@ pub fn build(cmd: &AdminCommand, live: &Live) -> Result<(OutCommand, Reply), Err
|
||||
if *channel_id != 0 { channel_exists(live, *channel_id, "channel")?; }
|
||||
let kind = match kind { PrivilegeKeyKind::ServerGroup => "0", PrivilegeKeyKind::ChannelGroup => "1" };
|
||||
let a = [("tokentype", kind.into()), ("tokenid1", s(*group_id)), ("tokenid2", s(*channel_id)), ("tokendescription", description.clone())];
|
||||
(menu::command("tokenadd", &a), Reply::Token { token: None, ambiguous: false })
|
||||
(menu::command("tokenadd", &a), Reply::Token { token: None })
|
||||
}
|
||||
C::PrivilegeKeyDelete { token, confirm: c, .. } => {
|
||||
confirm(c, token)?;
|
||||
@@ -1050,7 +965,6 @@ mod tests {
|
||||
fn direct_admin_and_permission_arguments_reject_invalid_values() {
|
||||
use extra::{Command as E, GroupKind, Permission};
|
||||
let invalid = [
|
||||
AdminCommand::ChannelMove { generation: 1, channel_id: 9, parent_id: 0, order: Some(9) },
|
||||
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)) },
|
||||
@@ -1078,72 +992,7 @@ mod tests {
|
||||
fn content(cmd: OutCommand) -> String { String::from_utf8(cmd.into_packet().content().to_vec()).unwrap() }
|
||||
|
||||
fn live<'a>(channel: &'a dyn Fn(u64) -> Option<String>) -> Live<'a> {
|
||||
Live { own_client: 7, server_uid: "srv=", channel, group_ids: &|_| Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_info_checks_identity_at_ack_even_when_updates_omit_uid() {
|
||||
let mut missing = ClientInfoReply::new(7, "original=".into());
|
||||
missing.collect(&crate::rawcmd::parse(b"notifyclientupdated clid=8 client_version=other").unwrap());
|
||||
assert_eq!(missing.finish(Some("original=")).unwrap_err().code, ErrorCode::ServerError);
|
||||
let collect = |extra: Option<&[u8]>| {
|
||||
let mut r = Reply::ClientInfo(ClientInfoReply::new(7, "original=".into()));
|
||||
r.collect(&crate::rawcmd::parse(b"notifyclientupdated clid=8 client_version=other|clid=7 client_version=test|client_platform=unscoped").unwrap());
|
||||
if let Some(packet) = extra { r.collect(&crate::rawcmd::parse(packet).unwrap()); }
|
||||
let Reply::ClientInfo(r) = r else { unreachable!() }; r
|
||||
};
|
||||
assert_eq!(collect(None).finish(Some("original=")).unwrap(), json!({"rows":[{"clid":"7","client_version":"test"}]}));
|
||||
for uid in [None, Some("replacement=")] {
|
||||
assert_eq!(collect(None).finish(uid).unwrap_err().code, ErrorCode::TargetChanged);
|
||||
}
|
||||
assert_eq!(collect(Some(b"notifyclientupdated clid=7 client_unique_identifier=replacement=")).finish(Some("original=")).unwrap_err().code, ErrorCode::TargetChanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn database_id_lookup_requires_the_requested_uid_and_one_positive_id() {
|
||||
let cmd = parse_json("client_database_id", json!({"uid":"peer/one="})).unwrap();
|
||||
let lookup = |packets: &[&[u8]]| {
|
||||
let (_, mut reply) = build(&cmd, &live(&|_| None)).unwrap();
|
||||
for packet in packets { reply.collect(&crate::rawcmd::parse(packet).unwrap()); }
|
||||
finish(reply)
|
||||
};
|
||||
let foreign = br"notifyclientdbidfromuid cluid=other cldbid=9|cldbid=10".as_slice();
|
||||
let zero = br"notifyclientdbidfromuid cluid=peer\/one= cldbid=0".as_slice();
|
||||
let found = br"notifyclientdbidfromuid cluid=other cldbid=9|cluid=peer\/one= cldbid=17|cldbid=23".as_slice();
|
||||
let conflict = br"notifyclientdbidfromuid cluid=peer\/one= cldbid=18".as_slice();
|
||||
assert_eq!(lookup(&[foreign,zero]).unwrap_err().code, ErrorCode::ServerError);
|
||||
assert_eq!(lookup(&[found,foreign,found]).unwrap(), json!({"rows":[{"cluid":"peer/one=","cldbid":"17"}]}));
|
||||
assert_eq!(lookup(&[found,conflict]).unwrap_err().code, ErrorCode::ServerError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_add_requires_a_unique_new_id_of_the_requested_type() {
|
||||
use extra::GroupKind;
|
||||
let group_ids = |kind| match kind {
|
||||
GroupKind::Server => [4].into_iter().collect(),
|
||||
GroupKind::Channel => [9].into_iter().collect(),
|
||||
};
|
||||
let state = Live { group_ids: &group_ids, ..live(&|_| None) };
|
||||
for (kind, notify, key, old) in [("server", "notifyservergrouplist", "sgid", 4), ("channel", "notifychannelgrouplist", "cgid", 9)] {
|
||||
let cmd = parse_json("group_add", json!({"generation":1,"kind":kind,"name":"Operators","type":1})).unwrap();
|
||||
let begin = || build(&cmd, &state).unwrap().1;
|
||||
let collect = |r: &mut Reply, id: u64, ty: u8| {
|
||||
let packet = format!("{notify} {key}={id} type={ty} name=Operators");
|
||||
r.collect(&crate::rawcmd::parse(packet.as_bytes()).unwrap());
|
||||
};
|
||||
let mut missing = begin();
|
||||
collect(&mut missing, old, 1); collect(&mut missing, 0, 1); collect(&mut missing, 31, 0);
|
||||
let error = finish(missing).unwrap_err();
|
||||
assert_eq!(error.code, ErrorCode::ServerError);
|
||||
assert_eq!(error.detail, Some(json!({"created":true})));
|
||||
let mut unique = begin();
|
||||
collect(&mut unique, old, 1); collect(&mut unique, 31, 0);
|
||||
collect(&mut unique, 32, 1); collect(&mut unique, 32, 1);
|
||||
assert_eq!(finish(unique).unwrap(), json!({"group_id":32}));
|
||||
let mut ambiguous = begin();
|
||||
collect(&mut ambiguous, 32, 1); collect(&mut ambiguous, 33, 1);
|
||||
assert_eq!(finish(ambiguous).unwrap_err().detail, Some(json!({"created":true})));
|
||||
}
|
||||
Live { own_client: 7, server_uid: "srv=", channel }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1219,7 +1068,7 @@ mod tests {
|
||||
assert!(text.starts_with("channelcreate cpid=0 "), "{text}");
|
||||
assert!(text.contains(&format!("channel_password={}", encode_password(b"secret").replace('/', "\\/"))), "{text}");
|
||||
assert!(text.contains("channel_flag_password=1") && text.contains("channel_flag_permanent=1") && text.contains("channel_codec_quality=10"));
|
||||
assert!(matches!(reply, Reply::Created { ref name, parent: 0, invoker: 7, channel_id: None, .. } if name == "Lobby"));
|
||||
assert!(matches!(reply, Reply::Created { ref name, invoker: 7, channel_id: None } if name == "Lobby"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1304,49 +1153,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_channel_description_ignores_other_channels_and_drops_invalidated_text() {
|
||||
let reply = || Reply::Description { channel_id: 8, description: None };
|
||||
let collect = |r: &mut Reply, bytes: &[u8]| r.collect(&crate::rawcmd::parse(bytes).unwrap());
|
||||
let mut r = reply();
|
||||
collect(&mut r, b"notifychanneledited cid=8 channel_description=Old");
|
||||
collect(&mut r, b"notifychanneldescriptionchanged cid=9");
|
||||
collect(&mut r, b"notifychanneldeleted cid=9");
|
||||
assert_eq!(finish(r).unwrap(), json!({"description":"Old"}));
|
||||
let mut r = reply();
|
||||
collect(&mut r, b"notifychanneledited cid=8 channel_description=Old");
|
||||
collect(&mut r, b"notifychanneldescriptionchanged cid=8");
|
||||
collect(&mut r, b"notifychanneledited cid=9 channel_description=Other");
|
||||
assert_eq!(finish(r).unwrap(), json!({"description":null}));
|
||||
let mut r = reply();
|
||||
collect(&mut r, b"notifychanneledited cid=8 channel_description");
|
||||
assert_eq!(finish(r).unwrap(), json!({"description":""}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_channel_reads_reject_reused_ids_after_deletion() {
|
||||
for mut reply in [Reply::Description { channel_id: 8, description: Some("Old".into()) }, Reply::ChannelInfo { channel_id: 8 }] {
|
||||
for packet in ["notifychanneldeleted cid=9|cid=8", "notifychannelcreated cid=8 channel_name=New", "notifychanneledited cid=8 channel_description=Replacement"] {
|
||||
reply.collect(&crate::rawcmd::parse(packet.as_bytes()).unwrap());
|
||||
}
|
||||
assert_eq!(reply.notification(), Some("notifychanneledited"));
|
||||
assert_eq!(finish(reply).unwrap_err().code, ErrorCode::TargetChanged);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permission_rows_follow_each_explicit_scope_across_packet_boundaries() {
|
||||
let mut reply = Reply::rows("notifyservergrouppermlist", Some(("sgid", 6)));
|
||||
for packet in [
|
||||
"notifyservergrouppermlist permid=1|sgid=7 permid=2|sgid=6 permid=3|permid=4|sgid=7 permid=5",
|
||||
"notifyservergrouppermlist permid=6|sgid=6 permid=7",
|
||||
"notifyservergrouppermlist permid=8",
|
||||
] { reply.collect(&crate::rawcmd::parse(packet.as_bytes()).unwrap()); }
|
||||
let value = finish(reply).unwrap();
|
||||
let ids: Vec<_> = value["rows"].as_array().unwrap().iter().map(|row| row["permid"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, ["3", "4", "7", "8"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replies_collect_only_their_rows() {
|
||||
let mut r = Reply::rows("notifyservergrouppermlist", Some(("sgid", 6)));
|
||||
@@ -1356,41 +1162,14 @@ mod tests {
|
||||
let rows = finish(r).unwrap();
|
||||
assert_eq!(rows["rows"].as_array().unwrap().len(), 3);
|
||||
|
||||
let created = || Reply::Created { name: "A b".into(), parent: 0, invoker: 7, channel_id: None, ambiguous: false };
|
||||
let mut c = created();
|
||||
let mut c = Reply::Created { name: "A b".into(), invoker: 7, channel_id: None };
|
||||
c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=11 cpid=0 channel_name=A\sb invokerid=8").unwrap());
|
||||
c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=10 cpid=3 channel_name=A\sb invokerid=7").unwrap());
|
||||
c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=0 cpid=0 channel_name=A\sb invokerid=7").unwrap());
|
||||
assert_eq!(finish(c).unwrap_err().code, ErrorCode::ServerError);
|
||||
let own = crate::rawcmd::parse(br"notifychannelcreated cid=12 cpid=0 channel_name=A\sb invokerid=7").unwrap();
|
||||
let mut c = created();
|
||||
c.collect(&own);
|
||||
c.collect(&own);
|
||||
c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=12 cpid=0 channel_name=A\sb invokerid=7").unwrap());
|
||||
assert_eq!(finish(c).unwrap(), json!({"channel_id": 12}));
|
||||
let mut c = created();
|
||||
c.collect(&own);
|
||||
c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=13 cpid=0 channel_name=A\sb invokerid=7").unwrap());
|
||||
assert_eq!(finish(c).unwrap_err().code, ErrorCode::ServerError);
|
||||
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_add_requires_one_distinct_usable_key() {
|
||||
let result = |packets: &[&[u8]]| {
|
||||
let mut reply = Reply::Token { token: None, ambiguous: false };
|
||||
for packet in packets { reply.collect(&crate::rawcmd::parse(packet).unwrap()); }
|
||||
finish(reply)
|
||||
};
|
||||
let empty = br"notifytokenadd token".as_slice();
|
||||
let one = br"notifytokenadd token|token=sample".as_slice();
|
||||
let other = br"notifytokenadd token=different".as_slice();
|
||||
assert_eq!(result(&[empty]).unwrap_err().detail, Some(json!({"created":true})));
|
||||
assert_eq!(result(&[one, empty, one]).unwrap(), json!({"token":"sample"}));
|
||||
for error in [result(&[one,other,one]), result(&[br"notifytokenadd token=sample|token=different"])] {
|
||||
let error = error.unwrap_err();
|
||||
assert_eq!(error.code, ErrorCode::ServerError);
|
||||
assert_eq!(error.detail, Some(json!({"created":true})));
|
||||
assert!(!error.message.contains("sample") && !error.message.contains("different"));
|
||||
}
|
||||
assert!(finish(Reply::Token { token: None }).is_err(), "no fake success without the key");
|
||||
let mut t = Reply::Token { token: None };
|
||||
t.collect(&crate::rawcmd::parse(br"notifytokenadd token=abc").unwrap());
|
||||
assert_eq!(finish(t).unwrap(), json!({"token": "abc"}));
|
||||
}
|
||||
}
|
||||
+12
-14
@@ -56,28 +56,26 @@ impl Command {
|
||||
|Self::GroupDelete{generation,..}|Self::GroupDeletePermissions{generation,..}|Self::ChannelDeletePermissions{generation,..}=>Some(*generation), _=>None,
|
||||
}}
|
||||
pub(super) fn validate(&self) -> Result<(),ErrorObj> {
|
||||
let positive=|id:u64| super::positive("target ID",id);
|
||||
if let Some(g)=self.generation(){super::generation(g)?;}
|
||||
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)?;}
|
||||
match self {
|
||||
Self::ServerLog{lines,begin_pos,..}=>{
|
||||
if !(1..=1000).contains(lines){return Err(menu::bad("lines must be 1..1000"));}
|
||||
super::nonnegative("begin_pos",*begin_pos)?;
|
||||
},
|
||||
Self::ServerLog{lines,..} if !(1..=1000).contains(lines)=>return Err(menu::bad("lines must be 1..1000")),
|
||||
Self::ClientDatabaseList{duration,..} if !(1..=200).contains(duration)=>return Err(menu::bad("duration must be 1..200")),
|
||||
Self::ClientDatabaseFind{pattern,..}=>super::check_str("pattern",pattern,255,false)?,
|
||||
Self::ClientDatabaseId{uid}=>super::check_str("uid",uid,128,false)?,
|
||||
Self::ClientDatabaseFind{pattern,..}=>text(pattern,255)?,
|
||||
Self::ClientDatabaseId{uid}=>text(uid,128)?,
|
||||
Self::ClientDatabaseDelete{client_database_id,confirm,..}=>{positive(*client_database_id)?;if confirm!=&client_database_id.to_string(){return Err(menu::bad("confirmation does not match the database ID"));}},
|
||||
Self::GroupAdd{name,group_type,..}=>{super::check_str("name",name,super::MAX_GROUP_NAME_CHARS,false)?;if *group_type>2{return Err(menu::bad("type must be 0..2"));}},
|
||||
Self::GroupRename{group_id,name,..}=>{positive(*group_id)?;super::check_str("name",name,super::MAX_GROUP_NAME_CHARS,false)?;},
|
||||
Self::GroupAdd{name,group_type,..}=>{text(name,128)?;if *group_type>2{return Err(menu::bad("type must be 0..2"));}},
|
||||
Self::GroupRename{group_id,name,..}=>{positive(*group_id)?;text(name,128)?;},
|
||||
Self::GroupSetPermissions{group_id,permissions,kind,..}=>{positive(*group_id)?;validate_permissions(permissions,*kind==GroupKind::Server)?;},
|
||||
Self::ChannelSetPermissions{channel_id,permissions,..}=>{positive(*channel_id)?;validate_permissions(permissions,false)?;},
|
||||
Self::GroupDelete{group_id,confirm,..}=>{positive(*group_id)?;if confirm!=&group_id.to_string(){return Err(menu::bad("confirmation does not match the group ID"));}},
|
||||
Self::GroupDeletePermissions{group_id,permissions,..}=>{positive(*group_id)?;validate_permission_ids(permissions)?;},
|
||||
Self::ChannelDeletePermissions{channel_id,permissions,..}=>{positive(*channel_id)?;validate_permission_ids(permissions)?;},
|
||||
Self::ChannelInfo{channel_id}=>positive(*channel_id)?,
|
||||
Self::ClientInfo{client_id,uid}=>{positive(u64::from(*client_id))?;super::check_str("uid",uid,128,false)?;},
|
||||
Self::ClientInfo{client_id,uid}=>{positive(u64::from(*client_id))?;text(uid,128)?;},
|
||||
Self::ServerGroupAddClient{group_id,client_database_id,..}=>{positive(*group_id)?;positive(*client_database_id)?;},
|
||||
Self::ServerGroupMemberAddUid{group_id,uid,..}=>{positive(*group_id)?;super::check_str("uid",uid,128,false)?;},
|
||||
Self::ServerGroupMemberAddUid{group_id,uid,..}=>{positive(*group_id)?;text(uid,128)?;},
|
||||
_=>{},
|
||||
} Ok(())
|
||||
}
|
||||
@@ -88,12 +86,12 @@ impl Command {
|
||||
Self::ClientDatabaseList{start,duration}=>(menu::command("clientdblist",&[("start",start.to_string()),("duration",duration.to_string())]),Reply::rows("notifyclientdblist",None)),
|
||||
Self::ClientDatabaseFind{pattern,uid}=>{let mut c=menu::command("clientdbfind",&[("pattern",pattern.clone()),("-details",String::new())]);if *uid{c.write_arg("-uid",&"");}(c,Reply::rows("notifyclientdbfind",None))},
|
||||
Self::ClientDatabaseDelete{client_database_id,..}=>(menu::command("clientdbdelete",&[("cldbid",s(*client_database_id))]),Reply::Ack),
|
||||
Self::ClientDatabaseId{uid}=>(menu::command("clientgetdbidfromuid",&[("cluid",uid.clone())]),Reply::DatabaseId{uid:uid.clone(),id:None,ambiguous:false}),
|
||||
Self::ClientDatabaseId{uid}=>(menu::command("clientgetdbidfromuid",&[("cluid",uid.clone())]),Reply::rows("notifyclientdbidfromuid",None)),
|
||||
Self::ServerGroupList{}=>(menu::command("servergrouplist",&[]),Reply::rows("notifyservergrouplist",None)),
|
||||
Self::ChannelGroupList{}=>(menu::command("channelgrouplist",&[]),Reply::rows("notifychannelgrouplist",None)),
|
||||
Self::GroupAdd{kind,name,group_type,..}=>{
|
||||
let (verb,notify,key)=group_names(*kind,"add");
|
||||
(menu::command(verb,&[("name",name.clone()),("type",group_type.to_string())]),Reply::GroupCreated{notify,key,name:name.clone(),group_type:*group_type,existing:(live.group_ids)(*kind),group_id:None,ambiguous:false})
|
||||
(menu::command(verb,&[("name",name.clone()),("type",group_type.to_string())]),Reply::GroupCreated{notify,key,name:name.clone(),group_id:None,ambiguous:false})
|
||||
},
|
||||
Self::GroupRename{kind,group_id,name,..}=>{let(verb,_,key)=group_names(*kind,"rename");(menu::command(verb,&[(key,s(*group_id)),("name",name.clone())]),Reply::Ack)},
|
||||
Self::GroupSetPermissions{kind,group_id,permissions,..}=>{let(verb,_,key)=group_names(*kind,"perm");(permission_command(verb,key,*group_id,permissions,*kind==GroupKind::Server),Reply::Ack)},
|
||||
|
||||
+6
-128
@@ -1,105 +1,6 @@
|
||||
//! Session integration of server/channel administration (`admin.rs`, `docs/bridge.md` §4.6).
|
||||
use super::*;
|
||||
|
||||
fn check_predecessor(
|
||||
channel: Option<u64>, parent: u64, order: Option<u64>,
|
||||
position_of: impl Fn(u64) -> Option<(u64, u64)>,
|
||||
) -> Result<(), ErrorObj> {
|
||||
if let Some(after) = order.filter(|id| *id != 0) {
|
||||
if Some(after) == channel || position_of(after).map(|p| p.0) != Some(parent) {
|
||||
return Err(ErrorObj::new(ErrorCode::TargetChanged, "preceding channel is no longer a sibling; reload the channel tree"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn move_changes_position(
|
||||
moving: u64, parent: u64, order: Option<u64>, channel_count: usize,
|
||||
position_of: impl Fn(u64) -> Option<(u64, u64)>,
|
||||
) -> Result<bool, ErrorObj> {
|
||||
let (old_parent, old_order) = position_of(moving)
|
||||
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "channel is no longer visible"))?;
|
||||
check_predecessor(Some(moving), parent, order, &position_of)?;
|
||||
let mut ancestor = parent;
|
||||
// Even an inconsistent book with a parent cycle must finish without a network write.
|
||||
for _ in 0..channel_count {
|
||||
if ancestor == 0 { break; }
|
||||
if ancestor == moving { break; }
|
||||
let Some((next, _)) = position_of(ancestor) else { break };
|
||||
ancestor = next;
|
||||
}
|
||||
if ancestor == 0 { Ok(parent != old_parent || order != Some(old_order)) } else {
|
||||
Err(ErrorObj::new(ErrorCode::TargetChanged, "destination is no longer a valid parent; reopen the move dialog"))
|
||||
}
|
||||
}
|
||||
|
||||
fn check_property_position(cmd: &admin::AdminCommand, position_of: impl Fn(u64) -> Option<(u64, u64)>) -> Result<(), ErrorObj> {
|
||||
let (channel, parent, properties) = match cmd {
|
||||
admin::AdminCommand::ChannelCreate { parent_id, properties, .. } => (None, Some(*parent_id), properties),
|
||||
admin::AdminCommand::ChannelEdit { channel_id, properties, .. } => (Some(*channel_id), None, properties),
|
||||
_ => return Ok(()),
|
||||
};
|
||||
let Some((_, order)) = properties.iter().find(|(key, _)| *key == "channel_order") else { return Ok(()) };
|
||||
let order = order.parse::<u64>().map_err(|_| ErrorObj::new(ErrorCode::BadRequest, "invalid channel_order"))?;
|
||||
if order == 0 { return Ok(()) }
|
||||
let parent = parent.or_else(|| channel.and_then(&position_of).map(|p| p.0))
|
||||
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "channel is no longer visible"))?;
|
||||
check_predecessor(channel, parent, Some(order), position_of)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod move_tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[test]
|
||||
fn channel_property_order_rechecks_current_siblings() {
|
||||
use admin::{AdminCommand, Properties};
|
||||
let commands = |order: Option<u64>| {
|
||||
let mut fields = serde_json::Map::from_iter([("channel_name".into(), json!("Example"))]);
|
||||
if let Some(order) = order { fields.insert("channel_order".into(), json!(order)); }
|
||||
[AdminCommand::ChannelCreate { generation: 1, parent_id: 8, properties: Properties::channel_create(fields.clone()).unwrap() },
|
||||
AdminCommand::ChannelEdit { generation: 1, channel_id: 42, properties: Properties::channel_edit(fields).unwrap() }]
|
||||
};
|
||||
let mut tree = HashMap::from([(8, (0, 0)), (42, (8, 0)), (13, (8, 42))]);
|
||||
let ordered = commands(Some(13));
|
||||
for cmd in &ordered { check_property_position(cmd, |id| tree.get(&id).copied()).unwrap(); }
|
||||
for next in [Some((0, 8)), None] {
|
||||
if let Some(pos) = next { tree.insert(13, pos); } else { tree.remove(&13); }
|
||||
for cmd in &ordered {
|
||||
assert_eq!(check_property_position(cmd, |id| tree.get(&id).copied()).unwrap_err().code, ErrorCode::TargetChanged);
|
||||
}
|
||||
}
|
||||
let [create, edit] = commands(Some(42));
|
||||
check_property_position(&create, |id| tree.get(&id).copied()).unwrap();
|
||||
assert_eq!(check_property_position(&edit, |id| tree.get(&id).copied()).unwrap_err().code, ErrorCode::TargetChanged);
|
||||
for cmd in commands(None).into_iter().chain(commands(Some(0))) {
|
||||
check_property_position(&cmd, |_| panic!("no predecessor to look up")).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_move_rechecks_parent_and_predecessor_at_dispatch() {
|
||||
let mut parents = HashMap::from([(42, 0), (8, 0), (13, 8), (99, 42)]);
|
||||
let check = |parents: &HashMap<u64,u64>, parent, order| {
|
||||
move_changes_position(42, parent, order, parents.len(), |id| parents.get(&id).copied().map(|p| (p, 0)))
|
||||
};
|
||||
assert!(check(&parents, 8, Some(13)).unwrap());
|
||||
assert!(check(&parents, 8, Some(0)).unwrap());
|
||||
assert!(check(&parents, 0, None).unwrap());
|
||||
assert!(!check(&parents, 0, Some(0)).unwrap());
|
||||
parents.insert(13, 0);
|
||||
assert_eq!(check(&parents, 8, Some(13)).unwrap_err().code, ErrorCode::TargetChanged);
|
||||
check(&parents, 0, Some(13)).unwrap();
|
||||
parents.remove(&13);
|
||||
assert_eq!(check(&parents, 0, Some(13)).unwrap_err().code, ErrorCode::TargetChanged);
|
||||
parents.insert(8, 99);
|
||||
assert_eq!(check(&parents, 8, Some(0)).unwrap_err().code, ErrorCode::TargetChanged);
|
||||
parents.insert(99, 8);
|
||||
assert_eq!(check(&parents, 8, None).unwrap_err().code, ErrorCode::TargetChanged);
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub(super) async fn admin(&mut self, id: &str, cmd: admin::AdminCommand) -> Result<Option<Value>, ErrorObj> {
|
||||
let c = self.connected_conn()?;
|
||||
@@ -110,25 +11,15 @@ impl Session {
|
||||
}
|
||||
}
|
||||
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
|
||||
let position_of = |id| book.channels.get(&ChannelId(id)).map(|ch| (ch.parent.0, ch.order.0));
|
||||
if let admin::AdminCommand::ChannelMove { channel_id, parent_id, order, .. } = &cmd {
|
||||
let changes = move_changes_position(*channel_id, *parent_id, *order, book.channels.len(), position_of)?;
|
||||
if !changes { return Ok(Some(json!({"changed": false}))); }
|
||||
} else {
|
||||
check_property_position(&cmd, position_of)?;
|
||||
}
|
||||
let (command, reply) = match &cmd {
|
||||
admin::AdminCommand::Context => (menu::command("permissionlist", &[]), admin::Reply::Context),
|
||||
admin::AdminCommand::Extra(admin::extra::Command::ChannelList {}) => {
|
||||
let rows: Vec<_> = snapshot::ordered_channels(&book.channels).into_iter()
|
||||
.filter_map(|(id, _)| {
|
||||
let channel = book.channels.get(&id)?;
|
||||
c.extras.channel_properties(id, channel.parent, channel.order)
|
||||
}).collect();
|
||||
.filter_map(|(id, _)| c.extras.channel_properties(id.0).cloned()).collect();
|
||||
if rows.len() != book.channels.len() {
|
||||
return Err(ErrorObj::new(ErrorCode::ServerError, "channel properties are incomplete; wait for the server channel list"));
|
||||
}
|
||||
return Ok(Some(Value::from_iter([("rows", Value::Array(rows))])));
|
||||
return Ok(Some(json!({ "rows": rows })));
|
||||
}
|
||||
admin::AdminCommand::Extra(admin::extra::Command::ChannelInfo { channel_id }) => {
|
||||
if !book.channels.contains_key(&ChannelId(*channel_id)) {
|
||||
@@ -140,7 +31,7 @@ impl Session {
|
||||
if book.clients.get(&ClientId(*client_id)).and_then(|client| client.uid.as_ref()).is_none_or(|current| current.to_string() != *uid) {
|
||||
return Err(ErrorObj::new(ErrorCode::TargetChanged, "client identity changed; reopen information"));
|
||||
}
|
||||
(menu::command("clientgetvariables", &[("clid", client_id.to_string())]), admin::Reply::ClientInfo(admin::ClientInfoReply::new(*client_id, uid.clone())))
|
||||
(menu::command("clientgetvariables", &[("clid", client_id.to_string())]), admin::Reply::rows("notifyclientupdated", Some(("clid", u64::from(*client_id)))))
|
||||
}
|
||||
admin::AdminCommand::TalkPower { target, grant, .. } => {
|
||||
let client = book
|
||||
@@ -155,11 +46,7 @@ impl Session {
|
||||
other => {
|
||||
let server_uid = book.server.public_key.get_uid();
|
||||
let channel = |cid: u64| book.channels.get(&ChannelId(cid)).map(|ch| ch.name.clone());
|
||||
let group_ids = |kind| match kind {
|
||||
admin::extra::GroupKind::Server => book.server_groups.keys().map(|id| id.0).collect(),
|
||||
admin::extra::GroupKind::Channel => book.channel_groups.keys().map(|id| id.0).collect(),
|
||||
};
|
||||
let live = admin::Live { own_client: book.own_client.0, server_uid: &server_uid, channel: &channel, group_ids: &group_ids };
|
||||
let live = admin::Live { own_client: book.own_client.0, server_uid: &server_uid, channel: &channel };
|
||||
admin::build(other, &live)?
|
||||
}
|
||||
};
|
||||
@@ -181,23 +68,14 @@ impl Session {
|
||||
};
|
||||
let answer = match (reply, res) {
|
||||
(admin::Reply::Context, res) => self.admin_context(res),
|
||||
(admin::Reply::ClientInfo(info), Ok(())) => {
|
||||
let current_uid = self.conn.as_ref().and_then(|c| c.con.get_state().ok())
|
||||
.and_then(|book| book.clients.get(&ClientId(info.client_id)))
|
||||
.and_then(|client| client.uid.as_ref()).map(|uid| uid.to_string());
|
||||
info.finish(current_uid.as_deref())
|
||||
}
|
||||
(admin::Reply::ChannelInfo { channel_id }, Ok(())) => {
|
||||
self.conn.as_ref().and_then(|c| {
|
||||
let channel = c.con.get_state().ok()?.channels.get(&ChannelId(channel_id))?;
|
||||
c.extras.channel_properties(channel.id, channel.parent, channel.order)
|
||||
}).map(|row| Value::from_iter([("rows", Value::Array(vec![row]))]))
|
||||
self.conn.as_ref().and_then(|c| c.extras.channel_properties(channel_id))
|
||||
.map(|row| json!({ "rows": [row] }))
|
||||
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "channel disappeared before its properties were read"))
|
||||
}
|
||||
(admin::Reply::Rows { notify: "notifyserverupdated", overflow: false, .. }, Ok(())) => {
|
||||
self.conn.as_ref().map(|c| json!({ "rows": [c.extras.server_properties()] })).ok_or_else(not_connected)
|
||||
}
|
||||
(admin::Reply::DatabaseId { .. }, Err(e)) if e.error.to_u32() == Some(admin::DATABASE_EMPTY_RESULT) => Ok(json!({ "rows": [] })),
|
||||
(admin::Reply::Rows { .. }, Err(e)) if empty(&e) => Ok(json!({ "rows": [] })),
|
||||
(_, Err(e)) => Err(command_error(&e)),
|
||||
(reply, Ok(())) => admin::finish(reply),
|
||||
|
||||
+24
-83
@@ -390,14 +390,12 @@ impl Receiver {
|
||||
if !deny {
|
||||
return Vec::new();
|
||||
}
|
||||
self.whisperers.clear();
|
||||
let mut removed = Vec::new();
|
||||
self.handler.get_mut_queues().retain(|id, queue| {
|
||||
if !queue.has_pending_whisper() { return true; }
|
||||
removed.push(id.0);
|
||||
self.dsp.remove(id.0);
|
||||
false
|
||||
});
|
||||
let removed: Vec<u16> = self.whisperers.drain().collect();
|
||||
let queues = self.handler.get_mut_queues();
|
||||
for id in &removed {
|
||||
queues.remove(&ClientId(*id));
|
||||
self.dsp.remove(*id);
|
||||
}
|
||||
self.whisper_starts.clear();
|
||||
removed
|
||||
}
|
||||
@@ -423,13 +421,6 @@ impl Receiver {
|
||||
RxEvent::None
|
||||
};
|
||||
}
|
||||
let started = match self.handler.handle_packet(ClientId(from), packet) {
|
||||
Ok(started) => started,
|
||||
Err(error) => {
|
||||
debug!(%error, client = from, "audio packet not queued");
|
||||
return RxEvent::None;
|
||||
}
|
||||
};
|
||||
if whisper && !end {
|
||||
if self.whisperers.insert(from) {
|
||||
self.whisper_starts.push(from);
|
||||
@@ -438,7 +429,15 @@ impl Receiver {
|
||||
// An empty whisper packet ends the whisper spurt; ordinary voice ends whispering.
|
||||
self.whisperers.remove(&from);
|
||||
}
|
||||
started.map_or(RxEvent::None, |id| RxEvent::Started(id.0))
|
||||
match self.handler.handle_packet(ClientId(from), packet) {
|
||||
Ok(Some(id)) => RxEvent::Started(id.0),
|
||||
Ok(None) => RxEvent::None,
|
||||
Err(error) => {
|
||||
// Late, duplicate or overflowing packets are normal jitter-buffer outcomes.
|
||||
debug!(%error, client = from, "audio packet not queued");
|
||||
RxEvent::None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull 20 ms from every speaker's jitter buffer, apply local gains, and mix to mono.
|
||||
@@ -538,30 +537,6 @@ mod tests {
|
||||
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_packets_cannot_start_or_interrupt_a_whisper_spurt() {
|
||||
let mut rx = Receiver::new();
|
||||
let mut encoder = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
|
||||
let packet = encoder.encode(&sine(&mut 0.0, 440.0)).unwrap();
|
||||
let data = &packet.content()[3..];
|
||||
let forward = |id, whisper| {
|
||||
let audio = if whisper { AudioData::S2CWhisper { id, from: 7, codec: CodecType::OpusVoice, data } }
|
||||
else { AudioData::S2C { id, from: 7, codec: CodecType::OpusVoice, data } };
|
||||
InAudioBuf::try_new(Direction::S2C, OutAudio::new(&audio).into_vec()).unwrap()
|
||||
};
|
||||
rx.handle_packet(forward(1, false));
|
||||
rx.handle_packet(forward(1, true));
|
||||
assert_eq!(rx.take_whisper_starts().next(), None);
|
||||
rx.handle_packet(forward(2, true));
|
||||
assert!(rx.take_whisper_starts().eq([7]));
|
||||
rx.handle_packet(forward(2, false));
|
||||
rx.handle_packet(forward(3, true));
|
||||
assert_eq!(rx.take_whisper_starts().next(), None);
|
||||
rx.handle_packet(forward(4, false));
|
||||
rx.handle_packet(forward(5, true));
|
||||
assert!(rx.take_whisper_starts().eq([7]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_whisper_codec_routes_and_incoming_block() {
|
||||
use crate::whisper::{Route, Whisper};
|
||||
@@ -607,30 +582,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denying_whispers_after_end_marker_purges_audio_without_muting_ordinary_speakers() {
|
||||
let mut rx = Receiver::new();
|
||||
let mut encoder = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
|
||||
let packet = encoder.encode(&sine(&mut 0.0, 440.0)).unwrap();
|
||||
let payload = &packet.content()[3..];
|
||||
let forward = |audio| InAudioBuf::try_new(Direction::S2C, OutAudio::new(&audio).into_vec()).unwrap();
|
||||
for id in 0..6 {
|
||||
rx.handle_packet(forward(AudioData::S2CWhisper { id, from: 7, codec: CodecType::OpusVoice, data: payload }));
|
||||
rx.handle_packet(forward(AudioData::S2C { id, from: 8, codec: CodecType::OpusVoice, data: payload }));
|
||||
}
|
||||
rx.handle_packet(forward(AudioData::S2CWhisper { id: 6, from: 7, codec: CodecType::OpusVoice, data: &[] }));
|
||||
assert_eq!(rx.set_deny_whispers(true), [7]);
|
||||
let mut out = [0; FRAME_SAMPLES];
|
||||
let mut heard = false;
|
||||
for _ in 0..12 {
|
||||
let mix = rx.mix(&mut out, |_| 1.0);
|
||||
assert!(!mix.speakers.contains(&7));
|
||||
heard |= mix.speakers.contains(&8) && out.iter().any(|s| s.unsigned_abs() > 500);
|
||||
}
|
||||
assert!(heard, "ordinary queued speech must remain audible");
|
||||
assert!(matches!(rx.handle_packet(forward(AudioData::S2C { id: 7, from: 7, codec: CodecType::OpusVoice, data: payload })), RxEvent::Started(7)));
|
||||
}
|
||||
|
||||
/// Offline real encoder/receiver proof for PCM captured by audit-voice-timed.mjs.
|
||||
/// Explicit opt-in: no device, socket or playback is opened by this test.
|
||||
#[test]
|
||||
@@ -1023,26 +974,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_codecs_neither_select_an_encoder_nor_enter_the_mix() {
|
||||
fn reset_rearms_unsupported_codec_report() {
|
||||
let mut rx = Receiver::new();
|
||||
for (channel, wire) in [
|
||||
(Codec::SpeexNarrowband, CodecType::SpeexNarrowband),
|
||||
(Codec::SpeexWideband, CodecType::SpeexWideband),
|
||||
(Codec::SpeexUltrawideband, CodecType::SpeexUltrawideband),
|
||||
(Codec::CeltMono, CodecType::CeltMono),
|
||||
] {
|
||||
assert_eq!(TxCodec::for_channel(channel), None);
|
||||
let packet = || {
|
||||
let out = OutAudio::new(&AudioData::S2C { id: 1, from: 9, codec: wire, data: &[1, 2, 3] });
|
||||
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
|
||||
};
|
||||
assert!(matches!(rx.handle_packet(packet()), RxEvent::Unsupported { client_id: 9, codec } if codec == wire));
|
||||
assert!(matches!(rx.handle_packet(packet()), RxEvent::None));
|
||||
let mut pcm = [i16::MAX; FRAME_SAMPLES];
|
||||
assert!(rx.mix(&mut pcm, |_| 1.).speakers.is_empty());
|
||||
assert_eq!(pcm, [0; FRAME_SAMPLES]);
|
||||
rx.reset();
|
||||
}
|
||||
let speex = || {
|
||||
let out = OutAudio::new(&AudioData::S2C { id: 1, from: 9, codec: CodecType::SpeexWideband, data: &[1, 2, 3] });
|
||||
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
|
||||
};
|
||||
assert!(matches!(rx.handle_packet(speex()), RxEvent::Unsupported { client_id: 9, .. }));
|
||||
assert!(matches!(rx.handle_packet(speex()), RxEvent::None));
|
||||
rx.reset();
|
||||
assert!(matches!(rx.handle_packet(speex()), RxEvent::Unsupported { client_id: 9, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+1
-16
@@ -99,7 +99,7 @@ pub fn from_raw(raw: &RawNotification, extras: &RawExtras, own_client: Option<u1
|
||||
"notifyclientmoved" => {
|
||||
let Some(clid) = num(row, "clid") else { continue };
|
||||
let (mut v, last) = client("client_move", clid);
|
||||
v["from_channel_id"] = json!(num::<u64>(row, "cfid").filter(|c| *c != 0).or(last));
|
||||
v["from_channel_id"] = json!(last);
|
||||
v["to_channel_id"] = json!(num::<u64>(row, "ctid"));
|
||||
out.push(v);
|
||||
}
|
||||
@@ -165,21 +165,6 @@ mod tests {
|
||||
assert_eq!(ev[0]["to_channel_id"], Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batched_client_moves_keep_each_origin_and_shared_destination() {
|
||||
let mut extras = RawExtras::default();
|
||||
extras.apply(&parse(b"notifycliententerview ctid=5 clid=1|clid=2|clid=3 ctid=8").unwrap());
|
||||
let moved = parse(b"notifyclientmoved ctid=9 reasonid=1 clid=2|clid=3|clid=4 cfid=7").unwrap();
|
||||
let events = from_raw(&moved, &extras, None);
|
||||
assert_eq!(events.len(), 3);
|
||||
for (event, (client, from)) in events.iter().zip([(2, 5), (3, 8), (4, 7)]) {
|
||||
assert_eq!(event["client_id"], client);
|
||||
assert_eq!(event["from_channel_id"], from);
|
||||
assert_eq!(event["to_channel_id"], 9);
|
||||
assert_eq!(event["reason"], "moved");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_and_talk_events() {
|
||||
let mut x = RawExtras::default();
|
||||
|
||||
+77
-306
@@ -1,4 +1,4 @@
|
||||
//! Channel file browser over classic TeamSpeak storage and S3 storage.
|
||||
//! Channel file browser over the legacy TeamSpeak file transfer protocol.
|
||||
//!
|
||||
//! Commands: `ftgetfilelist`, `ftcreatedir`, `ftrenamefile`, `ftdeletefile`, `ftinitdownload`,
|
||||
//! `ftinitupload`, `ftstop`. Listing rows and transfer grants arrive as raw notifications
|
||||
@@ -23,8 +23,8 @@
|
||||
//! continued while its length and modification time are unchanged. On the server side only a size
|
||||
//! change is observable; the legacy protocol has no content identity.
|
||||
//!
|
||||
//! Servers advertising `s3` support browsing and HTTPS uploads/downloads for ordinary channels;
|
||||
//! mutations of the directory tree, legacy pause/resume and HTTPFT remain unsupported.
|
||||
//! The TeamSpeak 6 `HTTPFT` and `s3` storage branches are not implemented: servers that advertise
|
||||
//! them in `virtualserver_capability_extensions` are reported, never silently treated as legacy.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fs::{File, OpenOptions};
|
||||
@@ -43,10 +43,7 @@ use tokio::sync::{mpsc, watch};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use crate::protocol::{ErrorCode, ErrorObj};
|
||||
use crate::rawcmd::{RawNotification, S3FileList};
|
||||
|
||||
pub(crate) mod s3;
|
||||
pub(crate) mod s3_http;
|
||||
use crate::rawcmd::RawNotification;
|
||||
|
||||
/// Longest remote path accepted (characters).
|
||||
pub const MAX_PATH_CHARS: usize = 512;
|
||||
@@ -221,11 +218,6 @@ pub struct RateLimit {
|
||||
next: tokio::sync::Mutex<Option<tokio::time::Instant>>,
|
||||
}
|
||||
impl RateLimit {
|
||||
/// Pace an S3 I/O chunk using at most one second of the current rate allowance.
|
||||
fn s3_chunk_len(&self, max: usize) -> usize {
|
||||
let rate = self.bytes_per_second.load(Ordering::Acquire);
|
||||
if rate == 0 { max } else { (max as u64).min(rate) as usize }
|
||||
}
|
||||
pub fn set(&self, bytes: u64) { self.bytes_per_second.store(bytes, Ordering::Release); }
|
||||
pub async fn acquire(&self, bytes: usize) {
|
||||
let mut next = self.next.lock().await;
|
||||
@@ -243,10 +235,7 @@ fn args<T: serde::de::DeserializeOwned>(raw: Option<&RawValue>) -> Result<T, Err
|
||||
}
|
||||
|
||||
fn channel(id: u64) -> Result<u64, ErrorObj> {
|
||||
if !(1..=9_007_199_254_740_991).contains(&id) {
|
||||
return Err(bad("channel_id must be a positive safe integer"));
|
||||
}
|
||||
Ok(id)
|
||||
if id == 0 { Err(bad("channel_id must be a channel (not 0)")) } else { Ok(id) }
|
||||
}
|
||||
|
||||
fn check_password(p: &str) -> Result<(), ErrorObj> {
|
||||
@@ -266,7 +255,7 @@ fn check_host_path(field: &str, path: &Path) -> Result<(), ErrorObj> {
|
||||
// Channel zero is reserved for the virtual server's icons (main-owned snapshots and icon manager),
|
||||
// never the renderer's file browser. Only canonical `/icons/icon_<nonzero u32>` names are accepted.
|
||||
fn transfer_channel(id: u64, path: &str) -> Result<u64, ErrorObj> {
|
||||
if id != 0 { return channel(id); }
|
||||
if id != 0 { return Ok(id); }
|
||||
let icon = path.strip_prefix("/icons/icon_").unwrap_or("");
|
||||
if icon.parse::<u32>().is_ok_and(|n| n != 0 && n.to_string() == icon) {
|
||||
Ok(0)
|
||||
@@ -365,10 +354,7 @@ pub(crate) fn validate(request: &mut Request) -> Result<(), ErrorObj> {
|
||||
check_password(password)?; check_host_path("source", source)?;
|
||||
}
|
||||
Request::FetchImage { channel_id, path } => { channel(*channel_id)?; check_remote_item(path)?; }
|
||||
Request::Cancel { transfer_id } | Request::Pause { transfer_id } | Request::Resume { transfer_id } => {
|
||||
if *transfer_id == 0 { return Err(bad("transfer_id must be positive")); }
|
||||
}
|
||||
Request::Transfers => {}
|
||||
Request::Cancel { .. } | Request::Pause { .. } | Request::Resume { .. } | Request::Transfers => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -471,58 +457,19 @@ pub fn local_component(name: &str) -> Result<(), ErrorObj> {
|
||||
|
||||
// ------------------------------------------------------------------ listing
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ListBackend { Legacy, S3 }
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ListData {
|
||||
Legacy { entries: Vec<Value>, malformed: usize, overflow: bool, finished: bool },
|
||||
S3(Option<Result<(Vec<Value>, usize), ErrorObj>>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ListJob {
|
||||
pub req: String,
|
||||
pub channel_id: u64,
|
||||
pub path: String,
|
||||
data: ListData,
|
||||
pub entries: Vec<Value>,
|
||||
pub malformed: usize,
|
||||
pub overflow: bool,
|
||||
pub finished: bool,
|
||||
pub result_ok: bool,
|
||||
pub started: Instant,
|
||||
}
|
||||
|
||||
impl ListJob {
|
||||
pub(crate) fn new(req: &str, channel_id: u64, path: String, backend: ListBackend) -> Self {
|
||||
let data = match backend {
|
||||
ListBackend::Legacy => ListData::Legacy { entries: Vec::new(), malformed: 0, overflow: false, finished: false },
|
||||
ListBackend::S3 => ListData::S3(None),
|
||||
};
|
||||
Self { req: req.into(), channel_id, path, data, result_ok: false, started: Instant::now() }
|
||||
}
|
||||
|
||||
pub(crate) fn backend(&self) -> ListBackend {
|
||||
match self.data {
|
||||
ListData::Legacy { .. } => ListBackend::Legacy,
|
||||
ListData::S3(_) => ListBackend::S3,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn acknowledge(&mut self) -> bool {
|
||||
self.result_ok = true;
|
||||
match &self.data {
|
||||
ListData::Legacy { finished, .. } => *finished,
|
||||
ListData::S3(result) => result.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish_legacy(&mut self) -> bool {
|
||||
let ListData::Legacy { finished, .. } = &mut self.data else { return false; };
|
||||
*finished = true;
|
||||
self.result_ok
|
||||
}
|
||||
|
||||
fn accepts_legacy_rows(&self) -> bool { matches!(self.data, ListData::Legacy { finished: false, .. }) }
|
||||
}
|
||||
|
||||
/// Value of `key` in entry `i`; TeamSpeak sends arguments common to all entries only once.
|
||||
fn field<'a>(items: &'a [BTreeMap<String, String>], i: usize, key: &str) -> Option<&'a str> {
|
||||
items[i].get(key).or_else(|| items[0].get(key)).map(String::as_str)
|
||||
@@ -669,12 +616,6 @@ pub enum Stage {
|
||||
/// Halted by the user, a lowered concurrency limit or a server interruption; `file_resume`
|
||||
/// continues it.
|
||||
Paused,
|
||||
/// A TeamSpeak S3 command is awaiting its correlated grant and ACK.
|
||||
S3Init { handle: u16, since: Instant },
|
||||
/// A signed HTTP request is streaming; there is no legacy ftid or pause/resume.
|
||||
S3Running { task: StreamTask },
|
||||
/// Storage accepted the PUT; TeamSpeak must acknowledge the upload notification.
|
||||
S3Confirming { handle: u16, since: Instant },
|
||||
}
|
||||
|
||||
/// Result of a `file_transfer_interrupted` status for a transfer.
|
||||
@@ -736,15 +677,12 @@ async fn halted(rx: &mut watch::Receiver<bool>) {
|
||||
pub struct Transfer {
|
||||
pub id: u32,
|
||||
pub direction: Direction,
|
||||
pub(crate) backend: ListBackend,
|
||||
pub channel_id: u64,
|
||||
pub path: String,
|
||||
pub cpw: String,
|
||||
pub overwrite: bool,
|
||||
pub local: Local,
|
||||
pub total: u64,
|
||||
/// The size of an S3 download becomes known only when the HTTPS response arrives.
|
||||
pub s3_total: Option<Arc<AtomicU64>>,
|
||||
pub stage: Stage,
|
||||
pub server_ftid: Option<u16>,
|
||||
pub confirmed: bool,
|
||||
@@ -768,8 +706,7 @@ pub struct Transfer {
|
||||
impl Transfer {
|
||||
pub fn ftid(&self) -> Option<u16> {
|
||||
match self.stage {
|
||||
Stage::Queued | Stage::Paused | Stage::S3Init { .. } | Stage::S3Running { .. }
|
||||
| Stage::S3Confirming { .. } => None,
|
||||
Stage::Queued | Stage::Paused => None,
|
||||
Stage::Init { ftid, .. }
|
||||
| Stage::Running { ftid, .. }
|
||||
| Stage::Pausing { ftid, .. }
|
||||
@@ -783,18 +720,15 @@ impl Transfer {
|
||||
pub fn state(&self) -> &'static str {
|
||||
match self.stage {
|
||||
Stage::Queued => "queued",
|
||||
Stage::Init { .. } | Stage::S3Init { .. } => "starting",
|
||||
Stage::Running { .. } | Stage::Pausing { .. } | Stage::Lost { .. } | Stage::S3Running { .. } => "running",
|
||||
Stage::Confirming { .. } | Stage::S3Confirming { .. } => "confirming",
|
||||
Stage::Init { .. } => "starting",
|
||||
Stage::Running { .. } | Stage::Pausing { .. } | Stage::Lost { .. } => "running",
|
||||
Stage::Confirming { .. } => "confirming",
|
||||
Stage::Paused => "paused",
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts against its channel's concurrency limit.
|
||||
pub fn in_progress(&self) -> bool {
|
||||
matches!(self.stage, Stage::Init { .. } | Stage::Running { .. } | Stage::Confirming { .. }
|
||||
| Stage::S3Init { .. } | Stage::S3Running { .. } | Stage::S3Confirming { .. })
|
||||
}
|
||||
pub fn in_progress(&self) -> bool { matches!(self.stage, Stage::Init { .. } | Stage::Running { .. } | Stage::Confirming { .. }) }
|
||||
|
||||
/// `ftinit*` resume argument for a start: `None` starts fresh with the original overwrite flag;
|
||||
/// `Some(bytes)` continues after a granted stream (download `seekpos`, upload `resume=1`).
|
||||
@@ -880,9 +814,8 @@ impl Transfer {
|
||||
"path": self.path,
|
||||
"name": file_name(&self.path),
|
||||
"state": state,
|
||||
"bytes": self.progress.load(Ordering::Acquire),
|
||||
"pause_supported": self.backend == ListBackend::Legacy && self.channel_id != 0,
|
||||
"total": self.s3_total.as_ref().map_or(self.total, |n| n.load(Ordering::Acquire)),
|
||||
"bytes": self.progress.load(Ordering::Relaxed),
|
||||
"total": self.total,
|
||||
});
|
||||
if let Some(e) = error {
|
||||
v["error"] = serde_json::to_value(e).expect("error serializes");
|
||||
@@ -891,12 +824,12 @@ impl Transfer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Dropping a transfer stops its I/O and lets the disk side delete its temporary file
|
||||
/// (a paused download's `Partial` deletes its own).
|
||||
/// Dropping a transfer stops its I/O: the stream task is aborted, which closes the TCP stream and
|
||||
/// lets the disk side delete its temporary file (a paused download's `Partial` deletes its own).
|
||||
impl Drop for Transfer {
|
||||
fn drop(&mut self) {
|
||||
self.commit.cancel();
|
||||
if let Stage::Running { task, .. } | Stage::Pausing { task, .. } | Stage::S3Running { task } = &self.stage {
|
||||
if let Stage::Running { task, .. } | Stage::Pausing { task, .. } = &self.stage {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
@@ -925,9 +858,8 @@ pub struct Files {
|
||||
pub stops: HashMap<u16, ()>,
|
||||
pub transfers: Vec<Transfer>,
|
||||
pub tombstones: HashMap<u16, Tombstone>,
|
||||
/// Display text is bounded; backend selection uses the complete announcement.
|
||||
capability_extensions: Option<String>,
|
||||
storage_extensions: (bool, bool),
|
||||
/// Last `virtualserver_capability_extensions` seen (`None` until the server sent it).
|
||||
pub capability_extensions: Option<String>,
|
||||
pub slots: Option<[usize; 2]>,
|
||||
/// Increments whenever a transfer starts.
|
||||
pub start_seq: u64,
|
||||
@@ -970,56 +902,30 @@ impl Files {
|
||||
|
||||
pub fn index_of_id(&self, id: u32) -> Option<usize> { self.transfers.iter().position(|t| t.id == id) }
|
||||
|
||||
fn unsupported_storage(&self) -> ErrorObj {
|
||||
ErrorObj::new(ErrorCode::MediaUnsupported, "This operation is unsupported by the server's HTTPFT/S3 storage backend")
|
||||
.with_detail(self.storage())
|
||||
}
|
||||
|
||||
/// Reject unsupported storage before issuing any legacy command or touching a local file.
|
||||
pub fn require_legacy(&self) -> Result<(), ErrorObj> {
|
||||
if self.storage_extensions != (false, false) { return Err(self.unsupported_storage()); }
|
||||
let ext = self.capability_extensions.as_deref().unwrap_or("");
|
||||
if ext.contains("HTTPFT") || ext.contains("s3") {
|
||||
return Err(ErrorObj::new(ErrorCode::MediaUnsupported, "This server advertises HTTPFT/S3 storage; the legacy file protocol cannot access it").with_detail(self.storage()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn list_backend(&self, channel_id: u64) -> Result<ListBackend, ErrorObj> {
|
||||
match self.storage_extensions {
|
||||
(_, true) if channel_id != 0 => Ok(ListBackend::S3),
|
||||
(false, false) => Ok(ListBackend::Legacy),
|
||||
_ => Err(self.unsupported_storage()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `virtualserver_capability_extensions` and operation support for ordinary channels.
|
||||
/// `virtualserver_capability_extensions` tokens relevant to file storage.
|
||||
pub fn storage(&self) -> Value {
|
||||
let (httpft, s3) = self.storage_extensions;
|
||||
// Same test as the official client: substring of the advertised extension list.
|
||||
let ext = self.capability_extensions.as_deref().unwrap_or("");
|
||||
let httpft = ext.contains("HTTPFT");
|
||||
let s3 = ext.contains("s3");
|
||||
json!({
|
||||
"capability_extensions": self.capability_extensions,
|
||||
"httpft": httpft,
|
||||
"s3": s3,
|
||||
// Do not issue legacy operations against a different storage backend.
|
||||
"supported": !(httpft || s3),
|
||||
"list_supported": s3 || !httpft,
|
||||
"read_only": false,
|
||||
"upload_supported": s3 || !httpft,
|
||||
"download_supported": s3 || !httpft,
|
||||
"pause_supported": !(s3 || httpft),
|
||||
"mutation_supported": !(s3 || httpft),
|
||||
})
|
||||
}
|
||||
|
||||
/// Correlate by the exact S3 command handle, not by channel/path or a legacy completion.
|
||||
/// Even a malformed notification waits for the ACK: a command rejection has the real TS error.
|
||||
pub(crate) fn apply_s3_list(&mut self, reply: S3FileList<'_>) -> Option<u16> {
|
||||
let handle = reply.handle?;
|
||||
let job = self.lists.get_mut(&handle)?;
|
||||
let ListData::S3(result @ None) = &mut job.data else { return None; };
|
||||
*result = Some(match reply.payload {
|
||||
Ok(payload) => s3::decode_list(&job.path, payload),
|
||||
Err(message) => Err(ErrorObj::new(ErrorCode::ServerError, message)),
|
||||
});
|
||||
job.result_ok.then_some(handle)
|
||||
}
|
||||
|
||||
/// Apply a tapped raw notification. Returns finished listings (handle) to answer.
|
||||
pub fn apply_raw(&mut self, raw: &RawNotification) -> Vec<u16> {
|
||||
let items = &raw.items;
|
||||
@@ -1028,10 +934,8 @@ impl Files {
|
||||
}
|
||||
match raw.name.as_str() {
|
||||
"initserver" | "notifyserverupdated" | "notifyserveredited" => {
|
||||
let extensions = items.iter().rev().find_map(|item| item.get("virtualserver_capability_extensions"));
|
||||
if raw.name == "initserver" || extensions.is_some() {
|
||||
self.storage_extensions = extensions.map_or((false, false), |v| (v.contains("HTTPFT"), v.contains("s3")));
|
||||
self.capability_extensions = extensions.map(|v| v.chars().take(1024).collect());
|
||||
if let Some(v) = items[0].get("virtualserver_capability_extensions") {
|
||||
self.capability_extensions = Some(v.chars().take(1024).collect());
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
@@ -1051,14 +955,13 @@ impl Files {
|
||||
for i in 0..items.len() {
|
||||
let Some(handle) = self.list_for(items, i) else { continue };
|
||||
let job = self.lists.get_mut(&handle).expect("found");
|
||||
let ListData::Legacy { entries, malformed, overflow, .. } = &mut job.data else { unreachable!() };
|
||||
if entries.len() >= MAX_LIST_ENTRIES {
|
||||
*overflow = true;
|
||||
if job.entries.len() >= MAX_LIST_ENTRIES {
|
||||
job.overflow = true;
|
||||
continue;
|
||||
}
|
||||
match list_entry(items, i) {
|
||||
Some(v) => entries.push(v),
|
||||
None => *malformed += 1,
|
||||
Some(v) => job.entries.push(v),
|
||||
None => job.malformed += 1,
|
||||
}
|
||||
}
|
||||
Vec::new()
|
||||
@@ -1067,7 +970,9 @@ impl Files {
|
||||
let mut done = Vec::new();
|
||||
for i in 0..items.len() {
|
||||
if let Some(handle) = self.list_for(items, i) {
|
||||
if self.lists.get_mut(&handle).expect("found").finish_legacy() {
|
||||
let job = self.lists.get_mut(&handle).expect("found");
|
||||
job.finished = true;
|
||||
if job.result_ok {
|
||||
done.push(handle);
|
||||
}
|
||||
}
|
||||
@@ -1082,13 +987,13 @@ impl Files {
|
||||
/// channel and path (only one listing per folder is ever pending).
|
||||
fn list_for(&self, items: &[BTreeMap<String, String>], i: usize) -> Option<u16> {
|
||||
if let Some(h) = field(items, i, "return_code").and_then(|r| r.parse::<u16>().ok()) {
|
||||
if self.lists.get(&h).is_some_and(ListJob::accepts_legacy_rows) {
|
||||
if self.lists.get(&h).is_some_and(|j| !j.finished) {
|
||||
return Some(h);
|
||||
}
|
||||
}
|
||||
let cid: u64 = field(items, i, "cid")?.parse().ok()?;
|
||||
let path = field(items, i, "path")?;
|
||||
self.lists.iter().find(|(_, j)| j.accepts_legacy_rows() && j.channel_id == cid && same_dir(&j.path, path)).map(|(h, _)| *h)
|
||||
self.lists.iter().find(|(_, j)| !j.finished && j.channel_id == cid && same_dir(&j.path, path)).map(|(h, _)| *h)
|
||||
}
|
||||
|
||||
pub fn list_pending(&self, channel_id: u64, path: &str) -> bool {
|
||||
@@ -1121,11 +1026,9 @@ impl Files {
|
||||
/// for an explicit resume).
|
||||
pub fn next_startable(&self, direction: Direction) -> Option<usize> {
|
||||
self.transfers.iter().position(|q| {
|
||||
if q.direction != direction || !matches!(q.stage, Stage::Queued) { return false; }
|
||||
let limit = self.limit(direction, q.channel_id);
|
||||
self.transfers.iter()
|
||||
.filter(|t| t.direction == direction && t.channel_id == q.channel_id && t.in_progress())
|
||||
.take(limit).count() < limit
|
||||
q.direction == direction
|
||||
&& matches!(q.stage, Stage::Queued)
|
||||
&& self.in_progress_of(direction, q.channel_id).len() < self.limit(direction, q.channel_id)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1140,7 +1043,7 @@ impl Files {
|
||||
for (_, channel_id, direction) in channels {
|
||||
let limit = self.limit(direction, channel_id);
|
||||
for &i in self.in_progress_of(direction, channel_id).iter().skip(limit) {
|
||||
if self.transfers[i].backend == ListBackend::Legacy && !matches!(self.transfers[i].stage, Stage::Confirming { .. }) {
|
||||
if !matches!(self.transfers[i].stage, Stage::Confirming { .. }) {
|
||||
out.push(self.transfers[i].id);
|
||||
}
|
||||
}
|
||||
@@ -1160,7 +1063,7 @@ impl Files {
|
||||
let excess = (running.len() + 1).saturating_sub(limit).min(running.len());
|
||||
running[..excess]
|
||||
.iter()
|
||||
.filter(|&&i| self.transfers[i].backend == ListBackend::Legacy && !matches!(self.transfers[i].stage, Stage::Confirming { .. }))
|
||||
.filter(|&&i| !matches!(self.transfers[i].stage, Stage::Confirming { .. }))
|
||||
.map(|&i| self.transfers[i].id)
|
||||
.collect()
|
||||
}
|
||||
@@ -1168,17 +1071,14 @@ impl Files {
|
||||
|
||||
/// Final answer for a completed listing.
|
||||
pub fn list_result(job: ListJob, capabilities: Value, storage: Value) -> Result<Value, ErrorObj> {
|
||||
let (entries, malformed) = match job.data {
|
||||
ListData::Legacy { overflow: true, .. } => return Err(ErrorObj::new(ErrorCode::ServerError,
|
||||
format!("the folder has more than {MAX_LIST_ENTRIES} entries; listing not complete"))),
|
||||
ListData::Legacy { entries, malformed, .. } => (entries, malformed),
|
||||
ListData::S3(result) => result.expect("S3 list notification received")?,
|
||||
};
|
||||
if job.overflow {
|
||||
return Err(ErrorObj::new(ErrorCode::ServerError, format!("the folder has more than {MAX_LIST_ENTRIES} entries; listing not complete")));
|
||||
}
|
||||
Ok(json!({
|
||||
"channel_id": job.channel_id,
|
||||
"path": job.path,
|
||||
"entries": entries,
|
||||
"malformed": malformed,
|
||||
"entries": job.entries,
|
||||
"malformed": job.malformed,
|
||||
"capabilities": capabilities,
|
||||
"storage": storage,
|
||||
}))
|
||||
@@ -1186,16 +1086,16 @@ pub fn list_result(job: ListJob, capabilities: Value, storage: Value) -> Result<
|
||||
|
||||
/// Channel permission hints (`notifychannelpermhints`) for the file browser. Unknown hints (`None`)
|
||||
/// mean the server decides, like the official client which treats missing hints as allowed.
|
||||
pub fn capabilities(hints: Option<u64>, s3: bool) -> Value {
|
||||
pub fn capabilities(hints: Option<u64>) -> Value {
|
||||
let bit = |b: u64| hints.is_none_or(|h| h & b != 0);
|
||||
json!({
|
||||
"known": hints.is_some(),
|
||||
"upload": bit(64),
|
||||
"download": bit(128),
|
||||
"delete": !s3 && bit(256),
|
||||
"rename": !s3 && bit(512),
|
||||
"delete": bit(256),
|
||||
"rename": bit(512),
|
||||
"browse": bit(1024),
|
||||
"create_directory": !s3 && bit(2048),
|
||||
"create_directory": bit(2048),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1287,8 +1187,6 @@ fn finalize(temp: &Path, target: &Path, overwrite: bool, name: &str) -> Result<(
|
||||
#[derive(Debug)]
|
||||
enum ToDisk {
|
||||
Data(Vec<u8>, usize),
|
||||
/// An owned HTTP frame, or a slice of one, can be staged without copying its bytes.
|
||||
HttpData(bytes::Bytes),
|
||||
Commit,
|
||||
/// Halt: keep the temporary file open and hand it back.
|
||||
Pause,
|
||||
@@ -1336,10 +1234,6 @@ fn disk_writer(
|
||||
while let Some(msg) = rx.blocking_recv() {
|
||||
if control.0.load(Ordering::Acquire) == 1 { return Err(cancelled()); }
|
||||
match msg {
|
||||
ToDisk::HttpData(buf) => {
|
||||
file.write_all(&buf).map_err(|e| io_err("cannot write the download", e))?;
|
||||
written += buf.len() as u64;
|
||||
}
|
||||
ToDisk::Data(buf, n) => {
|
||||
file.write_all(&buf[..n]).map_err(|e| io_err("cannot write the download", e))?;
|
||||
written += n as u64;
|
||||
@@ -1351,9 +1245,6 @@ fn disk_writer(
|
||||
foreign = true;
|
||||
return Err(ErrorObj::new(ErrorCode::Io, "the temporary download file was replaced; nothing was published"));
|
||||
}
|
||||
if file.metadata().map_err(|e| io_err("cannot inspect the download", e))?.len() != written {
|
||||
return Err(ErrorObj::new(ErrorCode::Io, "the temporary download file changed; nothing was published"));
|
||||
}
|
||||
return if control.begin_commit() { Ok(false) } else { Err(cancelled()) };
|
||||
}
|
||||
ToDisk::Pause => {
|
||||
@@ -1364,7 +1255,7 @@ fn disk_writer(
|
||||
}
|
||||
Err(cancelled())
|
||||
})();
|
||||
if foreign || (result.is_err() && !names_file(guard.0.as_ref().expect("armed"), &file)) {
|
||||
if foreign {
|
||||
guard.0 = None;
|
||||
}
|
||||
match result {
|
||||
@@ -1709,7 +1600,10 @@ mod tests {
|
||||
#[test]
|
||||
fn listing_merges_shared_arguments_and_bounds_rows() {
|
||||
let mut f = Files::default();
|
||||
f.lists.insert(7, ListJob::new("r", 4, "/".into(), ListBackend::Legacy));
|
||||
f.lists.insert(7, ListJob {
|
||||
req: "r".into(), channel_id: 4, path: "/".into(), entries: vec![], malformed: 0,
|
||||
overflow: false, finished: false, result_ok: false, started: Instant::now(),
|
||||
});
|
||||
let done = f.apply_raw(&raw("notifyfilelist", &[
|
||||
&[("cid", "4"), ("path", "/"), ("return_code", "7"), ("name", "Doc"), ("size", "0"), ("datetime", "5"), ("type", "0")],
|
||||
&[("name", "ü.txt"), ("size", "11984"), ("datetime", "1539276009"), ("type", "1"), ("incompletesize", "100")],
|
||||
@@ -1718,14 +1612,13 @@ mod tests {
|
||||
&[("name", "nested/file"), ("size", "1"), ("type", "1")],
|
||||
]));
|
||||
assert!(done.is_empty());
|
||||
let job = f.lists.get_mut(&7).unwrap();
|
||||
let ListData::Legacy { entries, malformed, .. } = &job.data else { panic!("not a legacy list") };
|
||||
assert_eq!(entries.len(), 2);
|
||||
assert_eq!(*malformed, 3);
|
||||
assert_eq!(entries[0]["type"], "folder");
|
||||
assert_eq!(entries[1]["name"], "ü.txt");
|
||||
assert_eq!(entries[1]["incomplete_size"], 100);
|
||||
assert!(!job.acknowledge());
|
||||
let job = &f.lists[&7];
|
||||
assert_eq!(job.entries.len(), 2);
|
||||
assert_eq!(job.malformed, 3);
|
||||
assert_eq!(job.entries[0]["type"], "folder");
|
||||
assert_eq!(job.entries[1]["name"], "ü.txt");
|
||||
assert_eq!(job.entries[1]["incomplete_size"], 100);
|
||||
f.lists.get_mut(&7).unwrap().result_ok = true;
|
||||
assert_eq!(f.apply_raw(&raw("notifyfilelistfinished", &[&[("cid", "4"), ("path", "/")]])), vec![7]);
|
||||
}
|
||||
|
||||
@@ -1738,119 +1631,11 @@ mod tests {
|
||||
assert_eq!(f.storage()["httpft"], true);
|
||||
assert_eq!(f.storage()["supported"], false);
|
||||
assert_eq!(f.require_legacy().unwrap_err().code, ErrorCode::MediaUnsupported);
|
||||
assert_eq!(f.storage()["list_supported"], false);
|
||||
assert!(f.list_backend(4).is_err());
|
||||
f.apply_raw(&raw("initserver", &[&[("virtualserver_capability_extensions", "MATRIXCHAT,HTTPFT,s3")]]));
|
||||
assert_eq!(f.list_backend(4).unwrap(), ListBackend::S3);
|
||||
assert_eq!(f.list_backend(0).unwrap_err().code, ErrorCode::MediaUnsupported);
|
||||
assert_eq!(f.require_legacy().unwrap_err().code, ErrorCode::MediaUnsupported);
|
||||
assert_eq!(f.storage()["supported"], false);
|
||||
assert_eq!(f.storage()["list_supported"], true);
|
||||
assert_eq!(f.storage()["read_only"], false);
|
||||
assert_eq!(f.storage()["upload_supported"], true);
|
||||
assert_eq!(f.storage()["download_supported"], true);
|
||||
assert_eq!(f.storage()["pause_supported"], false);
|
||||
assert_eq!(f.storage()["mutation_supported"], false);
|
||||
assert_eq!(capabilities(None, true)["browse"], true);
|
||||
assert_eq!(capabilities(None, true)["upload"], true);
|
||||
assert_eq!(capabilities(None, true)["download"], true);
|
||||
assert_eq!(capabilities(Some(0), true)["browse"], false);
|
||||
assert_eq!(capabilities(Some(0), true)["upload"], false);
|
||||
assert_eq!(capabilities(Some(0), true)["download"], false);
|
||||
for operation in ["delete", "rename", "create_directory"] {
|
||||
assert_eq!(capabilities(None, true)[operation], false);
|
||||
}
|
||||
f.apply_raw(&raw("initserver", &[&[]]));
|
||||
assert_eq!(f.list_backend(0).unwrap(), ListBackend::Legacy);
|
||||
assert_eq!(f.storage()["list_supported"], true);
|
||||
assert_eq!(f.storage()["read_only"], false);
|
||||
assert_eq!(capabilities(Some((1_u64 << 48) | 128), false)["download"], true);
|
||||
assert_eq!(capabilities(Some(1_u64 << 48), false)["download"], false);
|
||||
assert_eq!(capabilities(Some(1024 | 64), false)["upload"], true);
|
||||
assert_eq!(capabilities(Some(1024 | 64), false)["delete"], false);
|
||||
assert_eq!(capabilities(None, false)["delete"], true);
|
||||
}
|
||||
|
||||
fn s3_listing(path: &str) -> Files {
|
||||
let mut files = Files::default();
|
||||
files.lists.insert(7, ListJob::new("r", 4, path.into(), ListBackend::S3));
|
||||
files
|
||||
}
|
||||
|
||||
fn s3_notify(files: &mut Files, command: &[u8]) -> Option<u16> {
|
||||
files.apply_s3_list(crate::rawcmd::s3_file_list(command).unwrap())
|
||||
}
|
||||
|
||||
fn s3_list_answer(files: &mut Files) -> Result<Value, ErrorObj> {
|
||||
list_result(files.lists.remove(&7).unwrap(), capabilities(None, true), files.storage())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s3_listing_correlates_exact_handle_and_waits_for_ack_in_either_order() {
|
||||
for ack_first in [false, true] {
|
||||
let mut files = s3_listing("/");
|
||||
files.lists.insert(8, ListJob::new("legacy", 4, "/".into(), ListBackend::Legacy));
|
||||
if ack_first { assert!(!files.lists.get_mut(&7).unwrap().acknowledge()); }
|
||||
assert_eq!(files.apply_raw(&raw("notifyfilelistfinished", &[&[("return_code", "7")]])), Vec::<u16>::new());
|
||||
for foreign in [
|
||||
br"notify_s3ft_file_list return_code=8 b64_json".as_slice(),
|
||||
br"notify_s3ft_file_list return_code=9 b64_json chid=4 cid=4 path=\/",
|
||||
br"notify_s3ft_file_list b64_json chid=4 cid=4 path=\/",
|
||||
br"notify_s3ft_file_list return_code=x b64_json",
|
||||
br"notify_s3ft_file_list return_code=7 return_code=9 b64_json",
|
||||
] {
|
||||
assert_eq!(s3_notify(&mut files, foreign), None);
|
||||
}
|
||||
assert!(!files.lists.get_mut(&8).unwrap().acknowledge());
|
||||
assert_eq!(s3_notify(&mut files, br"notify_s3ft_file_list b64_json return_code=7"), ack_first.then_some(7));
|
||||
assert_eq!(s3_notify(&mut files, br"notify_s3ft_file_list b64_json=broken return_code=7"), None);
|
||||
if !ack_first { assert!(files.lists.get_mut(&7).unwrap().acknowledge()); }
|
||||
assert_eq!(s3_list_answer(&mut files).unwrap()["entries"], json!([]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s3_listing_rejects_missing_malformed_and_truncated_payloads() {
|
||||
for (command, message) in [
|
||||
("notify_s3ft_file_list return_code=7", "missing b64_json"),
|
||||
("notify_s3ft_file_list return_code=7 b64_json b64_json=e30=", "malformed S3 file list notification"),
|
||||
("notify_s3ft_file_list return_code=7|b64_json", "malformed S3 file list notification"),
|
||||
("notify_s3ft_file_list return_code=7 b64_json=e30", "invalid S3 file list base64"),
|
||||
(r"notify_s3ft_file_list return_code=7 b64_json=e30=\", "invalid escape"),
|
||||
("notify_s3ft_file_list return_code=7 b64_json=eyJjb250ZW50cyI6", "truncated S3 file list JSON"),
|
||||
("notify_s3ft_file_list return_code=7 b64_json=e30=", "malformed S3 file list JSON"),
|
||||
] {
|
||||
let mut files = s3_listing("/");
|
||||
assert_eq!(s3_notify(&mut files, command.as_bytes()), None);
|
||||
assert!(files.lists.get_mut(&7).unwrap().acknowledge());
|
||||
let error = s3_list_answer(&mut files).unwrap_err();
|
||||
assert_eq!(error.code, ErrorCode::ServerError);
|
||||
assert!(error.message.contains(message), "{error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s3_listing_projects_whole_channel_response_to_requested_directory() {
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
let payload = STANDARD.encode(br#"{"contents":[
|
||||
{"key":"a/sub/nested.bin","size":1},
|
||||
{"key":"a/file.bin","size":3,"last_modified":"2020-01-01T01:00:00+01:00"},
|
||||
{"key":"a/empty/.tsfolder","size":0},
|
||||
{"key":"ab/not-a-child","size":1},
|
||||
{"key":"a/../bad","size":1}
|
||||
]}"#);
|
||||
let mut files = s3_listing("/a/");
|
||||
assert!(!files.lists.get_mut(&7).unwrap().acknowledge());
|
||||
let command = format!("notify_s3ft_file_list return_code=7 b64_json={}", payload.replace('/', r"\/"));
|
||||
assert_eq!(s3_notify(&mut files, command.as_bytes()), Some(7));
|
||||
let result = s3_list_answer(&mut files).unwrap();
|
||||
assert_eq!(result["path"], "/a/");
|
||||
assert_eq!(result["malformed"], 1);
|
||||
assert_eq!(result["entries"], json!([
|
||||
{ "name": "empty", "type": "folder", "size": 0, "datetime": 0 },
|
||||
{ "name": "file.bin", "type": "file", "size": 3, "datetime": 1577836800 },
|
||||
{ "name": "sub", "type": "folder", "size": 0, "datetime": 0 },
|
||||
]));
|
||||
assert_eq!(capabilities(Some((1_u64 << 48) | 128))["download"], true);
|
||||
assert_eq!(capabilities(Some(1_u64 << 48))["download"], false);
|
||||
assert_eq!(capabilities(Some(1024 | 64))["upload"], true);
|
||||
assert_eq!(capabilities(Some(1024 | 64))["delete"], false);
|
||||
assert_eq!(capabilities(None)["delete"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1944,7 +1729,7 @@ mod tests {
|
||||
|
||||
fn md5_hex(b: &[u8]) -> String {
|
||||
use md5::{Digest, Md5};
|
||||
base16ct::lower::encode_string(&Md5::digest(b))
|
||||
format!("{:x}", Md5::digest(b))
|
||||
}
|
||||
|
||||
fn parts(dir: &Path) -> usize {
|
||||
@@ -2109,34 +1894,26 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn upload_sends_exact_bytes_and_sees_server_close() {
|
||||
let dir = scratch("ul");
|
||||
let data = pattern(5 * CHUNK);
|
||||
let data = pattern(2 * CHUNK + 999);
|
||||
let src = dir.join("Ünïcødé source.bin");
|
||||
std::fs::write(&src, &data).unwrap();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let len = data.len();
|
||||
let (ready, receiving) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut s, _) = listener.accept().await.unwrap();
|
||||
let mut key = [0u8; 32];
|
||||
s.read_exact(&mut key).await.unwrap();
|
||||
assert_eq!(&key, KEY);
|
||||
let mut got = vec![0u8; len];
|
||||
let started = Instant::now();
|
||||
ready.send(()).unwrap();
|
||||
s.read_exact(&mut got).await.unwrap();
|
||||
assert!(started.elapsed() >= Duration::from_millis(240), "five chunks arrived above the configured 1 MiB/s upload limit");
|
||||
let mut extra = [0u8; 1];
|
||||
assert_eq!(s.read(&mut extra).await.unwrap(), 0, "client closes its write half after the file");
|
||||
got
|
||||
});
|
||||
let (file, size) = prepare_upload(&src).unwrap();
|
||||
let progress = Arc::new(AtomicU64::new(0));
|
||||
let rate = Arc::new(RateLimit::default());
|
||||
rate.set(1024 * 1024);
|
||||
let stream = keyed(addr).await;
|
||||
receiving.await.unwrap();
|
||||
let ended = upload(stream, file, size, 0, progress.clone(), rate, quiet()).await.unwrap();
|
||||
let ended = upload(keyed(addr).await, file, size, 0, progress.clone(), Arc::default(), quiet()).await.unwrap();
|
||||
assert!(matches!(ended, Ended::Complete { closed: true }));
|
||||
let got = server.await.unwrap();
|
||||
assert_eq!(md5_hex(&got), md5_hex(&data));
|
||||
@@ -2242,14 +2019,12 @@ mod tests {
|
||||
let queued = |id: u32, direction: Direction, channel_id: u64| Transfer {
|
||||
id,
|
||||
direction,
|
||||
backend: ListBackend::Legacy,
|
||||
channel_id,
|
||||
path: format!("/f{id}"),
|
||||
cpw: String::new(),
|
||||
overwrite: false,
|
||||
local: Local::Upload { file: None, size: 0, modified: None },
|
||||
total: 0,
|
||||
s3_total: None,
|
||||
stage: Stage::Queued,
|
||||
server_ftid: None,
|
||||
confirmed: false,
|
||||
@@ -2300,14 +2075,12 @@ mod tests {
|
||||
let running = |id: u32, direction: Direction, started: u64| Transfer {
|
||||
id,
|
||||
direction,
|
||||
backend: ListBackend::Legacy,
|
||||
channel_id: 7,
|
||||
path: format!("/f{id}"),
|
||||
cpw: String::new(),
|
||||
overwrite: false,
|
||||
local: Local::Upload { file: None, size: 0, modified: None },
|
||||
total: 0,
|
||||
s3_total: None,
|
||||
stage: Stage::Init { ftid: id as u16, since: now },
|
||||
server_ftid: None,
|
||||
confirmed: false,
|
||||
@@ -2351,14 +2124,12 @@ mod tests {
|
||||
Transfer {
|
||||
id: 9,
|
||||
direction: if matches!(local, Local::Download { .. }) { Direction::Download } else { Direction::Upload },
|
||||
backend: ListBackend::Legacy,
|
||||
channel_id: 7,
|
||||
path: "/i.bin".into(),
|
||||
cpw: String::new(),
|
||||
overwrite: false,
|
||||
local,
|
||||
total: 0,
|
||||
s3_total: None,
|
||||
stage,
|
||||
server_ftid: Some(40),
|
||||
confirmed: false,
|
||||
|
||||
@@ -1,279 +0,0 @@
|
||||
//! TeamSpeak's S3 object metadata and channel file list projection.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeMap;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use serde::de::{value::MapAccessDeserializer, MapAccess, Visitor};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use super::{bad, check_remote_dir, remote_component, MAX_LIST_ENTRIES, MAX_PATH_CHARS};
|
||||
use crate::protocol::{ErrorCode, ErrorObj};
|
||||
|
||||
const FOLDER_MARKER: &str = ".tsfolder";
|
||||
// S3 limits the entire object key to 1,024 UTF-8 bytes, independent of the browser's char limit.
|
||||
const MAX_KEY_BYTES: usize = 1024;
|
||||
// The transport limits decompressed commands to 2 MiB. Also bound decoding here so a
|
||||
// caller cannot allocate from an unbounded field independently of the transport.
|
||||
const MAX_ENCODED_LIST_BYTES: usize = 2 * 1024 * 1024;
|
||||
/// Largest object size representable exactly in the bridge's JSON consumers.
|
||||
pub(super) const MAX_SAFE_SIZE: u64 = (1 << 53) - 1;
|
||||
|
||||
// Serde's default struct visitor also accepts positional arrays; the S3 format uses maps only.
|
||||
struct JsonObject<T>(T);
|
||||
|
||||
impl<'de, T: Deserialize<'de>> Deserialize<'de> for JsonObject<T> {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
|
||||
struct ObjectVisitor<T>(PhantomData<T>);
|
||||
impl<'de, T: Deserialize<'de>> Visitor<'de> for ObjectVisitor<T> {
|
||||
type Value = T;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("a JSON object") }
|
||||
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<T, A::Error> {
|
||||
T::deserialize(MapAccessDeserializer::new(map))
|
||||
}
|
||||
}
|
||||
de.deserialize_map(ObjectVisitor(PhantomData)).map(Self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Semantic fields from one channel-relative object; no wire envelope or transfer grant.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub(crate) struct ListObject<'a>(#[serde(borrow)] JsonObject<ListObjectFields<'a>>);
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ListObjectFields<'a> {
|
||||
#[serde(borrow)]
|
||||
key: Cow<'a, str>,
|
||||
size: u64,
|
||||
/// Parsed Unix seconds, or `None` if the object timestamp was absent or unparseable.
|
||||
#[serde(default, deserialize_with = "parse_timestamp")]
|
||||
last_modified: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ListEnvelope<'a> {
|
||||
#[serde(borrow)]
|
||||
contents: Vec<ListObject<'a>>,
|
||||
}
|
||||
|
||||
fn parse_timestamp<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<i64>, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
struct Timestamp<'a>(#[serde(borrow)] Cow<'a, str>);
|
||||
Ok(Option::<Timestamp<'_>>::deserialize(deserializer)?.and_then(|Timestamp(text)| {
|
||||
chrono::DateTime::parse_from_rfc3339(&text).ok().map(|time| time.timestamp())
|
||||
}))
|
||||
}
|
||||
|
||||
fn invalid_list(message: &'static str) -> ErrorObj { ErrorObj::new(ErrorCode::ServerError, message) }
|
||||
|
||||
/// The only TeamSpeak escape possible in standard base64 is `\/`.
|
||||
fn unescape_base64(raw: &[u8]) -> Result<Cow<'_, [u8]>, ErrorObj> {
|
||||
let mut parts = raw.split(|byte| *byte == b'\\');
|
||||
let first = parts.next().expect("split returns at least one part");
|
||||
let Some(second) = parts.next() else { return Ok(Cow::Borrowed(raw)); };
|
||||
let mut encoded = Vec::with_capacity(raw.len() - 1);
|
||||
encoded.extend_from_slice(first);
|
||||
for part in std::iter::once(second).chain(parts) {
|
||||
if !part.starts_with(b"/") { return Err(invalid_list("invalid escape in S3 file list base64")); }
|
||||
encoded.extend_from_slice(part);
|
||||
}
|
||||
Ok(Cow::Owned(encoded))
|
||||
}
|
||||
|
||||
/// Only a present, empty field stands for an empty channel. Nonempty data must decode to
|
||||
/// the whole JSON envelope; neither decoding errors nor server contents escape into errors.
|
||||
pub(super) fn decode_list(path: &str, raw: &[u8]) -> Result<(Vec<Value>, usize), ErrorObj> {
|
||||
if raw.is_empty() { return project_list(path, true, &[]); }
|
||||
if raw.len() > MAX_ENCODED_LIST_BYTES {
|
||||
return Err(invalid_list("S3 file list exceeds the payload limit; listing not complete"));
|
||||
}
|
||||
let encoded = unescape_base64(raw)?;
|
||||
let decoded = STANDARD.decode(encoded.as_ref()).map_err(|_| invalid_list("invalid S3 file list base64"))?;
|
||||
let JsonObject(envelope): JsonObject<ListEnvelope<'_>> = serde_json::from_slice(&decoded).map_err(|error| {
|
||||
if error.is_eof() { invalid_list("truncated S3 file list JSON") }
|
||||
else { invalid_list("malformed S3 file list JSON") }
|
||||
})?;
|
||||
project_list(path, true, &envelope.contents)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Child {
|
||||
File { size: u64, datetime: i64 },
|
||||
Folder,
|
||||
ConflictingFile,
|
||||
ConflictingFolder,
|
||||
}
|
||||
|
||||
fn validated_key(key: &str) -> Option<(&str, bool)> {
|
||||
if key.len() > MAX_KEY_BYTES || (key.len() >= MAX_PATH_CHARS && key.chars().count() >= MAX_PATH_CHARS) {
|
||||
return None;
|
||||
}
|
||||
let item = key.strip_suffix('/').unwrap_or(key);
|
||||
let trailing_slash = item.len() != key.len();
|
||||
let mut parts = item.split('/').peekable();
|
||||
while let Some(part) = parts.next() {
|
||||
remote_component(part).ok()?;
|
||||
// A marker may only be a leaf object, never a user-addressable directory.
|
||||
if part == FOLDER_MARKER && (trailing_slash || parts.peek().is_some()) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some((item, trailing_slash))
|
||||
}
|
||||
|
||||
/// Return the direct children and malformed count for a canonical browser directory (`/a/`).
|
||||
/// The caller must first validate the envelope, correlate it, and establish whether it succeeded.
|
||||
/// The input is the whole channel's object list; never publish a partial result after overflow.
|
||||
pub(crate) fn project_list(
|
||||
path: &str, success: bool, contents: &[ListObject<'_>],
|
||||
) -> Result<(Vec<Value>, usize), ErrorObj> {
|
||||
if !success {
|
||||
return Err(ErrorObj::new(ErrorCode::ServerError, "S3 file listing failed"));
|
||||
}
|
||||
check_remote_dir(path)?;
|
||||
let relative_dir = &path[1..];
|
||||
if !path.ends_with('/') || relative_dir.len() > MAX_KEY_BYTES
|
||||
|| relative_dir.split('/').any(|part| part == FOLDER_MARKER)
|
||||
{
|
||||
return Err(bad("invalid S3 directory path"));
|
||||
}
|
||||
if contents.len() > MAX_LIST_ENTRIES {
|
||||
return Err(ErrorObj::new(ErrorCode::ServerError,
|
||||
format!("the channel has more than {MAX_LIST_ENTRIES} S3 objects; listing not complete")));
|
||||
}
|
||||
|
||||
let mut malformed = 0;
|
||||
let mut children = BTreeMap::new();
|
||||
for ListObject(JsonObject(object)) in contents {
|
||||
if object.size > MAX_SAFE_SIZE { return Err(invalid_list("invalid S3 file list object size")); }
|
||||
let Some((key, trailing_slash)) = validated_key(&object.key) else {
|
||||
malformed += 1;
|
||||
continue;
|
||||
};
|
||||
let Some(relative) = key.strip_prefix(relative_dir).filter(|key| !key.is_empty()) else { continue };
|
||||
let (name, child) = match relative.split_once('/') {
|
||||
Some((folder, _)) => (folder, Child::Folder),
|
||||
None if relative == FOLDER_MARKER => continue,
|
||||
None if trailing_slash => (relative, Child::Folder),
|
||||
None => (relative, Child::File { size: object.size, datetime: object.last_modified.unwrap_or(0) }),
|
||||
};
|
||||
children.entry(name).and_modify(|old| {
|
||||
*old = match (*old, child) {
|
||||
(a, b) if a == b => a,
|
||||
(Child::Folder | Child::ConflictingFolder, _) | (_, Child::Folder) => Child::ConflictingFolder,
|
||||
_ => Child::ConflictingFile,
|
||||
};
|
||||
}).or_insert(child);
|
||||
}
|
||||
|
||||
// Keep colliding directories navigable, but never publish ambiguous file metadata.
|
||||
// An ambiguous direct child contributes one malformed entry, independent of input order.
|
||||
let mut entries = Vec::with_capacity(children.len());
|
||||
for (name, child) in children {
|
||||
let (kind, size, datetime) = match child {
|
||||
Child::Folder => ("folder", 0, 0),
|
||||
Child::File { size, datetime } => ("file", size, datetime),
|
||||
Child::ConflictingFile => { malformed += 1; continue; }
|
||||
Child::ConflictingFolder => { malformed += 1; ("folder", 0, 0) }
|
||||
};
|
||||
entries.push(json!({ "name": name, "type": kind, "size": size, "datetime": datetime }));
|
||||
}
|
||||
Ok((entries, malformed))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn object(key: &str, size: u64, last_modified: Option<i64>) -> ListObject<'_> {
|
||||
ListObject(JsonObject(ListObjectFields { key: Cow::Borrowed(key), size, last_modified }))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversize_and_structurally_invalid_wire_lists() {
|
||||
let too_large = vec![b'A'; MAX_ENCODED_LIST_BYTES + 1];
|
||||
assert!(decode_list("/", &too_large).unwrap_err().message.contains("payload limit"));
|
||||
for wire in [r"[[]]", r#"{"contents":[["x",1,null]]}"#, r#"{"contents":[{"key":"x","size":9007199254740992}]}"#] {
|
||||
assert_eq!(decode_list("/", STANDARD.encode(wire).as_bytes()).unwrap_err().code, ErrorCode::ServerError);
|
||||
}
|
||||
assert_eq!(unescape_base64(br"AA\/Z").unwrap().as_ref(), b"AA/Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projects_only_direct_children_in_name_order() {
|
||||
let contents = [
|
||||
object("a/sub/nested/file", 9, None),
|
||||
object("a/slash/", 9, Some(123)),
|
||||
object("a/empty/.tsfolder", 0, Some(123)),
|
||||
object("a/.tsfolder", 0, None),
|
||||
object("a/\u{e9}.txt", 3, Some(100)),
|
||||
object("a/b.txt", 8, None),
|
||||
object("a/c.txt", 9, Some(-1)),
|
||||
object("a/", 0, None),
|
||||
object("a", 0, None),
|
||||
object("ab/not-a-child", 1, None),
|
||||
];
|
||||
let (entries, malformed) = project_list("/a/", true, &contents).unwrap();
|
||||
assert_eq!(malformed, 0);
|
||||
assert_eq!(entries, vec![
|
||||
json!({ "name": "b.txt", "type": "file", "size": 8, "datetime": 0 }),
|
||||
json!({ "name": "c.txt", "type": "file", "size": 9, "datetime": -1 }),
|
||||
json!({ "name": "empty", "type": "folder", "size": 0, "datetime": 0 }),
|
||||
json!({ "name": "slash", "type": "folder", "size": 0, "datetime": 0 }),
|
||||
json!({ "name": "sub", "type": "folder", "size": 0, "datetime": 0 }),
|
||||
json!({ "name": "\u{e9}.txt", "type": "file", "size": 3, "datetime": 100 }),
|
||||
]);
|
||||
assert!(project_list("/a/empty/", true, &contents).unwrap().0.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unsafe_or_oversize_keys_before_inferring_folders() {
|
||||
let four_bytes = "\u{1f642}".repeat(255);
|
||||
let too_many_bytes = format!("{four_bytes}/abc\u{e9}");
|
||||
let full_byte_limit = format!("{four_bytes}/abc");
|
||||
let ascii = "a".repeat(255);
|
||||
let too_many_chars = format!("{ascii}/{ascii}/a");
|
||||
let too_long_name = "a".repeat(256);
|
||||
let contents = [
|
||||
object("/absolute", 1, None), object("parent/../file", 1, None),
|
||||
object("parent//file", 1, None), object("parent/./file", 1, None),
|
||||
object("parent\\file", 1, None), object("parent/\nfile", 1, None),
|
||||
object("parent/.tsfolder/file", 1, None), object("parent/.tsfolder/", 1, None),
|
||||
object("https://private.invalid/file?signature=secret", 1, None), object("", 1, None),
|
||||
object(&too_many_bytes, 1, None), object(&too_many_chars, 1, None),
|
||||
object(&too_long_name, 1, None), object(&full_byte_limit, 1, None),
|
||||
];
|
||||
let (entries, malformed) = project_list("/", true, &contents).unwrap();
|
||||
assert_eq!(malformed, contents.len() - 1);
|
||||
assert_eq!(entries, vec![json!({ "name": four_bytes, "type": "folder", "size": 0, "datetime": 0 })]);
|
||||
assert!(project_list("/parent/../", true, &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_path_and_metadata_collisions_independently_of_input_order() {
|
||||
let mut contents = [
|
||||
object("same", 7, Some(123)), object("same/.tsfolder", 0, None),
|
||||
object("same/child", 7, None), object("duplicate", 2, None),
|
||||
object("duplicate", 2, Some(0)), object("contradictory", 3, Some(456)),
|
||||
object("contradictory", 4, Some(456)),
|
||||
];
|
||||
let projected = project_list("/", true, &contents).unwrap();
|
||||
contents.reverse();
|
||||
assert_eq!(project_list("/", true, &contents).unwrap(), projected);
|
||||
assert_eq!(projected, (vec![
|
||||
json!({ "name": "duplicate", "type": "file", "size": 2, "datetime": 0 }),
|
||||
json!({ "name": "same", "type": "folder", "size": 0, "datetime": 0 }),
|
||||
], 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_failed_or_overflowed_backend_lists() {
|
||||
assert_eq!(project_list("/", false, &[object("file", 2, None)]).unwrap_err().code, ErrorCode::ServerError);
|
||||
let contents: Vec<_> = (0..=MAX_LIST_ENTRIES).map(|_| object("nested/file", 2, None)).collect();
|
||||
assert_eq!(project_list("/", true, &contents).unwrap_err().code, ErrorCode::ServerError);
|
||||
assert_eq!(project_list("/", true, &[]).unwrap(), (vec![], 0));
|
||||
}
|
||||
}
|
||||
@@ -1,542 +0,0 @@
|
||||
//! Direct object-storage I/O. The correlated TeamSpeak grant supplies the only HTTP credential.
|
||||
|
||||
use std::fmt;
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use bytes::Bytes;
|
||||
use reqwest::header::{CONTENT_LENGTH, CONTENT_RANGE, IF_NONE_MATCH};
|
||||
use reqwest::{Client, ClientBuilder, Response, StatusCode, Url};
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
|
||||
use crate::protocol::{ErrorCode, ErrorObj};
|
||||
|
||||
use super::{
|
||||
bad, disk_writer, io_err, upload_source_unchanged, CancelOnDrop, CommitControl, Ended,
|
||||
RateLimit, ToDisk, Written, BUFFERS, CHUNK, CONFIRM_DEADLINE, STALL_DEADLINE,
|
||||
};
|
||||
|
||||
use super::s3::MAX_SAFE_SIZE;
|
||||
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const TRANSFER_TIMEOUT: Duration = Duration::from_secs(60 * 60);
|
||||
const MAX_URL_BYTES: usize = 16 * 1024;
|
||||
|
||||
/// An already-correlated grant. The URL must not be shown in diagnostics or bridge output.
|
||||
pub(crate) struct SignedUrl(Url);
|
||||
|
||||
impl fmt::Debug for SignedUrl {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("SignedUrl(<redacted>)") }
|
||||
}
|
||||
|
||||
impl SignedUrl {
|
||||
pub(crate) fn parse(raw: &str) -> Result<Self, ErrorObj> {
|
||||
let invalid = || ErrorObj::new(ErrorCode::ServerError, "storage grant did not include a usable HTTPS URL");
|
||||
if raw.len() > MAX_URL_BYTES || !raw.bytes().all(|b| b.is_ascii_graphic()) {
|
||||
return Err(invalid());
|
||||
}
|
||||
let rest = raw.strip_prefix("https://").ok_or_else(invalid)?;
|
||||
let authority = rest.split(['/', '?', '#']).next().expect("split returns at least one item");
|
||||
if authority.is_empty() || authority.contains('@') || raw.contains('\\') {
|
||||
return Err(invalid());
|
||||
}
|
||||
let url = Url::parse(raw).map_err(|_| invalid())?;
|
||||
// Parsing must not rewrite parts of the signed request, e.g. encoded dot segments.
|
||||
if !url.has_host() || url.fragment().is_some() || url.as_str() != raw {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(Self(url))
|
||||
}
|
||||
}
|
||||
|
||||
fn client_builder() -> ClientBuilder {
|
||||
Client::builder()
|
||||
.tls_backend_rustls()
|
||||
.no_proxy()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.retry(reqwest::retry::never())
|
||||
.referer(false)
|
||||
.no_gzip().no_brotli().no_deflate().no_zstd()
|
||||
.http1_only()
|
||||
.pool_max_idle_per_host(0)
|
||||
.connect_timeout(CONNECT_TIMEOUT)
|
||||
.timeout(TRANSFER_TIMEOUT)
|
||||
}
|
||||
|
||||
fn client() -> Result<Client, ErrorObj> {
|
||||
client_builder().https_only(true).build()
|
||||
.map_err(|_| ErrorObj::new(ErrorCode::Internal, "cannot initialize HTTPS storage transport"))
|
||||
}
|
||||
|
||||
fn timeout() -> ErrorObj { ErrorObj::new(ErrorCode::Io, "storage transfer timed out") }
|
||||
|
||||
// In particular, do not format the reqwest error, its causes, the response body or headers.
|
||||
// URLs, signature errors and redirects can all contain the presigned credential.
|
||||
fn network_error(error: reqwest::Error) -> ErrorObj {
|
||||
if error.is_timeout() { return timeout(); }
|
||||
ErrorObj::new(ErrorCode::Io, "HTTPS storage transfer failed")
|
||||
}
|
||||
|
||||
fn response_error(status: StatusCode, conditional_put: bool) -> ErrorObj {
|
||||
let (code, message) = match status {
|
||||
StatusCode::PRECONDITION_FAILED | StatusCode::CONFLICT if conditional_put =>
|
||||
(ErrorCode::FileExists, "storage declined the upload without overwrite"),
|
||||
StatusCode::NOT_FOUND => (ErrorCode::NotFound, "file was not found in storage"),
|
||||
StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => (ErrorCode::ServerError, "storage declined the authorization"),
|
||||
_ if status.is_redirection() => (ErrorCode::ServerError, "storage tried to redirect the request"),
|
||||
_ => (ErrorCode::ServerError, "storage refused the request"),
|
||||
};
|
||||
ErrorObj::new(code, format!("{message} (HTTP {})", status.as_u16()))
|
||||
}
|
||||
|
||||
fn size_error() -> ErrorObj { ErrorObj::new(ErrorCode::Io, "storage response did not match the expected file size") }
|
||||
|
||||
fn download_size(response: &Response, expected: Option<u64>) -> Result<u64, ErrorObj> {
|
||||
let length = response.content_length();
|
||||
if response.headers().contains_key(CONTENT_RANGE) ||
|
||||
matches!((expected, length), (Some(expected), Some(length)) if expected != length)
|
||||
{
|
||||
return Err(size_error());
|
||||
}
|
||||
expected.or(length).filter(|&n| n <= MAX_SAFE_SIZE).ok_or_else(size_error)
|
||||
}
|
||||
|
||||
pub(crate) struct Download {
|
||||
pub id: u32,
|
||||
pub dir: PathBuf,
|
||||
pub name: String,
|
||||
pub overwrite: bool,
|
||||
pub expected_size: Option<u64>,
|
||||
pub total: Arc<AtomicU64>,
|
||||
pub progress: Arc<AtomicU64>,
|
||||
pub control: Arc<CommitControl>,
|
||||
pub rate: Arc<RateLimit>,
|
||||
}
|
||||
|
||||
impl Download {
|
||||
pub(crate) async fn run(self, url: SignedUrl) -> Result<Ended, ErrorObj> {
|
||||
self.run_with(client()?, url).await
|
||||
}
|
||||
|
||||
async fn run_with(self, client: Client, url: SignedUrl) -> Result<Ended, ErrorObj> {
|
||||
let Self { id, dir, name, overwrite, expected_size, total, progress, control, rate } = self;
|
||||
let _cancel = CancelOnDrop(Some(control.clone()));
|
||||
super::local_component(&name)?;
|
||||
let mut response = tokio::time::timeout(STALL_DEADLINE, client.get(url.0).send()).await
|
||||
.map_err(|_| timeout())?.map_err(network_error)?;
|
||||
if response.status() != StatusCode::OK {
|
||||
return Err(response_error(response.status(), false));
|
||||
}
|
||||
let size = download_size(&response, expected_size)?;
|
||||
total.store(size, Ordering::Release);
|
||||
let (tx, rx) = mpsc::channel(BUFFERS);
|
||||
let (back, _) = mpsc::channel(1);
|
||||
let writer = tokio::task::spawn_blocking(move || disk_writer(dir, id, overwrite, name, rx, back, control, None));
|
||||
let streamed = tokio::time::timeout(TRANSFER_TIMEOUT, async {
|
||||
let mut remaining = size;
|
||||
loop {
|
||||
let Some(mut frame) = tokio::time::timeout(STALL_DEADLINE, response.chunk()).await
|
||||
.map_err(|_| timeout())?.map_err(network_error)? else { break };
|
||||
if frame.len() as u64 > remaining { return Err(size_error()); }
|
||||
while !frame.is_empty() {
|
||||
let n = rate.s3_chunk_len(frame.len().min(CHUNK));
|
||||
rate.acquire(n).await;
|
||||
let chunk = if n == frame.len() { std::mem::take(&mut frame) } else { frame.split_to(n) };
|
||||
if tx.send(ToDisk::HttpData(chunk)).await.is_err() { return Ok(false); }
|
||||
remaining -= n as u64;
|
||||
progress.fetch_add(n as u64, Ordering::Release);
|
||||
}
|
||||
}
|
||||
if remaining != 0 { return Err(size_error()); }
|
||||
Ok(true)
|
||||
}).await.unwrap_or_else(|_| Err(timeout()));
|
||||
if matches!(streamed, Ok(true)) {
|
||||
// Only an exact, fully received body can open the existing atomic publication gate.
|
||||
let _ = tx.send(ToDisk::Commit).await;
|
||||
}
|
||||
drop(tx);
|
||||
let written = writer.await.map_err(|_| ErrorObj::new(ErrorCode::Internal, "download staging task failed"))?;
|
||||
streamed?;
|
||||
match written? {
|
||||
Written::Published => Ok(Ended::Complete { closed: true }),
|
||||
Written::Paused(_) => Err(ErrorObj::new(ErrorCode::Internal, "HTTPS download did not publish")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Upload {
|
||||
pub file: File,
|
||||
pub size: u64,
|
||||
pub modified: Option<SystemTime>,
|
||||
pub overwrite: bool,
|
||||
pub progress: Arc<AtomicU64>,
|
||||
pub rate: Arc<RateLimit>,
|
||||
}
|
||||
|
||||
/// Return the backing buffer after the HTTP client writes or drops the last view of these bytes.
|
||||
struct UploadChunk {
|
||||
buf: Option<Vec<u8>>,
|
||||
len: usize,
|
||||
back: mpsc::Sender<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for UploadChunk {
|
||||
fn as_ref(&self) -> &[u8] { &self.buf.as_ref().expect("owned buffer")[..self.len] }
|
||||
}
|
||||
|
||||
impl Drop for UploadChunk {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.back.try_send(self.buf.take().expect("owned buffer"));
|
||||
}
|
||||
}
|
||||
|
||||
struct UploadBody {
|
||||
rx: mpsc::Receiver<(Vec<u8>, usize)>,
|
||||
back: mpsc::Sender<Vec<u8>>,
|
||||
frame: Bytes,
|
||||
remaining: u64,
|
||||
progress: Arc<AtomicU64>,
|
||||
rate: Arc<RateLimit>,
|
||||
activity: watch::Sender<UploadActivity>,
|
||||
}
|
||||
|
||||
impl UploadBody {
|
||||
async fn next(mut self) -> Option<(io::Result<Bytes>, Self)> {
|
||||
if self.remaining == 0 { return None; }
|
||||
if self.frame.is_empty() {
|
||||
let Some((buf, len)) = self.rx.recv().await else {
|
||||
self.remaining = 0;
|
||||
return Some((Err(io::Error::other("upload source ended early")), self));
|
||||
};
|
||||
self.frame = Bytes::from_owner(UploadChunk { buf: Some(buf), len, back: self.back.clone() });
|
||||
}
|
||||
let n = self.rate.s3_chunk_len(self.frame.len());
|
||||
self.activity.send_replace(UploadActivity::Pacing);
|
||||
self.rate.acquire(n).await;
|
||||
let chunk = if n == self.frame.len() { std::mem::take(&mut self.frame) } else { self.frame.split_to(n) };
|
||||
self.remaining -= n as u64;
|
||||
self.progress.fetch_add(n as u64, Ordering::Relaxed);
|
||||
self.activity.send_replace(if self.remaining == 0 { UploadActivity::AwaitingResponse } else { UploadActivity::Sending });
|
||||
Some((Ok(chunk), self))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum UploadActivity { Sending, Pacing, AwaitingResponse }
|
||||
|
||||
async fn upload_watchdog(mut activity: watch::Receiver<UploadActivity>) -> ErrorObj {
|
||||
loop {
|
||||
let current = *activity.borrow_and_update();
|
||||
let wait = match current {
|
||||
UploadActivity::Sending => STALL_DEADLINE,
|
||||
UploadActivity::AwaitingResponse => CONFIRM_DEADLINE,
|
||||
// Waiting for a configured shared bandwidth allowance is not a network stall.
|
||||
UploadActivity::Pacing => {
|
||||
if activity.changed().await.is_err() { return timeout(); }
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if !matches!(tokio::time::timeout(wait, activity.changed()).await, Ok(Ok(()))) {
|
||||
return timeout();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_upload(
|
||||
mut file: File,
|
||||
size: u64,
|
||||
modified: Option<SystemTime>,
|
||||
prepared: oneshot::Sender<Result<(), ErrorObj>>,
|
||||
tx: mpsc::Sender<(Vec<u8>, usize)>,
|
||||
mut back: mpsc::Receiver<Vec<u8>>,
|
||||
source_error: Arc<OnceLock<ErrorObj>>,
|
||||
) {
|
||||
let ready = upload_source_unchanged(&file, size, modified);
|
||||
let failed = ready.is_err();
|
||||
if prepared.send(ready).is_err() || failed { return; }
|
||||
let mut remaining = size;
|
||||
while remaining != 0 {
|
||||
let Some(mut buf) = back.blocking_recv() else { return };
|
||||
let n = remaining.min(CHUNK as u64) as usize;
|
||||
if let Err(e) = file.read_exact(&mut buf[..n]) {
|
||||
let _ = source_error.set(io_err("cannot read the full upload source", e));
|
||||
return;
|
||||
}
|
||||
remaining -= n as u64;
|
||||
// Check before handing the HTTP client the final bytes that can commit the PUT.
|
||||
if remaining == 0 {
|
||||
if let Err(e) = upload_source_unchanged(&file, size, modified) {
|
||||
let _ = source_error.set(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if tx.blocking_send((buf, n)).is_err() { return; }
|
||||
}
|
||||
}
|
||||
|
||||
impl Upload {
|
||||
pub(crate) async fn run(self, url: SignedUrl) -> Result<Ended, ErrorObj> {
|
||||
self.run_with(client()?, url).await
|
||||
}
|
||||
|
||||
async fn run_with(self, client: Client, url: SignedUrl) -> Result<Ended, ErrorObj> {
|
||||
let Self { file, size, modified, overwrite, progress, rate } = self;
|
||||
if size > MAX_SAFE_SIZE { return Err(bad("upload file is too large")); }
|
||||
let (ready, prepared) = oneshot::channel();
|
||||
let (tx, rx) = mpsc::channel(BUFFERS);
|
||||
let (back, bufs) = mpsc::channel(BUFFERS);
|
||||
for _ in 0..size.div_ceil(CHUNK as u64).min(BUFFERS as u64) {
|
||||
back.try_send(vec![0; size.min(CHUNK as u64) as usize]).expect("capacity");
|
||||
}
|
||||
let source_error = Arc::new(OnceLock::new());
|
||||
let source = source_error.clone();
|
||||
let _reader = tokio::task::spawn_blocking(move || read_upload(file, size, modified, ready, tx, bufs, source));
|
||||
tokio::time::timeout(STALL_DEADLINE, prepared).await.map_err(|_| timeout())?
|
||||
.map_err(|_| ErrorObj::new(ErrorCode::Internal, "upload source task failed"))??;
|
||||
let mut request = client.put(url.0).header(CONTENT_LENGTH, size);
|
||||
if !overwrite { request = request.header(IF_NONE_MATCH, "*"); }
|
||||
let initial = if size == 0 { UploadActivity::AwaitingResponse } else { UploadActivity::Sending };
|
||||
let (activity, watch) = watch::channel(initial);
|
||||
if size != 0 {
|
||||
let body = UploadBody {
|
||||
rx, back, frame: Bytes::new(), remaining: size, progress: progress.clone(), rate,
|
||||
activity: activity.clone(),
|
||||
};
|
||||
request = request.body(reqwest::Body::wrap_stream(futures::stream::unfold(body, UploadBody::next)));
|
||||
}
|
||||
// Hold the activity sender even if the HTTP client drops the request body as soon as it
|
||||
// sees response headers, so that headers (e.g. an early 412) decide the outcome.
|
||||
let _activity = activity;
|
||||
let response = tokio::select! {
|
||||
biased;
|
||||
result = request.send() => result.map_err(|e| source_error.get().cloned().unwrap_or_else(|| network_error(e)))?,
|
||||
error = upload_watchdog(watch) => return Err(error),
|
||||
};
|
||||
if !response.status().is_success() { return Err(response_error(response.status(), !overwrite)); }
|
||||
if progress.load(Ordering::Relaxed) != size {
|
||||
return Err(source_error.get().cloned().unwrap_or_else(|| ErrorObj::new(ErrorCode::Io, "storage answered before the whole file was uploaded")));
|
||||
}
|
||||
Ok(Ended::Complete { closed: true })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
const TARGET: &str = "/bucket/file%2B.bin?X-Amz-Signature=signature-secret&k=%2B%2F%25";
|
||||
const CASE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
struct Scratch(PathBuf);
|
||||
impl Scratch {
|
||||
fn new(tag: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("tp-s3-{tag}-{}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
fn parts(&self) -> usize {
|
||||
std::fs::read_dir(&self.0).unwrap().filter(|e| e.as_ref().unwrap().path().extension().is_some_and(|e| e == "part")).count()
|
||||
}
|
||||
fn download(&self, expected_size: Option<u64>) -> Download {
|
||||
Download {
|
||||
id: 9, dir: self.0.clone(), name: "download.bin".into(), overwrite: false,
|
||||
expected_size, total: Arc::default(), progress: Arc::default(), control: Arc::default(), rate: Arc::default(),
|
||||
}
|
||||
}
|
||||
fn upload(&self, data: &[u8], overwrite: bool) -> Upload {
|
||||
let path = self.0.join("upload.bin");
|
||||
std::fs::write(&path, data).unwrap();
|
||||
let (file, size) = super::super::prepare_upload(&path).unwrap();
|
||||
let modified = file.metadata().unwrap().modified().ok();
|
||||
Upload { file, size, modified, overwrite, progress: Arc::default(), rate: Arc::default() }
|
||||
}
|
||||
}
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); }
|
||||
}
|
||||
|
||||
// These byte-contract tests bypass only URL construction and the HTTPS-only scheme guard.
|
||||
async fn fixture() -> (TcpListener, Client, SignedUrl) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let url = SignedUrl(Url::parse(&format!("http://{addr}{TARGET}")).unwrap());
|
||||
(listener, client_builder().build().unwrap(), url)
|
||||
}
|
||||
|
||||
async fn read_request(listener: TcpListener, verb: &str) -> (BufReader<TcpStream>, BTreeMap<String, String>) {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut stream = BufReader::new(stream);
|
||||
let mut line = String::new();
|
||||
stream.read_line(&mut line).await.unwrap();
|
||||
assert_eq!(line, format!("{verb} {TARGET} HTTP/1.1\r\n"));
|
||||
let mut headers = BTreeMap::new();
|
||||
loop {
|
||||
line.clear();
|
||||
assert_ne!(stream.read_line(&mut line).await.unwrap(), 0, "short request headers");
|
||||
if line == "\r\n" { break; }
|
||||
let (name, value) = line.split_once(':').unwrap();
|
||||
assert!(headers.insert(name.to_ascii_lowercase(), value.trim().to_owned()).is_none());
|
||||
}
|
||||
for name in ["authorization", "cookie", "proxy-authorization", "referer", "accept-encoding", "range"] {
|
||||
assert!(!headers.contains_key(name));
|
||||
}
|
||||
(stream, headers)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grants_must_be_https_and_remain_private() {
|
||||
let url = SignedUrl::parse(&format!("https://storage.example{TARGET}")).unwrap();
|
||||
assert_eq!(format!("{url:?}"), "SignedUrl(<redacted>)");
|
||||
for bad in [
|
||||
"http://storage.example/?sig=signature-secret",
|
||||
"https://user:pw@storage.example/?sig=signature-secret",
|
||||
"https://@storage.example/?sig=signature-secret",
|
||||
"https://storage.example/a/%2e%2e/b?sig=signature-secret",
|
||||
"https://storage.example/a?sig=signature-secret#fragment",
|
||||
"https://storage.example/\t?sig=signature-secret",
|
||||
] {
|
||||
let error = SignedUrl::parse(bad).unwrap_err();
|
||||
assert_eq!(error.code, ErrorCode::ServerError);
|
||||
assert!(!format!("{error:?}").contains("signature-secret"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn put_sends_exact_length_and_conditional_header() {
|
||||
tokio::time::timeout(CASE_TIMEOUT, async {
|
||||
let dir = Scratch::new("put");
|
||||
let large = vec![42; CHUNK * 5 + 17];
|
||||
for (data, overwrite, response) in [
|
||||
(large.as_slice(), false, "200 OK"),
|
||||
(b"".as_slice(), true, "200 OK"),
|
||||
(b"taken".as_slice(), false, "412 Precondition Failed"),
|
||||
] {
|
||||
let (listener, client, url) = fixture().await;
|
||||
let upload = dir.upload(data, overwrite);
|
||||
let progress = upload.progress.clone();
|
||||
let server = async {
|
||||
let (mut stream, headers) = read_request(listener, "PUT").await;
|
||||
assert_eq!(headers["content-length"], data.len().to_string());
|
||||
assert_eq!(headers.get("if-none-match").map(String::as_str), (!overwrite).then_some("*"));
|
||||
assert!(!headers.contains_key("transfer-encoding"));
|
||||
let mut received = vec![0; data.len()];
|
||||
stream.read_exact(&mut received).await.unwrap();
|
||||
assert_eq!(received, data);
|
||||
let answer = format!("HTTP/1.1 {response}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
||||
stream.get_mut().write_all(answer.as_bytes()).await.unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(upload.run_with(client, url), server);
|
||||
if response.starts_with("200") {
|
||||
assert!(matches!(result.unwrap(), Ended::Complete { .. }));
|
||||
} else {
|
||||
assert_eq!(result.unwrap_err().code, ErrorCode::FileExists);
|
||||
}
|
||||
assert_eq!(progress.load(Ordering::Relaxed), data.len() as u64);
|
||||
}
|
||||
}).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_checks_size_and_only_publishes_without_clobber() {
|
||||
tokio::time::timeout(CASE_TIMEOUT, async {
|
||||
let dir = Scratch::new("get");
|
||||
let target = dir.0.join("download.bin");
|
||||
for (reply, expected, error) in [
|
||||
(b"Content-Length: 2\r\n\r\nhi".as_slice(), None, None),
|
||||
(b"Content-Length: 3\r\n\r\nhi".as_slice(), Some(3), Some(ErrorCode::Io)),
|
||||
(b"Content-Length: 2\r\n\r\nhi".as_slice(), Some(1), Some(ErrorCode::Io)),
|
||||
(b"Transfer-Encoding: chunked\r\n\r\n2\r\nhi\r\n0\r\n\r\n".as_slice(), Some(1), Some(ErrorCode::Io)),
|
||||
(b"Content-Length: 2\r\n\r\nhi".as_slice(), Some(2), Some(ErrorCode::FileExists)),
|
||||
] {
|
||||
let (listener, client, url) = fixture().await;
|
||||
let download = dir.download(expected);
|
||||
let (total, progress) = (download.total.clone(), download.progress.clone());
|
||||
let server = async {
|
||||
let (mut stream, _) = read_request(listener, "GET").await;
|
||||
if error == Some(ErrorCode::FileExists) { std::fs::write(&target, b"keep").unwrap(); }
|
||||
stream.get_mut().write_all(b"HTTP/1.1 200 OK\r\nConnection: close\r\n").await.unwrap();
|
||||
stream.get_mut().write_all(reply).await.unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(download.run_with(client, url), server);
|
||||
if let Some(error) = error {
|
||||
assert_eq!(result.unwrap_err().code, error);
|
||||
if error == ErrorCode::FileExists {
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"keep");
|
||||
} else {
|
||||
assert!(!target.exists());
|
||||
}
|
||||
} else {
|
||||
assert!(matches!(result.unwrap(), Ended::Complete { .. }));
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"hi");
|
||||
assert_eq!(total.load(Ordering::Acquire), 2);
|
||||
assert_eq!(progress.load(Ordering::Acquire), 2);
|
||||
std::fs::remove_file(&target).unwrap();
|
||||
}
|
||||
assert_eq!(dir.parts(), 0);
|
||||
}
|
||||
}).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redirects_and_error_body_are_not_exposed() {
|
||||
tokio::time::timeout(CASE_TIMEOUT, async {
|
||||
let dir = Scratch::new("redirect");
|
||||
let (listener, client, url) = fixture().await;
|
||||
let server = async {
|
||||
let (mut stream, _) = read_request(listener, "GET").await;
|
||||
stream.get_mut().write_all(b"HTTP/1.1 307 Temporary Redirect\r\nLocation: /other?token=location-secret\r\nContent-Length: 11\r\n\r\nbody-secret").await.unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(dir.download(None).run_with(client, url), server);
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.code, ErrorCode::ServerError);
|
||||
assert_eq!(error.message, "storage tried to redirect the request (HTTP 307)");
|
||||
assert_eq!(dir.parts(), 0);
|
||||
}).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aborting_get_discards_incomplete_staging() {
|
||||
tokio::time::timeout(CASE_TIMEOUT, async {
|
||||
let dir = Scratch::new("abort");
|
||||
let (listener, client, url) = fixture().await;
|
||||
let download = dir.download(Some(4));
|
||||
let (control, progress) = (download.control.clone(), download.progress.clone());
|
||||
let task = tokio::spawn(download.run_with(client, url));
|
||||
let (mut stream, _) = read_request(listener, "GET").await;
|
||||
stream.get_mut().write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nhi").await.unwrap();
|
||||
while progress.load(Ordering::Acquire) != 2 || dir.parts() != 1 { tokio::task::yield_now().await; }
|
||||
assert!(control.cancel());
|
||||
task.abort();
|
||||
assert!(task.await.unwrap_err().is_cancelled());
|
||||
while dir.parts() != 0 { tokio::task::yield_now().await; }
|
||||
assert!(!dir.0.join("download.bin").exists());
|
||||
}).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aborting_put_closes_connection_without_finishing_body() {
|
||||
tokio::time::timeout(CASE_TIMEOUT, async {
|
||||
let dir = Scratch::new("abort-put");
|
||||
let (listener, client, url) = fixture().await;
|
||||
let upload = dir.upload(b"not sent", false);
|
||||
let rate = upload.rate.clone();
|
||||
let progress = upload.progress.clone();
|
||||
// Hold the pacing lock so no body can be yielded, even on a fast client.
|
||||
let _pacing = rate.next.lock().await;
|
||||
let task = tokio::spawn(upload.run_with(client, url));
|
||||
let (mut stream, headers) = read_request(listener, "PUT").await;
|
||||
assert_eq!(headers["content-length"], "8");
|
||||
task.abort();
|
||||
assert!(task.await.unwrap_err().is_cancelled());
|
||||
assert_eq!(stream.read(&mut [0u8; 1]).await.unwrap(), 0);
|
||||
assert_eq!(progress.load(Ordering::Relaxed), 0);
|
||||
}).await.unwrap();
|
||||
}
|
||||
}
|
||||
+38
-132
@@ -9,12 +9,9 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use futures::FutureExt;
|
||||
use tsclientlib::{FileDownloadResult, FileUploadResult};
|
||||
|
||||
use crate::file_transfer::{self as ft, Direction, Ended, ListBackend, ListJob, Local, Partial, Request, Stage, Tombstone, Transfer};
|
||||
use crate::file_transfer::{self as ft, Direction, Ended, ListJob, Local, Partial, Request, Stage, Tombstone, Transfer};
|
||||
use crate::rawcmd::RawNotification;
|
||||
|
||||
#[path = "files_session/s3.rs"]
|
||||
pub(super) mod s3;
|
||||
|
||||
/// Channel passwords travel hashed, like tsclientlib's own `download_file`/`upload_file`.
|
||||
fn cpw(password: &str) -> String {
|
||||
if password.is_empty() { String::new() } else { tsproto_types::crypto::encode_password(password.as_bytes()) }
|
||||
@@ -58,15 +55,6 @@ fn channel_known(c: &Conn, channel_id: u64) -> Result<(), ErrorObj> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn list_command(backend: ListBackend, channel_id: u64, path: &str, password: &str) -> OutCommand {
|
||||
match backend {
|
||||
ListBackend::Legacy => menu::command("ftgetfilelist", &[("cid", channel_id.to_string()), ("cpw", cpw(password)), ("path", path.into())]),
|
||||
// Full clients send the same SHA-1/base64 channel password in chpw. S3 lists the entire
|
||||
// channel; the requested browser directory is applied locally, never sent on the wire.
|
||||
ListBackend::S3 => menu::command("s3ft_list_files", &[("chid", channel_id.to_string()), ("chpw", cpw(password))]),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ftstop` for a granted transfer. An aborted upload's partial file is deleted on the server; a
|
||||
/// paused one (`keep`, official haltTransfer without deleteUnfinishedFile) is kept for resume.
|
||||
/// Cancelling a transfer that is already paused sends nothing, like the official
|
||||
@@ -93,9 +81,6 @@ fn release(c: &mut Conn, ftid: u16, server_ftid: Option<u16>, direction: Directi
|
||||
|
||||
/// Remove a transfer that will not complete. Dropping the record aborts its I/O.
|
||||
fn retire(c: &mut Conn, t: Transfer) {
|
||||
if let Stage::S3Init { handle, .. } | Stage::S3Confirming { handle, .. } = t.stage {
|
||||
c.s3_receipts.remove(&handle);
|
||||
}
|
||||
if let Some(ftid) = t.ftid() {
|
||||
release(c, ftid, t.server_ftid, t.direction, false);
|
||||
}
|
||||
@@ -134,18 +119,6 @@ fn halt(c: &mut Conn, i: usize) -> Option<Value> {
|
||||
/// doFileDownload/doFileUpload with resume: download `seekpos` = kept bytes, upload `resume=1`
|
||||
/// without overwrite). On a send failure the transfer is removed and its `failed` event returned.
|
||||
fn start(c: &mut Conn, i: usize, resume: bool) -> Result<Value, (Value, ErrorObj)> {
|
||||
let t = &c.files.transfers[i];
|
||||
match c.files.list_backend(t.channel_id) {
|
||||
Ok(backend) if backend == t.backend => {}
|
||||
Ok(_) => {
|
||||
let e = ErrorObj::new(ErrorCode::MediaUnsupported, "file storage changed while the transfer was queued");
|
||||
return Err((c.files.transfers.remove(i).event("failed", Some(&e)), e));
|
||||
}
|
||||
Err(e) => return Err((c.files.transfers.remove(i).event("failed", Some(&e)), e)),
|
||||
}
|
||||
if t.backend == ListBackend::S3 {
|
||||
return s3::start(c, i);
|
||||
}
|
||||
let ftid = c.transfer_id();
|
||||
let t = &c.files.transfers[i];
|
||||
let resume_at = t.resume_args(resume);
|
||||
@@ -214,7 +187,7 @@ fn init_command(direction: Direction, ftid: u16, channel_id: u64, path: &str, ha
|
||||
|
||||
impl Session {
|
||||
pub(super) async fn files_request(&mut self, id: &str, request: Request) -> Result<Option<Value>, ErrorObj> {
|
||||
if matches!(&request, Request::Mkdir { .. } | Request::Rename { .. } | Request::Delete { .. } | Request::FetchImage { .. }) {
|
||||
if !matches!(&request, Request::Cancel { .. } | Request::Pause { .. } | Request::Resume { .. } | Request::Transfers | Request::Config { .. }) {
|
||||
self.connected_conn()?.files.require_legacy()?;
|
||||
}
|
||||
match request {
|
||||
@@ -224,8 +197,8 @@ impl Session {
|
||||
c.files.slots = Some([download_slots, upload_slots]);
|
||||
c.files.download_rate.set(download_limit);
|
||||
c.files.upload_rate.set(upload_limit);
|
||||
// Legacy transfers pause when their slots are removed. S3 transfers cannot resume;
|
||||
// they drain before the queue starts any more above the new limit.
|
||||
// Official updateConcurrentTransferLimits: a changed limit pauses each channel's
|
||||
// excess in-progress transfers; they wait for an explicit resume.
|
||||
let mut events = Vec::new();
|
||||
if changed {
|
||||
for transfer_id in c.files.over_limit() {
|
||||
@@ -243,9 +216,6 @@ impl Session {
|
||||
let c = self.connected_conn()?;
|
||||
let i = c.files.index_of_id(transfer_id).ok_or_else(|| not_active(transfer_id))?;
|
||||
let t = &c.files.transfers[i];
|
||||
if t.backend == ListBackend::S3 {
|
||||
return Err(ErrorObj::new(ErrorCode::MediaUnsupported, "S3 file transfers cannot be paused"));
|
||||
}
|
||||
if t.channel_id == 0 {
|
||||
return Err(menu::bad("server icon transfers cannot be paused"));
|
||||
}
|
||||
@@ -260,14 +230,23 @@ impl Session {
|
||||
Request::Resume { transfer_id } => self.files_resume(transfer_id).await,
|
||||
Request::List { channel_id, path, password } => {
|
||||
let c = self.connected_conn()?;
|
||||
let backend = c.files.list_backend(channel_id)?;
|
||||
if channel_id != 0 { channel_known(c, channel_id)?; }
|
||||
if c.files.list_pending(channel_id, &path) {
|
||||
return Err(menu::bad("a listing of this folder is already pending"));
|
||||
}
|
||||
let cmd = list_command(backend, channel_id, &path, &password);
|
||||
let cmd = menu::command("ftgetfilelist", &[("cid", channel_id.to_string()), ("cpw", cpw(&password)), ("path", path.clone())]);
|
||||
let handle = c.send(cmd).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
|
||||
c.files.lists.insert(handle, ListJob::new(id, channel_id, path, backend));
|
||||
c.files.lists.insert(handle, ListJob {
|
||||
req: id.into(),
|
||||
channel_id,
|
||||
path,
|
||||
entries: Vec::new(),
|
||||
malformed: 0,
|
||||
overflow: false,
|
||||
finished: false,
|
||||
result_ok: false,
|
||||
started: Instant::now(),
|
||||
});
|
||||
Ok(None)
|
||||
}
|
||||
Request::Mkdir { channel_id, path, password } => {
|
||||
@@ -290,16 +269,16 @@ impl Session {
|
||||
self.files_simple(id, channel_id, cmd)
|
||||
}
|
||||
Request::Download { channel_id, password, path, dest_dir, subdirs, overwrite } => {
|
||||
let backend = self.files_transfer_backend(channel_id)?;
|
||||
if channel_id != 0 { self.connected_conn().and_then(|c| channel_known(c, channel_id))?; }
|
||||
let name = ft::file_name(&path).to_owned();
|
||||
let checked = name.clone();
|
||||
let dir = tokio::task::spawn_blocking(move || ft::prepare_download(&dest_dir, &subdirs, &checked, overwrite))
|
||||
.await
|
||||
.map_err(internal)??;
|
||||
self.files_enqueue(backend, Direction::Download, channel_id, path, &password, overwrite, Local::Download { dir, name, overwrite, partial: None }, 0)
|
||||
self.files_enqueue(Direction::Download, channel_id, path, &password, overwrite, Local::Download { dir, name, overwrite, partial: None }, 0)
|
||||
}
|
||||
Request::Upload { channel_id, password, path, source, overwrite } => {
|
||||
let backend = self.files_transfer_backend(channel_id)?;
|
||||
if channel_id != 0 { self.connected_conn().and_then(|c| channel_known(c, channel_id))?; }
|
||||
let (file, size, modified) = tokio::task::spawn_blocking(move || {
|
||||
ft::prepare_upload(&source).map(|(file, size)| {
|
||||
let modified = file.metadata().ok().and_then(|m| m.modified().ok());
|
||||
@@ -308,7 +287,7 @@ impl Session {
|
||||
})
|
||||
.await
|
||||
.map_err(internal)??;
|
||||
self.files_enqueue(backend, Direction::Upload, channel_id, path, &password, overwrite, Local::Upload { file: Some(file), size, modified }, size)
|
||||
self.files_enqueue(Direction::Upload, channel_id, path, &password, overwrite, Local::Upload { file: Some(file), size, modified }, size)
|
||||
}
|
||||
Request::Cancel { transfer_id } => self.files_cancel(transfer_id).await,
|
||||
Request::FetchImage { channel_id, path } => {
|
||||
@@ -323,13 +302,6 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn files_transfer_backend(&mut self, channel_id: u64) -> Result<ListBackend, ErrorObj> {
|
||||
let c = self.connected_conn()?;
|
||||
let backend = c.files.list_backend(channel_id)?;
|
||||
if channel_id != 0 { channel_known(c, channel_id)?; }
|
||||
Ok(backend)
|
||||
}
|
||||
|
||||
fn files_simple(&mut self, id: &str, channel_id: u64, cmd: OutCommand) -> Result<Option<Value>, ErrorObj> {
|
||||
let c = self.connected_conn()?;
|
||||
// Channel 0 (server icons) is not a tree channel; the parser admitted only icon paths for it.
|
||||
@@ -343,7 +315,6 @@ impl Session {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn files_enqueue(
|
||||
&mut self,
|
||||
backend: ListBackend,
|
||||
direction: Direction,
|
||||
channel_id: u64,
|
||||
path: String,
|
||||
@@ -360,7 +331,6 @@ impl Session {
|
||||
let now = Instant::now();
|
||||
let t = Transfer {
|
||||
id,
|
||||
backend,
|
||||
direction,
|
||||
channel_id,
|
||||
path,
|
||||
@@ -368,7 +338,6 @@ impl Session {
|
||||
overwrite,
|
||||
local,
|
||||
total,
|
||||
s3_total: None,
|
||||
stage: Stage::Queued,
|
||||
server_ftid: None,
|
||||
confirmed: false,
|
||||
@@ -394,13 +363,10 @@ impl Session {
|
||||
.files
|
||||
.index_of_id(transfer_id)
|
||||
.ok_or_else(|| not_active(transfer_id))?;
|
||||
let t = &c.files.transfers[i];
|
||||
if matches!(t.stage, Stage::Confirming { .. } | Stage::S3Confirming { .. })
|
||||
|| t.direction == Direction::Upload && matches!(&t.stage, Stage::S3Running { task } if task.is_finished())
|
||||
{
|
||||
if matches!(c.files.transfers[i].stage, Stage::Confirming { .. }) {
|
||||
return Err(menu::bad("the upload is complete and awaiting the server's confirmation"));
|
||||
}
|
||||
if !t.commit.cancel() {
|
||||
if !c.files.transfers[i].commit.cancel() {
|
||||
return Err(menu::bad("the download is being committed and can no longer be cancelled"));
|
||||
}
|
||||
let t = c.files.transfers.remove(i);
|
||||
@@ -416,9 +382,6 @@ impl Session {
|
||||
let c = self.connected_conn()?;
|
||||
let i = c.files.index_of_id(transfer_id).ok_or_else(|| not_active(transfer_id))?;
|
||||
let t = &c.files.transfers[i];
|
||||
if t.backend == ListBackend::S3 {
|
||||
return Err(ErrorObj::new(ErrorCode::MediaUnsupported, "S3 file transfers cannot be resumed or force-started"));
|
||||
}
|
||||
if t.channel_id == 0 {
|
||||
return Err(menu::bad("server icon transfers cannot be resumed"));
|
||||
}
|
||||
@@ -478,10 +441,8 @@ impl Session {
|
||||
.and_then(|b| b.channels.get(&ChannelId(job.channel_id)))
|
||||
.and_then(|ch| ch.permission_hints)
|
||||
.map(|h| h.bits());
|
||||
let s3 = job.backend() == ListBackend::S3;
|
||||
let storage = c.files.storage();
|
||||
let req = job.req.clone();
|
||||
match ft::list_result(job, ft::capabilities(hints, s3), storage) {
|
||||
match ft::list_result(job, ft::capabilities(hints), c.files.storage()) {
|
||||
Ok(v) => self.out.ok(&req, v).await,
|
||||
Err(e) => self.out.err(&req, e).await,
|
||||
}
|
||||
@@ -489,27 +450,21 @@ impl Session {
|
||||
|
||||
pub(super) async fn files_result(&mut self, handle: u16, res: Result<(), CommandError>) {
|
||||
let Some(c) = &mut self.conn else { return };
|
||||
if c.s3_receipts.contains_key(&handle) {
|
||||
if let Some(event) = s3::acknowledge(c, handle, res) {
|
||||
self.out.json(&event).await;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(job) = c.files.lists.get_mut(&handle) {
|
||||
let ready = match res {
|
||||
Ok(()) => job.acknowledge(),
|
||||
// Only the legacy protocol uses "database empty result set" for an empty folder.
|
||||
Err(e) if job.backend() == ListBackend::Legacy && e.error.to_u32() == Some(ft::TS_DATABASE_EMPTY_RESULT) => {
|
||||
job.finish_legacy();
|
||||
job.acknowledge()
|
||||
match res {
|
||||
Ok(()) => job.result_ok = true,
|
||||
// An empty folder is answered with "database empty result set" and no rows.
|
||||
Err(e) if e.error.to_u32() == Some(ft::TS_DATABASE_EMPTY_RESULT) => {
|
||||
job.result_ok = true;
|
||||
job.finished = true;
|
||||
}
|
||||
Err(e) => {
|
||||
let req = c.files.lists.remove(&handle).expect("present").req;
|
||||
self.out.err(&req, command_error(&e)).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
if ready {
|
||||
}
|
||||
if job.finished {
|
||||
self.files_answer_list(handle).await;
|
||||
}
|
||||
return;
|
||||
@@ -541,13 +496,6 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn files_s3_transfer(&mut self, reply: crate::rawcmd::S3TransferReply<'_>) {
|
||||
let Some(c) = &mut self.conn else { return };
|
||||
if let Some(event) = s3::notification(c, reply) {
|
||||
self.out.json(&event).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn files_raw(&mut self, raw: &RawNotification) {
|
||||
let Some(c) = &mut self.conn else { return };
|
||||
for handle in c.files.apply_raw(raw) {
|
||||
@@ -555,13 +503,6 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn files_s3_list(&mut self, reply: crate::rawcmd::S3FileList<'_>) {
|
||||
let Some(c) = &mut self.conn else { return };
|
||||
if let Some(handle) = c.files.apply_s3_list(reply) {
|
||||
self.files_answer_list(handle).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn files_download(&mut self, ftid: u16, result: FileDownloadResult) -> Option<FileDownloadResult> {
|
||||
let Some(c) = &mut self.conn else { return Some(result) };
|
||||
if let Some(tomb) = c.files.tombstones.remove(&ftid) {
|
||||
@@ -714,19 +655,19 @@ impl Session {
|
||||
/// Answer every file request and fail every transfer of the current connection.
|
||||
pub(super) async fn files_fail_all(&mut self, why: &str) {
|
||||
let Some(c) = &mut self.conn else { return };
|
||||
c.s3_receipts.clear();
|
||||
let f = &mut c.files;
|
||||
let reqs: Vec<String> = f.lists.drain().map(|(_, j)| j.req).chain(f.simple.drain().map(|(_, r)| r)).collect();
|
||||
f.inits.clear();
|
||||
f.stops.clear();
|
||||
f.tombstones.clear();
|
||||
let transfers: Vec<Transfer> = f.transfers.drain(..).collect();
|
||||
let err = ErrorObj::new(ErrorCode::NotConnected, why);
|
||||
// Abort every task before an output write can await, including tasks with a retained URL.
|
||||
let events: Vec<Value> = f.transfers.drain(..).map(|t| t.event("failed", Some(&err))).collect();
|
||||
for req in reqs {
|
||||
self.out.err(&req, err.clone()).await;
|
||||
}
|
||||
for event in events {
|
||||
for t in transfers {
|
||||
let event = t.event("failed", Some(&err));
|
||||
drop(t);
|
||||
self.out.json(&event).await;
|
||||
}
|
||||
}
|
||||
@@ -756,16 +697,10 @@ impl Session {
|
||||
Stage::Running { task, .. } | Stage::Pausing { task, .. } if task.is_finished() => {
|
||||
Some((&mut *task).now_or_never().expect("finished").unwrap_or_else(|e| Err(internal(e))))
|
||||
}
|
||||
Stage::S3Running { task } if task.is_finished() => {
|
||||
Some((&mut *task).now_or_never().expect("finished").unwrap_or_else(|_| {
|
||||
Err(ErrorObj::new(ErrorCode::Internal, "S3 transfer task failed"))
|
||||
}))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
enum Outcome {
|
||||
Done,
|
||||
ConfirmS3Upload,
|
||||
Failed(ErrorObj),
|
||||
/// Halted (`None`) or broken (`Some`) stream with its kept partial.
|
||||
Stopped(Option<Partial>, Option<ErrorObj>),
|
||||
@@ -773,12 +708,6 @@ impl Session {
|
||||
}
|
||||
let outcome = match finished {
|
||||
Some(Err(e)) => Outcome::Failed(e),
|
||||
Some(Ok(Ended::Complete { .. })) if t.backend == ListBackend::S3 => {
|
||||
if t.direction == Direction::Upload { Outcome::ConfirmS3Upload } else { Outcome::Done }
|
||||
}
|
||||
Some(Ok(Ended::Paused(_) | Ended::Lost { .. })) if t.backend == ListBackend::S3 => {
|
||||
Outcome::Failed(ErrorObj::new(ErrorCode::Io, "S3 file transfer ended before it completed"))
|
||||
}
|
||||
Some(Ok(Ended::Paused(partial))) => Outcome::Stopped(partial, None),
|
||||
Some(Ok(Ended::Lost { error, partial })) => Outcome::Stopped(partial, Some(error)),
|
||||
Some(Ok(Ended::Complete { closed })) if t.direction == Direction::Download || closed || t.confirmed => Outcome::Done,
|
||||
@@ -791,12 +720,6 @@ impl Session {
|
||||
Stage::Init { since, .. } if now - *since >= ft::GRANT_DEADLINE => {
|
||||
Outcome::Failed(ErrorObj::new(ErrorCode::ServerError, "server did not start the file transfer"))
|
||||
}
|
||||
Stage::S3Init { since, .. } if now - *since >= ft::GRANT_DEADLINE => {
|
||||
Outcome::Failed(ErrorObj::new(ErrorCode::ServerError, "server did not grant the S3 file transfer"))
|
||||
}
|
||||
Stage::S3Confirming { since, .. } if now - *since >= ft::CONFIRM_DEADLINE => {
|
||||
Outcome::Failed(ErrorObj::new(ErrorCode::ServerError, "server did not confirm the S3 upload"))
|
||||
}
|
||||
Stage::Running { .. } if now - t.last_change >= ft::STALL_DEADLINE => {
|
||||
Outcome::Failed(ErrorObj::new(ErrorCode::Io, "file transfer stalled"))
|
||||
}
|
||||
@@ -815,21 +738,13 @@ impl Session {
|
||||
match outcome {
|
||||
Outcome::Done => {
|
||||
let t = c.files.transfers.remove(i);
|
||||
if t.backend == ListBackend::Legacy { t.progress.store(t.total, Ordering::Relaxed); }
|
||||
t.progress.store(t.total, Ordering::Relaxed);
|
||||
events.push(t.event("done", None));
|
||||
}
|
||||
Outcome::ConfirmS3Upload => match s3::confirm_upload(c, i, now) {
|
||||
Ok(event) => {
|
||||
events.push(event);
|
||||
i += 1;
|
||||
}
|
||||
Err(e) => events.push(c.files.transfers.remove(i).event("failed", Some(&e))),
|
||||
},
|
||||
Outcome::Failed(e) => {
|
||||
let t = c.files.transfers.remove(i);
|
||||
events.push(t.event("failed", Some(&e)));
|
||||
let ended = !matches!(t.stage, Stage::Running { .. } | Stage::Pausing { .. } | Stage::Init { .. } | Stage::Lost { .. }
|
||||
| Stage::S3Init { .. } | Stage::S3Confirming { .. });
|
||||
let ended = !matches!(t.stage, Stage::Running { .. } | Stage::Pausing { .. } | Stage::Init { .. } | Stage::Lost { .. });
|
||||
if ended {
|
||||
drop(t);
|
||||
} else {
|
||||
@@ -861,7 +776,7 @@ impl Session {
|
||||
}
|
||||
Outcome::Keep => {
|
||||
let t = &mut c.files.transfers[i];
|
||||
if matches!(t.stage, Stage::Running { .. } | Stage::S3Running { .. }) && bytes != t.reported && now - t.last_emit >= ft::PROGRESS_INTERVAL {
|
||||
if matches!(t.stage, Stage::Running { .. }) && bytes != t.reported && now - t.last_emit >= ft::PROGRESS_INTERVAL {
|
||||
t.reported = bytes;
|
||||
t.last_emit = now;
|
||||
events.push(t.event("running", None));
|
||||
@@ -887,15 +802,6 @@ mod tests {
|
||||
|
||||
fn content(cmd: OutCommand) -> String { String::from_utf8(cmd.into_packet().content().to_vec()).unwrap() }
|
||||
|
||||
#[test]
|
||||
fn s3_list_uses_channel_password_hash_and_sends_no_path() {
|
||||
assert_eq!(content(list_command(ListBackend::S3, 9, "/some/folder/", "")), "s3ft_list_files chid=9 chpw");
|
||||
assert_eq!(
|
||||
content(list_command(ListBackend::S3, 9, "/", "abc")),
|
||||
"s3ft_list_files chid=9 chpw=qZk+NkcGgWq6PiVxeFDCbJzQ2J0="
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_icons_use_classic_wire_names_and_channels_stay_unchanged() {
|
||||
let icon = "/icons/icon_3558086607".to_owned();
|
||||
|
||||
@@ -1,207 +0,0 @@
|
||||
use super::*;
|
||||
use crate::file_transfer::s3_http::{Download, SignedUrl, Upload};
|
||||
use crate::rawcmd::{S3TransferKind, S3TransferReply};
|
||||
use tsproto_packets::packets::{Direction as WireDirection, Flags, PacketType};
|
||||
|
||||
/// Both the successful command ACK and the exact object grant are required, in either order.
|
||||
#[derive(Default)]
|
||||
struct GrantReceipt {
|
||||
acked: bool,
|
||||
grant: Option<Result<SignedUrl, ErrorObj>>,
|
||||
}
|
||||
|
||||
impl GrantReceipt {
|
||||
fn ready(&self) -> bool { self.acked && self.grant.is_some() }
|
||||
}
|
||||
|
||||
enum Awaiting {
|
||||
Grant(GrantReceipt),
|
||||
/// This notification is the business result; the server sends no successful ACK after it.
|
||||
UploadDone,
|
||||
}
|
||||
|
||||
pub(in crate::session) struct Receipt {
|
||||
transfer_id: u32,
|
||||
awaiting: Awaiting,
|
||||
}
|
||||
|
||||
fn channel_command(name: &str, channel_id: u64, password: &str) -> OutCommand {
|
||||
let mut cmd = OutCommand::new(WireDirection::C2S, Flags::empty(), PacketType::Command, name);
|
||||
cmd.write_arg("chid", &channel_id);
|
||||
cmd.write_arg("chpw", &password);
|
||||
cmd
|
||||
}
|
||||
|
||||
fn presign_command(direction: Direction, channel_id: u64, path: &str, hashed_password: &str, total: u64) -> OutCommand {
|
||||
let mut cmd = channel_command("s3ft_getpresignedurl", channel_id, hashed_password);
|
||||
// The channel/password header and the object request must be separate rows. The command
|
||||
// sender appends return_code to the last row, as on the normal TS6 wire.
|
||||
cmd.start_new_part();
|
||||
cmd.write_arg("key", &path);
|
||||
let (verb, length) = match direction {
|
||||
Direction::Download => ("GET", 0),
|
||||
Direction::Upload => ("PUT", total),
|
||||
};
|
||||
cmd.write_arg("verb", &verb);
|
||||
cmd.write_arg("length", &length);
|
||||
cmd
|
||||
}
|
||||
|
||||
fn send(c: &mut Conn, cmd: OutCommand) -> Result<u16, ErrorObj> {
|
||||
// Never relay raw packet errors from this path; fixed errors also keep passwords private.
|
||||
c.send(cmd).map_err(|_| ErrorObj::new(ErrorCode::NotConnected, "could not send the S3 file command"))
|
||||
}
|
||||
|
||||
pub(super) fn start(c: &mut Conn, i: usize) -> Result<Value, (Value, ErrorObj)> {
|
||||
let t = &c.files.transfers[i];
|
||||
let transfer_id = t.id;
|
||||
let cmd = presign_command(t.direction, t.channel_id, &t.path, &t.cpw, t.total);
|
||||
match send(c, cmd) {
|
||||
Ok(handle) => {
|
||||
c.s3_receipts.insert(handle, Receipt { transfer_id, awaiting: Awaiting::Grant(GrantReceipt::default()) });
|
||||
c.files.start_seq += 1;
|
||||
let t = &mut c.files.transfers[i];
|
||||
t.started = c.files.start_seq;
|
||||
t.stage = Stage::S3Init { handle, since: Instant::now() };
|
||||
Ok(t.event("starting", None))
|
||||
}
|
||||
Err(e) => Err((c.files.transfers.remove(i).event("failed", Some(&e)), e)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn confirm_upload(c: &mut Conn, i: usize, now: Instant) -> Result<Value, ErrorObj> {
|
||||
let t = &c.files.transfers[i];
|
||||
let transfer_id = t.id;
|
||||
let cmd = channel_command("s3ft_upload_done_notification", t.channel_id, &t.cpw);
|
||||
let handle = send(c, cmd)?;
|
||||
c.s3_receipts.insert(handle, Receipt { transfer_id, awaiting: Awaiting::UploadDone });
|
||||
let t = &mut c.files.transfers[i];
|
||||
t.stage = Stage::S3Confirming { handle, since: now };
|
||||
Ok(t.event("confirming", None))
|
||||
}
|
||||
|
||||
fn failed(c: &mut Conn, i: usize, error: ErrorObj) -> Value {
|
||||
c.files.transfers.remove(i).event("failed", Some(&error))
|
||||
}
|
||||
|
||||
fn server_error(message: &'static str) -> ErrorObj { ErrorObj::new(ErrorCode::ServerError, message) }
|
||||
|
||||
fn apply_grant(c: &mut Conn, handle: u16, i: usize) -> Option<Value> {
|
||||
let receipt = c.s3_receipts.remove(&handle)?;
|
||||
let Awaiting::Grant(GrantReceipt { grant: Some(grant), .. }) = receipt.awaiting else { return None };
|
||||
let url = match grant {
|
||||
Ok(url) => url,
|
||||
Err(e) => return Some(failed(c, i, e)),
|
||||
};
|
||||
let t = &mut c.files.transfers[i];
|
||||
let task = match &mut t.local {
|
||||
Local::Download { dir, name, overwrite, partial: None } => {
|
||||
let total = Arc::new(AtomicU64::new(0));
|
||||
t.s3_total = Some(total.clone());
|
||||
tokio::spawn(Download {
|
||||
id: t.id,
|
||||
dir: std::mem::take(dir),
|
||||
name: std::mem::take(name),
|
||||
overwrite: *overwrite,
|
||||
expected_size: None,
|
||||
total,
|
||||
progress: t.progress.clone(),
|
||||
control: t.commit.clone(),
|
||||
rate: c.files.download_rate.clone(),
|
||||
}.run(url))
|
||||
}
|
||||
Local::Upload { file, size, modified } => {
|
||||
let Some(file) = file.take() else {
|
||||
return Some(failed(c, i, ErrorObj::new(ErrorCode::Internal, "S3 upload source is not open")));
|
||||
};
|
||||
tokio::spawn(Upload {
|
||||
file,
|
||||
size: *size,
|
||||
modified: *modified,
|
||||
overwrite: t.overwrite,
|
||||
progress: t.progress.clone(),
|
||||
rate: c.files.upload_rate.clone(),
|
||||
}.run(url))
|
||||
}
|
||||
Local::Download { .. } => {
|
||||
return Some(failed(c, i, ErrorObj::new(ErrorCode::Internal, "S3 downloads do not resume partial data")));
|
||||
}
|
||||
};
|
||||
t.stage = Stage::S3Running { task };
|
||||
Some(t.event("running", None))
|
||||
}
|
||||
|
||||
pub(super) fn acknowledge(c: &mut Conn, handle: u16, result: Result<(), CommandError>) -> Option<Value> {
|
||||
let receipt = c.s3_receipts.get_mut(&handle)?;
|
||||
let i = c.files.index_of_id(receipt.transfer_id)?;
|
||||
match result {
|
||||
Err(e) => {
|
||||
let error = match receipt.awaiting {
|
||||
Awaiting::Grant(_) => init_error(&e, ft::file_name(&c.files.transfers[i].path)),
|
||||
Awaiting::UploadDone => command_error(&e),
|
||||
};
|
||||
c.s3_receipts.remove(&handle);
|
||||
Some(failed(c, i, error))
|
||||
}
|
||||
Ok(()) => {
|
||||
if let Awaiting::Grant(grant) = &mut receipt.awaiting {
|
||||
grant.acked = true;
|
||||
if grant.ready() { return apply_grant(c, handle, i); }
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn notification(c: &mut Conn, reply: S3TransferReply<'_>) -> Option<Value> {
|
||||
let handle = reply.handle?;
|
||||
let receipt = c.s3_receipts.get_mut(&handle)?;
|
||||
let i = c.files.index_of_id(receipt.transfer_id)?;
|
||||
match (&mut receipt.awaiting, reply.kind) {
|
||||
(Awaiting::Grant(grant), S3TransferKind::Presign) if grant.grant.is_none() => {
|
||||
let t = &c.files.transfers[i];
|
||||
grant.grant = Some(reply.presigned_url(&t.path).map_err(server_error).and_then(|arg| {
|
||||
let url = arg.get_str().map_err(|_| server_error("server returned an invalid S3 file grant"))?;
|
||||
SignedUrl::parse(&url)
|
||||
}));
|
||||
if grant.ready() { return apply_grant(c, handle, i); }
|
||||
None
|
||||
}
|
||||
(Awaiting::UploadDone, S3TransferKind::UploadDone) => {
|
||||
c.s3_receipts.remove(&handle);
|
||||
match reply.upload_success() {
|
||||
Ok(true) => Some(c.files.transfers.remove(i).event("done", None)),
|
||||
Ok(false) => Some(failed(c, i, server_error("server could not refresh the S3 file list after upload"))),
|
||||
Err(message) => Some(failed(c, i, server_error(message))),
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn presign_keeps_channel_header_and_object_on_separate_rows() {
|
||||
let get = presign_command(Direction::Download, 3, "/nested/a b", "", 987).into_packet();
|
||||
assert_eq!(get.content(), br"s3ft_getpresignedurl chid=3 chpw|key=\/nested\/a\sb verb=GET length=0");
|
||||
let put = presign_command(Direction::Upload, 3, "/nested/a b", &cpw("abc"), 987).into_packet();
|
||||
assert_eq!(put.content(), br"s3ft_getpresignedurl chid=3 chpw=qZk+NkcGgWq6PiVxeFDCbJzQ2J0=|key=\/nested\/a\sb verb=PUT length=987");
|
||||
let done = channel_command("s3ft_upload_done_notification", 3, "").into_packet();
|
||||
assert_eq!(done.content(), b"s3ft_upload_done_notification chid=3 chpw");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_either_part_does_not_settle_a_presign() {
|
||||
let mut receipt = GrantReceipt::default();
|
||||
assert!(!receipt.ready());
|
||||
receipt.acked = true;
|
||||
assert!(!receipt.ready());
|
||||
receipt.grant = Some(Err(server_error("test failure")));
|
||||
assert!(receipt.ready());
|
||||
receipt.acked = false;
|
||||
assert!(!receipt.ready());
|
||||
}
|
||||
}
|
||||
+8
-30
@@ -59,11 +59,6 @@ impl Action {
|
||||
}}
|
||||
}
|
||||
pub fn bad(message: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest,message) }
|
||||
pub const MAX_POKE_BYTES: usize = 1024;
|
||||
pub const MAX_MOVE_PASSWORD_BYTES: usize = 1024;
|
||||
pub fn valid_poke_message(message: &str) -> bool {
|
||||
(1..=MAX_POKE_BYTES).contains(&message.len()) && !message.bytes().any(|byte| byte.is_ascii_control())
|
||||
}
|
||||
pub fn validate_target(t: &Target) -> Result<(), ErrorObj> {
|
||||
if t.client_id == 0 || t.uid.is_empty() || t.uid.len()>128 || t.uid.chars().any(char::is_control) { return Err(bad("invalid client target")); }
|
||||
Ok(())
|
||||
@@ -79,16 +74,16 @@ pub fn parse_action(mut value: Value) -> Result<ActionRequest, ErrorObj> {
|
||||
|
||||
pub(crate) fn validate_action(request: &ActionRequest) -> Result<(), ErrorObj> {
|
||||
validate_target(&request.target)?;
|
||||
crate::admin::generation(request.generation)?;
|
||||
if request.generation == 0 { return Err(bad("generation is required")); }
|
||||
match &request.action {
|
||||
Action::Poke{message} if !valid_poke_message(message) =>return Err(bad("poke message must be 1..1024 UTF-8 bytes without ASCII controls")),
|
||||
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{expected_channel_id,..} if !(1..=crate::admin::MAX_SAFE_INTEGER).contains(expected_channel_id)=>return Err(bad("expected_channel_id must be a positive safe integer")),
|
||||
Action::MoveToOwnChannel{password:Some(p),..} if p.len()>MAX_MOVE_PASSWORD_BYTES || 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)?;},
|
||||
_=>{},
|
||||
}
|
||||
@@ -195,7 +190,7 @@ fn cap(allowed:Option<bool>,source:&str)->Value {json!({"allowed":allowed,"reaso
|
||||
pub fn tapped(name:&[u8])->bool{matches!(name,b"notifypermissionlist"|b"notifyclientneededpermissions"|b"notifyconnectioninfo"|b"notifyclientpermlist"|b"notifychannelclientpermlist")}
|
||||
|
||||
fn validate_live_identity(target:&Target,client_id:u16,uid:Option<&tsclientlib::UidBuf>)->Result<(),ErrorObj>{
|
||||
if target.client_id!=client_id || uid.is_none_or(|uid|uid.to_string()!=target.uid){return Err(ErrorObj::new(ErrorCode::TargetChanged,"client identity changed; reopen the menu"));}
|
||||
if target.client_id!=client_id || uid.is_none_or(|uid|uid.to_string()!=target.uid){return Err(bad("client identity changed; reopen the menu"));}
|
||||
Ok(())
|
||||
}
|
||||
fn target_hint(own:bool,key:&str,hints:Option<u64>,bit:u64)->Value {
|
||||
@@ -213,13 +208,6 @@ pub fn response_matches(row:&Row,response:&str,client_id:u16,dbid:u64,channel:Op
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish_read(target:&Target, current_uid:Option<&str>, response:&str, rows:Vec<Row>)->Result<Value,ErrorObj>{
|
||||
if current_uid!=Some(target.uid.as_str()){return Err(ErrorObj::new(ErrorCode::TargetChanged,"client identity changed; reopen the menu"));}
|
||||
if rows.len()>4096{return Err(ErrorObj::new(ErrorCode::ServerError,"server returned too many client data rows; result not complete"));}
|
||||
if response=="notifyconnectioninfo" && rows.is_empty(){return Err(ErrorObj::new(ErrorCode::ServerError,"server returned no connection statistics for the requested client"));}
|
||||
Ok(json!({"rows":rows}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -260,16 +248,6 @@ mod tests {
|
||||
assert!(!response_matches(&row,"notifychannelclientpermlist",2,8,Some(4)));
|
||||
assert!(!response_matches(&row,"notifyconnectioninfo",2,8,None));
|
||||
}
|
||||
#[test] fn connection_statistics_require_a_current_uid_and_reported_rows(){
|
||||
let target=Target{client_id:2,uid:"speaker=".into()};
|
||||
let rows=||crate::rawcmd::parse(b"notifyconnectioninfo clid=2 connection_ping=7.25").unwrap().items;
|
||||
for uid in [None,Some("replacement=")] {
|
||||
assert_eq!(finish_read(&target,uid,"notifyconnectioninfo",rows()).unwrap_err().code,ErrorCode::TargetChanged);
|
||||
}
|
||||
assert_eq!(finish_read(&target,Some("speaker="),"notifyconnectioninfo",vec![]).unwrap_err().code,ErrorCode::ServerError);
|
||||
assert_eq!(finish_read(&target,Some("speaker="),"notifyconnectioninfo",rows()).unwrap()["rows"][0]["connection_ping"],"7.25");
|
||||
assert_eq!(finish_read(&target,Some("speaker="),"notifyclientpermlist",vec![]).unwrap(),json!({"rows":[]}));
|
||||
}
|
||||
#[test] fn all_mutation_fixtures_build_expected_wire_verbs(){
|
||||
for (action,verb) in [
|
||||
(Action::Poke{message:"hi".into()},"clientpoke"),
|
||||
@@ -306,9 +284,9 @@ mod tests {
|
||||
let first=tsclientlib::UidBuf(vec![1;20]); let second=tsclientlib::UidBuf(vec![2;20]);
|
||||
let target=Target{client_id:42,uid:first.to_string()};
|
||||
assert!(validate_live_identity(&target,42,Some(&first)).is_ok());
|
||||
for (id,uid) in [(42,Some(&second)),(43,Some(&first)),(42,None)] {
|
||||
assert_eq!(validate_live_identity(&target,id,uid).unwrap_err().code,ErrorCode::TargetChanged);
|
||||
}
|
||||
assert!(validate_live_identity(&target,42,Some(&second)).is_err());
|
||||
assert!(validate_live_identity(&target,43,Some(&first)).is_err());
|
||||
assert!(validate_live_identity(&target,42,None).is_err());
|
||||
let mut persisted=HashMap::new(); persisted.insert(second.0.clone(),-6.0);
|
||||
let mut volumes=LocalVolumes::default(); volumes.set(&first.0,-8.0,true);
|
||||
assert_eq!(volumes.get(&first.0,&persisted),(-8.0,true)); assert_eq!(volumes.gain(&first.0,&persisted),0.0);
|
||||
|
||||
@@ -13,7 +13,7 @@ impl Session {
|
||||
|
||||
pub(super) async fn client_action(&mut self, id: &str, request: ActionRequest) -> Result<Option<Value>, ErrorObj> {
|
||||
let c=self.connected_conn()?;
|
||||
if request.generation!=c.generation{return Err(ErrorObj::new(ErrorCode::TargetChanged,"connection changed; reopen the menu"));}
|
||||
if request.generation!=c.generation{return Err(menu::bad("connection changed; reopen the menu"));}
|
||||
let book=c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e))?;
|
||||
let context=c.permissions.context(book,&request.target,c.generation)?;
|
||||
let key=request.action.key();
|
||||
@@ -45,7 +45,7 @@ impl Session {
|
||||
MenuAction::Avatar{data}=>{
|
||||
if c.avatar.is_some(){return Err(menu::bad("an avatar upload is already pending"));}
|
||||
let data=menu::avatar_bytes(data)?;
|
||||
let hash=base16ct::lower::encode_string(&Md5::digest(&data));
|
||||
let hash=format!("{:x}",Md5::digest(&data));
|
||||
let ftid=c.transfer_id();
|
||||
let command=menu::command("ftinitupload",&[("clientftfid",ftid.to_string()),("name","/avatar".into()),("cid","0".into()),("cpw",String::new()),("size",data.len().to_string()),("overwrite","1".into()),("resume","0".into()),("proto","1".into())]);
|
||||
let handle=c.send(command).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
|
||||
|
||||
+1
-12
@@ -84,8 +84,7 @@ impl Out {
|
||||
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.entry("generation".to_owned())
|
||||
.or_insert_with(|| Value::from(self.inner.generation.load(Ordering::Acquire)));
|
||||
object.insert("generation".into(), Value::from(self.inner.generation.load(Ordering::Acquire)));
|
||||
}
|
||||
let _ = self.inner.control.send(value).await;
|
||||
}
|
||||
@@ -123,16 +122,6 @@ impl Out {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn control_preserves_an_explicit_event_generation() {
|
||||
let (out, mut control, _playback) = Out::new();
|
||||
out.set_generation(8);
|
||||
out.control(json!({"event":"whisper_received","generation":7})).await;
|
||||
out.control(json!({"event":"talking"})).await;
|
||||
assert_eq!(control.try_recv().unwrap()["generation"], 7);
|
||||
assert_eq!(control.try_recv().unwrap()["generation"], 8);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn playback_discards_oldest_without_relabeling_reconnected_frames() {
|
||||
let (out, _control, mut playback) = Out::new();
|
||||
|
||||
+3
-28
@@ -874,6 +874,9 @@ impl Store {
|
||||
}
|
||||
other => other?,
|
||||
};
|
||||
if vault.entries.len() + parsed.len() > MAX_IDENTITIES {
|
||||
return Err(StoreError::BadRequest(format!("at most {MAX_IDENTITIES} identities")));
|
||||
}
|
||||
let mut outcome = ImportOutcome { imported: Vec::new(), existing: Vec::new() };
|
||||
let mut legacy_raised = None;
|
||||
for p in parsed {
|
||||
@@ -890,9 +893,6 @@ impl Store {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if vault.entries.len() >= MAX_IDENTITIES {
|
||||
return Err(StoreError::BadRequest(format!("at most {MAX_IDENTITIES} identities")));
|
||||
}
|
||||
if vault.entries.is_empty() {
|
||||
vault.default = p.uid.clone();
|
||||
}
|
||||
@@ -1419,31 +1419,6 @@ pub mod tests {
|
||||
assert_eq!(store.load_identity().unwrap().unwrap().identity.counter(), high.counter());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_capacity_counts_new_uids_only_and_refuses_overflow_atomically() {
|
||||
let dir = TempDir::new("import-capacity");
|
||||
let store = Store::new(&dir.0);
|
||||
let mut vault = Vault::empty();
|
||||
for _ in 1..MAX_IDENTITIES {
|
||||
vault.entries.push(Store::new_entry(Identity::new(EccKeyPrivP256::create(), 0), "Member".into(), String::new()));
|
||||
}
|
||||
vault.default = vault.entries[0].uid.clone();
|
||||
{ let _guard = store.write_lock().unwrap(); store.write_vault(&vault).unwrap(); }
|
||||
let existing = store.export_ini(&vault.default).unwrap();
|
||||
let fresh = || format!("[Identity]\nid=New\nidentity=\"0V{}\"\n", EccKeyPrivP256::create().to_ts());
|
||||
let last = fresh();
|
||||
let before = snapshot(&dir.0);
|
||||
assert!(matches!(store.import_ini(&[&existing, &last, &fresh()]), Err(StoreError::BadRequest(_))));
|
||||
assert_eq!(snapshot(&dir.0), before);
|
||||
let result = store.import_ini(&[&existing, &last, &last]).unwrap();
|
||||
assert_eq!(result.existing, [vault.default.clone()]);
|
||||
assert_eq!(result.imported.len(), 1);
|
||||
assert_eq!(store.import_ini(&[&last]).unwrap().existing, result.imported);
|
||||
let saved = store.list().unwrap();
|
||||
assert_eq!(saved.identities.len(), MAX_IDENTITIES);
|
||||
assert_eq!(saved.default_id.as_deref(), Some(vault.default.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ts_ini_export_import_roundtrip_and_no_key_duplicates() {
|
||||
let a = TempDir::new("export");
|
||||
|
||||
+34
-199
@@ -104,10 +104,6 @@ impl ErrorObj {
|
||||
|
||||
fn bad(msg: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest, msg) }
|
||||
|
||||
fn check_identity_id(uid: &str) -> Result<(), ErrorObj> {
|
||||
if crate::profile::valid_uid(uid) { Ok(()) } else { Err(bad("invalid identity_id")) }
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TextTarget {
|
||||
@@ -124,7 +120,7 @@ pub enum Command {
|
||||
Connect(ConnectArgs),
|
||||
Disconnect { message: Option<String> },
|
||||
JoinChannel { channel_id: u64, password: Option<String> },
|
||||
SendText { target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<String>, expected_channel_id: Option<u64>, message: String },
|
||||
SendText { target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<String>, message: String },
|
||||
SetAudio { input_muted: Option<bool>, output_muted: Option<bool> },
|
||||
/// `None` = direct transmission (push-to-talk / open microphone decided by the caller).
|
||||
SetTransmit { vad: Option<GateMode> },
|
||||
@@ -194,23 +190,12 @@ impl Command {
|
||||
}
|
||||
|
||||
/// A command whose transport-independent arguments have been checked and normalized.
|
||||
/// Callers can inspect it without changing it; only the core can unwrap it.
|
||||
/// 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 fn as_command(&self) -> &Command { &self.0 }
|
||||
|
||||
/// Bind the selected default to a connect that did not specify an identity.
|
||||
pub fn bind_default_identity(&mut self, uid: &str) -> Result<(), ErrorObj> {
|
||||
let Command::Connect(args) = &mut self.0 else { return Err(bad("identity binding requires connect")); };
|
||||
if args.identity_id.is_some() { return Err(bad("identity_id is already set")); }
|
||||
check_identity_id(uid)?;
|
||||
args.identity_id = Some(uid.to_owned());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn into_inner(self) -> Command { self.0 }
|
||||
}
|
||||
|
||||
@@ -218,25 +203,20 @@ impl ValidatedCommand {
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ConnectArgs {
|
||||
pub address: String,
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
#[serde(default)]
|
||||
pub server_password: Option<String>,
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
#[serde(default)]
|
||||
pub channel: Option<String>,
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
#[serde(default)]
|
||||
pub channel_password: Option<String>,
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
#[serde(default)]
|
||||
pub identity_id: Option<String>,
|
||||
/// Nickname for this connection only (bookmark override); absent: the identity's
|
||||
/// nickname/name. Validated by `Store::open_for_connect`; the identity is never changed.
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
#[serde(default)]
|
||||
pub nickname: Option<String>,
|
||||
}
|
||||
|
||||
// Omission selects the default. An explicitly supplied null is not a string.
|
||||
pub(crate) fn present_string<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<String>, D::Error> {
|
||||
String::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
/// One parsed stdin line.
|
||||
#[derive(Debug)]
|
||||
pub enum Input {
|
||||
@@ -262,15 +242,10 @@ struct Envelope<'a> {
|
||||
id: Option<Cow<'a, str>>,
|
||||
#[serde(borrow)]
|
||||
cmd: Cow<'a, str>,
|
||||
#[serde(default, borrow, deserialize_with = "present_args")]
|
||||
#[serde(default, borrow)]
|
||||
args: Option<&'a RawValue>,
|
||||
}
|
||||
|
||||
// A missing field uses the default; an explicit null must still be checked.
|
||||
fn present_args<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<&'de RawValue>, D::Error> {
|
||||
<&RawValue>::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Empty {}
|
||||
@@ -284,7 +259,7 @@ struct NicknameArgs {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct DisconnectArgs {
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
#[serde(default)]
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
@@ -304,24 +279,18 @@ struct SendTextArgs {
|
||||
client_id: Option<u16>,
|
||||
#[serde(default)]
|
||||
expected_client_uid: Option<String>,
|
||||
#[serde(default)]
|
||||
expected_channel_id: Option<u64>,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SetAudioArgs {
|
||||
#[serde(default, deserialize_with = "present_bool")]
|
||||
#[serde(default)]
|
||||
input_muted: Option<bool>,
|
||||
#[serde(default, deserialize_with = "present_bool")]
|
||||
#[serde(default)]
|
||||
output_muted: Option<bool>,
|
||||
}
|
||||
|
||||
fn present_bool<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<bool>, D::Error> {
|
||||
bool::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct StreamListArgs {
|
||||
@@ -445,28 +414,6 @@ fn check_stream_id(id: &str) -> Result<(), ErrorObj> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// The original bridge measured string limits in UTF-16 units. Only SDP descriptions are multiline.
|
||||
fn bounded_text(text: &str, min: usize, max: usize, multiline: bool) -> bool {
|
||||
(min..=max).contains(&text.encode_utf16().count()) && !text.bytes().any(|b| {
|
||||
(b < 0x20 || b == 0x7f) && !(multiline && matches!(b, b'\n' | b'\r' | b'\t'))
|
||||
})
|
||||
}
|
||||
|
||||
fn check_signal(value: &Value) -> Result<(), ErrorObj> {
|
||||
let envelope = value.as_object().filter(|v| v.len() == 2).ok_or_else(|| bad("json must contain only cmd and args"))?;
|
||||
let args = envelope.get("args").and_then(Value::as_object).ok_or_else(|| bad("json.args must be an object"))?;
|
||||
let text = |key: &str, min, max, multiline| args.get(key).and_then(Value::as_str).is_some_and(|s| bounded_text(s, min, max, multiline));
|
||||
let valid = match envelope.get("cmd").and_then(Value::as_str) {
|
||||
Some("answer") => args.len() == 1 && text("answer", 1, 60_000, true),
|
||||
Some("reconnectOffer") => args.len() == 1 && text("offer", 1, 60_000, true),
|
||||
Some("iceCandidate") => args.len() == 3 && args.get("mLine").and_then(Value::as_u64).is_some_and(|n| n <= 9_007_199_254_740_991)
|
||||
&& text("mid", 0, 64, false) && text("sdp", 0, 2048, false),
|
||||
_ => return Err(bad("unknown outgoing stream signal")),
|
||||
};
|
||||
if !valid { return Err(bad("invalid arguments for outgoing stream signal")); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decodes base64 PCM straight into a frame without intermediate heap buffers.
|
||||
pub fn decode_frame(b64: &str) -> Result<Box<Frame>, ErrorObj> {
|
||||
let mut bytes = [0u8; FRAME_BYTES];
|
||||
@@ -489,9 +436,6 @@ pub fn decode_frame(b64: &str) -> Result<Box<Frame>, ErrorObj> {
|
||||
|
||||
/// Parse one stdin line (without trailing newline).
|
||||
pub fn parse_line(line: &str) -> Input {
|
||||
if !line.trim_start().starts_with('{') {
|
||||
return Input::Invalid { id: None, error: bad("request must be an object") };
|
||||
}
|
||||
let env: Envelope = match serde_json::from_str(line) {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
@@ -504,11 +448,6 @@ pub fn parse_line(line: &str) -> Input {
|
||||
}
|
||||
};
|
||||
|
||||
if env.args.is_some_and(|raw| !raw.get().starts_with('{')) {
|
||||
let id = if matches!(env.cmd.as_ref(), "audio_frame" | "audio_end") { None }
|
||||
else { env.id.filter(|id| valid_id(id)).map(Cow::into_owned) };
|
||||
return Input::Invalid { id, error: bad("args must be an object") };
|
||||
}
|
||||
// High-rate audio commands carry no id and get no response.
|
||||
match env.cmd.as_ref() {
|
||||
"audio_frame" => {
|
||||
@@ -571,7 +510,7 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
|
||||
}
|
||||
"send_text" => {
|
||||
let a: SendTextArgs = args_owned(raw)?;
|
||||
Command::SendText { target: a.target, client_id: a.client_id, expected_client_uid: a.expected_client_uid, expected_channel_id: a.expected_channel_id, message: a.message }
|
||||
Command::SendText { target: a.target, client_id: a.client_id, expected_client_uid: a.expected_client_uid, message: a.message }
|
||||
}
|
||||
"set_audio" => {
|
||||
let a: SetAudioArgs = args_owned(raw)?;
|
||||
@@ -644,28 +583,15 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
|
||||
let update = matches!(&command, Command::StreamUpdate(_));
|
||||
match &mut command {
|
||||
Command::Connect(a) => {
|
||||
for (field, value, min, max) in [
|
||||
("address", Some(a.address.as_str()), 1, 255),
|
||||
("server_password", a.server_password.as_deref(), 0, 255),
|
||||
("channel", a.channel.as_deref(), 1, 512),
|
||||
("channel_password", a.channel_password.as_deref(), 0, 255),
|
||||
("nickname", a.nickname.as_deref(), 1, 64),
|
||||
] {
|
||||
if value.is_some_and(|s| !bounded_text(s, min, max, false)) { return Err(bad(format!("invalid {field}"))); }
|
||||
}
|
||||
if let Some(uid) = a.identity_id.as_deref() { check_identity_id(uid)?; }
|
||||
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 } => {
|
||||
if message.as_deref().is_some_and(|s| !bounded_text(s, 0, 80, false)) { return Err(bad("invalid disconnect message")); }
|
||||
}
|
||||
Command::JoinChannel { channel_id, password } => {
|
||||
if *channel_id == 0 { return Err(bad("channel_id must be positive")); }
|
||||
check_opt("password", password)?;
|
||||
}
|
||||
Command::SendText { target, client_id, expected_client_uid, expected_channel_id, message } => {
|
||||
if expected_channel_id.is_some_and(|id| id == 0 || *target != TextTarget::Channel) {
|
||||
return Err(bad("expected_channel_id must be positive and is only allowed for target channel"));
|
||||
}
|
||||
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")),
|
||||
@@ -680,19 +606,11 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
|
||||
}
|
||||
Command::SetTransmit { vad } => crate::voice_dsp::validate_transmit(*vad)?,
|
||||
Command::SetLocalVolumes(a) => crate::voice_dsp::validate_local_volumes(a)?,
|
||||
Command::StreamList { client_id: Some(0) } | Command::StreamJoin { client_id: 0, .. }
|
||||
| Command::StreamSignal { client_id: 0, .. } | Command::StreamLeave { client_id: 0, .. }
|
||||
| Command::StreamRespond { client_id: 0, .. } | Command::StreamRemove { client_id: 0, .. } => {
|
||||
return Err(bad("client_id must be positive"));
|
||||
}
|
||||
Command::StreamJoin { stream_id, message, .. } => {
|
||||
check_stream_id(stream_id)?;
|
||||
if message.as_deref().is_some_and(|s| !bounded_text(s, 0, 200, false)) { return Err(bad("invalid stream join message")); }
|
||||
}
|
||||
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}")))?;
|
||||
check_signal(&value)?;
|
||||
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;
|
||||
@@ -707,15 +625,18 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
|
||||
return Err(bad("invalid stream metadata (only P2P is supported)"));
|
||||
}
|
||||
}
|
||||
Command::StreamRespond { stream_id, decision, offer, message, .. } => {
|
||||
Command::StreamRespond { stream_id, client_id, decision, offer, message } => {
|
||||
check_stream_id(stream_id)?;
|
||||
check_text("message", message, 200, true)?;
|
||||
if *decision == offer.is_empty() || offer.len() > 60000
|
||||
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, .. } => check_stream_id(stream_id)?,
|
||||
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)?,
|
||||
@@ -827,37 +748,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_connect_accepts_the_reference_field_limits() {
|
||||
let pair = "\u{10000}";
|
||||
let mut args = ConnectArgs {
|
||||
address: pair.repeat(127) + "x", channel: Some(pair.repeat(256)),
|
||||
identity_id: Some("test/9PZ9vww/Bpf5vJxtJhpz80=".into()), nickname: Some(pair.repeat(32)),
|
||||
server_password: Some("x".repeat(255)), channel_password: Some(String::new()),
|
||||
};
|
||||
assert!(validate_command(Command::Connect(args.clone())).is_ok());
|
||||
args.channel.as_mut().unwrap().push('x');
|
||||
assert_bad(Command::Connect(args));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_identity_binding_requires_a_valid_uid_and_omission() {
|
||||
let args = ConnectArgs { address: "localhost".into(), server_password: None, channel: None,
|
||||
channel_password: None, identity_id: None, nickname: None };
|
||||
let mut command = validate_command(Command::Connect(args.clone())).unwrap();
|
||||
assert_eq!(command.bind_default_identity("").unwrap_err().code, ErrorCode::BadRequest);
|
||||
assert_eq!(command.as_command(), &Command::Connect(args.clone()));
|
||||
|
||||
let uid = "test/9PZ9vww/Bpf5vJxtJhpz80=";
|
||||
let chosen = Command::Connect(ConnectArgs { identity_id: Some(uid.into()), ..args });
|
||||
command.bind_default_identity(uid).unwrap();
|
||||
assert_eq!(command.as_command(), &chosen);
|
||||
assert_eq!(command.bind_default_identity(uid).unwrap_err().code, ErrorCode::BadRequest);
|
||||
let mut explicit = validate_command(chosen.clone()).unwrap();
|
||||
assert_eq!(explicit.bind_default_identity(uid).unwrap_err().code, ErrorCode::BadRequest);
|
||||
assert_eq!(explicit.as_command(), &chosen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_rejects_non_string_nickname_overrides() {
|
||||
let parse = |args: Value| parse_line(&serde_json::json!({"id":"c","cmd":"connect","args":args}).to_string());
|
||||
@@ -908,19 +798,10 @@ mod tests {
|
||||
assert_eq!(validate_command(command).unwrap_err().code, ErrorCode::BadRequest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_requires_a_positive_channel_in_both_transports() {
|
||||
let join = |channel_id| Command::JoinChannel { channel_id, password: None };
|
||||
let Input::Invalid { error, .. } = parse_line(r#"{"id":"j","cmd":"join_channel","args":{"channel_id":0}}"#) else { panic!("zero channel accepted") };
|
||||
assert_eq!(error.code, ErrorCode::BadRequest);
|
||||
assert_eq!(error, validate_command(join(0)).unwrap_err());
|
||||
assert_eq!(validate_command(join(1)).unwrap().into_inner(), join(1));
|
||||
}
|
||||
|
||||
#[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, expected_channel_id: None, message: "hello".into(),
|
||||
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())));
|
||||
@@ -931,73 +812,27 @@ mod tests {
|
||||
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, expected_channel_id: None, message: "hello".into() });
|
||||
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: Some("uid".into()), expected_channel_id: None, message: "hello".into() });
|
||||
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, expected_channel_id: None, message });
|
||||
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 expected_channel_id_is_a_guard_only_for_channel_text() {
|
||||
for (target, channel) in [(TextTarget::Channel, 0), (TextTarget::Server, 7), (TextTarget::Client, 7)] {
|
||||
let private = target == TextTarget::Client;
|
||||
assert_bad(Command::SendText { target, client_id: private.then_some(2), expected_client_uid: private.then(|| "peer".into()),
|
||||
expected_channel_id: Some(channel), message: "draft".into() });
|
||||
}
|
||||
let Input::Request { cmd, .. } = parse_line(r#"{"id":"t","cmd":"send_text","args":{"target":"channel","expected_channel_id":7,"message":"draft"}}"#) else { panic!("valid guarded send rejected") };
|
||||
assert!(matches!(cmd.into_inner(), Command::SendText { expected_channel_id: Some(7), .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_operations_reject_zero_client_at_the_shared_boundary() {
|
||||
for cmd in [Command::StreamList { client_id: Some(0) },
|
||||
Command::StreamJoin { stream_id: "s1".into(), client_id: 0, message: None },
|
||||
Command::StreamLeave { stream_id: "s1".into(), client_id: 0 },
|
||||
Command::StreamSignal { stream_id: "s1".into(), client_id: 0, json: r#"{"cmd":"answer","args":{"answer":"v=0"}}"#.into() },
|
||||
Command::StreamRemove { stream_id: "s1".into(), client_id: 0 },
|
||||
Command::StreamRespond { stream_id: "s1".into(), client_id: 0, decision: false, offer: String::new(), message: String::new() }] {
|
||||
assert_bad(cmd);
|
||||
}
|
||||
assert!(validate_command(Command::StreamList { client_id: None }).is_ok());
|
||||
assert!(matches!(parse_line(r#"{"id":"z","cmd":"stream_signal","args":{"stream_id":"s1","client_id":0,"json":{"cmd":"answer","args":{"answer":"v=0"}}}}"#), Input::Invalid { .. }));
|
||||
}
|
||||
|
||||
#[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 prefix = r#"{"args":{"answer":""#;
|
||||
let suffix = r#""},"cmd":"answer"}"#;
|
||||
let available = MAX_SIGNAL_JSON_BYTES - prefix.len() - suffix.len();
|
||||
let payload = "\\t".repeat(available / 2) + &"a".repeat(available % 2);
|
||||
let compact = format!("{prefix}{payload}{suffix}");
|
||||
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!("{prefix}{payload}x{suffix}")));
|
||||
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 outgoing_signal_shapes_and_join_messages_match_bridge() {
|
||||
let signal = |value: Value| Command::StreamSignal { stream_id: "s1".into(), client_id: 7, json: value.to_string() };
|
||||
for valid in [serde_json::json!({"cmd":"reconnectOffer","args":{"offer":"v=0\r\n"}}),
|
||||
serde_json::json!({"cmd":"iceCandidate","args":{"mLine":0,"mid":"","sdp":""}})] {
|
||||
assert!(validate_command(signal(valid)).is_ok());
|
||||
}
|
||||
for invalid in [serde_json::json!({"cmd":"offer","args":{"offer":"v=0"}}), serde_json::json!({"cmd":"answer","args":{"answer":""}}),
|
||||
serde_json::json!({"cmd":"answer","args":{"answer":"v=0"},"other":true}), serde_json::json!({"cmd":"answer","args":{"answer":"v=0","sdp":"other"}}),
|
||||
serde_json::json!({"cmd":"iceCandidate","args":{"mLine":"0","mid":"0","sdp":"x"}}), serde_json::json!({"cmd":"iceCandidate","args":{"mLine":0,"mid":"0","sdp":"x\n"}})] {
|
||||
assert_bad(signal(invalid));
|
||||
}
|
||||
let join = |s: String| Command::StreamJoin { stream_id:"s1".into(), client_id:7, message:Some(s) };
|
||||
assert!(validate_command(join("x".repeat(200))).is_ok());
|
||||
assert_bad(join("x".repeat(201))); assert_bad(join("a\tb".into())); assert_bad(join("\u{10000}".repeat(101)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_publisher_metadata_and_join_response_are_validated() {
|
||||
let args = StreamPublishArgs { stream_id: None, name: "Screen".into(), stream_type: 3,
|
||||
|
||||
+3
-152
@@ -6,7 +6,7 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use tsproto_packets::commands::{CommandArgumentValue, CommandItem, CommandParser};
|
||||
use tsproto_packets::commands::{CommandItem, CommandParser};
|
||||
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
|
||||
|
||||
/// Outgoing verbs the bridge may send (never caller-chosen names).
|
||||
@@ -80,8 +80,7 @@ pub fn publish_stream(a: &crate::protocol::StreamPublishArgs) -> OutCommand {
|
||||
}
|
||||
|
||||
pub fn stop_stream(stream_id: &str) -> OutCommand {
|
||||
// beta14 requires the reason even for a publisher ending its own stream (LEFT = 1).
|
||||
build(StreamVerb::StopStream, &[("id", stream_id), ("reason", "1")])
|
||||
build(StreamVerb::StopStream, &[("id", stream_id)])
|
||||
}
|
||||
|
||||
pub fn respond_stream(stream_id: &str, client_id: u16, decision: bool, offer: &str, message: &str) -> OutCommand {
|
||||
@@ -109,13 +108,11 @@ pub fn tap(name: &[u8]) -> bool {
|
||||
|| crate::admin::tapped(name)
|
||||
|| crate::events::tapped(name)
|
||||
|| crate::file_transfer::tapped(name)
|
||||
|| S3TransferKind::from_name(name).is_some()
|
||||
|| matches!(
|
||||
name,
|
||||
b"channellist"
|
||||
| b"notifychannelcreated"
|
||||
| b"notifychanneledited"
|
||||
| b"notifychanneldescriptionchanged"
|
||||
| b"notifychanneldeleted"
|
||||
| b"notifycliententerview"
|
||||
| b"notifyclientupdated"
|
||||
@@ -129,152 +126,6 @@ pub fn is_stream_notification(name: &str) -> bool {
|
||||
|| matches!(name, "notifyjoinstreamrequest" | "notifyrespondjoinstreamrequest" | "notifyremovedfromstream" | "notifysfuaccessinfo")
|
||||
}
|
||||
|
||||
/// The S3 list envelope is a single row. Retain a raw slice so an unsolicited reply never needs
|
||||
/// to unescape, allocate or decode its payload. An ambiguous handle cannot be matched to a job.
|
||||
pub(crate) struct S3FileList<'a> {
|
||||
pub handle: Option<u16>,
|
||||
pub payload: Result<&'a [u8], &'static str>,
|
||||
}
|
||||
|
||||
pub(crate) fn s3_file_list(content: &[u8]) -> Option<S3FileList<'_>> {
|
||||
let (name, parser) = CommandParser::new(content);
|
||||
if name != b"notify_s3ft_file_list" { return None; }
|
||||
let mut return_code = None;
|
||||
let mut payload = None;
|
||||
let mut ambiguous_handle = false;
|
||||
let mut malformed = false;
|
||||
for item in parser {
|
||||
match item {
|
||||
CommandItem::NextCommand => malformed = true,
|
||||
CommandItem::Argument(arg) => match arg.name() {
|
||||
b"return_code" => ambiguous_handle |= return_code.replace(arg.value().get_raw()).is_some(),
|
||||
b"b64_json" => malformed |= payload.replace(arg.value().get_raw()).is_some(),
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
let handle = return_code.filter(|code| !ambiguous_handle && code.iter().all(u8::is_ascii_digit))
|
||||
.and_then(|code| std::str::from_utf8(code).ok()?.parse().ok());
|
||||
let payload = if malformed { Err("malformed S3 file list notification") } else { payload.ok_or("S3 file list notification is missing b64_json") };
|
||||
Some(S3FileList { handle, payload })
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum S3TransferKind { Presign, UploadDone }
|
||||
|
||||
impl S3TransferKind {
|
||||
fn from_name(name: &[u8]) -> Option<Self> {
|
||||
match name {
|
||||
b"notify_presigned_urls" => Some(Self::Presign),
|
||||
b"notify_s3ft_upload_done" => Some(Self::UploadDone),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_s3_transfer_notification(content: &[u8]) -> bool {
|
||||
S3TransferKind::from_name(CommandParser::new(content).0).is_some()
|
||||
}
|
||||
|
||||
/// Keep credentials in their wire representation until this exact command owns the reply.
|
||||
pub(crate) struct S3TransferReply<'a> {
|
||||
pub kind: S3TransferKind,
|
||||
pub handle: Option<u16>,
|
||||
parser: CommandParser<'a>,
|
||||
}
|
||||
|
||||
pub(crate) fn s3_transfer(content: &[u8]) -> Option<S3TransferReply<'_>> {
|
||||
let (name, parser) = CommandParser::new(content);
|
||||
let kind = S3TransferKind::from_name(name)?;
|
||||
let mut codes = parser.clone().filter_map(|item| match item {
|
||||
CommandItem::Argument(arg) if arg.name() == b"return_code" => Some(arg.value().get_raw()),
|
||||
_ => None,
|
||||
});
|
||||
let handle = codes.next().filter(|code| codes.next().is_none() && code.iter().all(u8::is_ascii_digit))
|
||||
.and_then(|code| std::str::from_utf8(code).ok()?.parse().ok());
|
||||
Some(S3TransferReply { kind, handle, parser })
|
||||
}
|
||||
|
||||
impl<'a> S3TransferReply<'a> {
|
||||
/// Only one key was requested. Do not use a URL from any other file or an ambiguous row.
|
||||
pub fn presigned_url(self, expected_key: &str) -> Result<CommandArgumentValue<'a>, &'static str> {
|
||||
const INVALID: &str = "server returned an invalid S3 file grant";
|
||||
let mut matched = None;
|
||||
let mut key = None;
|
||||
let mut url = None;
|
||||
let mut finish_row = |key: Option<CommandArgumentValue<'a>>, url: Option<CommandArgumentValue<'a>>| {
|
||||
if let Some(url) = url.filter(|url| !url.get_raw().is_empty()) {
|
||||
if key.and_then(|key| key.get_str().ok()).as_deref() != Some(expected_key) || matched.replace(url).is_some() {
|
||||
return Err(INVALID);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
for item in self.parser {
|
||||
match item {
|
||||
CommandItem::NextCommand => finish_row(key.take(), url.take())?,
|
||||
CommandItem::Argument(arg) => {
|
||||
let field = match arg.name() {
|
||||
b"key" => &mut key,
|
||||
b"url" => &mut url,
|
||||
_ => continue,
|
||||
};
|
||||
if field.replace(arg.value().clone()).is_some() { return Err(INVALID); }
|
||||
}
|
||||
}
|
||||
}
|
||||
finish_row(key, url)?;
|
||||
matched.ok_or("server did not return an S3 file grant")
|
||||
}
|
||||
|
||||
pub fn upload_success(self) -> Result<bool, &'static str> {
|
||||
const INVALID: &str = "server returned an invalid S3 upload confirmation";
|
||||
let mut success = None;
|
||||
for item in self.parser {
|
||||
if let CommandItem::Argument(arg) = item {
|
||||
if arg.name() != b"success" { continue; }
|
||||
let value = match arg.value().get_raw() {
|
||||
b"0" => false,
|
||||
b"1" => true,
|
||||
_ => return Err(INVALID),
|
||||
};
|
||||
if success.replace(value).is_some() { return Err(INVALID); }
|
||||
}
|
||||
}
|
||||
success.ok_or(INVALID)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod s3_transfer_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn presign_matches_its_handle_and_object_row() {
|
||||
let raw = br"notify_presigned_urls return_code=17 url|key=\/dir\/a\sb\pc url=opaque";
|
||||
let reply = s3_transfer(raw).unwrap();
|
||||
assert_eq!(reply.kind, S3TransferKind::Presign);
|
||||
assert_eq!(reply.handle, Some(17));
|
||||
assert!(reply.presigned_url("/dir/a b|c").is_ok());
|
||||
assert!(s3_transfer(raw).unwrap().presigned_url("/other").is_err());
|
||||
assert!(s3_transfer(br"notify_presigned_urls return_code=17|key=\/a url=one|key=\/a url=two")
|
||||
.unwrap().presigned_url("/a").is_err());
|
||||
assert!(s3_transfer(br"notify_presigned_urls return_code=17|key=\/a|url=opaque")
|
||||
.unwrap().presigned_url("/a").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_or_ambiguous_business_replies_cannot_report_success() {
|
||||
let reply = s3_transfer(b"notify_s3ft_upload_done success=1 return_code=3|return_code=4").unwrap();
|
||||
assert_eq!(reply.handle, None);
|
||||
let success = |raw: &[u8]| s3_transfer(raw).unwrap().upload_success();
|
||||
assert_eq!(success(b"notify_s3ft_upload_done success=0 return_code=3"), Ok(false));
|
||||
assert_eq!(success(b"notify_s3ft_upload_done success=1 return_code=3"), Ok(true));
|
||||
assert!(success(b"notify_s3ft_upload_done success=1 success=0 return_code=3").is_err());
|
||||
assert!(success(b"notify_s3ft_upload_done return_code=3").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// A parsed raw command: name plus one unescaped key/value map per `|`-separated entry.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct RawNotification {
|
||||
@@ -367,7 +218,7 @@ mod tests {
|
||||
assert_eq!(std::str::from_utf8(&content(respond_stream("7", 4, false, "", "not_authorized"))).unwrap(),
|
||||
"respondjoinstreamrequest id=7 clid=4 decision=0 offer msg=not_authorized");
|
||||
assert_eq!(std::str::from_utf8(&content(remove_stream_client("7", 4))).unwrap(), "removeclientfromstream id=7 clid=4 reason=4");
|
||||
assert_eq!(std::str::from_utf8(&content(stop_stream("7"))).unwrap(), "stopstream id=7 reason=1");
|
||||
assert_eq!(std::str::from_utf8(&content(stop_stream("7"))).unwrap(), "stopstream id=7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1064,12 +1064,6 @@ impl Recorder {
|
||||
}
|
||||
Err(TrySendError::Full(msg)) => {
|
||||
self.dropped_chunks += 1;
|
||||
// Dropped ticks are written as silence, including at the end of the WAV.
|
||||
for track in &mut self.tracks {
|
||||
if track.first_bucket + track.peaks.len() as u64 == tick + 1 {
|
||||
if let Some(peak) = track.peaks.back_mut() { *peak = 0; }
|
||||
}
|
||||
}
|
||||
match self.dropped_ranges.last_mut() {
|
||||
Some(r) if r[1] == tick => r[1] = tick + 1,
|
||||
_ => self.dropped_ranges.push([tick, tick + 1]),
|
||||
|
||||
@@ -385,7 +385,7 @@ fn slow_disk_drops_whole_ticks_truthfully_and_keeps_alignment() {
|
||||
let mut dropped_reports = 0;
|
||||
const TICKS: u64 = 60;
|
||||
for tick in 0..TICKS {
|
||||
let f: Frame = [((tick as i16) + 1) * 256; FRAME_SAMPLES];
|
||||
let f: Frame = [(tick as i16) + 1; FRAME_SAMPLES];
|
||||
match rec.end_tick(&f, ident, &LOBBY) {
|
||||
TickOutcome::Overflow { .. } => dropped_reports += 1,
|
||||
TickOutcome::Ok => {}
|
||||
@@ -395,7 +395,6 @@ fn slow_disk_drops_whole_ticks_truthfully_and_keeps_alignment() {
|
||||
let dropped = rec.info()["droppedChunks"].as_u64().unwrap();
|
||||
assert!(dropped > 0 && dropped < TICKS, "dropped={dropped}");
|
||||
assert!(dropped_reports >= 1);
|
||||
let waveform = rec.waveform(0, 0).unwrap();
|
||||
assert!(finish_wait(rec, "stopped").ok);
|
||||
let dir = session_dir(&base);
|
||||
let m = manifest(&dir);
|
||||
@@ -414,8 +413,7 @@ fn slow_disk_drops_whole_ticks_truthfully_and_keeps_alignment() {
|
||||
for t in 0..ticks {
|
||||
let v = w.samples[(t * 960) as usize];
|
||||
let was_dropped = ranges.iter().any(|(a, b)| (*a..*b).contains(&t));
|
||||
assert_eq!(v, if was_dropped { 0 } else { (t as i16 + 1) * 256 }, "tick {t}");
|
||||
assert_eq!(waveform["peaks"][t as usize], json!(peak_of(&[v; FRAME_SAMPLES])), "waveform at tick {t}");
|
||||
assert_eq!(v, if was_dropped { 0 } else { t as i16 + 1 }, "tick {t}");
|
||||
}
|
||||
let _ = fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
+2
-6
@@ -2,7 +2,7 @@
|
||||
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, ValidatedCommand}, session::Session};
|
||||
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)]
|
||||
@@ -43,11 +43,7 @@ impl Drop for PendingRequest {
|
||||
|
||||
impl CoreHandle {
|
||||
pub async fn request(&self, command: Command) -> Result<Value, ErrorObj> {
|
||||
self.request_validated(validate_command(command)?).await
|
||||
}
|
||||
|
||||
/// Send a command that has already passed shared protocol validation.
|
||||
pub async fn request_validated(&self, command: ValidatedCommand) -> 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();
|
||||
|
||||
+33
-200
@@ -115,16 +115,6 @@ enum Phase {
|
||||
Disconnecting { req: Option<String>, deadline: Instant },
|
||||
}
|
||||
|
||||
impl Phase {
|
||||
fn state(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Connecting { .. } => "connecting",
|
||||
Self::Connected => "connected",
|
||||
Self::Disconnecting { .. } => "disconnecting",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Pending {
|
||||
Simple { req: String },
|
||||
MenuContext { req: String, target: Target },
|
||||
@@ -174,7 +164,6 @@ struct Conn {
|
||||
gains: menu::LocalVolumes,
|
||||
avatar: Option<AvatarUpload>,
|
||||
files: crate::file_transfer::Files,
|
||||
s3_receipts: HashMap<u16, files_session::s3::Receipt>,
|
||||
}
|
||||
|
||||
struct AvatarUpload {
|
||||
@@ -374,11 +363,8 @@ impl Session {
|
||||
self.out.json(&v).await;
|
||||
}
|
||||
|
||||
async fn emit_state(&self, state: &str, address: Option<&str>, reason: Option<ErrorObj>, previous: Option<&Phase>) {
|
||||
async fn emit_state(&self, state: &str, address: Option<&str>, reason: Option<ErrorObj>) {
|
||||
let mut v = json!({ "event": "state", "state": state, "address": address });
|
||||
if let Some(phase) = previous {
|
||||
v["previous_state"] = json!(phase.state());
|
||||
}
|
||||
if let Some(c) = &self.conn {
|
||||
v["identity_id"] = json!(c.identity.uid);
|
||||
}
|
||||
@@ -436,7 +422,7 @@ impl Session {
|
||||
Command::Connect(args) => self.connect(&id, args).await,
|
||||
Command::Disconnect { message } => self.disconnect(Some(id.clone()), message).await,
|
||||
Command::JoinChannel { channel_id, password } => self.join_channel(&id, channel_id, password),
|
||||
Command::SendText { target, client_id, expected_client_uid, expected_channel_id, message } => self.send_text(&id, target, client_id, expected_client_uid.as_deref(), expected_channel_id, &message),
|
||||
Command::SendText { target, client_id, expected_client_uid, message } => self.send_text(&id, target, client_id, expected_client_uid.as_deref(), &message),
|
||||
Command::SetAudio { input_muted, output_muted } => self.set_audio(&id, input_muted, output_muted).await,
|
||||
Command::SetTransmit { vad } => self.set_transmit(vad).await.map(Some),
|
||||
Command::SetLocalVolumes(update) => self.set_local_volumes(update).map(Some),
|
||||
@@ -585,14 +571,13 @@ impl Session {
|
||||
gains: menu::LocalVolumes::default(),
|
||||
avatar: None,
|
||||
files: Default::default(),
|
||||
s3_receipts: HashMap::new(),
|
||||
ft_waiting: VecDeque::new(),
|
||||
ft_active: HashMap::new(),
|
||||
ft_in_flight: 0,
|
||||
next_ftid: 1,
|
||||
server_port,
|
||||
});
|
||||
self.emit_state("connecting", Some(&args.address), None, None).await;
|
||||
self.emit_state("connecting", Some(&args.address), None).await;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
@@ -621,7 +606,7 @@ impl Session {
|
||||
}
|
||||
let address = c.address.clone();
|
||||
c.phase = Phase::Disconnecting { req, deadline: Instant::now() + DISCONNECT_TIMEOUT };
|
||||
self.emit_state("disconnecting", Some(&address), None, None).await;
|
||||
self.emit_state("disconnecting", Some(&address), None).await;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -647,7 +632,7 @@ impl Session {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn send_text(&mut self, id: &str, target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<&str>, expected_channel_id: Option<u64>, message: &str) -> Result<Option<Value>, ErrorObj> {
|
||||
fn send_text(&mut self, id: &str, target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<&str>, message: &str) -> Result<Option<Value>, ErrorObj> {
|
||||
let target = match (target, client_id) {
|
||||
(TextTarget::Server, _) => MessageTarget::Server,
|
||||
(TextTarget::Channel, _) => MessageTarget::Channel,
|
||||
@@ -656,11 +641,6 @@ impl Session {
|
||||
};
|
||||
let c = self.connected_conn()?;
|
||||
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
|
||||
if let Some(expected) = expected_channel_id {
|
||||
if book.clients.get(&book.own_client).map(|client| client.channel.0) != Some(expected) {
|
||||
return Err(ErrorObj::new(ErrorCode::TargetChanged, "own channel changed before sending the message"));
|
||||
}
|
||||
}
|
||||
if let Some(cid) = client_id {
|
||||
let current = book.clients.get(&ClientId(cid)).and_then(|client| client.uid.as_ref());
|
||||
if current.is_none_or(|uid| Some(uid.to_string()).as_deref() != expected_client_uid) {
|
||||
@@ -674,11 +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_none() && output_muted.is_none() {
|
||||
self.emit_audio_state().await;
|
||||
return Ok(Some(self.audio_state()));
|
||||
}
|
||||
self.audio_in.invalidate();
|
||||
if input_muted.is_some() || output_muted.is_some() { self.audio_in.invalidate(); }
|
||||
if let Some(m) = input_muted {
|
||||
self.flags.input_muted = m;
|
||||
}
|
||||
@@ -704,9 +680,13 @@ impl Session {
|
||||
if let Some(m) = output_muted {
|
||||
part = part.set_output_muted(m);
|
||||
}
|
||||
let handle = c.send(part).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
|
||||
c.pending.insert(handle, Pending::SetAudio { req: id.to_owned() });
|
||||
Ok(None)
|
||||
if input_muted.is_none() && output_muted.is_none() {
|
||||
Ok(Some(self.audio_state()))
|
||||
} else {
|
||||
let handle = c.send(part).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
|
||||
c.pending.insert(handle, Pending::SetAudio { req: id.to_owned() });
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
// Applied through ConnectOptions at the next (re)connect.
|
||||
_ => Ok(Some(self.audio_state())),
|
||||
@@ -983,19 +963,13 @@ impl Session {
|
||||
}
|
||||
let ignored = c.rx.set_deny_whispers(self.whisper.deny_incoming);
|
||||
let event = c.rx.handle_packet(packet);
|
||||
let whisper_starts: Vec<u16> = c.rx.take_whisper_starts().collect();
|
||||
for cid in ignored {
|
||||
self.out.json(&json!({ "event": "talking", "client_id": cid, "talking": false })).await;
|
||||
}
|
||||
for cid in c.rx.take_whisper_starts() {
|
||||
// Capture the sender from this connection before another roster update can recycle the ID.
|
||||
let client = c.con.get_state().ok().and_then(|book| book.clients.get(&ClientId(cid)));
|
||||
let uid = client.and_then(|client| client.uid.as_ref()).filter(|uid| !uid.0.is_empty())
|
||||
.map(|uid| format!("{}", &**uid));
|
||||
let nickname = client.map(|client| client.name.as_str()).filter(|name| !name.is_empty());
|
||||
self.out.control(json!({
|
||||
"event": "whisper_received", "generation": c.generation, "client_id": cid,
|
||||
"uid": uid, "nickname": nickname,
|
||||
})).await;
|
||||
for cid in whisper_starts {
|
||||
// Official `onWhisperStart`: feeds the reply history and the whisper notification.
|
||||
self.out.json(&json!({ "event": "whisper_received", "client_id": cid })).await;
|
||||
}
|
||||
match event {
|
||||
RxEvent::None => {}
|
||||
@@ -1016,10 +990,6 @@ impl Session {
|
||||
}
|
||||
}
|
||||
StreamItem::RawCommandCopy(content) => {
|
||||
if let Some(reply) = rawcmd::s3_transfer(&content) {
|
||||
self.files_s3_transfer(reply).await;
|
||||
return;
|
||||
}
|
||||
let Some(c) = &mut self.conn else { return };
|
||||
let Some(raw) = rawcmd::parse(&content) else { return };
|
||||
c.permissions.apply(&raw);
|
||||
@@ -1077,15 +1047,7 @@ impl Session {
|
||||
self.ft_finish(handle.0, err).await;
|
||||
}
|
||||
StreamItem::UnknownCommand(cmd) => {
|
||||
let content = cmd.data().packet().content();
|
||||
// The raw tap already delivered S3 transfer receipts. Never parse their credentials
|
||||
// into the general notification pipeline.
|
||||
if rawcmd::is_s3_transfer_notification(content) { return; }
|
||||
if let Some(reply) = rawcmd::s3_file_list(content) {
|
||||
self.files_s3_list(reply).await;
|
||||
return;
|
||||
}
|
||||
let Some(raw) = rawcmd::parse(content) else { return };
|
||||
let Some(raw) = rawcmd::parse(cmd.data().packet().content()) else { return };
|
||||
if rawcmd::is_stream_notification(&raw.name) {
|
||||
// Payloads (SDP/ICE/tokens) are never logged.
|
||||
debug!(name = %raw.name, entries = raw.items.len(), "stream notification");
|
||||
@@ -1095,12 +1057,6 @@ impl Session {
|
||||
}
|
||||
}
|
||||
StreamItem::DisconnectedTemporarily(reason) => {
|
||||
if let Some(Phase::Disconnecting { req, .. }) = self.conn.as_mut().map(|c| &mut c.phase) {
|
||||
// The transport has queued a reconnect, but the user already asked to leave.
|
||||
let respond = req.take().map(|r| (r, json!({ "clean": false })));
|
||||
self.close_conn(None, respond).await;
|
||||
return;
|
||||
}
|
||||
warn!(?reason, "connection lost, tsclientlib reconnects");
|
||||
self.fail_pending("connection lost before the server answered").await;
|
||||
self.fail_media("connection lost before the download finished").await;
|
||||
@@ -1119,7 +1075,7 @@ impl Session {
|
||||
tsclientlib::TemporaryDisconnectReason::Timeout(t) => format!("timeout: {t}"),
|
||||
tsclientlib::TemporaryDisconnectReason::Serverstop => "server stopped".to_owned(),
|
||||
};
|
||||
self.emit_state("connecting", Some(&address), Some(ErrorObj::new(ErrorCode::NotConnected, msg)), None)
|
||||
self.emit_state("connecting", Some(&address), Some(ErrorObj::new(ErrorCode::NotConnected, msg)))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
@@ -1149,8 +1105,6 @@ impl Session {
|
||||
async fn on_book_events(&mut self, events: Vec<Event>) {
|
||||
let Some(c) = &mut self.conn else { return };
|
||||
let own = c.con.get_state().map(|b| b.own_client).ok();
|
||||
let moved = c.connected() && c.con.get_state().ok().and_then(|book| book.clients.get(&book.own_client))
|
||||
.is_some_and(|me| revoke_capture_on_move(&self.audio_in, me.id, me.channel, &events));
|
||||
let mut texts = Vec::new();
|
||||
for e in &events {
|
||||
match e {
|
||||
@@ -1180,13 +1134,10 @@ impl Session {
|
||||
info!(own_client = ?own_id, "connected");
|
||||
self.emit_snapshot().await;
|
||||
self.emit_audio_state().await;
|
||||
self.emit_state("connected", Some(&address), None, None).await;
|
||||
self.emit_state("connected", Some(&address), None).await;
|
||||
if let Some(r) = req {
|
||||
self.out.ok(&r, json!({ "own_client_id": own_id })).await;
|
||||
}
|
||||
} else if moved {
|
||||
// The host renews its microphone permit on the new own-channel snapshot.
|
||||
self.emit_snapshot().await;
|
||||
}
|
||||
for t in texts {
|
||||
self.out.json(&t).await;
|
||||
@@ -1194,7 +1145,7 @@ impl Session {
|
||||
}
|
||||
|
||||
async fn on_result(&mut self, handle: u16, res: Result<(), CommandError>) {
|
||||
if self.conn.as_ref().is_some_and(|c| c.files.owns_handle(handle) || c.s3_receipts.contains_key(&handle)) {
|
||||
if self.conn.as_ref().is_some_and(|c| c.files.owns_handle(handle)) {
|
||||
self.files_result(handle, res).await;
|
||||
return;
|
||||
}
|
||||
@@ -1226,13 +1177,11 @@ impl Session {
|
||||
Err(e)=>self.out.err(&req,e).await,
|
||||
}
|
||||
},
|
||||
Pending::MenuRead { req, target, response, rows, .. } => match res {
|
||||
Pending::MenuRead { req, target, rows, .. } => match res {
|
||||
Err(e)=>self.out.err(&req,command_error(&e)).await,
|
||||
Ok(())=>match c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e)).and_then(|book| {
|
||||
let uid=book.clients.get(&ClientId(target.client_id)).and_then(|client|client.uid.as_ref()).map(|uid|uid.to_string());
|
||||
menu::finish_read(&target,uid.as_deref(),response,rows)
|
||||
}) {
|
||||
Ok(reply)=>self.out.ok(&req,reply).await,
|
||||
Ok(())=>match c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e)).and_then(|b|c.permissions.context(b,&target,c.generation)) {
|
||||
Ok(_) if rows.len()>4096=>self.out.err(&req,ErrorObj::new(ErrorCode::ServerError,"server returned too many permission rows; result not complete")).await,
|
||||
Ok(_)=>self.out.ok(&req,json!({"rows":rows})).await,
|
||||
Err(e)=>self.out.err(&req,e).await,
|
||||
},
|
||||
},
|
||||
@@ -1379,7 +1328,7 @@ impl Session {
|
||||
self.out.err(r, err).await;
|
||||
}
|
||||
self.tx.encoder = None;
|
||||
self.emit_state("disconnected", Some(&c.address), reason, Some(&c.phase)).await;
|
||||
self.emit_state("disconnected", Some(&c.address), reason).await;
|
||||
if let Some((r, v)) = respond {
|
||||
self.out.ok(&r, v).await;
|
||||
}
|
||||
@@ -1503,8 +1452,8 @@ impl Session {
|
||||
async fn tx_frame(&mut self, frame: &CapturedFrame) {
|
||||
if !self.audio_in.validate(frame) { return; }
|
||||
let whisper = frame.whisper;
|
||||
// Neither stale whisper audio nor pre-whisper ordinary audio may alter the current spurt.
|
||||
if whisper != self.whisper.active_epoch() {
|
||||
// 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;
|
||||
@@ -1649,9 +1598,11 @@ impl Session {
|
||||
if c.connected() {
|
||||
let end = match spurt {
|
||||
None => Some(audio::end_of_voice(enc.codec())),
|
||||
// The roster can change between the last frame and key release.
|
||||
Some(epoch) => c.con.get_state().ok()
|
||||
.and_then(|book| self.whisper.route_for_send(epoch, c.generation, book))
|
||||
// A cleared route has nobody left to tell.
|
||||
Some(epoch) => self
|
||||
.whisper
|
||||
.route_mut(epoch, c.generation)
|
||||
.filter(|r| !r.is_empty())
|
||||
.map(|r| audio::end_of_whisper(enc.codec(), r)),
|
||||
};
|
||||
if let Some(end) = end {
|
||||
@@ -1737,14 +1688,6 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn revoke_capture_on_move(queue: &AudioInQueue, own: ClientId, channel: ChannelId, events: &[Event]) -> bool {
|
||||
let moved = events.iter().any(|e| matches!(e, Event::PropertyChanged {
|
||||
id: PropertyId::ClientChannel(id), old: tsclientlib::events::PropertyValue::ChannelId(old), ..
|
||||
} if *id == own && *old != channel));
|
||||
if moved { queue.invalidate(); }
|
||||
moved
|
||||
}
|
||||
|
||||
fn text_event(target: MessageTarget, invoker: &Invoker, message: &str) -> Value {
|
||||
let (target, to) = match target {
|
||||
MessageTarget::Server => ("server", None),
|
||||
@@ -1765,113 +1708,3 @@ fn text_event(target: MessageTarget, invoker: &Invoker, message: &str) -> Value
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod disconnect_tests {
|
||||
use super::*;
|
||||
use crate::profile::tests::TempDir;
|
||||
|
||||
#[test]
|
||||
fn only_an_own_channel_move_revokes_old_audio() {
|
||||
use tsclientlib::{AudioSendGuard, AudioSendMetadata};
|
||||
let queue = AudioInQueue::new();
|
||||
let frame = CapturedFrame { pcm: [9; FRAME_SAMPLES], captured_at: Instant::now(), connection_generation: queue.generation(), capture_epoch: queue.epoch(), whisper: None };
|
||||
assert!(queue.try_push(frame.clone()));
|
||||
let change = |id, old| Event::PropertyChanged { id: PropertyId::ClientChannel(ClientId(id)), old: tsclientlib::events::PropertyValue::ChannelId(ChannelId(old)), invoker: None, extra: Default::default() };
|
||||
assert!(!revoke_capture_on_move(&queue, ClientId(1), ChannelId(5), &[change(2, 4), change(1, 5)]));
|
||||
assert!(queue.validate(&frame));
|
||||
let metadata = AudioSendMetadata { captured_at: frame.captured_at, capture_epoch: frame.capture_epoch, connection_generation: frame.connection_generation };
|
||||
assert!(revoke_capture_on_move(&queue, ClientId(1), ChannelId(6), &[change(1, 5)]));
|
||||
queue.with_valid_audio(&metadata, &mut || panic!("transport sent old-channel PCM"));
|
||||
assert!(!queue.try_push(frame.clone()));
|
||||
assert!(matches!(queue.pop(), Some(AudioIn::End)));assert!(queue.pop().is_none());
|
||||
assert!(queue.try_push(CapturedFrame { capture_epoch: queue.epoch(), ..frame }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_stop_reconnects_only_without_an_explicit_disconnect() {
|
||||
for leaving in [false, true] {
|
||||
let dir = TempDir::new("server-stop");
|
||||
let store = Store::new(&dir.0);
|
||||
store.create("Disconnect Test").unwrap();
|
||||
let (out, mut events, _playback) = Out::new();
|
||||
let mut session = Session::new(store, out, Arc::new(AudioInQueue::new()));
|
||||
let args = serde_json::from_value(json!({"address":"127.0.0.1:9987"})).unwrap();
|
||||
session.connect("join", args).await.unwrap();
|
||||
// Drive session events directly; the transport's connect future is never polled.
|
||||
session.conn.as_mut().unwrap().phase = Phase::Connected;
|
||||
if leaving { session.disconnect(Some("leave".into()), None).await.unwrap(); }
|
||||
while events.try_recv().is_ok() {}
|
||||
|
||||
session.on_item(StreamItem::DisconnectedTemporarily(tsclientlib::TemporaryDisconnectReason::Serverstop)).await;
|
||||
let mut states = Vec::new();
|
||||
let mut replies = Vec::new();
|
||||
while let Ok(event) = events.try_recv() {
|
||||
if event["event"] == "state" { states.push(event["state"].clone()); }
|
||||
if event["id"] == "leave" { replies.push(event); }
|
||||
}
|
||||
if leaving {
|
||||
assert!(session.conn.is_none());
|
||||
assert_eq!(states, [json!("disconnected")]);
|
||||
assert_eq!(replies, [json!({"id":"leave", "ok":true, "result":{"clean":false}})]);
|
||||
} else {
|
||||
assert!(matches!(session.conn.unwrap().phase, Phase::Connecting { req: None }));
|
||||
assert_eq!(states, [json!("connecting")]);
|
||||
assert!(replies.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn whisper_receipt_without_a_roster_entry_does_not_infer_sender_identity() {
|
||||
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
|
||||
let dir = TempDir::new("unknown-whisper-sender");
|
||||
let store = Store::new(&dir.0);
|
||||
store.create("Whisper Test").unwrap();
|
||||
let (out, mut events, _playback) = Out::new();
|
||||
let mut session = Session::new(store, out, Arc::new(AudioInQueue::new()));
|
||||
let args = serde_json::from_value(json!({"address":"127.0.0.1:9987"})).unwrap();
|
||||
session.connect("join", args).await.unwrap();
|
||||
let generation = session.conn.as_ref().unwrap().generation;
|
||||
// Drive receipt handling with no book data, as when audio precedes the sender's roster entry.
|
||||
let audio = OutAudio::new(&AudioData::S2CWhisper { id: 1, from: 7, codec: CodecType::OpusVoice, data: &[1, 2, 3] });
|
||||
let audio = InAudioBuf::try_new(Direction::S2C, audio.into_vec()).unwrap();
|
||||
session.on_item(StreamItem::Audio(audio)).await;
|
||||
let receipt = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.find(|event| event["event"] == "whisper_received").unwrap();
|
||||
assert_eq!(receipt, json!({
|
||||
"event": "whisper_received", "generation": generation, "client_id": 7,
|
||||
"uid": null, "nickname": null,
|
||||
}));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_state_preserves_which_phase_failed_or_finished() {
|
||||
for (phase, previous_state, transport_error, expected_code) in [
|
||||
(Phase::Connecting { req: Some("join".into()) }, "connecting", false, Some("not_connected")),
|
||||
(Phase::Connecting { req: Some("join".into()) }, "connecting", true, Some("connect_failed")),
|
||||
(Phase::Connected, "connected", true, Some("not_connected")),
|
||||
(Phase::Disconnecting { req: None, deadline: Instant::now() }, "disconnecting", true, Some("not_connected")),
|
||||
(Phase::Disconnecting { req: None, deadline: Instant::now() }, "disconnecting", false, None),
|
||||
] {
|
||||
let dir = TempDir::new("terminal-state-phase");
|
||||
let store = Store::new(&dir.0);
|
||||
store.create("Disconnect Test").unwrap();
|
||||
let (out, mut events, _playback) = Out::new();
|
||||
let mut session = Session::new(store, out, Arc::new(AudioInQueue::new()));
|
||||
let args = serde_json::from_value(json!({"address":"127.0.0.1:9987"})).unwrap();
|
||||
session.connect("join", args).await.unwrap();
|
||||
session.conn.as_mut().unwrap().phase = phase;
|
||||
if transport_error {
|
||||
session.on_conn_error(tsclientlib::Error::NotConnected).await;
|
||||
} else {
|
||||
session.on_stream_end().await;
|
||||
}
|
||||
let event = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.find(|event| event["event"] == "state" && event["state"] == "disconnected").unwrap();
|
||||
assert_eq!(event["previous_state"], previous_state);
|
||||
assert_eq!(event["reason"]["code"].as_str(), expected_code);
|
||||
assert_eq!(event["generation"], 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-80
@@ -31,6 +31,8 @@ pub struct RawExtras {
|
||||
channels: HashMap<u64, ChannelExtra>,
|
||||
clients: HashMap<u16, ClientExtra>,
|
||||
server_properties: BTreeMap<String, String>,
|
||||
/// Raw `virtualserver_capability_extensions` of `initserver`; `None` = not announced.
|
||||
capability_extensions: Option<String>,
|
||||
}
|
||||
|
||||
/// Server features exactly as the official client derives them (`hasFeature`, installed
|
||||
@@ -65,8 +67,10 @@ struct ChannelExtra {
|
||||
impl ChannelExtra {
|
||||
fn merge(&mut self, item: &BTreeMap<String, String>) {
|
||||
for (key, value) in item {
|
||||
if key == "cid" || (key.starts_with("channel_") && key != "channel_order") {
|
||||
if key.starts_with("channel_") || matches!(key.as_str(), "cid" | "cpid") {
|
||||
self.properties.insert(key.clone(), value.clone());
|
||||
} else if key == "order" {
|
||||
self.properties.insert("channel_order".into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(u) = item.get("channel_banner_gfx_url") {
|
||||
@@ -155,14 +159,9 @@ fn non_empty(s: &str) -> Option<String> { (!s.is_empty()).then(|| s.to_owned())
|
||||
|
||||
impl RawExtras {
|
||||
pub fn server_properties(&self) -> &BTreeMap<String, String> { &self.server_properties }
|
||||
/// The book also relinks siblings that did not receive an individual move notification.
|
||||
pub fn channel_properties(&self, channel_id: ChannelId, parent: ChannelId, order: ChannelId) -> Option<Value> {
|
||||
let fields = &self.channels.get(&channel_id.0)?.properties;
|
||||
let mut row = serde_json::Map::with_capacity(fields.len() + 2);
|
||||
row.extend(fields.iter().map(|(k, v)| (k.clone(), Value::String(v.clone()))));
|
||||
row.insert("cpid".into(), Value::String(parent.0.to_string()));
|
||||
row.insert("channel_order".into(), Value::String(order.0.to_string()));
|
||||
Some(Value::Object(row))
|
||||
/// Ordinary channel fields observed on this connection, not a ServerQuery snapshot.
|
||||
pub fn channel_properties(&self, channel_id: u64) -> Option<&BTreeMap<String, String>> {
|
||||
self.channels.get(&channel_id).map(|c| &c.properties)
|
||||
}
|
||||
/// myTeamSpeak avatar URLs of a client (`(variant, url)`), empty if none.
|
||||
pub fn client_myts_avatars(&self, client_id: u16) -> &[(u32, String)] {
|
||||
@@ -199,11 +198,13 @@ impl RawExtras {
|
||||
let mut changed = false;
|
||||
match raw.name.as_str() {
|
||||
"initserver" | "notifyserverupdated" | "notifyserveredited" => {
|
||||
if raw.name == "initserver" { self.server_properties.clear(); }
|
||||
for item in &raw.items {
|
||||
for (key, value) in item {
|
||||
if key.starts_with("virtualserver_") { self.server_properties.insert(key.clone(), value.clone()); }
|
||||
}
|
||||
if let Some(value) = item.get("virtualserver_capability_extensions") {
|
||||
self.capability_extensions = Some(value.clone());
|
||||
}
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
@@ -221,22 +222,14 @@ impl RawExtras {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
"notifychanneldescriptionchanged" => {
|
||||
for (cid, _) in cids() {
|
||||
if let Some(channel) = self.channels.get_mut(&cid) {
|
||||
changed |= channel.properties.remove("channel_description").is_some();
|
||||
}
|
||||
}
|
||||
}
|
||||
"notifychanneldeleted" => {
|
||||
for (cid, _) in cids() {
|
||||
changed |= self.channels.remove(&cid).is_some();
|
||||
}
|
||||
}
|
||||
"notifycliententerview" => {
|
||||
let shared_channel = raw.items.first().and_then(|item| item.get("ctid")).and_then(|v| v.parse().ok());
|
||||
for (clid, item) in clids() {
|
||||
let mut e = ClientExtra { channel: shared_channel, ..ClientExtra::default() };
|
||||
let mut e = ClientExtra::default();
|
||||
e.merge(item);
|
||||
self.clients.insert(clid, e);
|
||||
changed = true;
|
||||
@@ -485,7 +478,6 @@ pub fn build(book: &Connection, rev: u64, extras: &RawExtras) -> Value {
|
||||
let mut cgroups: Vec<&ChannelGroup> = book.channel_groups.values().collect();
|
||||
cgroups.sort_by_key(|g| (g.sort_id, g.id.0));
|
||||
let s = &book.server;
|
||||
let extensions = extras.server_properties.get("virtualserver_capability_extensions").map(String::as_str);
|
||||
json!({
|
||||
"event": "snapshot",
|
||||
"rev": rev,
|
||||
@@ -509,8 +501,8 @@ pub fn build(book: &Connection, rev: u64, extras: &RawExtras) -> Value {
|
||||
"default_channel_admin_group": extras.server_properties.get("virtualserver_default_channel_admin_group").and_then(|value| value.parse::<u64>().ok()),
|
||||
// Raw string or null when the server did not announce it; features are null then too
|
||||
// (unknown), never false.
|
||||
"capability_extensions": extensions,
|
||||
"features": server_features(extensions),
|
||||
"capability_extensions": extras.capability_extensions,
|
||||
"features": server_features(extras.capability_extensions.as_deref()),
|
||||
},
|
||||
"own_client_id": own,
|
||||
"own_channel_id": own_channel,
|
||||
@@ -526,64 +518,6 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::rawcmd;
|
||||
|
||||
#[test]
|
||||
fn channel_description_invalidation_distinguishes_unknown_from_empty() {
|
||||
let mut extras = RawExtras::default();
|
||||
let apply = |extras: &mut RawExtras, bytes: &[u8]| {
|
||||
let raw = rawcmd::parse(bytes).unwrap();
|
||||
assert!(rawcmd::tap(raw.name.as_bytes()));
|
||||
extras.apply(&raw)
|
||||
};
|
||||
apply(&mut extras, b"channellist cid=8 channel_name=One channel_description=Old|cid=9 channel_name=Two channel_description=Keep");
|
||||
assert!(apply(&mut extras, b"notifychanneldescriptionchanged cid=8"));
|
||||
let row = |extras: &RawExtras, id| extras.channel_properties(ChannelId(id), ChannelId(0), ChannelId(0)).unwrap();
|
||||
let stale = row(&extras, 8);
|
||||
assert!(stale.get("channel_description").is_none());
|
||||
assert_eq!(stale["channel_name"], "One");
|
||||
assert_eq!(row(&extras, 9)["channel_description"], "Keep");
|
||||
assert!(!apply(&mut extras, b"notifychanneldescriptionchanged cid=42"));
|
||||
apply(&mut extras, b"notifychanneledited cid=8 channel_description");
|
||||
assert_eq!(row(&extras, 8)["channel_description"], "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_readback_uses_current_sibling_position_and_retains_extra_fields() {
|
||||
let mut extras = RawExtras::default();
|
||||
extras.apply(&rawcmd::parse(b"channellist cid=8 cpid=2 channel_order=3 channel_name=Music channel_banner_mode=2").unwrap());
|
||||
extras.apply(&rawcmd::parse(b"notifychanneledited cid=8 channel_topic=Updated").unwrap());
|
||||
let row = extras.channel_properties(ChannelId(8), ChannelId(0), ChannelId(7)).unwrap();
|
||||
assert_eq!(row, json!({"cid":"8", "cpid":"0", "channel_order":"7", "channel_name":"Music", "channel_banner_mode":"2", "channel_topic":"Updated"}));
|
||||
extras.apply(&rawcmd::parse(b"notifychanneldeleted cid=8").unwrap());
|
||||
assert!(extras.channel_properties(ChannelId(8), ChannelId(0), ChannelId(0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_backend_and_snapshot_follow_complete_capability_announcements() {
|
||||
use crate::file_transfer::{Files, ListBackend};
|
||||
let mut extras = RawExtras::default();
|
||||
let mut files = Files::default();
|
||||
let advertised = format!("{}HTTPFT,s3", "extension,".repeat(104));
|
||||
let announcement = format!("notifyserverupdated virtualserver_name=Test|virtualserver_capability_extensions={advertised}");
|
||||
for (command, expected, backend) in [
|
||||
(announcement.as_str(), Some(advertised.as_str()), ListBackend::S3),
|
||||
("notifyserveredited virtualserver_name=Renamed", Some(advertised.as_str()), ListBackend::S3),
|
||||
("notifyserveredited virtualserver_capability_extensions", Some(""), ListBackend::Legacy),
|
||||
("initserver virtualserver_capability_extensions=s3", Some("s3"), ListBackend::S3),
|
||||
("initserver virtualserver_name=Other", None, ListBackend::Legacy),
|
||||
] {
|
||||
let raw = rawcmd::parse(command.as_bytes()).unwrap();
|
||||
extras.apply(&raw);
|
||||
files.apply_raw(&raw);
|
||||
let current = extras.server_properties().get("virtualserver_capability_extensions").map(String::as_str);
|
||||
assert_eq!(current, expected);
|
||||
assert_eq!(server_features(current)["file_transfer_s3"], json!(expected.map(|v| v.contains("s3"))));
|
||||
let storage = files.storage();
|
||||
assert_eq!(storage["httpft"], expected.is_some_and(|v| v.contains("HTTPFT")));
|
||||
assert_eq!(storage["capability_extensions"], json!(expected.map(|v| v.chars().take(1024).collect::<String>())));
|
||||
assert_eq!(files.list_backend(4).unwrap(), backend);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_extras_track_banners_and_streaming() {
|
||||
let mut x = RawExtras::default();
|
||||
|
||||
@@ -478,46 +478,6 @@ pub mod tests {
|
||||
assert!(held.iter().all(Option::is_none));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn released_capture_cannot_restart_after_a_stalled_consumer() {
|
||||
use crate::audio::{AudioIn, AudioInQueue};
|
||||
use tsclientlib::{AudioSendGuard, AudioSendMetadata};
|
||||
|
||||
let queue = AudioInQueue::new();
|
||||
let mut vad = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
|
||||
assert_eq!(vad.push_captured(&captured_frame(&queue, 1)), Decision::Hold);
|
||||
assert!(queue.try_push(captured_frame(&queue, 2)));
|
||||
let Some(AudioIn::Frame(dequeued)) = queue.pop() else { panic!("missing dequeued frame") };
|
||||
assert!(queue.try_push(captured_frame(&queue, 3)));
|
||||
let metadata = |f: &CapturedFrame| AudioSendMetadata {
|
||||
captured_at: f.captured_at, capture_epoch: f.capture_epoch, connection_generation: f.connection_generation,
|
||||
};
|
||||
// The last frame may already be encoded and awaiting socket readiness at key-up.
|
||||
let pending_send = metadata(&dequeued);
|
||||
let epoch = queue.invalidate();
|
||||
queue.with_valid_audio(&pending_send, &mut || panic!("revoked packet sent before stall"));
|
||||
std::thread::sleep(std::time::Duration::from_millis(600));
|
||||
|
||||
let mut preroll = std::array::from_fn(|_| None);
|
||||
assert_eq!(vad.take_captured_preroll(&mut preroll), 1);
|
||||
for frame in [dequeued, preroll[0].take().unwrap()] {
|
||||
assert!(queue.with_valid_frame(&frame, || panic!("stale PCM encoded")).is_none());
|
||||
queue.with_valid_audio(&metadata(&frame), &mut || panic!("stale PCM sent"));
|
||||
}
|
||||
assert!(matches!(queue.pop(), Some(AudioIn::End)));
|
||||
assert!(queue.pop().is_none(), "release must discard the queued frame");
|
||||
vad.reset();
|
||||
let fresh = captured_frame(&queue, 20_000);
|
||||
assert_eq!(fresh.capture_epoch, epoch);
|
||||
assert!(queue.try_push(fresh));
|
||||
let Some(AudioIn::Frame(fresh)) = queue.pop() else { panic!("missing fresh frame") };
|
||||
assert_eq!(vad.push_captured(&fresh), Decision::Start);
|
||||
assert_eq!(vad.take_captured_preroll(&mut preroll), 0);
|
||||
let mut sent = false;
|
||||
queue.with_valid_audio(&metadata(&fresh), &mut || sent = true);
|
||||
assert!(sent, "fresh burst blocked after release");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_preroll_is_revoked_by_every_routing_boundary() {
|
||||
let queue = crate::audio::AudioInQueue::new();
|
||||
|
||||
@@ -10,19 +10,20 @@ impl Session {
|
||||
/// the old mode is sent under the new one. A changed sensitivity or level of the same detector (the
|
||||
/// user moving the VAD level slider) applies from the next frame without interrupting speech.
|
||||
pub(super) async fn set_transmit(&mut self, mode: Option<GateMode>) -> Result<Value, ErrorObj> {
|
||||
match (mode, self.vad.as_mut()) {
|
||||
(None, None) => (),
|
||||
(Some(new), Some(state)) if std::mem::discriminant(&new) == std::mem::discriminant(&state.gate.mode()) => state.gate.set_mode(new),
|
||||
_ => {
|
||||
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!(epoch, "transmit queue invalidated for a mode change");
|
||||
let same_detector = matches!((mode, self.vad.as_ref()), (Some(new), Some(state))
|
||||
if std::mem::discriminant(&new) == std::mem::discriminant(&state.gate.mode()));
|
||||
if same_detector {
|
||||
let state = self.vad.as_mut().expect("checked above");
|
||||
state.gate.set_mode(mode.expect("checked above"));
|
||||
} else {
|
||||
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!(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");
|
||||
|
||||
+5
-26
@@ -509,7 +509,7 @@ pub fn resolve(spec: &TargetSpec, view: &View) -> Result<Route, ErrorObj> {
|
||||
ENTRY_CHANNEL if e.uuid == view.server_uid => {
|
||||
if let Some(channel) = view.find_channel_by_path(&e.name) {
|
||||
ids.channel(channel);
|
||||
for c in view.clients.iter().filter(|c| c.channel == channel && c.uid.is_some_and(|uid| !uid.is_empty())) {
|
||||
for c in view.clients.iter().filter(|c| c.channel == channel) {
|
||||
ids.client(c.id);
|
||||
}
|
||||
}
|
||||
@@ -528,13 +528,10 @@ pub fn resolve(spec: &TargetSpec, view: &View) -> Result<Route, ErrorObj> {
|
||||
TargetSpec::Group { group_type, target_mode, group_id, server_uuid } => {
|
||||
let by_group = *group_type == GROUP_SERVER_GROUP || *group_type == GROUP_CHANNEL_GROUP;
|
||||
let target_id = if by_group {
|
||||
if server_uuid.is_empty() || *server_uuid != view.server_uid {
|
||||
if server_uuid.is_empty() || *server_uuid != view.server_uid || group_id.is_empty() || group_id == "0" {
|
||||
return Err(invalid_list("group whisper list targets another server or no group"));
|
||||
}
|
||||
if !group_id.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(invalid_list("group id must be a positive decimal number"));
|
||||
}
|
||||
group_id.parse::<std::num::NonZeroU64>().map_err(|_| invalid_list("group id must be a positive decimal number"))?.get()
|
||||
group_id.parse::<u64>().map_err(|_| invalid_list("group id is not a number"))?
|
||||
} else {
|
||||
// Protocol: the id is ignored for channel commander / all clients (ts3protocol.md).
|
||||
0
|
||||
@@ -544,8 +541,8 @@ pub fn resolve(spec: &TargetSpec, view: &View) -> Result<Route, ErrorObj> {
|
||||
TargetSpec::Ids { clients, channel_ids } => {
|
||||
let mut ids = IdsBuilder::new();
|
||||
for r in clients {
|
||||
let Some(uid) = r.uid.as_deref().filter(|uid| !uid.is_empty()) else { continue };
|
||||
if view.client(r.id).and_then(|c| c.uid).is_some_and(|current| current == uid_bytes(uid)) {
|
||||
let expected = r.uid.as_deref().map(uid_bytes);
|
||||
if view.client(r.id).is_some_and(|c| c.uid == expected.as_deref()) {
|
||||
ids.client(r.id);
|
||||
}
|
||||
}
|
||||
@@ -800,12 +797,6 @@ mod tests {
|
||||
};
|
||||
assert_eq!(resolve(&group(0, "6", SERVER), &v).unwrap(), Route::Group { whisper_type: 0, target: 1, target_id: 6 });
|
||||
assert_eq!(resolve(&group(1, "8", SERVER), &v).unwrap(), Route::Group { whisper_type: 1, target: 1, target_id: 8 });
|
||||
assert_eq!(resolve(&group(1, "008", SERVER), &v).unwrap(), Route::Group { whisper_type: 1, target: 1, target_id: 8 });
|
||||
for id in ["00", "00000000000000000000", "+1", "18446744073709551616"] {
|
||||
for kind in [GROUP_SERVER_GROUP, GROUP_CHANNEL_GROUP] {
|
||||
assert_eq!(resolve(&group(kind, id, SERVER), &v).unwrap_err().detail, Some(json!({ "whisper": "invalid_list" })));
|
||||
}
|
||||
}
|
||||
for invalid in [group(0, "6", "other"), group(0, "0", SERVER), group(1, "", SERVER), group(0, "x", SERVER), group(1, "8", "")] {
|
||||
assert_eq!(resolve(&invalid, &v).unwrap_err().detail, Some(json!({ "whisper": "invalid_list" })));
|
||||
}
|
||||
@@ -830,18 +821,6 @@ mod tests {
|
||||
assert_eq!(resolve(&empty, &v).unwrap_err().detail, Some(json!({ "whisper": "no_targets" })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unidentified_clients_are_not_individual_whisper_targets() {
|
||||
let mut v = view();
|
||||
v.clients[2].uid = None; // Bob is the only occupant of Games.
|
||||
v.clients[3].uid = Some(b"");
|
||||
let clients = vec![ClientRef { id: 3, uid: None }, ClientRef { id: 4, uid: Some(String::new()) }];
|
||||
let direct = TargetSpec::Ids { clients, channel_ids: vec![] };
|
||||
assert_eq!(resolve(&direct, &v).unwrap_err(), no_targets());
|
||||
let list = TargetSpec::List { entries: vec![Entry { kind: ENTRY_CHANNEL, uuid: SERVER.into(), name: "Games".into() }] };
|
||||
assert_eq!(ids(&resolve(&list, &v).unwrap()), (vec![2], vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_resolved_targets_are_refused() {
|
||||
let names: Vec<String> = (0..300).map(|i| format!("c{i}")).collect();
|
||||
|
||||
@@ -99,36 +99,6 @@ fn cli(args: &[&std::ffi::OsStr]) -> (i32, Value) {
|
||||
(out.status.code().unwrap(), v)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_recording_commands_leave_destination_and_status_untouched() {
|
||||
let profile = TempDir::new("recording-protocol");
|
||||
let destination = profile.0.join("takes");
|
||||
std::fs::create_dir(&destination).unwrap();
|
||||
let existing = destination.join("existing.wav");
|
||||
std::fs::write(&existing, b"previous take").unwrap();
|
||||
let mut core = Core::start(&profile.0);
|
||||
for (cmd, args) in [
|
||||
("recording_start", json!({"directory":destination,"mode":4})),
|
||||
("recording_stop", json!({"force":true})),
|
||||
("recording_pause", json!({"track_id":0})),
|
||||
("recording_resume", json!({"track_id":0})),
|
||||
("recording_status", json!({"session":0})),
|
||||
("recording_info", json!({"track_id":0})),
|
||||
("recording_waveform", json!({"track_id":0,"from_bucket":-1})),
|
||||
] {
|
||||
let (reply, events) = core.request(cmd, cmd, args);
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
|
||||
assert!(!events.iter().any(|e| e["event"].as_str().is_some_and(|s| s.starts_with("recording_"))), "{cmd}: {events:?}");
|
||||
}
|
||||
let (reply, _) = core.request("status", "recording_status", json!({}));
|
||||
assert_eq!(reply["result"], json!({"isRecording":false,"isPaused":false}));
|
||||
let (reply, _) = core.request("info", "recording_info", json!({}));
|
||||
assert_eq!(reply["result"], json!({"isRecording":false}));
|
||||
core.shutdown();
|
||||
assert_eq!(std::fs::read(existing).unwrap(), b"previous take");
|
||||
assert_eq!(std::fs::read_dir(destination).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_lifecycle_over_stdio() {
|
||||
let dir = TempDir::new("life");
|
||||
@@ -260,21 +230,7 @@ fn client_menu_commands_are_validated_and_never_fake_success_offline() {
|
||||
let mut core=Core::start(&dir.0);
|
||||
let (r,_)=core.request("ctx","client_context",json!({"client_id":42,"uid":"fixture"}));
|
||||
assert_eq!(r["error"]["code"],"not_connected");
|
||||
for args in [json!({"client_id":0,"uid":"fixture"}),json!({"client_id":65536,"uid":"fixture"}),
|
||||
json!({"client_id":42,"uid":""}),json!({"client_id":42,"uid":"fixture","unexpected":true})] {
|
||||
let (reply,_) = core.request("invalid-context","client_context",args);
|
||||
assert_eq!(reply["error"]["code"],"bad_request","{reply}");
|
||||
}
|
||||
let (r,_)=core.request("invalid-stats","client_action",json!({"client_id":42,"uid":"fixture","generation":9_007_199_254_740_992u64,"action":"connection_info"}));
|
||||
assert_eq!(r["error"]["code"],"bad_request","{r}");
|
||||
for flag in [None,Some(json!(1)),Some(Value::Null)] {
|
||||
let mut args=json!({"client_id":42,"uid":"fixture","generation":1,"action":"commander"});
|
||||
if let Some(flag)=flag {args["enabled"]=flag;}
|
||||
let (reply,_) = core.request("invalid-commander","client_action",args);
|
||||
assert_eq!(reply["error"]["code"],"bad_request","{reply}");
|
||||
}
|
||||
let actions=[
|
||||
json!({"action":"move_to_own_channel","expected_channel_id":9_007_199_254_740_991u64}),
|
||||
json!({"action":"poke","message":"fixture"}),json!({"action":"connection_info"}),
|
||||
json!({"action":"commander","enabled":true}),json!({"action":"server_group","group_id":6,"enabled":true}),
|
||||
json!({"action":"channel_group","group_id":7,"channel_id":1}),json!({"action":"client_permissions"}),
|
||||
@@ -290,8 +246,6 @@ fn client_menu_commands_are_validated_and_never_fake_success_offline() {
|
||||
assert_eq!(r["error"]["code"],"not_connected","{r}");
|
||||
}
|
||||
for (i,args) in [
|
||||
json!({"client_id":42,"uid":"fixture","generation":1,"action":"move_to_own_channel","expected_channel_id":0}),
|
||||
json!({"client_id":42,"uid":"fixture","generation":1,"action":"move_to_own_channel","expected_channel_id":9_007_199_254_740_992u64}),
|
||||
json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","value":3,"muted":false}),
|
||||
json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","db":10.5,"muted":false}),
|
||||
json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","db":-3.25,"muted":false}),
|
||||
@@ -306,350 +260,6 @@ fn client_menu_commands_are_validated_and_never_fake_success_offline() {
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_and_disconnect_validate_arguments_before_network_io() {
|
||||
let dir = TempDir::new("connection-args");
|
||||
let mut core = Core::start(&dir.0);
|
||||
for (field, value) in [
|
||||
("address", json!("x".repeat(256))), ("address", json!("localhost\n")),
|
||||
("channel", json!("")), ("channel", json!("x".repeat(513))),
|
||||
("nickname", json!("x".repeat(65))), ("identity_id", Value::Null), ("identity_id", json!("other")),
|
||||
("server_password", json!("x".repeat(256))), ("channel_password", json!("bad\tpassword")),
|
||||
] {
|
||||
let mut args = json!({"address":"127.0.0.1"}); args[field] = value;
|
||||
let (reply, events) = core.request("invalid-connect", "connect", args);
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{field}: {reply}");
|
||||
assert!(!events.iter().any(|e| e["state"] == "connecting"));
|
||||
}
|
||||
let limit = "\u{10000}".repeat(40);
|
||||
for args in [json!({"message":format!("{limit}x")}), json!({"message":"\r"}), json!({"message":null})] {
|
||||
let (reply, _) = core.request("invalid-disconnect", "disconnect", args);
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{reply}");
|
||||
}
|
||||
for valid in [json!({}), json!({"message":""}), json!({"message":limit})] {
|
||||
let (reply, _) = core.request("valid-disconnect", "disconnect", valid);
|
||||
assert_eq!(reply["error"]["code"], "not_connected", "{reply}");
|
||||
}
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn database_list_rejects_invalid_pages_before_connection_lookup() {
|
||||
let dir = TempDir::new("database-pages");
|
||||
let mut core = Core::start(&dir.0);
|
||||
for (args, expected) in [
|
||||
(json!({"start":0,"duration":1}), "not_connected"),
|
||||
(json!({"start":u32::MAX,"duration":200}), "not_connected"),
|
||||
(json!({"start":0,"duration":0}), "bad_request"),
|
||||
(json!({"start":0,"duration":201}), "bad_request"),
|
||||
(json!({"start":4294967296_u64,"duration":1}), "bad_request"),
|
||||
(json!({"start":0,"duration":1,"unexpected":false}), "bad_request"),
|
||||
] {
|
||||
let (reply, _) = core.request("page", "client_database_list", args);
|
||||
assert_eq!(reply["error"]["code"], expected, "{reply}");
|
||||
}
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_database_text_bounds_count_unicode_scalars_before_dispatch() {
|
||||
let dir=TempDir::new("database-text-limits");
|
||||
let mut core=Core::start(&dir.0);
|
||||
for (cmd,field,max,mut args) in [
|
||||
("client_database_find","pattern",255,json!({"uid":false})),
|
||||
("client_database_id","uid",128,json!({})),
|
||||
("client_info","uid",128,json!({"client_id":1})),
|
||||
("server_group_member_add_uid","uid",128,json!({"generation":1,"group_id":1})),
|
||||
] {
|
||||
let limit="я".repeat(max-1)+"\u{1f3b5}";
|
||||
for (value,expected) in [(limit.clone(),"not_connected"),(format!("{limit}x"),"bad_request"),
|
||||
(String::new(),"bad_request"),("a\u{85}b".into(),"bad_request")] {
|
||||
args[field]=json!(value);
|
||||
let (reply,_)=core.request("text-boundary",cmd,args.clone());
|
||||
assert_eq!(reply["error"]["code"],expected,"{cmd}.{field}: {reply}");
|
||||
}
|
||||
}
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_group_names_are_validated_before_connecting() {
|
||||
let dir=TempDir::new("unicode-group-names");
|
||||
let mut core=Core::start(&dir.0);
|
||||
let limit="я".repeat(127)+"\u{1f3b5}";
|
||||
for (cmd,mut args) in [("group_add",json!({"generation":1,"kind":"server","type":1})),
|
||||
("group_rename",json!({"generation":1,"kind":"channel","group_id":3}))] {
|
||||
for (name,code) in [(limit.clone(),"not_connected"),(format!("{limit}x"),"bad_request"),("line\nbreak".into(),"bad_request")] {
|
||||
args["name"]=json!(name);
|
||||
let (reply,_)=core.request("group-name",cmd,args.clone());
|
||||
assert_eq!(reply["error"]["code"],code,"{cmd}: {reply}");
|
||||
}
|
||||
}
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admin_ids_and_log_offsets_respect_the_safe_integer_boundary_before_connecting() {
|
||||
let dir=TempDir::new("admin-integer-boundary");
|
||||
let mut core=Core::start(&dir.0);
|
||||
const MAX:u64=(1<<53)-1;
|
||||
for (cmd,property,mut args) in [
|
||||
("channel_create","channel_order",json!({"generation":1,"parent_id":0,"properties":{"channel_name":"Fixture"}})),
|
||||
("channel_edit","channel_order",json!({"generation":1,"channel_id":2,"properties":{}})),
|
||||
("server_edit","virtualserver_download_quota",json!({"generation":1,"confirm":"Fixture","properties":{}})),
|
||||
("server_edit","virtualserver_default_server_group",json!({"generation":1,"confirm":"Fixture","properties":{}})),
|
||||
] {
|
||||
for (value,expected) in [(MAX,"not_connected"),(MAX+1,"bad_request")] {
|
||||
args["properties"][property]=json!(value);
|
||||
let (reply,_)=core.request("property-boundary",cmd,args.clone());
|
||||
assert_eq!(reply["error"]["code"],expected,"{property}: {reply}");
|
||||
}
|
||||
}
|
||||
for (cmd, field, mut args) in [
|
||||
("channel_description", "channel_id", json!({})),
|
||||
("channel_move", "parent_id", json!({"generation":1,"channel_id":2})),
|
||||
("channel_move", "order", json!({"generation":1,"channel_id":2,"parent_id":0})),
|
||||
("channel_create", "parent_id", json!({"generation":1,"properties":{"channel_name":"Fixture"}})),
|
||||
("channel_info", "channel_id", json!({})),
|
||||
("server_group_perm_list", "group_id", json!({})),
|
||||
("temp_password_add", "channel_id", json!({"generation":1,"password":"fixture","duration_s":60})),
|
||||
("server_log", "begin_pos", json!({"lines":1,"reverse":false,"instance":false})),
|
||||
] {
|
||||
for (value,expected) in [(MAX,"not_connected"),(MAX+1,"bad_request")] {
|
||||
args[field]=json!(value);
|
||||
let (reply,_)=core.request("boundary",cmd,args.clone());
|
||||
assert_eq!(reply["error"]["code"],expected,"{cmd}.{field}: {reply}");
|
||||
}
|
||||
}
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn talk_power_validates_its_captured_target_before_dispatch() {
|
||||
let dir = TempDir::new("talk-power-args");
|
||||
let mut core = Core::start(&dir.0);
|
||||
let valid = json!({"generation":9_007_199_254_740_991u64,"client_id":65535,"uid":"peer=","grant":false});
|
||||
for (field,value) in [("generation",json!(0)),("generation",json!(9_007_199_254_740_992u64)),
|
||||
("client_id",json!(0)),("client_id",json!(65536)),("uid",json!("")),("grant",json!(1)),("unexpected",json!(true))] {
|
||||
let mut args = valid.clone(); args[field] = value;
|
||||
let (reply,_) = core.request("invalid", "talk_power", args);
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{field}: {reply}");
|
||||
}
|
||||
let (reply,_) = core.request("valid", "talk_power", valid);
|
||||
assert_eq!(reply["error"]["code"], "not_connected", "{reply}");
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_messages_are_optional_but_must_be_valid_when_present() {
|
||||
let dir=TempDir::new("status-message-args");
|
||||
let mut core=Core::start(&dir.0);
|
||||
for (cmd, flag, max) in [("set_away", "away", 80), ("talk_request", "request", 50)] {
|
||||
let limit="\u{10000}".repeat(max);
|
||||
for (enabled,msg) in [(true,Value::Null),(true,json!(format!("{limit}x"))),
|
||||
(true,json!("bad\u{85}message")),(false,json!(""))] {
|
||||
let mut args=json!({"message":msg});args[flag]=enabled.into();
|
||||
let (reply,_) = core.request("invalid-status",cmd,args);
|
||||
assert_eq!(reply["error"]["code"],"bad_request","{cmd}: {reply}");
|
||||
}
|
||||
for (enabled,msg) in [(true,Some(limit)),(false,None)] {
|
||||
let mut args=json!({});args[flag]=enabled.into();
|
||||
if let Some(msg)=msg {args["message"]=msg.into();}
|
||||
let (reply,_) = core.request("valid-status",cmd,args);
|
||||
assert_eq!(reply["error"]["code"],"not_connected","{cmd}: {reply}");
|
||||
}
|
||||
}
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poke_validates_utf8_bytes_before_connection_lookup() {
|
||||
let dir = TempDir::new("poke-args"); let mut core = Core::start(&dir.0);
|
||||
let exact = "\u{10000}".repeat(256);
|
||||
for (message, expected) in [(String::new(),"bad_request"),(format!("{exact}x"),"bad_request"),
|
||||
("no\nline".into(),"bad_request"),("no\u{7f}del".into(),"bad_request"),(exact,"not_connected")] {
|
||||
let (reply,_) = core.request("poke", "client_action", json!({"client_id":2,"uid":"peer=","generation":1,"action":"poke","message":message}));
|
||||
assert_eq!(reply["error"]["code"],expected,"{reply}");
|
||||
}
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_info_requires_explicit_client_identity() {
|
||||
let dir = TempDir::new("client-info-args"); let mut core = Core::start(&dir.0);
|
||||
for args in [json!({"client_id":0,"uid":"peer="}),json!({"client_id":65536,"uid":"peer="}),json!({"client_id":7}),json!({"client_id":7,"uid":""}),json!({"client_id":7,"uid":"peer=","unknown":true})] {
|
||||
let (reply,_) = core.request("invalid-info","client_info",args); assert_eq!(reply["error"]["code"],"bad_request","{reply}");
|
||||
}
|
||||
let (reply,_) = core.request("offline-info","client_info",json!({"client_id":7,"uid":"peer="}));
|
||||
assert_eq!(reply["error"]["code"],"not_connected","{reply}"); core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_flag_updates_are_partial_and_reject_explicit_null() {
|
||||
let dir = TempDir::new("audio-flag-args");
|
||||
let mut core = Core::start(&dir.0);
|
||||
for (args, muted, deafened) in [(json!({"input_muted":true}), true, false),
|
||||
(json!({"output_muted":true}), true, true), (json!({"input_muted":false}), false, true)] {
|
||||
let (reply, _) = core.request("set", "set_audio", args);
|
||||
assert_eq!(reply["result"], json!({"input_muted":muted,"output_muted":deafened,"transmitting":false}));
|
||||
}
|
||||
for invalid in [json!({"input_muted":null,"output_muted":false}),json!({"output_muted":null}),json!({"input_muted":"false"})] {
|
||||
let (reply, _) = core.request("invalid", "set_audio", invalid);
|
||||
assert_eq!(reply["error"]["code"], "bad_request");
|
||||
}
|
||||
let (reply, events) = core.request("read", "set_audio", json!({}));
|
||||
assert_eq!(reply["result"], json!({"input_muted":false,"output_muted":true,"transmitting":false}));
|
||||
assert!(events.iter().any(|e| e["event"]=="audio_state" && e["input_muted"]==false && e["output_muted"]==true));
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_queries_validate_arguments_before_connection_lookup() {
|
||||
let dir = TempDir::new("channel-query-args");
|
||||
let mut core = Core::start(&dir.0);
|
||||
for cmd in ["channel_info", "channel_description", "channel_list"] {
|
||||
let valid = if cmd == "channel_list" { json!({}) } else { json!({"channel_id": 1}) };
|
||||
let mut extra = valid.clone(); extra["unexpected"] = json!(true);
|
||||
for args in [extra, json!({"channel_id":0})] {
|
||||
let (reply, _) = core.request("invalid", cmd, args);
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
|
||||
}
|
||||
let (reply, _) = core.request("valid", cmd, valid);
|
||||
assert_eq!(reply["error"]["code"], "not_connected", "{cmd}: {reply}");
|
||||
}
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdio_requires_objects_without_dispatching_positional_commands() {
|
||||
let dir = TempDir::new("object-envelope");
|
||||
let mut core = Core::start(&dir.0);
|
||||
for (cmd, args) in [("profile_create", json!(["Positional"])), ("channel_description", json!([1])),
|
||||
("admin_context", json!([])), ("shutdown", Value::Null)] {
|
||||
let (reply, _) = core.request("invalid", cmd, args);
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
|
||||
}
|
||||
for input in [json!(["unexpected", "shutdown", {}]), json!({"id":"ignored", "cmd":"audio_end", "args":[]})] {
|
||||
core.send(input);
|
||||
let event = core.next();
|
||||
assert_eq!(event["event"], "error", "{event}");
|
||||
assert_eq!(event["error"]["code"], "bad_request");
|
||||
assert!(event.get("id").is_none());
|
||||
}
|
||||
core.send(json!({"id":"alive", "cmd":"profile_get"}));
|
||||
let profile = core.next();
|
||||
assert_eq!(profile["id"], "alive");
|
||||
assert_eq!(profile["ok"], true, "{profile}");
|
||||
assert_eq!(profile["result"]["exists"], false, "{profile}");
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whisper_commands_reject_invalid_epochs_and_targets_before_connection_lookup() {
|
||||
let dir = TempDir::new("whisper-args");
|
||||
let mut core = Core::start(&dir.0);
|
||||
let target = json!({"kind":"ids", "clients":[], "channel_ids":[1]});
|
||||
for (cmd, args) in [
|
||||
("whisper_start", json!({"epoch":0,"target":target})),
|
||||
("whisper_start", json!({"epoch":1,"target":{"kind":"ids","clients":[],"channel_ids":[],"extra":true}})),
|
||||
("whisper_stop", json!({"epoch":0})),
|
||||
("whisper_stop", json!({"epoch":4294967296_u64})),
|
||||
("whisper_stop", json!({"epoch":1,"extra":true})),
|
||||
] {
|
||||
let (reply, _) = core.request("invalid", cmd, args);
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
|
||||
}
|
||||
let (reply, _) = core.request("unheld", "whisper_stop", json!({"epoch":u32::MAX}));
|
||||
assert_eq!(reply["result"], json!({"epoch":u32::MAX,"stopped":false}));
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_subscriptions_validate_arguments_before_connection_lookup() {
|
||||
const SINGLE: &str = "channel_subscribe";
|
||||
const ALL: &str = "channel_subscribe_all";
|
||||
const MAX_CHANNEL_ID: u64 = (1 << 53) - 1;
|
||||
let dir = TempDir::new("channel-subscription-args");
|
||||
let mut core = Core::start(&dir.0);
|
||||
|
||||
for (cmd, args) in [
|
||||
(SINGLE, json!({"channel_id": 1, "subscribe": true})),
|
||||
(SINGLE, json!({"channel_id": MAX_CHANNEL_ID, "subscribe": false})),
|
||||
(ALL, json!({"subscribe": true})),
|
||||
(ALL, json!({"subscribe": false})),
|
||||
] {
|
||||
let (reply, _) = core.request("valid-subscription", cmd, args);
|
||||
assert_eq!(reply["ok"], false, "{cmd}: {reply}");
|
||||
assert_eq!(reply["error"]["code"], "not_connected", "{cmd}: {reply}");
|
||||
}
|
||||
|
||||
for (cmd, args) in [
|
||||
(SINGLE, json!({"subscribe": true})),
|
||||
(SINGLE, json!({"channel_id": 0, "subscribe": true})),
|
||||
(SINGLE, json!({"channel_id": -1, "subscribe": false})),
|
||||
(SINGLE, json!({"channel_id": 1.5, "subscribe": true})),
|
||||
(SINGLE, json!({"channel_id": "1", "subscribe": true})),
|
||||
(SINGLE, json!({"channel_id": MAX_CHANNEL_ID + 1, "subscribe": false})),
|
||||
(SINGLE, json!({"channel_id": 1})),
|
||||
(SINGLE, json!({"channel_id": 1, "subscribe": null})),
|
||||
(SINGLE, json!({"channel_id": 1, "subscribe": 1})),
|
||||
(SINGLE, json!({"channel_id": 1, "subscribe": "false"})),
|
||||
(SINGLE, json!({"channel_id": 1, "subscribe": false, "generation": 1})),
|
||||
(SINGLE, json!([1, false])),
|
||||
(ALL, json!({})),
|
||||
(ALL, json!({"subscribe": null})),
|
||||
(ALL, json!({"subscribe": 0})),
|
||||
(ALL, json!({"subscribe": "true"})),
|
||||
(ALL, json!({"channel_id": 1, "subscribe": false})),
|
||||
(ALL, json!([true])),
|
||||
] {
|
||||
let (reply, _) = core.request("invalid-subscription", cmd, args.clone());
|
||||
assert_eq!(reply["ok"], false, "{cmd} with {args}: {reply}");
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{cmd} with {args}: {reply}");
|
||||
}
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_browser_rejects_invalid_list_before_connection() {
|
||||
let dir = TempDir::new("file-list-boundary");
|
||||
let mut core = Core::start(&dir.0);
|
||||
for args in [json!({"channel_id":0,"path":"/"}), json!({"channel_id":9_007_199_254_740_992u64,"path":"/"}),
|
||||
json!({"channel_id":1,"path":"/a/../b"}), json!({"channel_id":1,"path":"/","unexpected":true})] {
|
||||
let (reply, _) = core.request("invalid-list", "file_list", args);
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{reply}");
|
||||
}
|
||||
let (reply, _) = core.request("valid-list", "file_list", json!({"channel_id":9_007_199_254_740_991u64,"path":"/"}));
|
||||
assert_eq!(reply["error"]["code"], "not_connected", "{reply}");
|
||||
for args in [json!({"channel_id":0,"path":"/image.png"}), json!({"channel_id":1,"path":"/images/"}),
|
||||
json!({"channel_id":1,"path":"/image.png","destination":"unapproved"})] {
|
||||
let (reply, _) = core.request("invalid-image", "file_fetch_image", args);
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{reply}");
|
||||
}
|
||||
let (reply, _) = core.request("invalid-history", "file_transfers", json!({"channel_id":1}));
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{reply}");
|
||||
let (reply, _) = core.request("offline-history", "file_transfers", json!({}));
|
||||
assert_eq!(reply["error"]["code"], "not_connected", "{reply}");
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transfer_controls_validate_the_id_before_connection_lookup() {
|
||||
let dir = TempDir::new("transfer-control-ids");
|
||||
let mut core = Core::start(&dir.0);
|
||||
for cmd in ["file_cancel", "file_pause", "file_resume"] {
|
||||
for id in [0, u64::from(u32::MAX) + 1] {
|
||||
let (reply, _) = core.request("invalid-id", cmd, json!({"transfer_id":id}));
|
||||
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
|
||||
}
|
||||
for id in [1, u32::MAX] {
|
||||
let (reply, _) = core.request("valid-id", cmd, json!({"transfer_id":id}));
|
||||
assert_eq!(reply["error"]["code"], "not_connected", "{cmd}: {reply}");
|
||||
}
|
||||
}
|
||||
core.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publisher_commands_validate_through_real_stdio_without_server() {
|
||||
let dir = TempDir::new("publisher");
|
||||
|
||||
+1
-26
@@ -33,38 +33,13 @@ async fn embedded_identity_survives_repeated_worker_lifetimes() {
|
||||
again.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn transmit_mode_invalidates_frames_only_on_detector_change() {
|
||||
use teamspeach_core::{audio::CapturedFrame, protocol::FRAME_SAMPLES, vad::GateMode};
|
||||
let profile = Profile::new();
|
||||
let (core, _events) = spawn(profile.config(1)).unwrap();
|
||||
let direct = core.audio_epoch();
|
||||
let frame = |capture_epoch| CapturedFrame { pcm: [1; FRAME_SAMPLES], captured_at: std::time::Instant::now(),
|
||||
connection_generation: core.connection_generation(), capture_epoch, whisper: None };
|
||||
let result = core.request(Command::SetTransmit { vad: None }).await.unwrap();
|
||||
assert_eq!(result["mode"], "direct");
|
||||
assert!(core.push_audio(frame(direct)));
|
||||
core.request(Command::SetTransmit { vad: Some(GateMode::VolumeGate { level_db: -30. }) }).await.unwrap();
|
||||
let vad = core.audio_epoch();
|
||||
assert!(!core.push_audio(frame(direct)));
|
||||
core.request(Command::SetTransmit { vad: Some(GateMode::VolumeGate { level_db: -25. }) }).await.unwrap();
|
||||
assert!(core.push_audio(frame(vad)));
|
||||
core.request(Command::SetTransmit { vad: None }).await.unwrap();
|
||||
assert!(!core.push_audio(frame(vad)));
|
||||
core.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();
|
||||
for (id, expected) in [(0, ErrorCode::BadRequest), (1, ErrorCode::NotConnected)] {
|
||||
let error = core.request(Command::JoinChannel { channel_id: id, password: None }).await.unwrap_err();
|
||||
assert_eq!(error.code, expected);
|
||||
}
|
||||
let error = core.request(Command::SendText { target: TextTarget::Client, client_id: None,
|
||||
expected_client_uid: None, expected_channel_id: None, message: "private".into() }).await.unwrap_err();
|
||||
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);
|
||||
|
||||
Vendored
+3
-22
@@ -7,9 +7,9 @@
|
||||
- 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).
|
||||
- `tsclientlib`, `tsproto` and `tsproto-packets` are vendored from that revision.
|
||||
`ts-bookkeeping` and `tsproto-types` remain pinned git dependencies. The root workspace
|
||||
patches select the local `tsproto` and `tsproto-packets` for every consumer.
|
||||
- `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
|
||||
|
||||
@@ -41,7 +41,6 @@ the historical patch alone no longer reproduces the complete tree.
|
||||
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.
|
||||
7. `src/audio.rs`: `AudioQueue::has_pending_whisper` identifies decoder and jitter-buffer state that must be discarded when the receiver switches to Deny All, even after a whisper end marker arrived.
|
||||
|
||||
## `tsproto/`
|
||||
|
||||
@@ -52,21 +51,3 @@ socket send attempt, including a retry after backpressure, the guard synchronize
|
||||
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.
|
||||
|
||||
## `tsproto-packets/`
|
||||
|
||||
The six package files come from upstream `utils/tsproto-packets/` at the revision above;
|
||||
`LICENSE-MIT` and `LICENSE-APACHE` are copied verbatim from the upstream root. This crate
|
||||
has no sibling dependencies to re-pin. A local `[workspace]` lets the regression tests
|
||||
run independently of the application workspace.
|
||||
|
||||
`src/commands.rs` now accepts `_` alongside ASCII alphanumerics in command names, so
|
||||
TeamSpeak 6 commands such as `notify_s3ft_file_list` retain their wire names. A name still
|
||||
ends at an ASCII space or at the end of the input. Argument-only input, multipart
|
||||
separators and escaping are unchanged.
|
||||
|
||||
Run the public API regression tests from the repository root:
|
||||
|
||||
```sh
|
||||
cargo test --manifest-path core/vendor/tsproto-packets/Cargo.toml --test command_grammar
|
||||
```
|
||||
Vendored
-7
@@ -209,13 +209,6 @@ impl AudioQueue {
|
||||
pub fn get_decoder(&self) -> &Decoder { &self.decoder }
|
||||
pub fn is_whispering(&self) -> bool { self.whispering }
|
||||
|
||||
/// A whisper may still play from buffered packets, decoded samples or loss concealment.
|
||||
pub fn has_pending_whisper(&self) -> bool {
|
||||
self.whispering || self.packet_buffer.iter().any(|p| {
|
||||
matches!(p.packet.data().data(), AudioData::S2CWhisper { data, .. } if data.len() > 1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Size is in samples.
|
||||
fn add_buffer_size(&mut self, size: usize) {
|
||||
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
|
||||
|
||||
-172
@@ -1,172 +0,0 @@
|
||||
# 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 = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "num-derive"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "omnom"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "66562a92c66d5937e9d549597c2d3cafe3d2367dd08dc257da730587c2cfc218"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[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 = "self_cell"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[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.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsproto-packets"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bitflags",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
"omnom",
|
||||
"self_cell",
|
||||
"serde",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
[package]
|
||||
name = "tsproto-packets"
|
||||
version = "0.1.0"
|
||||
authors = ["Flakebi <flakebi@t-online.de>"]
|
||||
description = "Parse and serialize TeamSpeak packets and commands."
|
||||
repository = "https://github.com/ReSpeak/tsclientlib/tree/master/utils/tsproto-packets"
|
||||
readme = "README.md"
|
||||
keywords = ["teamspeak3", "ts3"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2018"
|
||||
include = [
|
||||
"/Cargo.toml",
|
||||
"/README.md",
|
||||
"/src/*.rs",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22"
|
||||
bitflags = "2"
|
||||
num-derive = "0.4"
|
||||
num-traits = "0.2"
|
||||
omnom = "3"
|
||||
self_cell = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
thiserror = "2"
|
||||
|
||||
# Keep standalone packet regression tests out of the application's package set.
|
||||
[workspace]
|
||||
-201
@@ -1,201 +0,0 @@
|
||||
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
@@ -1,21 +0,0 @@
|
||||
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.
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
# tsproto-packets [](https://docs.rs/tsproto-packets)
|
||||
`tsproto-packets` parses and serializes TeamSpeak packets and commands.
|
||||
|
||||
## License
|
||||
Licensed under either of
|
||||
|
||||
* [Apache License, Version 2.0](../../LICENSE-APACHE)
|
||||
* [MIT license](../../LICENSE-MIT)
|
||||
|
||||
at your option.
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
# tsproto-packets [](https://docs.rs/tsproto-packets)
|
||||
{{readme}}
|
||||
|
||||
## License
|
||||
Licensed under either of
|
||||
|
||||
* [Apache License, Version 2.0](../../LICENSE-APACHE)
|
||||
* [MIT license](../../LICENSE-MIT)
|
||||
|
||||
at your option.
|
||||
-294
@@ -1,294 +0,0 @@
|
||||
use std::borrow::Cow;
|
||||
use std::str::{self, FromStr};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Parses arguments of a command.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CommandParser<'a> {
|
||||
data: &'a [u8],
|
||||
index: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum CommandItem<'a> {
|
||||
Argument(CommandArgument<'a>),
|
||||
/// Pipe symbol marking the start of the next command.
|
||||
NextCommand,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CommandArgument<'a> {
|
||||
name: &'a [u8],
|
||||
value: CommandArgumentValue<'a>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CommandArgumentValue<'a> {
|
||||
raw: &'a [u8],
|
||||
/// The number of escape sequences in this value.
|
||||
escapes: usize,
|
||||
}
|
||||
|
||||
impl<'a> CommandParser<'a> {
|
||||
/// Returns the name and arguments of the given command.
|
||||
#[inline]
|
||||
pub fn new(data: &'a [u8]) -> (&'a [u8], Self) {
|
||||
let mut name_end = 0;
|
||||
while name_end < data.len() {
|
||||
let byte = data[name_end];
|
||||
if !byte.is_ascii_alphanumeric() && byte != b'_' {
|
||||
if byte == b' ' {
|
||||
break;
|
||||
}
|
||||
// Not a command name
|
||||
name_end = 0;
|
||||
break;
|
||||
}
|
||||
name_end += 1;
|
||||
}
|
||||
|
||||
(&data[..name_end], Self { data, index: name_end })
|
||||
}
|
||||
|
||||
fn cur(&self) -> u8 { self.data[self.index] }
|
||||
fn cur_in(&self, cs: &[u8]) -> bool { cs.contains(&self.cur()) }
|
||||
/// Advance
|
||||
fn adv(&mut self) { self.index += 1; }
|
||||
fn at_end(&self) -> bool { self.index >= self.data.len() }
|
||||
|
||||
fn skip_space(&mut self) {
|
||||
while !self.at_end() && self.cur_in(b"\x0b\x0c\t\r\n ") {
|
||||
self.adv();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for CommandParser<'a> {
|
||||
type Item = CommandItem<'a>;
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.skip_space();
|
||||
if self.at_end() {
|
||||
return None;
|
||||
}
|
||||
if self.cur() == b'|' {
|
||||
self.adv();
|
||||
return Some(CommandItem::NextCommand);
|
||||
}
|
||||
|
||||
let name_start = self.index;
|
||||
while !self.at_end() && !self.cur_in(b" =|") {
|
||||
self.adv();
|
||||
}
|
||||
let name_end = self.index;
|
||||
if self.at_end() || self.cur() != b'=' {
|
||||
return Some(CommandItem::Argument(CommandArgument {
|
||||
name: &self.data[name_start..name_end],
|
||||
value: CommandArgumentValue { raw: &[], escapes: 0 },
|
||||
}));
|
||||
}
|
||||
|
||||
self.adv();
|
||||
let value_start = self.index;
|
||||
let mut escapes = 0;
|
||||
while !self.at_end() {
|
||||
if self.cur_in(b"\x0b\x0c\t\r\n| ") {
|
||||
break;
|
||||
}
|
||||
if self.cur() == b'\\' {
|
||||
escapes += 1;
|
||||
self.adv();
|
||||
if self.at_end() || self.cur_in(b"\x0b\x0c\t\r\n| ") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.adv();
|
||||
}
|
||||
let value_end = self.index;
|
||||
Some(CommandItem::Argument(CommandArgument {
|
||||
name: &self.data[name_start..name_end],
|
||||
value: CommandArgumentValue { raw: &self.data[value_start..value_end], escapes },
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> CommandArgument<'a> {
|
||||
#[inline]
|
||||
pub fn name(&self) -> &'a [u8] { self.name }
|
||||
#[inline]
|
||||
pub fn value(&self) -> &CommandArgumentValue<'a> { &self.value }
|
||||
}
|
||||
|
||||
impl<'a> CommandArgumentValue<'a> {
|
||||
fn unescape(&self) -> Vec<u8> {
|
||||
let mut res = Vec::with_capacity(self.raw.len() - self.escapes);
|
||||
let mut i = 0;
|
||||
while i < self.raw.len() {
|
||||
if self.raw[i] == b'\\' {
|
||||
i += 1;
|
||||
if i == self.raw.len() {
|
||||
return res;
|
||||
}
|
||||
res.push(match self.raw[i] {
|
||||
b'v' => b'\x0b',
|
||||
b'f' => b'\x0c',
|
||||
b't' => b'\t',
|
||||
b'r' => b'\r',
|
||||
b'n' => b'\n',
|
||||
b'p' => b'|',
|
||||
b's' => b' ',
|
||||
c => c,
|
||||
});
|
||||
} else {
|
||||
res.push(self.raw[i]);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_raw(&self) -> &'a [u8] { self.raw }
|
||||
#[inline]
|
||||
pub fn get(&self) -> Cow<'a, [u8]> {
|
||||
if self.escapes == 0 { Cow::Borrowed(self.raw) } else { Cow::Owned(self.unescape()) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_str(&self) -> Result<Cow<'a, str>> {
|
||||
if self.escapes == 0 {
|
||||
Ok(Cow::Borrowed(str::from_utf8(self.raw)?))
|
||||
} else {
|
||||
Ok(Cow::Owned(String::from_utf8(self.unescape())?))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_parse<E, T: FromStr>(&self) -> std::result::Result<T, E>
|
||||
where
|
||||
E: From<<T as FromStr>::Err>,
|
||||
E: From<Error>,
|
||||
{
|
||||
Ok(self.get_str()?.as_ref().parse()?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::packets::{Direction, Flags, OutCommand, PacketType};
|
||||
use std::str;
|
||||
|
||||
/// Parse and write again.
|
||||
fn test_loop_with_result(data: &[u8], result: &[u8]) {
|
||||
let (name, parser) = CommandParser::new(data);
|
||||
let name = str::from_utf8(name).unwrap();
|
||||
|
||||
let mut out_command =
|
||||
OutCommand::new(Direction::S2C, Flags::empty(), PacketType::Command, name);
|
||||
|
||||
println!("\nParsing {}", str::from_utf8(data).unwrap());
|
||||
for item in parser {
|
||||
println!("Item: {:?}", item);
|
||||
match item {
|
||||
CommandItem::NextCommand => out_command.start_new_part(),
|
||||
CommandItem::Argument(arg) => {
|
||||
out_command.write_arg(
|
||||
str::from_utf8(arg.name()).unwrap(),
|
||||
&arg.value().get_str().unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let packet = out_command.into_packet();
|
||||
let in_str = str::from_utf8(result).unwrap();
|
||||
let out_str = str::from_utf8(packet.content()).unwrap();
|
||||
assert_eq!(in_str, out_str);
|
||||
}
|
||||
|
||||
/// Parse and write again.
|
||||
fn test_loop(data: &[u8]) { test_loop_with_result(data, data); }
|
||||
|
||||
const TEST_COMMANDS: &[&str] = &[
|
||||
"cmd a=1 b=2 c=3",
|
||||
"cmd a=\\s\\\\ b=\\p c=abc\\tdef",
|
||||
"cmd a=1 c=3 b=2|b=4|b=5",
|
||||
"initivexpand2 l=AQCVXTlKF+UQc0yga99dOQ9FJCwLaJqtDb1G7xYPMvHFMwIKVfKADF6zAAcAAAAgQW5vbnltb3VzAAAKQo71lhtEMbqAmtuMLlY8Snr0k2Wmymv4hnHNU6tjQCALKHewCykgcA== beta=\\/8kL8lcAYyMJovVOP6MIUC1oZASyuL\\/Y\\/qjVG06R4byuucl9oPAvR7eqZI7z8jGm9jkGmtJ6 omega=MEsDAgcAAgEgAiBxu2eCLQf8zLnuJJ6FtbVjfaOa1210xFgedoXuGzDbTgIgcGk35eqFavKxS4dROi5uKNSNsmzIL4+fyh5Z\\/+FWGxU= ot=1 proof=MEUCIQDRCP4J9e+8IxMJfCLWWI1oIbNPGcChl+3Jr2vIuyDxzAIgOrzRAFPOuJZF4CBw\\/xgbzEsgKMtEtgNobF6WXVNhfUw= tvd time=1544221457",
|
||||
|
||||
"clientinitiv alpha=41Te9Ar7hMPx+A== omega=MEwDAgcAAgEgAiEAq2iCMfcijKDZ5tn2tuZcH+\\/GF+dmdxlXjDSFXLPGadACIHzUnbsPQ0FDt34Su4UXF46VFI0+4wjMDNszdoDYocu0 ip",
|
||||
|
||||
// Well, that's more corrupted packet, but the parser should be robust
|
||||
"initserver virtualserver_name=Server\\sder\\sVerplanten \
|
||||
virtualserver_welcomemessage=This\\sis\\sSplamys\\sWorld \
|
||||
virtualserver_platform=Linux \
|
||||
virtualserver_version=3.0.13.8\\s[Build:\\s1500452811] \
|
||||
virtualserver_maxclients=32 virtualserver_created=0 \
|
||||
virtualserver_nodec_encryption_mode=1 \
|
||||
virtualserver_hostmessage=Lé\\sServer\\sde\\sSplamy \
|
||||
virtualserver_name=Server_mode=0 virtualserver_default_server \
|
||||
group=8 virtualserver_default_channel_group=8 \
|
||||
virtualserver_hostbanner_url virtualserver_hostmessagegfx_url \
|
||||
virtualserver_hostmessagegfx_interval=2000 \
|
||||
virtualserver_priority_speaker_dimm_modificat",
|
||||
|
||||
"channellist cid=2 cpid=0 channel_name=Trusted\\sChannel \
|
||||
channel_topic channel_codec=0 channel_codec_quality=0 \
|
||||
channel_maxclients=0 channel_maxfamilyclients=-1 channel_order=1 \
|
||||
channel_flag_permanent=1 channel_flag_semi_permanent=0 \
|
||||
channel_flag_default=0 channel_flag_password=0 \
|
||||
channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 \
|
||||
channel_delete_delay=0 channel_flag_maxclients_unlimited=0 \
|
||||
channel_flag_maxfamilyclients_unlimited=0 \
|
||||
channel_flag_maxfamilyclients_inherited=1 \
|
||||
channel_needed_talk_power=0 channel_forced_silence=0 \
|
||||
channel_name_phonetic channel_icon_id=0 \
|
||||
channel_flag_private=0|cid=4 cpid=2 \
|
||||
channel_name=Ding\\s•\\s1\\s\\p\\sSplamy´s\\sBett channel_topic \
|
||||
channel_codec=4 channel_codec_quality=7 channel_maxclients=-1 \
|
||||
channel_maxfamilyclients=-1 channel_order=0 \
|
||||
channel_flag_permanent=1 channel_flag_semi_permanent=0 \
|
||||
channel_flag_default=0 channel_flag_password=0 \
|
||||
channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 \
|
||||
channel_delete_delay=0 channel_flag_maxclients_unlimited=1 \
|
||||
channel_flag_maxfamilyclients_unlimited=0 \
|
||||
channel_flag_maxfamilyclients_inherited=1 \
|
||||
channel_needed_talk_power=0 channel_forced_silence=0 \
|
||||
channel_name_phonetic=Neo\\sSeebi\\sEvangelion channel_icon_id=0 \
|
||||
channel_flag_private=0", //|cid=6 cpid=2 channel_name=Ding\\s\xe2\x80\xa2\\s2\\s\\p\\sThe\\sBook\\sof\\sHeavy\\sMetal channel_topic channel_codec=2 channel_codec_quality=7 channel_maxclients=-1 channel_maxfamilyclients=-1 channel_order=4 channel_flag_permanent=1 channel_flag_semi_permanent=0 channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 channel_delete_delay=0 channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic=Not\\senought\\sChannels channel_icon_id=0 channel_flag_private=0|cid=30 cpid=2 channel_name=Ding\\s\xe2\x80\xa2\\s3\\s\\p\\sSenpai\\sGef\xc3\xa4hrlich channel_topic channel_codec=2 channel_codec_quality=7 channel_maxclients=-1 channel_maxfamilyclients=-1 channel_order=6 channel_flag_permanent=1 channel_flag_semi_permanent=0 channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 channel_delete_delay=0 channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic=The\\strashcan\\shas\\sthe\\strash channel_icon_id=0 channel_flag_private=0",
|
||||
|
||||
"notifychannelsubscribed cid=2|cid=4 es=3867|cid=5 es=18694|cid=6 es=18694|cid=7 es=18694|cid=11 es=18694|cid=13 es=18694|cid=14 es=18694|cid=16 es=18694|cid=22 es=18694|cid=23 es=18694|cid=24 es=18694|cid=25 es=18694|cid=30 es=18694|cid=163 es=18694",
|
||||
|
||||
"notifypermissionlist group_id_end=0|group_id_end=7|group_id_end=13|group_id_end=18|group_id_end=21|group_id_end=21|group_id_end=33|group_id_end=47|group_id_end=77|group_id_end=82|group_id_end=83|group_id_end=106|group_id_end=126|group_id_end=132|group_id_end=143|group_id_end=151|group_id_end=160|group_id_end=162|group_id_end=170|group_id_end=172|group_id_end=190|group_id_end=197|group_id_end=215|group_id_end=227|group_id_end=232|group_id_end=248|permname=b_serverinstance_help_view permdesc=Retrieve\\sinformation\\sabout\\sServerQuery\\scommands|permname=b_serverinstance_version_view permdesc=Retrieve\\sglobal\\sserver\\sversion\\s(including\\splatform\\sand\\sbuild\\snumber)|permname=b_serverinstance_info_view permdesc=Retrieve\\sglobal\\sserver\\sinformation|permname=b_serverinstance_virtualserver_list permdesc=List\\svirtual\\sservers\\sstored\\sin\\sthe\\sdatabase",
|
||||
|
||||
// Server query
|
||||
"cmd=1 cid=2",
|
||||
"channellistfinished",
|
||||
// With newlines
|
||||
"sendtextmessage text=\\nmess\\nage\\n return_code=11",
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn loop_test() {
|
||||
for cmd in TEST_COMMANDS {
|
||||
test_loop(cmd.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_arg() {
|
||||
test_loop(b"cmd a");
|
||||
test_loop(b"cmd a b=1");
|
||||
|
||||
test_loop_with_result(b"cmd a=", b"cmd a");
|
||||
test_loop_with_result(b"cmd a= b=1", b"cmd a b=1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_slash_escape() {
|
||||
let in_cmd = "clientinitiv alpha=giGMvmfHzbY3ig== omega=MEsDAgcAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50= ot=1 ip";
|
||||
let out_cmd = "clientinitiv alpha=giGMvmfHzbY3ig== omega=MEsDAgcAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC\\/50= ot=1 ip";
|
||||
|
||||
test_loop_with_result(in_cmd.as_bytes(), out_cmd.as_bytes());
|
||||
}
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
//! `tsproto-packets` parses and serializes TeamSpeak packets and commands.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
pub mod commands;
|
||||
pub mod packets;
|
||||
|
||||
type Result<T, E = Error> = std::result::Result<T, E>;
|
||||
|
||||
pub const S2C_HEADER_LEN: usize = 11;
|
||||
pub const C2S_HEADER_LEN: usize = 13;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Base64(#[from] base64::DecodeError),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error(transparent)]
|
||||
ParseInt(#[from] std::num::ParseIntError),
|
||||
#[error(transparent)]
|
||||
Utf8(#[from] std::str::Utf8Error),
|
||||
#[error(transparent)]
|
||||
StringUtf8(#[from] std::string::FromUtf8Error),
|
||||
|
||||
#[error("Invalid init step {0}")]
|
||||
InvalidInitStep(u8),
|
||||
#[error("Invalid audio codec {0}")]
|
||||
InvalidCodec(u8),
|
||||
#[error("Packet content is too short (length {0})")]
|
||||
PacketContentTooShort(usize),
|
||||
#[error("Packet is too short (length {0})")]
|
||||
PacketTooShort(usize),
|
||||
#[error("Cannot parse command ({0})")]
|
||||
ParseCommand(String),
|
||||
#[error("Got a packet with unknown type ({0})")]
|
||||
UnknownPacketType(u8),
|
||||
#[error("Tried to parse a packet from the wrong direction")]
|
||||
WrongDirection,
|
||||
#[error("Wrong mac, expected TS3INIT1 but got {0:?}")]
|
||||
WrongInitMac(Vec<u8>),
|
||||
#[error("Wrong packet type ({0:?})")]
|
||||
WrongPacketType(packets::PacketType),
|
||||
}
|
||||
|
||||
pub struct HexSlice<'a, T: fmt::LowerHex + 'a>(pub &'a [T]);
|
||||
|
||||
impl<'a> fmt::Display for HexSlice<'a, u8> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "Hex[")?;
|
||||
if let Some((l, m)) = self.0.split_last() {
|
||||
for b in m {
|
||||
write!(f, "{:02x} ", b)?;
|
||||
}
|
||||
write!(f, "{:02x}", l)?;
|
||||
}
|
||||
write!(f, "]")
|
||||
}
|
||||
}
|
||||
-1251
File diff suppressed because it is too large.
Load diff
@@ -1,48 +0,0 @@
|
||||
use tsproto_packets::commands::{CommandItem, CommandParser};
|
||||
|
||||
#[test]
|
||||
fn accepts_underscore_and_legacy_alphanumerics_in_command_names() {
|
||||
for input in [b"notify_s3ft_file_list".as_slice(), b"initivexpand2", b"Az09", b"_x_"] {
|
||||
let (name, mut args) = CommandParser::new(input);
|
||||
assert_eq!(name, input);
|
||||
assert!(args.next().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_arguments_when_there_is_no_command_name() {
|
||||
for (input, expected_key) in [
|
||||
(b"client_name=123".as_slice(), b"client_name".as_slice()),
|
||||
(b" client_name=123", b"client_name"),
|
||||
(b"invalid-name=123", b"invalid-name"),
|
||||
(b"invalid\xff=123", b"invalid\xff"),
|
||||
] {
|
||||
let (name, mut args) = CommandParser::new(input);
|
||||
assert!(name.is_empty());
|
||||
let Some(CommandItem::Argument(arg)) = args.next() else {
|
||||
panic!("expected the first argument in {input:?}");
|
||||
};
|
||||
assert_eq!(arg.name(), expected_key);
|
||||
assert_eq!(arg.value().get_raw(), b"123");
|
||||
assert!(args.next().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_multipart_arguments_and_escapes_after_underscore_command() {
|
||||
let (name, mut args) = CommandParser::new(br"notify_s3ft_file_list name=\v\f\t\r\n\p\s\/\\|name=next");
|
||||
assert_eq!(name, b"notify_s3ft_file_list");
|
||||
let Some(CommandItem::Argument(first)) = args.next() else {
|
||||
panic!("expected the first list entry");
|
||||
};
|
||||
assert_eq!(first.name(), b"name");
|
||||
assert_eq!(first.value().get_raw(), br"\v\f\t\r\n\p\s\/\\");
|
||||
assert_eq!(first.value().get_str().unwrap(), "\x0b\x0c\t\r\n| /\\");
|
||||
assert!(matches!(args.next(), Some(CommandItem::NextCommand)));
|
||||
let Some(CommandItem::Argument(second)) = args.next() else {
|
||||
panic!("expected the second list entry");
|
||||
};
|
||||
assert_eq!(second.name(), b"name");
|
||||
assert_eq!(second.value().get_raw(), b"next");
|
||||
assert!(args.next().is_none());
|
||||
}
|
||||
+33
-124
@@ -59,7 +59,7 @@ Request (stdin):
|
||||
(high-rate, never answered; an `id` there is ignored).
|
||||
- `cmd`: one of the commands in §4. Unknown `cmd` → `unknown_command`.
|
||||
- `args`: object; may be omitted when a command takes no arguments.
|
||||
Explicit `null`, positional arrays and unknown argument keys are rejected (`bad_request`).
|
||||
Unknown argument keys are rejected (`bad_request`).
|
||||
|
||||
Response (stdout), exactly one per request with `id`:
|
||||
|
||||
@@ -105,7 +105,7 @@ branch on human-readable message wording.
|
||||
| `not_connected` | command needs an active connection |
|
||||
| `already_connected` | `connect` while connecting/connected |
|
||||
| `connect_failed` | could not connect (resolve, timeout, server refused …; `ts_error` when the server sent one) |
|
||||
| `server_error` | server rejected a command (`ts_error` set), or its required response data was invalid or did not arrive by the deadline (§4.19) |
|
||||
| `server_error` | server answered a command with an error (`ts_error` set) |
|
||||
| `audio_format` | `audio_frame.pcm` not 1920 bytes after base64 decode |
|
||||
| `audio_overflow` | outgoing PCM queue full, oldest frames dropped (event, throttled ≤1/s) |
|
||||
| `audio_muted` | `audio_frame` while input or output muted; frames discarded (event, once per burst) |
|
||||
@@ -165,7 +165,7 @@ Nickname rules: after trimming, 3–30 Unicode scalar values, no control charact
|
||||
### 4.4 `connect` — `{address, server_password?, channel?, channel_password?, identity_id?, nickname?}`
|
||||
|
||||
- `address`: `host`, `host:port`, `[v6]:port` (default port 9987). Not a path.
|
||||
- String limits at the request boundary count UTF-16 code units: address 1–255, server and channel passwords 0–255, channel 1–512, nickname override 1–64. These fields reject ASCII control characters and DEL. Omit optional fields rather than supplying JSON null.
|
||||
- `server_password`: optional string.
|
||||
- `channel`: optional initial channel, either numeric channel id string `"cid:12"` or a
|
||||
path `"Parent/Child"`.
|
||||
- `identity_id`: selected vault UID; omitted selects the default. Server-demanded proof-of-work is handled by the bounded identity CLI, not automatically during connect.
|
||||
@@ -198,8 +198,6 @@ against every program running as that user. Platform hardware key-store acceptan
|
||||
|
||||
### 4.5 `disconnect` — `{message?: string}`
|
||||
|
||||
An explicit message is single-line and at most 80 UTF-16 code units; the empty string is allowed.
|
||||
|
||||
Sends a clean `clientdisconnect` and waits (≤ 3 s) for the server. Result
|
||||
`{"clean": true}` when the server confirmed, `{"clean": false}` on timeout or when a
|
||||
pending connect attempt was abandoned. `not_connected` if idle. Emits
|
||||
@@ -207,13 +205,12 @@ pending connect attempt was abandoned. `not_connected` if idle. Emits
|
||||
|
||||
### 4.6 `join_channel` — `{channel_id: number, password?: string}`
|
||||
|
||||
Moves self (`clientmove`). A zero channel ID returns `bad_request` before checking the connection or sending anything. Result `{}` after the server confirms; snapshot follows.
|
||||
Moves self (`clientmove`). Result `{}` after the server confirms; snapshot follows.
|
||||
|
||||
### 4.7 `send_text` — `{target: "channel"|"server"|"client", client_id?: number, expected_client_uid?: string, expected_channel_id?: number, message: string}`
|
||||
### 4.7 `send_text` — `{target: "channel"|"server"|"client", client_id?: number, expected_client_uid?: string, message: string}`
|
||||
|
||||
`client_id` and `expected_client_uid` are required iff `target = "client"`. Native rechecks the UID immediately before sending, otherwise `target_changed`. Message 1–8192 bytes UTF-8;
|
||||
TeamSpeak escaping is done by the core. Result `{}` after server confirmation.
|
||||
For channel chat the native client supplies `expected_channel_id`. This is a positive ID checked against the core's current own channel before enqueue. A mismatch returns `target_changed`; the field never addresses another channel. Diagnostic requests may omit it to send to the current channel.
|
||||
The server echoes our own messages as `text` events (verified live for private messages:
|
||||
the sender receives exactly one `text` with `to_client_id` = recipient); the core adds no
|
||||
synthetic echo.
|
||||
@@ -225,9 +222,6 @@ flags (`client_input_muted` / `client_output_muted`) when connected, and the cor
|
||||
gates: while `input_muted || output_muted` outgoing frames are discarded; while
|
||||
`output_muted` no `audio` events are emitted. Allowed when disconnected (applied at
|
||||
next connect). Result = audio state object; emits `audio_state`.
|
||||
Omitting a flag preserves its previous value. Explicit null is not a boolean and
|
||||
returns `bad_request`. With neither flag supplied, the command reports state without
|
||||
updating the server, ending a transmission, or revoking the current capture permit.
|
||||
Initial state at process start: both `false`.
|
||||
|
||||
### 4.9 `audio_frame` — `{pcm: string, whisper?: u32}` (no `id`, no response)
|
||||
@@ -266,19 +260,12 @@ The ignored Rust `captured_speech_quality_matrix` accepts `TEAMSPEACH_AUDIT_PCM`
|
||||
`TEAMSPEACH_AUDIT_OUT` for real encoding/receiving at quality 0/6/10, both codecs and a context reset.
|
||||
File-fed/generated media does not prove natural microphone quality, private DSP identity or Asahi hardware.
|
||||
|
||||
A separate two-way core CLI run with silent disposable profiles verified synthetic voice over the
|
||||
server: 99 of 101 received frames matched the expected 900 Hz tone and 100 of 101 matched the
|
||||
expected 500 Hz tone in the reverse direction. No real microphone or playback device was used;
|
||||
official-client peer and acoustic/device validation remain pending.
|
||||
|
||||
### 4.10 `audio_end` — no args (no `id`, no response)
|
||||
|
||||
Ends the current transmission burst (core sends the TeamSpeak end-of-voice packet). In mode
|
||||
`vad` it also discards the detector state and preroll when capture or the native audio service stops
|
||||
forwarding.
|
||||
|
||||
For a native capture release the connection manager invalidates the old epoch and queues the end marker together. An input acknowledgement that arrives after release cannot reinstall the old capture route. The stdio audio_end marker remains ordered with preceding frames.
|
||||
|
||||
### 4.11 `set_transmit` — `{mode: "direct"|"vad", detector?: "automatic"|"volume_gate"|"hybrid", sensitivity?: "high"|"normal"|"low", level_db?: number}`
|
||||
|
||||
Selects who decides when voice is sent. `direct` (initial state at process start): every
|
||||
@@ -308,7 +295,7 @@ changes between `direct`/`vad` or to another detector: before answering such a c
|
||||
discards frames still queued from the previous mode and ends any open burst; the native audio service
|
||||
forwards nothing until it has this answer. A `set_transmit` that only changes `sensitivity` or
|
||||
`level_db` of the active detector (the user moving the VAD level slider) applies from the next
|
||||
frame without discarding audio or ending the spurt. Reapplying `direct` when already in direct mode also preserves the capture epoch and does not end the current burst.
|
||||
frame without discarding audio or ending the spurt.
|
||||
Result `{"mode":"direct"}`, `{"mode":"vad","detector":"automatic","sensitivity":"normal"}`,
|
||||
`{"mode":"vad","detector":"volume_gate","level_db":-30}` or
|
||||
`{"mode":"vad","detector":"hybrid","sensitivity":"normal","level_db":-30}`.
|
||||
@@ -338,8 +325,6 @@ Result `{"agc": bool}`.
|
||||
|
||||
### 4.12 `stream_list` — `{client_id?: number}`
|
||||
|
||||
Stream commands that address a client require a positive 16-bit client ID. Zero is rejected by both the embedded API and the JSON bridge before dispatch; it is not a broadcast selector.
|
||||
|
||||
TS6 screenshare discovery. Sends `requeststreaminfo clid=<id>` for `client_id`, or for
|
||||
every other client in our current channel when omitted. Result:
|
||||
|
||||
@@ -356,7 +341,6 @@ So: "is streaming" ⇔ the `notifystreaminfo` item has `id`.
|
||||
### 4.13 `stream_join` — `{stream_id: string, client_id: number, message?: string}`
|
||||
|
||||
Sends `joinstreamrequest id=<stream_id> clid=<client_id> msg=<message|our nickname> is_remove=0`.
|
||||
An explicitly supplied join message is single-line and at most 200 UTF-16 code units, as in the historical client contract.
|
||||
Result `{}` (or `server_error`). The SDP offer arrives as `stream` event
|
||||
`notifyrespondjoinstreamrequest` (`decision=1`, `offer=<sdp>`).
|
||||
|
||||
@@ -367,7 +351,6 @@ Examples of `json`: `{"cmd":"answer","args":{"answer":"<sdp>"}}`,
|
||||
`{"cmd":"iceCandidate","args":{"mLine":0,"mid":"0","sdp":"candidate:..."}}`.
|
||||
Publisher ICE restart responses use `{"cmd":"reconnectOffer","args":{"offer":"<sdp>"}}`.
|
||||
Shared core validation accepts only `answer`, `iceCandidate`, and `reconnectOffer`, never arbitrary signaling commands.
|
||||
The outbound envelope and its arguments reject additional fields. SDP descriptions allow tab and line breaks and are limited to 60000 UTF-16 units. ICE uses a nonnegative safe integer `mLine` and single-line strings `mid` (64 units) and `sdp` (2048 units). Incoming alias handling is separate.
|
||||
Max serialized `json` size 60 KiB (the whole stdin line is capped at 256 KiB). Result `{}` or `server_error`.
|
||||
|
||||
### 4.15 `stream_leave` — `{stream_id: string, client_id: number}`
|
||||
@@ -386,7 +369,7 @@ unlimited), and `audio` is boolean, serialized as `1`/`0`.
|
||||
|---|---|---|
|
||||
| `stream_setup` | none | `setupstream name type bitrate accessibility mode viewer_limit audio` |
|
||||
| `stream_update` | `stream_id` (required) | `updatestream id name type bitrate accessibility mode viewer_limit audio` |
|
||||
| `stream_stop` | only `stream_id` | `stopstream id reason=1` (publisher left) |
|
||||
| `stream_stop` | only `stream_id` | `stopstream id` |
|
||||
| `stream_respond` | only `stream_id, client_id, decision, offer, message` | `respondjoinstreamrequest id clid decision offer msg` |
|
||||
| `stream_remove` | only `stream_id, client_id` | `removeclientfromstream id clid reason=4` |
|
||||
|
||||
@@ -515,12 +498,7 @@ participant kicks, bans or permission/group mutations.
|
||||
|
||||
### 4.19 Channel file browser: `file_list`, `file_mkdir`, `file_rename`, `file_delete`, `file_download`, `file_upload`, `file_cancel`, `file_transfers`, `file_fetch_image`
|
||||
|
||||
Channel file operations are implemented in `core/src/file_transfer.rs` and `core/src/files_session.rs`.
|
||||
They require an established connection (`not_connected` otherwise); commands addressing a channel
|
||||
require it to be visible (`not_found`). The legacy backend uses `ftgetfilelist`, `ftcreatedir`,
|
||||
`ftrenamefile`, `ftdeletefile`, `ftinitdownload`, `ftinitupload` and `ftstop`. Trusted native icon
|
||||
and snapshot services can address legacy `/icons/` and `/icons/icon_<u32 CRC32>` at `channel_id:0`;
|
||||
ordinary channel operations require a nonzero channel ID.
|
||||
Legacy TeamSpeak file transfer (`ftgetfilelist`, `ftcreatedir`, `ftrenamefile`, `ftdeletefile`, `ftinitdownload`, `ftinitupload`, `ftstop`), implemented in `core/src/file_transfer.rs` and `core/src/files_session.rs`. Every command needs an established connection (`not_connected` otherwise) and a channel the client can see (`not_found`). The native service-only snapshot exception permits `channel_id:0` for listing `/icons/` and transferring `/icons/icon_<u32 CRC32>`; UI file operations still require a nonzero channel. `channel_password` is optional; it travels as base64(SHA-1), like tsclientlib's own transfers, and an empty one is sent as the bare `cpw` flag.
|
||||
|
||||
Remote paths are UTF-8, start with `/`, are at most 512 characters, and every component is non-empty, not `.` or `..`, and contains no control character or backslash. A folder path (`file_list`) is normalized to `/` or `/a/b/`. A file or folder path (`file_mkdir`, `file_rename`, `file_delete`, `file_download`, `file_upload`, `file_fetch_image`) has no trailing slash and is not the root.
|
||||
|
||||
@@ -536,48 +514,17 @@ Remote paths are UTF-8, start with `/`, are at most 512 characters, and every co
|
||||
| `file_transfers` | `{}` | `{transfers:[record…], storage}` |
|
||||
| `file_fetch_image` | `{channel_id, path}` | `{mime, bytes, data}` (base64; same pipeline and limits as §4.17 channel banners) |
|
||||
|
||||
**`file_list`: status and data**
|
||||
**`file_list` details**
|
||||
- The server's empty-folder answer (error 0x0501 "database empty result set") becomes an empty `entries`.
|
||||
- Rows of `notifyfilelist` are matched by the echoed `return_code`, or else by channel and path. Only one listing per folder may be pending; a second one is `bad_request`.
|
||||
- Arguments sent once for all `|`-joined entries are inherited by the later entries.
|
||||
- A row is counted in `malformed` instead of being returned if any of these hold: the name is invalid, `type` is not `0` (folder) or `1` (file), or size/datetime are not numbers.
|
||||
- More than 10 000 rows is an error, never a truncated list.
|
||||
- The listing fails if the server does not complete it within 20 s.
|
||||
|
||||
- Both backends allow only one pending listing per channel and normalized directory; a duplicate is
|
||||
`bad_request`. A listing ends in `server_error` after 20 s if the required status or data is
|
||||
missing, never success with a synthetic empty list.
|
||||
- Legacy sends `ftgetfilelist` with `cid`, `path` and `cpw`. It correlates `notifyfilelist` rows
|
||||
and `notifyfilelistfinished` by echoed `return_code` or by channel and path. Rows separated by
|
||||
`|` inherit shared arguments from the first row. The successful command result and list completion
|
||||
are separate; the legacy status `0x0501` (database empty result set) is an explicit empty result.
|
||||
Invalid names, types other than `0` (folder) or `1` (file), or invalid numeric fields count in
|
||||
`malformed` rather than becoming entries. A list exceeding 10,000 entries fails, not truncates.
|
||||
- S3 sends `s3ft_list_files` with `chid` and `chpw`, without a path. For both backends the channel
|
||||
password is base64(SHA-1); an empty password is sent as a bare `cpw` or `chpw` flag. TeamSpeak
|
||||
command names accept ASCII letters, digits and `_` so `notify_s3ft_file_list` is recognized
|
||||
under its exact name, with normal argument escaping unchanged.
|
||||
- S3 list data comes from a single `notify_s3ft_file_list` matched by the exact numeric `return_code`.
|
||||
Missing, ambiguous or unrelated codes cannot complete a job. Success requires both that data and
|
||||
the successful command acknowledgement (`error id=0`), in either order. A rejected command keeps
|
||||
its TeamSpeak error even when data arrived first. An explicitly present but empty `b64_json` means
|
||||
an empty channel; a missing, malformed or truncated payload is `server_error` after a successful
|
||||
acknowledgement, not an empty channel.
|
||||
- Nonempty S3 data is TeamSpeak-unescaped standard base64 of a JSON object with `contents`. The core
|
||||
projects only the direct children of the requested directory from the channel-wide object list;
|
||||
prefixes and `.tsfolder` markers supply directory entries, not downloadable marker files. Invalid
|
||||
keys and ambiguous children contribute to `malformed`; structurally invalid data, an encoded value
|
||||
over 2 MiB, or more than 10,000 objects fails the whole listing.
|
||||
**`capabilities`** are the full-width `u64` channel permission hints (`notifychannelpermhints`): `{known, upload, download, delete, rename, browse, create_directory}`. Unknown hints count as allowed, as in the official client; the server decides. No narrowing cast discards high bits.
|
||||
|
||||
**`capabilities`** are derived from the full-width `u64` channel permission hints
|
||||
(`notifychannelpermhints`): `{known, upload, download, delete, rename, browse, create_directory}`.
|
||||
Unknown hints let the server decide, as in the official client; neither a permission hint nor a
|
||||
storage flag proves an operation succeeded. For S3, directory mutation hints are suppressed.
|
||||
|
||||
**`storage`** reports `capability_extensions`, `httpft`, `s3` and operation support. The backend
|
||||
flags are case-sensitive substring checks for `HTTPFT` and `s3` in
|
||||
`virtualserver_capability_extensions` from `initserver`, `notifyserverupdated` or `notifyserveredited`.
|
||||
Backend selection uses the full announcement; the file browser's diagnostic string retains at most 1024 characters. Partial edits retain the flags when the property is absent. A new initserver starts a new baseline even when it has no capability property.
|
||||
The compatibility field `supported` indicates legacy storage, not whether the browser can list;
|
||||
use `list_supported` for ordinary channels and do not infer other operations from it. When both
|
||||
flags are set, an ordinary channel lists with S3. HTTPFT without S3 is blocked, and neither flag
|
||||
permits a legacy retry for a newer store. The core returns `media_unsupported` with storage detail
|
||||
for operations that backend cannot perform, before issuing any legacy command or touching local
|
||||
files. Absent or unrecognized flags retain legacy requests and authoritative server errors.
|
||||
**`storage`** is `{capability_extensions, httpft, s3, supported}`. It is computed from `virtualserver_capability_extensions` (tapped from `initserver`/`notifyserverupdated`/`notifyserveredited`) using the official substring test. Known `HTTPFT` or `s3` advertisements cause every file operation except transfer inspection/cancellation to fail with `media_unsupported` and storage detail **before any legacy command or local disk side effect**. No UI override falls back to a different store. Unknown/unannounced capability flags retain legacy requests and authoritative server errors; they do not prove newer-storage support.
|
||||
|
||||
**Host paths belong only at the trusted core boundary.** Native file services resolve session/purpose-owned chooser grants before constructing download/upload commands; UI fields cannot provide arbitrary paths.
|
||||
- `dest_dir` is an absolute, existing folder.
|
||||
@@ -590,8 +537,7 @@ files. Absent or unrecognized flags retain legacy requests and authoritative ser
|
||||
- `source` must be a regular file. Its size is measured once and sent in `ftinitupload`. Exactly that many bytes are streamed; a file that shrinks fails the upload.
|
||||
- With `overwrite:false` a server-side "file already exists" (0x0802) fails the transfer with code `file_exists`.
|
||||
|
||||
**Legacy TCP transfers**
|
||||
|
||||
**Transfers**
|
||||
- Native scheduling allocates app-global directional slots (combined maximum ten); at most 512 native records per connection.
|
||||
- Transfer ids are bridge-visible `u32` values, unique per connection.
|
||||
- Lifecycle: `queued` → `starting` (`ftinit*` sent) → `running` (stream granted) → [`confirming`, upload only] → `done` | `failed` | `cancelled`.
|
||||
@@ -610,27 +556,10 @@ files. Absent or unrecognized flags retain legacy requests and authoritative ser
|
||||
- A grant that arrives after the cancel is dropped and stopped.
|
||||
- Progress is emitted at most every 250 ms while bytes move.
|
||||
|
||||
**Newer storage limits and evidence**
|
||||
|
||||
- S3 listing does not enable folder creation, rename/move, delete, pause/resume, inline images,
|
||||
file-link copying, avatars or server/snapshot icon operations. Listing success is metadata only,
|
||||
not evidence of uploading, downloading or mutating through TeamSpeak. HTTPFT is blocked; there
|
||||
is no fallback to legacy TCP or to direct object-store access.
|
||||
- The isolated official TS6 Server beta14 run negotiated `s3`, received a matching notification
|
||||
with an empty `b64_json` followed by status `0`, and returned `entries:[]`, `malformed:0`,
|
||||
`storage.s3:true`, `storage.list_supported:true` and `storage.read_only:true` for channel 1's
|
||||
root. The client disconnected cleanly. This records the tested build's result, not a guarantee
|
||||
for other operations. A subsequent ordinary guest upload grant was refused by the fixture;
|
||||
this verifies rejection, not a successful grant or file transfer. Nonempty listing, file bytes
|
||||
and remote mutations through TeamSpeak remain unverified live. A separate direct SigV4
|
||||
seed/list/readback is not TeamSpeak channel evidence. Live-peer validation remains pending.
|
||||
- [Native file-transfer notes](evidence/ts6-filetransfer-native.json) and their
|
||||
[continuation](evidence/ts6-filetransfer-native-continuation.json) are historical static evidence;
|
||||
recovered constructors or endpoint arguments alone do not establish a working operation.
|
||||
- Keep live checks separately authorized, on disposable channels/profiles/storage with explicitly
|
||||
approved actions and scoped evidence output. Retain only sanitized status, counts, byte lengths
|
||||
and fixture hashes; no credentials, signed URLs, private files or unrelated server state.
|
||||
- Drag-and-drop upload without a purpose-bound native resource grant remains unavailable.
|
||||
Not implemented (explicit limits):
|
||||
- The TeamSpeak 6 `HTTPFT` and `s3` branches. Exact recovered constructor arguments, bounded RIP-relative/native-function continuation, and unresolved endpoint/payload semantics are in `docs/evidence/ts6-filetransfer-native.json` and `docs/evidence/ts6-filetransfer-native-continuation.json`. These are static interoperability evidence, not server acknowledgements.
|
||||
- Resume/pause.
|
||||
- Drag-and-drop upload without a purpose-bound native resource grant.
|
||||
|
||||
### `file_transfer` (event)
|
||||
|
||||
@@ -638,10 +567,7 @@ files. Absent or unrecognized flags retain legacy requests and authoritative ser
|
||||
|
||||
New error codes (§3): `file_exists` (target name exists and replacing it was not confirmed; `detail.name`), `transfer_cancelled`.
|
||||
|
||||
Native chooser and overwrite-confirmation continuations capture and recheck the originating
|
||||
`SessionKey`. Grants bind purpose and session; delayed or revoked results cannot start work on a
|
||||
replacement connection. Destructive actions and overwrite require explicit user confirmation.
|
||||
Isolated tests use disposable resources without OS dialogs or folder opening.
|
||||
Native chooser and overwrite-confirmation continuations capture/recheck the originating SessionKey before use. Grants bind purpose and session; delayed/revoked results cannot start work on a replacement connection. Isolated tests use disposable resources without OS dialogs/folder opening.
|
||||
|
||||
Native regression requirements include real loopback bytes/hash, cancellation, Unicode, empty/short/conflicting files and deterministic cancellation/publication gates in `core/src/file_transfer.rs` and native file services. Existence is not an execution result.
|
||||
|
||||
@@ -668,26 +594,18 @@ Regression requirements include approved-destination persistence, rejected UI pa
|
||||
|
||||
Every mutation below is answered only after its real server command result. Permission hints never manufacture success. Requests capture a server connection ID in native service and its native `generation`; stale mutations fail. Read replies are `{rows:[wire-key/string-value objects]}`, not HTML. Only one reader per notification type is allowed in flight; over 10,000 rows fails rather than silently truncating. Empty database/permission-list replies become empty rows.
|
||||
|
||||
For a scoped list, each explicit scope ID applies from that row onward, including across packet boundaries. Rows before the first scope ID and rows belonging to a different scope are excluded.
|
||||
|
||||
`admin_context {}` returns `{generation,server_uid,own_client_id,catalog_received,permissions,permissions_catalog,permission_error?}`. Permissions are the official named hint values (null if unknown); catalog entries are `{id,name,description}`.
|
||||
|
||||
For an isolated Windows beta14 fixture at `127.0.0.1:19987`, set `TEAMSPEACH_QA_CORE` to the absolute diagnostic core executable and run `cargo run --locked -p teamspeach-core --example channel_admin_qa`. It checks a newly created temporary channel, edit acknowledgements and independent readbacks. A missing wire property is unreported, not false. A server permission refusal is reported separately from an accepted write.
|
||||
|
||||
Pass `-- --client-database-id` for the read-only database identity check. It looks up the disposable guest's roster UID and compares the result with an independent nickname search. Both commands must succeed for the scenario to pass; a fixture that denies database searches cannot verify the comparison.
|
||||
|
||||
Pass `-- --client-info` to read the guest's client version and platform and verify local rejection of a mismatched UID for the same client number.
|
||||
|
||||
| Command | Arguments / result |
|
||||
|---|---|
|
||||
| `channel_create` | `{generation,parent_id,properties}` → `{channel_id}` from the client's own channel-created notification matching name and parent. A nonzero `channel_order` must still be a child of `parent_id` at dispatch. If the server accepted creation but no unique positive ID was received, the error detail contains `created: true`; refresh the tree instead of retrying creation. |
|
||||
| `channel_edit` | `{generation,channel_id,properties}`; a nonzero `channel_order` must still be a sibling distinct from the edited channel. A stale predecessor returns `target_changed` without sending the edit. |
|
||||
| `channel_move` | `{generation,channel_id,parent_id,order?}`; parent 0 means server root, order 0 means first. A nonzero predecessor must still belong to the destination parent. A missing or cyclic destination ancestry, a destination below the moving channel, or a stale predecessor is refused before sending. An exact match of parent and explicit predecessor returns `{"changed":false}` locally, without a server request. An omitted order does not qualify. |
|
||||
| `channel_create` | `{generation,parent_id,properties}` → `{channel_id}` from own channel-created event |
|
||||
| `channel_edit` | `{generation,channel_id,properties}` |
|
||||
| `channel_move` | `{generation,channel_id,parent_id,order?}` |
|
||||
| `channel_delete` | `{generation,channel_id,force,confirm}`; confirm exact current channel name |
|
||||
| `channel_subscribe` / `channel_subscribe_all` | `{channel_id,subscribe}` / `{subscribe}` |
|
||||
| `channel_description` | `{channel_id}` → `{description}`: a string (including the empty string) if reported; null if not received or invalidated before acknowledgement. A description-change notice invalidates only that channel's cached text until a fresh value arrives. |
|
||||
| `channel_list` / `channel_info` | `{}` / `{channel_id}`; observed channel properties, with `cpid` and `channel_order` taken from the current channel tree as decimal strings; info refreshes description |
|
||||
| `client_info` | `{client_id,uid}`; requests `clientgetvariables` only for a matching live identity. Only rows explicitly naming the requested client number are collected. A conflicting UID in a row, disappearance of the client, or reassignment of its number before a successful acknowledgement returns `target_changed` instead of client information. |
|
||||
| `channel_description` | `{channel_id}` → `{description}` |
|
||||
| `channel_list` / `channel_info` | `{}` / `{channel_id}`; observed channel wire properties, info refreshes description |
|
||||
| `client_info` | `{client_id,uid}`; checks current UID, requests `clientgetvariables` |
|
||||
| `set_away` | `{away,message?}`; message only when away, ≤80 characters |
|
||||
| `talk_request` | `{request,message?}`; message only when requesting, ≤50 characters |
|
||||
| `talk_power` | `{generation,client_id,uid,grant}`; UID checked against live target |
|
||||
@@ -697,7 +615,7 @@ Pass `-- --client-info` to read the guest's client version and platform and veri
|
||||
| `ban_add` | `{generation,ip?,name?,uid?,duration_s,reason?}`; at least one target; 0 seconds permanent |
|
||||
| `ban_delete` / `ban_delete_all` | `{generation,ban_id,confirm}` / `{generation,confirm}`; confirm decimal ID / `all_bans` |
|
||||
| `privilege_key_list` | `{}` |
|
||||
| `privilege_key_add` | `{generation,kind:"server_group"|"channel_group",group_id,channel_id?,description?}`; channel ID iff channel group. Returns `{token}` only for one distinct usable key. Repeated reports of that key are accepted; missing or conflicting keys after acknowledgement give an error with `created: true`. Reload the list before taking further action. |
|
||||
| `privilege_key_add` | `{generation,kind:"server_group"|"channel_group",group_id,channel_id?,description?}`; channel ID iff channel group; → `{token}` |
|
||||
| `privilege_key_use` / `privilege_key_delete` | `{generation,token}` / `{generation,token,confirm}`; confirm exact token |
|
||||
| `temp_password_list` | `{}` |
|
||||
| `temp_password_add` | `{generation,password,description?,duration_s,channel_id?,channel_password?}`; positive duration |
|
||||
@@ -706,12 +624,12 @@ Pass `-- --client-info` to read the guest's client version and platform and veri
|
||||
| `client_database_list` | `{start:u32,duration:1..200}` |
|
||||
| `client_database_find` | `{pattern,uid:bool}`; `clientdbfind -details [-uid]` |
|
||||
| `client_database_delete` | `{generation,client_database_id,confirm}`; confirm decimal database ID |
|
||||
| `client_database_id` | `{uid}`; returns one row with the exact requested `cluid` and a positive decimal-string `cldbid`. Duplicate reports of the same ID are accepted. A successful command result without a unique matching ID is an error; the server's explicit database-empty result returns an empty list. |
|
||||
| `client_database_id` | `{uid}`; rows with `cluid/cldbid` |
|
||||
| `server_group_list` / `channel_group_list` | `{}` |
|
||||
| `server_group_perm_list` / `channel_group_perm_list` | `{group_id}` |
|
||||
| `channel_perm_list` | `{channel_id}` |
|
||||
| `server_group_client_list` | `{group_id}`; sends `-names` to include UID/nickname |
|
||||
| `group_add` | `{generation,kind:"server"|"channel",name,type:0|1|2}` → `{group_id}`. The group list must identify one positive ID not present in the live book for this kind before dispatch, matching the requested name and type. Repeated rows for the same ID are allowed. If creation was accepted but no unique ID was identified, the error detail contains `created: true`; reload the list instead of retrying creation. |
|
||||
| `group_add` | `{generation,kind:"server"|"channel",name,type:0|1|2}` → `{group_id}`; missing/ambiguous resulting ID fails with created detail |
|
||||
| `group_rename` | `{generation,kind,group_id,name}` |
|
||||
| `group_set_permissions` | `{generation,kind,group_id,permissions:[{id:string,value:i32,negate?,skip?}]}`; 1..512 rows; negate/skip only server group |
|
||||
| `channel_set_permissions` | `{generation,channel_id,permissions:[{id:string,value:i32}]}` |
|
||||
@@ -732,13 +650,9 @@ Native snapshot orchestration in `native/src/services/snapshots.rs` uses ordinar
|
||||
|
||||
### 4.22 Whisper routes
|
||||
|
||||
A client number is not an identity. An individual recipient needs a nonempty UID matching the live roster. A missing, empty or mismatched UID omits that recipient; if nothing resolves, the command returns `no_targets`. An explicitly targeted channel remains a channel target even when an occupant has no visible UID.
|
||||
|
||||
`whisper_start {epoch:u32,target}` resolves a route against the live connection; epoch must be nonzero. Target is `{kind:"list",entries:[{type:1|2,uuid,name}]}`, `{kind:"group",group_type:0..3,target_mode:0..6,group_id,server_uuid}`, or `{kind:"ids",clients:[{id,uid}],channel_ids:[…]}`. At most 255 resolved clients and channels. `whisper_stop {epoch}` stops that route; `set_whisper_receive {mode:"allow_all"|"deny_all"}` controls incoming whispers.
|
||||
|
||||
`audio_frame` accepts optional `whisper:epoch`; stale/stopped/other-generation tags drop, never fall back to ordinary voice. Untagged queued frames also drop while a whisper route is held. Transitions end the previous spurt and discard capture queued before the transition. Receive deny mode removes queued whispers.
|
||||
|
||||
`whisper_received` carries the receiver's connection `generation` and the sender's numeric `client_id`. When known, `uid` and `nickname` identify the sender at receipt; a later roster cannot supply missing identity. An unidentified whisper can notify but cannot become a reply target. Reply requires the original UID and client number to still match in the same session.
|
||||
`audio_frame` accepts optional `whisper:epoch`; stale/stopped/other-generation tags drop, never fall back to ordinary voice. Untagged queued frames also drop while a whisper route is held. Transitions end the previous spurt and discard capture queued before the transition. Incoming `whisper_received {client_id}` feeds reply history; receive deny mode removes queued whispers. This is real TeamSpeak whisper packet routing, not local recipient filtering.
|
||||
|
||||
### Local recording (`recording_*`)
|
||||
|
||||
@@ -757,8 +671,6 @@ Events: `recording_state {isRecording, isPaused, outputDirectory, mode, reason?,
|
||||
|
||||
Files (`<directory>/<label>[_N]/`): `NN <name>.wav` per track (48 kHz mono s16le; `00 master.wav`, `NN capture - <nick>.wav`, client tracks by nickname, `(k)` for a concurrent second connection of the same UID), `… (part N).wav` past the 4 GiB RIFF limit, and `session.json` (`finalized:false` until stop) with per-track speech segments `{startFrame, endFrame, startEpochMs, clientId, nickname, channelId, channelName, whisper}`, pauses, `droppedRanges`, `endReason`, `errors`.
|
||||
|
||||
`totalBytes` counts PCM payload bytes across all WAV tracks and parts, excluding each 44-byte RIFF header. The final event and `session.json` report the same count. To compare it with a WAV reader, sum `frames × channels × bytes_per_sample` across the files, not their filesystem lengths.
|
||||
|
||||
Signal paths: client tracks = each speaker's decoded audio before local volume (official: "individual tracks stay untouched"); capture = frames this connection actually encoded and sent (after mute/PTT/VAD); master = the local playback mix with local volumes plus the sent capture. A full disk queue (2 s) drops whole 20 ms ticks, counts them and pads them with silence so tracks stay aligned. Headers are refreshed every 2 s. TeamsPeach's file layout/format is its own; the official native format is not published.
|
||||
|
||||
Starting a second recorder while prior files finalize is refused. Dropped capture includes queued TX discarded on pause/stop; dropped tails are padded through declared timelines, empty master is a valid 44-byte WAV. Header-finalization errors keep finalized false, are recorded, and actual final file bytes are recomputed. Multitrack taps are pre-gain/pre-AGC; master is post-client-gain/AGC plus sent capture, not native device output gain.
|
||||
@@ -786,9 +698,6 @@ See §1.
|
||||
{"event":"state","state":"connecting|connected|disconnecting|disconnected",
|
||||
"address":"10.10.10.160:9987","reason":{"code":"...","message":"...","ts_error":{...}}}
|
||||
```
|
||||
A terminal `disconnected` event reports `previous_state` (`connecting`, `connected`, or
|
||||
`disconnecting`). Use it to distinguish a failed connection attempt, a dropped live session,
|
||||
and a requested exit without guessing from the error text.
|
||||
`reason` only on `disconnected` when not user-initiated (kicked, banned, timeout,
|
||||
server shutdown, connect failure) and on an automatic-reconnect `connecting`. For a
|
||||
server-closed connection `reason.detail.reason` is one of `kicked`, `banned`,
|
||||
|
||||
@@ -1,79 +1,4 @@
|
||||
# TeamSpeak 6 visual reference and historical selector source map
|
||||
|
||||
## Current account-free desktop reference (6.0.0.5232)
|
||||
|
||||
The Windows reference ran the installed **TeamSpeak 6.0.0.5232** Vue frontend from
|
||||
`html/client_ui` in an isolated, offscreen reference runner; it did not run the official native client.
|
||||
The `served` fields of all four `target/evidence/official-5232-pc/official/*/manifest-chat-full.json`
|
||||
files record these SHA-256 fingerprints:
|
||||
|
||||
| Bundle | SHA-256 |
|
||||
|---|---|
|
||||
| `main.js` | `352683c3eb1d674c6b0fe098ec8ba132b696739a33424080c9266b751de41537` |
|
||||
| `main.css` | `ae349aa2f33da6ae6e638c211e758e9a6cd1da2d07399701453a52ed7a2ac72d` |
|
||||
|
||||
These screenshots are not user-account state. A shared canonical fixture supplies synthetic
|
||||
connected server/tree, chat and device data; no real server session, normal profile, account login
|
||||
or media device is used. The reference-only `pair-report.json` records a passing instrument self-test
|
||||
and fixture equality, not a visual pass. It records five blocked requests, 15 unanswered bridge calls
|
||||
and 11 page errors per variant; the requested scenes were captured, but unprovided services were not tested.
|
||||
|
||||
Reference and native coverage: dark/light × EN/RU at 1280×800, with full channel chat (`main`),
|
||||
Alex private chat (`private`), Alex's client context menu (`menu`), and the top of Audio and
|
||||
Appearance settings. The account-free product retains independent branding and omits account-only
|
||||
sidebar actions, account/homebase settings and Remote Apps. Native caption presentation is not
|
||||
tested offscreen. The native comparator scores the entire frame even where differences are declared.
|
||||
|
||||
### Capture and compare from the repository root
|
||||
|
||||
The reference runner is a **QA-only** export of the historical scripts, with Node/Electron and
|
||||
`playwright-core` available. This does not restore Electron to the product. The official `html/client_ui`
|
||||
must match the pinned hashes; the fixture is a local synthetic evidence artifact, not a dependency
|
||||
on the official profile. The recorded artifact names below are examples: use fresh output paths
|
||||
for reruns and update the corresponding comparator inputs.
|
||||
|
||||
```powershell
|
||||
New-Item -ItemType Directory -Path target/reference-ui-5232-tools -ErrorAction Stop | Out-Null
|
||||
git archive --output=target/reference-ui-5232-tools/runner.tar eb24965076599267687c8c4dd6f24f22953b15f6 scripts/official-pair-capture-offscreen.mjs scripts/lib
|
||||
tar -xf target/reference-ui-5232-tools/runner.tar -C target/reference-ui-5232-tools
|
||||
$fixture = 'C:/Users/Admin/tmp/teamspeach-exact-design-20261101/expanded-reference/fixture-data.json'
|
||||
node target/reference-ui-5232-tools/scripts/official-pair-capture-offscreen.mjs --official-only --out target/evidence/official-5232-pc --themes dark,light --locales en,ru --sizes 1280x800 --screens main,private,settings:audio,settings:appearance,menu --fixture $fixture
|
||||
|
||||
$out = Join-Path (Get-Location) 'target/evidence/native-5232-pc-03'
|
||||
New-Item -ItemType Directory -Path $out -ErrorAction Stop | Out-Null
|
||||
$env:TEAMSPEACH_PC_PARITY_FIXTURE = $fixture
|
||||
$env:TEAMSPEACH_SMOKE_NO_NETWORK = '1'
|
||||
$env:TEAMSPEACH_SMOKE_NO_OS_ACTIONS = '1'
|
||||
$env:TEAMSPEACH_SMOKE_NO_PHYSICAL_CAPTURE = '1'
|
||||
$env:TEAMSPEACH_PROFILE_DIR = Join-Path $out 'profile'
|
||||
cargo run --locked -p teamspeach-native --bin teamspeach --target x86_64-pc-windows-msvc --no-default-features --features test-harness -- --smoke pc-parity --profile-dir $env:TEAMSPEACH_PROFILE_DIR --output $out
|
||||
|
||||
python native/tools/compare_desktop_parity.py --official target/evidence/official-5232-pc/official --native target/evidence/native-5232-pc-03/native --out target/evidence/compare-5232-pc-03
|
||||
```
|
||||
|
||||
The native capture receipt is `native-5232-pc-03/parity.json`; scene JSON/PNGs are under its
|
||||
`native/` directory. The comparator requires Python with Pillow and an output directory that
|
||||
does not yet exist. It writes `parity-report.json`, whole-frame and region diff images and threshold
|
||||
masks under the compare root. A pixel differs if any RGB channel delta exceeds 16/255, the pixel
|
||||
limit is 0.5%, and independently measured region geometry must match within 1 px. Crops share
|
||||
official coordinates without alignment, resizing or masking. Missing geometry is not a pass.
|
||||
|
||||
Both `-02` and `-03` completed 20/20 native captures; both compare reports record **0 passed,
|
||||
20 failed, 0 blocked**. Whole-frame differing pixel ratios across the four variants were:
|
||||
|
||||
| Scene | `compare-5232-pc-02` | `compare-5232-pc-03` |
|
||||
|---|---:|---:|
|
||||
| Main | 12.88–15.68% | 7.36–8.85% |
|
||||
| Private chat | 5.81–7.10% | 4.83–5.88% |
|
||||
| Client context menu | 50.90–76.44% | 8.98–10.99% |
|
||||
| Audio settings | 11.14–12.90% | 11.18–13.12% |
|
||||
| Appearance settings | 13.47–16.30% | 11.64–13.37% |
|
||||
|
||||
These offscreen captures do not establish strict visual parity, installed-window behavior or
|
||||
functional interoperability. See [FEATURE_COMPATIBILITY.md](../../../FEATURE_COMPATIBILITY.md)
|
||||
for the separate functional evidence and open acceptance gates.
|
||||
|
||||
## Historical source map (6.0.0.5163, visual cutover 2026-11-01)
|
||||
# TeamsPeach selector → official TeamSpeak 6 source map (visual cutover, 2026-11-01)
|
||||
|
||||
Source: installed TeamSpeak 6.0.0.5163, `html/client_ui/main.css` (sha256 `bc700401d04954d0…`) and
|
||||
`main.js` (sha256 `9d6bea2ee5333086…`), read-only. `css@N` = main.css character offset; `D@N` / `L@N` =
|
||||
|
||||
@@ -329,7 +329,7 @@ flowchart LR
|
||||
Этот раздел дополняет, а не исправляет исторический снимок выше. Владелец выбрал маршрут
|
||||
**Windows-разработка → ручной Gitea Actions → вся Android-сборка на Linux CI → скачивание
|
||||
артефактов → установка тестового APK через Windows `adb`**. Точные workflow, runner label,
|
||||
repository variables и имена артефактов указаны в [актуальном README](../README.md#android-development-windows-linux-ci).
|
||||
repository variables и имена артефактов указаны в [актуальном README](../README.md#android-development-windows-separate-linux-build-host).
|
||||
Существующие Linux desktop workflows остаются отдельными: Linux desktop package не является Android APK.
|
||||
|
||||
### Где выполняется сборка
|
||||
@@ -371,9 +371,98 @@ repository variables и имена артефактов указаны в [ак
|
||||
**Граница доказательства:** конфигурация CI, receipts проверки пакета и даже успешная установка
|
||||
test-only APK не доказывают полноценную Android-приёмку, живой голос с официальным клиентом,
|
||||
Bluetooth, lifecycle/background, screenshare, доступность или право на распространение. Тестовый
|
||||
host ограничен smoke/harness-сценариями и не подменяет проверку production build. Этот раздел
|
||||
host не подменяет проверку production build. **Уточнение read-only preflight 2026-11-11,
|
||||
HEAD `82334f8`:** offline isolation включается при переданных smoke extras; без них
|
||||
`smoke_request` возвращает `None` ([smoke.rs](../native/src/platform/android/smoke.rs):16–40),
|
||||
а Android runtime разрешает network/OS actions ([android.rs](../native/src/platform/android.rs):61–85).
|
||||
По исходникам обычный запуск harness APK может служить кандидатом для первого live voice proof
|
||||
на отдельном согласованном тестовом устройстве с disposable app data; сам proof не выполнен.
|
||||
Application ID `dev.teamspeach.mobile` общий с production ([Gradle](../platform/android/build.gradle.kts):20–35),
|
||||
поэтому тестовый APK не следует устанавливать поверх реального профиля. Этот раздел
|
||||
не заявляет успешного CI run, полученного APK/AAB, установки или работы на телефоне.
|
||||
|
||||
**iOS не переносится на Windows:** сборка и packaging по-прежнему требуют macOS с Xcode/Apple SDK
|
||||
локально либо на отдельно provisioned macOS CI. Signing/provisioning и реальная приёмка iPhone/iPad
|
||||
остаются отдельными prerequisites; Android Linux workflow не создаёт IPA и не доказывает iOS support.
|
||||
|
||||
## Android implementation update, 2026-11-11
|
||||
|
||||
Основание: рабочее дерево `feature/mobile-port` поверх `cb1d682`; пользователь явно перенёс Linux
|
||||
build/test/CI и provisioning на потом и разрешил доработку самого Android-порта. iOS не изменялся.
|
||||
Ниже — новые реализации, не mobile acceptance; исторические утверждения §7 относятся к прежнему снимку.
|
||||
|
||||
- **Audio lifecycle:** `VoiceService` ведёт focus и communication mode; Android 12+ сообщает фактическую
|
||||
смену communication device, первоначальная регистрация списка устройств не считается переключением.
|
||||
[CallAudioState](../native/src/platform/android/call_audio.rs) разделяет право на output и capture;
|
||||
потеря focus/route/permission отзывает capture, gain не возвращает микрофон автоматически.
|
||||
[Android bridge](../native/src/platform/android.rs) передаёт `SessionKey`, lease token и revision через
|
||||
`AndroidCallAudio`; [runtime](../native/src/app/runtime/mobile_calls.rs) игнорирует устаревшие события,
|
||||
останавливает захват и восстанавливает разрешённое прослушивание, отдельно выставляя input-muted.
|
||||
Cached mobile lease повторно проверяется по реальному состоянию Android. Capture/transmission gates
|
||||
в runtime учитывают эту авторизацию; non-Android ветви сохраняют прежние условия.
|
||||
- **Routing boundary:** [VoiceService](../platform/android/src/main/java/dev/teamspeach/mobile/VoiceService.java)
|
||||
использует `MODE_IN_COMMUNICATION`, освобождая mode при завершении. Добавлено обычное permission
|
||||
`MODIFY_AUDIO_SETTINGS`. Это не доказательство фактического Bluetooth mic/output, AEC или OS device selection;
|
||||
отдельного нового route-picker и обещания HFP/LE parity нет.
|
||||
- **Network:** [PlatformBridge](../platform/android/src/main/java/dev/teamspeach/mobile/PlatformBridge.java)
|
||||
отслеживает текущую default Network. Повторные capability callbacks больше не создают ложный
|
||||
`NetworkChanged`; реальная потеря/смена сети сохраняет privacy boundary. Reconnect не объявлен проверенным.
|
||||
- **SAF и identity:** typed `file_exists` проходит из [SafGrant](../platform/android/src/main/java/dev/teamspeach/mobile/SafGrant.java)
|
||||
через [JNI](../native/src/platform/android/documents.rs); Android
|
||||
[file workflow](../native/src/app/runtime/file_actions/io.rs) предлагает Save picker для другого имени,
|
||||
а не подтверждение несуществующей atomic-replace возможности. Новый документ не получает ложный overwrite prompt.
|
||||
[Identity export](../native/src/app/runtime/settings_actions/identities.rs) на Android пишет приватный staging,
|
||||
затем `commit_document`; успешный commit удаляет staging, ошибка сохраняет защищённый источник.
|
||||
Невозможность безопасно заменить существующий provider document остаётся явной ошибкой, не обходится.
|
||||
- **External links:** добавлена отсутствовавшая `android::open_external_url`, уже вызываемая общим
|
||||
`RuntimeServices::open_approved`. Разрешены http/https/mailto после privacy consent; Java выполняет
|
||||
ACTION_VIEW только из видимой Activity и возвращает отказ, если обработчика нет.
|
||||
- **Phone UI:** [shell](../native/src/ui/shell.rs) и [Slint shell](../native/ui/shell.slint) дают явные
|
||||
действия connection tabs/selected targets, раскрывают результаты query без автоматического Join/Delete,
|
||||
возвращаются по stack/settings Back. Android-specific ветви в dialogs/settings/chat ограничивают
|
||||
высоту меню/форм, прокручивают focused fields при IME и сохраняют отдельные voice controls.
|
||||
PTT освобождается при cancel/drag-out/focus loss и смене target; Android Enter в composer не отправляет
|
||||
сообщение случайно. Реальная геометрия, TalkBack/IME и жесты остаются непроверенными.
|
||||
- **Проверка:** 2 standalone regression tests реального `CallAudioState` прошли на Windows под локальным
|
||||
memory guard, без Cargo/dependency/native build. Cached Slint1.18.1 compiler проверил полный
|
||||
`app.slint` с material и fluent: parse/typecheck/codegen success. Ошибочный `Window.active` выявлен
|
||||
этой проверкой и заменён Android lifecycle → UI callback. Rust parser проверил изменённые Rust files,
|
||||
XML parser — manifest. Полный Rust/JNI/Java typecheck, native app runtime, APK/device, desktop runtime
|
||||
regression и tests Linux не выполнялись. Compatibility inventory остаётся pending; CI больше не запускался.
|
||||
|
||||
### Завершение известных Android implementation gaps перед внешней сборкой
|
||||
|
||||
Рабочее дерево поверх `cb1d682`, без нового commit/push. Пользователь выбрал следующий маршрут:
|
||||
доработка приложения здесь → передача committed revision другому разработчику → сборка у него
|
||||
в WSL2 Linux x64. WSL/SDK на текущем Windows-ПК не устанавливаются; CI/provisioning отложены.
|
||||
Команды и состав возвращаемого bundle — [README handoff](../README.md#handoff-to-another-developers-wsl2-machine).
|
||||
|
||||
- `CallAudioState` сохраняет pending output restart при более позднем отзыве capture; подтверждение
|
||||
устаревшей revision не снимает этот restart. Runtime сериализует explicit Android authorization
|
||||
с обработчиком recovery через существующий audio_configuration mutex. Повторный focus callback
|
||||
не выключает разрешённый микрофон без смены focus.
|
||||
- Activity pause приходит как `Visibility(false)`, не `Focus(false)`: теперь этот Android event
|
||||
синхронно освобождает held input и сбрасывает UI long-press. Он не отзывает MediaProjection/Camera2
|
||||
только из-за появления окна согласия или ухода Activity в фон.
|
||||
- `CaptureConsentActivity` ждёт resumed перед запуском FGS и закрывается только после foreground
|
||||
handoff из `CaptureService`. Ошибка permission-launch завершает pending native request.
|
||||
`CaptureSession` оставляет handler живым до закрытия даже поздно открывшейся Camera2; старые
|
||||
ImageReader callbacks после resize игнорируются. Изменения находятся в
|
||||
[Android capture adapter](../platform/android/src/main/java/dev/teamspeach/mobile/capture/).
|
||||
- `TeamsPeachActivity` не запрашивает write grant для чтения, различает отмену picker и некорректный
|
||||
successful result, сообщает effective permission state и очищает pending request при исключении.
|
||||
`SafGrant` проверяет возвращённые URI access flags и закрывает provider handle до detach дубликата fd;
|
||||
JNI закрывает capability при ошибке преобразования, не оставляя persistable lease.
|
||||
- **Реально проверено в продолжении:** 3 standalone Rust regression tests `CallAudioState` passed под
|
||||
локальным Job Object/memory guard; parser-only проверка 6 изменённых Rust files; 26 Java native
|
||||
declarations имеют соответствующие Rust export names; Bash syntax блока WSL2 handoff прошёл.
|
||||
Проверка имён JNI не является проверкой типов/ABI. Java/Android compilation и runtime не запускались;
|
||||
результаты прежней Slint material/fluent проверки остаются прежними, новой UI-разметки здесь нет.
|
||||
- **Не выдавать за законченную платформенную приёмку:** физический routing/Bluetooth, IME/TalkBack,
|
||||
background/OEM lifecycle, camera/screen/audio playback capture, file-provider behavior и двусторонний
|
||||
voice остаются отдельными device gates. Полный Rust/Java/JNI build ещё не выполнен и может выявить
|
||||
integration errors. Intentional product exclusions (SFU/MATRIXCHAT/HTTPFT/S3/legacy codecs/account
|
||||
services) остаются exclusions, а не молча реализованными функциями. Existing-provider atomic replace
|
||||
по-прежнему fail-closed; повторный выбор grants обязателен после restart, retained failed identity
|
||||
staging не имеет отдельного UI восстановления. Compatibility inventory не повышен из pending.
|
||||
|
||||
+93
-526
@@ -1,537 +1,70 @@
|
||||
# Мобильный порт: передача состояния
|
||||
|
||||
Обновлено: **2026-11-11**. Принятая Windows-база фиксируется тегом **`desktop-baseline-0.1.7-20261111`** в `main` (предыдущий HEAD `5ce12714acc306f6055bf1e9db3282c5af7704cb`). Дальнейшая мобильная разработка — `feature/mobile-port` от этой базы. Единственный application host — Rust/Slint; результаты ниже отделены от первоначального read-only исследования.
|
||||
Updated **2026-11-11**. Windows baseline remains `05e8d34bcf0e24a44f76e65220293c45b6821798`; active branch is `feature/mobile-port`. The owner explicitly authorized using existing WSL Ubuntu for Android builds (server1 container only as fallback), then committing/pushing fixes and publishing a separate Android APK tag/release. This supersedes the older no-local-WSL and no-release decisions below. Source base: `3d2e76eddd281e6801bb5fc591d2443a957568b7`, with the build fixes described here; the delivered build-info includes the exact source patch rather than claiming an unchanged base revision.
|
||||
|
||||
## First Android APK build
|
||||
|
||||
- Existing WSL Ubuntu24.04 x64, `/home/user/src/TeamsPeach`; full pinned Android WebRTC source build and Rust/Slint ARM64 release library succeeded. JDK21, Rust1.96, SDK36/build-tools36.0.0, full NDK28.2.13676358, LLVM18 and matching Skia m153-0.101.2 sources; one Cargo/Ninja job. No server1 container was needed.
|
||||
- Fixed actual first-build failures: Chromium DEPS NDK is sysroot-only (Cargo needs complete NDK); Skia uses `ANDROID_NDK`, Slint Java compilation needs explicit SDK36 `ANDROID_JAR` despite native API26; vendored jar destination used the wrong target root; accessibility cast needs NonNull::as_ptr; Gradle launcher CRLF and implicit build-tools35; permission observer used non-public PackageManager API; WebRTC JNI linker arguments must be emitted by the final cdylib build script.
|
||||
- `xtask package` and `verify-package` passed for `TeamsPeach-0.1.7-android-arm64-harness-test.apk`, 121385639 bytes, SHA256 `ab0c4119b4a8abfebbb31ed185459da8b1ef6c57c86324ad7862014aa1085d1b`. APK v2 test signature, ARM64, 16-KiB ZIP/ELF alignment and JNI exports verified. Android8/API26 minimum. Install with `adb install -t`; not a production signing identity.
|
||||
- Delivery: `C:/Users/Admin/Desktop/TeamsPeach-Android-0.1.7/`, APK plus build-info, exact build-fixes.patch and dependency/build/package verification receipts. Private test keystore is not included. WSL caches retained for incremental builds. Phone runtime/UI/voice/background acceptance has NOT run; no device installed, microphone activated, server connected or Windows installation modified.
|
||||
- Publication requested as a separate Android prerelease, not a `v*` desktop tag or desktop updater manifest. Record successful push/release only after remote acknowledgement; authorization failures are not publication.
|
||||
|
||||
## Текущий этап: реализация Android, CI отложен
|
||||
|
||||
- По последнему указанию пользователя работа переключена с runner/provisioning на **сам Android-порт**.
|
||||
Linux build/test/CI и iOS отложены; не возвращаться к настройке runner вместо реализации приложения.
|
||||
Изменения реализации подготовлены поверх `cb1d682`; владелец явно разрешил commit и push только `feature/mobile-port` для передачи другому разработчику. Main, теги и релизы не входят в публикацию.
|
||||
- Исправлены Android audio focus/route/permission transitions: receive-only recovery, новый call-scoped
|
||||
event с SessionKey/token/revision, повторная проверка закэшированной capture authorization, stale callback
|
||||
rejection. `VoiceService` управляет communication mode; Android12+ получает communication-device changes.
|
||||
Микрофон после interruption/route revoke не включается без явного действия. Общие runtime файлы меняются
|
||||
только Android-gated ветвями; core/DSP и iOS не менялись. Физический routing/Bluetooth/AEC не проверены.
|
||||
- Исправлены ложные network-change events на capability refresh; отсутствовавший Android external-link
|
||||
adapter; SAF collision → выбор нового имени; Android identity export → private staging/commit/cleanup.
|
||||
Provider atomic replace не имитируется, существующие файлы не перезаписываются небезопасно.
|
||||
- Доработан Android compact UI: overflow connection tabs, действия выбранных каналов/файлов, query detail,
|
||||
settings Back, PTT cancel/focus/drag-out, IME-aware forms/chat/settings. Сохранён существующий Rust/Slint
|
||||
клиент и desktop presentation; исходники UI и функциональные ветви, а не новый host или второй стек.
|
||||
- Реально выполнены **2 standalone audio state tests: passed**, guarded one-job/below-normal execution,
|
||||
без Cargo/full build. Пройдены **Slint1.18.1 material+fluent parse/typecheck/codegen** с готовыми rlib,
|
||||
Rust syntax-only parsing и AndroidManifest XML parse. Первая Slint-проверка выявила `Window.active`;
|
||||
исправлено через существующий Android lifecycle callback, повторная проверка успешна. LSP initialization
|
||||
завершился code0, rustfmt/JDK не найдены; полная Java/Rust/JNI проверка не заявляется.
|
||||
- Временные validation runners/generated sources удалены; готовые dependency caches не трогались.
|
||||
Ни приложения, ни APK/телефон/микрофон/сервер не запускались. Нет новых screenshots или device evidence;
|
||||
Windows baseline не переустанавливался, desktop runtime regression не выполнен. `compatibility.json`
|
||||
остаётся pending. Подробные новые знания — последний раздел assessment; `.ua` остаётся прежним stale snapshot.
|
||||
|
||||
### Продолжение перед передачей другому разработчику
|
||||
|
||||
- Закрыты дополнительные source-level дефекты: `Visibility(false)` освобождает Android touch PTT и
|
||||
long-press; повторный audio-focus callback не выключает микрофон; pending output recovery сохраняется
|
||||
при более позднем capture revoke; explicit authorization сериализована с audio recovery.
|
||||
- Capture consent теперь остаётся видимым до FGS handoff; permission-launch failure завершает request.
|
||||
Camera2 shutdown дожидается late-open/close callback, resize игнорирует старые ImageReader callbacks.
|
||||
Pause host Activity не используется как blanket stop для foreground camera/projection capture.
|
||||
- Android picker/permission callbacks различают отмену, отказ и некорректный результат; read-only open
|
||||
не запрашивает write permission. SAF проверяет grant flags, освобождает capability при JNI error и
|
||||
не теряет raw fd при ошибке закрытия provider handle. Desktop/iOS branches не менялись.
|
||||
- **Проверено сейчас:** 3 actual standalone audio-state tests passed; Rust syntax-only parse 6 файлов;
|
||||
26 Java native entrypoint names сопоставлены с Rust exports; Bash syntax инструкции передачи прошёл.
|
||||
Compiler test выполнялся с 5GiB job cap/2GiB headroom/below-normal, без Cargo/full/native build.
|
||||
Java/JNI typecheck, runtime UI/device и desktop regression остаются непроверенными; APK не создавался.
|
||||
- [README handoff](../README.md#handoff-to-another-developers-wsl2-machine) содержит точный существующий
|
||||
recipe и список receipts для другого ПК. Передавать нужно новый full SHA commit со **всеми** Android-изменениями;
|
||||
старый `cb1d682` их не включает. Commit/push разрешены; успешность доставки устанавливается по remote SHA, не наличию этой записи.
|
||||
Не передавать локальную ресурсную политику, credentials, signing keys, профили и Windows caches.
|
||||
- Scope остаётся честным: известные подтверждённые пробелы доработаны, но «все 718 требований готовы»
|
||||
не доказано. Перед первой Android-сборкой нельзя исключить Rust/Java/Gradle/JNI integration errors.
|
||||
Остальные device gates и намеренные unsupported product features перечислены в последнем assessment.
|
||||
|
||||
## Возврат к разработке на ПК, 2026-11-26
|
||||
|
||||
Windows, база `815c7c4`: закрыто поле admin-property:channel_create.channel_description. На локальном beta14 гостю добавлено право b_channel_create_with_description. Адресный тест формы Slint прошёл: после создания многострочный текст совпал с отдельным ответом ядра по ID канала и значением в заново открытом редакторе. Стенд остановлен.
|
||||
|
||||
Windows, база `dd433fa`: после отзыва скачанного релиза повторная проверка обнуляет прогресс, удаляет кэш и не предлагает текущую либо более старую версию. Прошли шесть адресных тестов. Вместе с проверками канала и целостности закрыты preload:checkForUpdates и preference:updateChannel на локальном стенде; установка не выполнялась.
|
||||
|
||||
Windows, база `fa0546e`: закрыт preload:downloadUpdate на локальном HTTP-стенде. Семь адресных тестов прошли: ручная загрузка при активном соединении, отложенная автоматическая загрузка, отказ при неверном размере или SHA512, отмена старого запроса. Укороченный пакет не попал в кэш и не изменил тестовый исполняемый файл; установка не проверялась.
|
||||
|
||||
Windows, база `20e99f0`: при переключении канала обновлений сбрасывается время проверки старого канала. Закрыт preload:setUpdateChannel: выбор Stable из панели «О программе», два перезапуска, отказ записи и устаревшие ответы Preview проверены. Девять адресных тестов прошли на временном профиле и loopback; установщик не запускался.
|
||||
|
||||
Windows, база `d2617e4`: исправлены предупреждения о конфликте клавиш между разными профилями и подписи безымянных папок в диалоге перемещения закладок. Прошли девять адресных тестов нативного клиента; закрыты поля id, name и parent папок закладок. Проверены маршрутизация клавиш после перезапуска и локальная блокировка сообщений по UID. Системная регистрация клавиш, физическая клавиатура и живой чат в этот прогон не входили.
|
||||
|
||||
Windows, база `17089bc`: в панели базы клиентов можно выбрать ник или UID и отправить запрос по Enter. На beta14 оба режима вернули ту же запись, что и список. Прошли три теста: поиск, защита от устаревшего ответа, локальный фильтр файлов. Тест нашёл переключатель в дереве Slint и вызвал обработчик отправки; выбор мышью и Enter не имитировались. Стенд остановлен.
|
||||
|
||||
Windows, база `bf6adcd`: закрыты client_database_list и client_database_find. На приватном beta14 список и поиск Slint показали одинаковую запись гостя (имя, UID, ID базы). Отдельный CLI-прогон подтвердил совпадение поиска по UID и нику. Прошли четыре нативных теста и два теста stdio. Записи базы не менялись, стенд остановлен; действие client_database_id из UI этим не проверено.
|
||||
|
||||
Windows, база `f453f48`: при просмотре соседней вкладки кнопки микрофона и динамика Slint меняли флаги владельца ввода. Оба списка участников beta14 подтвердили выключение микрофона, включение и выключение звука; у наблюдателя флаги не изменились. Прошёл один адресный тест. Включение физического микрофона не проверялось, стенд остановлен.
|
||||
|
||||
Windows, база `6dfaf45`: заглушение и повторное включение звука другой вкладки не отзывают разрешение захвата отправителя. На beta14 проверены сохранение разрешения, продолжение передачи и смена состояния получателя. Прошли три нативных теста; стенд остановлен. Физические устройства не использовались.
|
||||
|
||||
Windows, база `a47bebf`: пустой set_audio во время передачи вернул transmitting=true и сохранил действующее разрешение захвата. Частичное обновление оставляет второй флаг без изменений; явный null отклоняется. Прошли один тест stdio и два нативных теста, включая передачу через beta14. Физические устройства не открывались, стенд остановлен.
|
||||
|
||||
Windows, база `0064353`: закрыт preload:onAudio. После первого сигнала и паузы до тишины получатель отсоединил UI; второй сигнал через beta14 дал новые ненулевые блоки на тестовом выходе без повторного подключения. Прошли четыре адресных нативных теста, включая усиление голоса и изоляцию вкладок. Физические устройства не открывались, стенд остановлен.
|
||||
|
||||
Windows, база `a1bf10f`: исправлено разрешение воспроизведения по неполному снимку и audio_state. Проверка отсчётов микшера различает тишину, явное снятие заглушения и повторное закрытие маршрута. Прошли четыре проверки микшера и три интеграционных теста привязки звука. Отсоединение UI в этот прогон не входило.
|
||||
|
||||
Windows, база `aab5a34`: закрыт preload:sendAudioFrame для нативного тракта. На beta14 проверена передача синтетического сигнала через DSP и ядро. Отдельно проверены возраст всего кадра, сброс половины кадра при смене разрешения и отзыв предыдущего владельца до подтверждения нового. Прошли пять нативных тестов и три теста ядра. Физический микрофон не использовался; стенд остановлен.
|
||||
|
||||
Windows, база `4aaab8f`: закрыт preload:endAudio для нативного пути. После отзыва разрешения и паузы потребителя на 600 мс очередь сохранила только маркер конца; извлечённый кадр и кадр из VAD не прошли к отправке. Свежий кадр с новой меткой начал новую передачу. Прошли четыре теста ядра. Пауза проверена без сети; живые остановки PTT и шёпота проверялись отдельно.
|
||||
|
||||
Windows, база `0f5551a`: приватный beta14 отклонил создание каналов с кодеками 0, 1, 2 и 3 (WebQuery 1538). Контрольный канал с кодеком 4 создан, значение подтверждено channelinfo. Проверка живого входа в Speex/CELT и отсутствия исходящих пакетов остаётся открытой; стенд остановлен.
|
||||
|
||||
Windows, база `9cbf0bd`: закрыт pttEnabled. После отпускания клавиши выключение PTT восстановило передачу уже разрешённого синтетического ввода, а включение остановило её у обоих клиентов beta14. Прошли два адресных теста, включая перезапуск Slint и отказ при сохранении. Физические устройства не открывались.
|
||||
|
||||
Windows, база `ef5c9a8`: закрыт pttCode. В настройках аудио видны состояние записи, ошибка и отмена. После Ctrl+F9 и ошибки записи сохранилась F8; F10 пережила два перезапуска. На beta14 старая F8 не передавала звук, новая F10 передавала с заданной задержкой. Прошли три нативных теста. Физические устройства и системная регистрация не проверялись.
|
||||
|
||||
Windows, база `59d5a92`: F9 (Push to Mute) остановила передачу по F8 без изменения флагов микрофона. Отпускание F9 возобновило звук только при удерживаемой F8; при обратном порядке оба клиента остались в тишине. Устранена лишняя перенастройка ввода при закрытии передачи. Прошли три нативных теста, включая две вкладки beta14 с синтетическим микрофоном. Стенд остановлен.
|
||||
|
||||
Windows, база `639b8b7`: повторное нажатие PTT после окончания задержки возобновляет ранее активный, разрешённый ввод в той же сессии. На локальном beta14 с непрерывным синтетическим сигналом отправитель завершил TX через 127/523/15 мс при 100/500/Off; при потере фокуса через 15 мс после события. Прошли три адресных теста; измерены состояния двух клиентов, не слышимая задержка физического устройства. Стенд остановлен.
|
||||
|
||||
Windows, база `0e6b285`: отпускание экранной кнопки PTT не отзывает разрешение захвата, пока удерживается другая клавиша или действует заданная задержка. Повторное отпускание не продлевает таймер, отмена удержаний отзывает разрешение сразу. Прошли четыре адресных теста, включая Slint и перезапуск настроек. Момент последнего переданного аудиокадра здесь не измерялся.
|
||||
|
||||
Windows, база `d8e40b4`: на двух вкладках beta14 переключатель Deny All подавил речь и уведомление для шёпота по F9; Allow All восстановил речь и одно уведомление от отправителя. В обоих случаях отправитель подтвердил передачу. Для синтетического PCM использованы отдельные часы 20 мс, без физических устройств. Прошли три нативных проверки, включая перезапуск, и две проверки ядра.
|
||||
|
||||
Windows, база `bbd2c35`: закрыты whisper_start и whisper_stop. В нативном клиенте метка шёпота привязывается вместе с разрешением захвата. На beta14 две локальные клавиши заменяли маршрут; отпускание старой не остановило новую. Синтетический звук через разрешение менеджера появился в истории получателя, последующее отпускание отозвало разрешение. Прошли пять нативных тестов и тест stdio. Без запуска физических устройств и регистрации системных клавиш.
|
||||
|
||||
Windows, база `ea957ec`: в `duplex_qa --group-whisper` получатель в том же канале с Allow All не получил звук, признак речи или уведомление для двух чужих групп (серверной и канальной). Отправки в его собственные группы до и после этих попыток доставлены; сервер подтвердил оба отключения. Без изменения прав или физических устройств.
|
||||
|
||||
Windows, база `748e760`: проверка `duplex_qa --group-whisper` через приватный beta14 подтвердила доставку серверной и канальной группам в текущем канале. Проверены ID маршрута, декодированный тон и событие с UID отправителя, подтверждены оба отключения. Это две копии Rust-ядра, без физического аудио и клавиш Slint.
|
||||
|
||||
Windows, база `bf8f819`: при смене типа группы список шёпота сохраняет выбранный сервер, сбрасывает старую группу и область доставки. Действие выбора группы привязано к типу каталога. Прошли тест Slint с перезапуском, тест формирования команды и интеграционный тест сохранения списка. Групповая доставка через сервер не проверялась.
|
||||
|
||||
Windows, база `d77d0c3`: при разрешении маршрута группового шёпота нулевой ID с ведущими нулями, знак плюс и переполнение отклоняются. Схема сохранённых черновиков не менялась. Прошли два теста ядра на разрешение групп и формат пакета; доставка группе на сервере не проверялась.
|
||||
|
||||
Windows, база `8be4404`: при завершении шёпота ядро проверяет адресатов по текущему списку, как и при передаче звука. Прошли четыре теста маршрута и пакетного формата, затем duplex_qa --whisper на приватном beta14 с тремя подтверждёнными отключениями. Повторное использование ID проверено тестом маршрута, не принудительно на сервере.
|
||||
|
||||
Windows, `82a72e2`: после исправления приёмника запущен `duplex_qa --whisper` с двумя заново собранными stdio-ядрами на beta14. Allow All дал 43 кадра с верным отправителем, Deny All не дал ни воспроизведения, ни уведомления, после возврата к Allow All пришли 42 кадра. Устаревшая метка отброшена после остановки и переподключения; обычная речь после переподключения не создала запись шёпота. Сервер подтвердил все три отключения. Без устройств и горячих клавиш Slint.
|
||||
|
||||
Windows, база `6d5e016`: отклонённые буфером голосовые пакеты больше не начинают и не прерывают входящий шёпот. Четыре теста ядра прошли, включая дубликаты пакетов Opus, очистку очереди при Deny All и событие без записи участника в списке. Проверена обработка пакетов; межклиентская доставка на сервере в этом прогоне не проверялась.
|
||||
|
||||
Windows, база `0e7d0b9`: закрыт server_log. С правом b_virtualserver_log_view строки в панели совпали с независимым запросом; чтение журнала экземпляра получило отказ с сохранением полей. Исправлено отображение флажков сразу после редактирования. Прошли четыре нативных теста; содержимое строк не выводилось, стенд остановлен.
|
||||
|
||||
Windows, база `0d7edae`: stdio проверяет форму JSON до диспетчеризации. Позиционный запрос, массив аргументов и явный null отклоняются; невалидный shutdown не завершает процесс, а чтение профиля без поля args работает. Прошли 19 тестов парсера/stdio и 19 процессных тестов bridge_smoke. Встроенный Rust API не менялся.
|
||||
|
||||
Windows, база `49cfd53`: подписка на третий ограниченный канал beta14 вернула видимый PermissionsClientInsufficient и не изменила флаги обеих вкладок. Запоздавший отказ привязан к целевой вкладке, поколению сессии и текущему UI. Прошли три нативных теста; смена сессии при обработке отказа проверена моделью, не принудительным сетевым разрывом.
|
||||
|
||||
Windows, база `1d5e4ba`: четыре команды подписки из меню Slint проверены новыми снимками двух каналов на beta14; подписки второй вкладки не изменились. Обе stdio-команды отклоняют позиционные массивы. Прошли две проверки нативного клиента и одна stdio. Живой отказ в правах и переподключение до подтверждения не моделировались.
|
||||
|
||||
Windows, база `e15858b`: импорт keybinds v2 учитывает пропущенные дубликаты UUID профилей и привязок в диагностике, оставляет первую запись и не переписывает исходный файл при открытии. Пять тестов прошли, включая резервную копию v1 и восстановление точного совпадения после перезапуска. Физическая регистрация Windows не проверялась.
|
||||
|
||||
Windows, база `c8cbf46`: ядро отклоняет ожидающий ответ channel_info/channel_description при удалении целевого канала. Повторное использование ID проверено последовательностью протокольных событий; в живом beta14 проверено редактирование и чтение описания, не повторное использование ID. Прошли три теста ядра, один stdio и четыре нативных. Стенд остановлен.
|
||||
|
||||
Windows, база `d72c273`: на отдельном канале classic beta14 подтверждены file_mkdir, file_rename и file_delete из нативного браузера. После каждой операции состояние сверено отдельным запросом списка; отмена удаления сохранила папку. Временный канал без прав по-прежнему вернул видимый отказ. Три адресных теста прошли, стенд остановлен.
|
||||
|
||||
Windows, база `f76a7fb`: проверены uploadSlots, limitUpload и uploadMiB на отдельном канале classic beta14. После перезапуска две вкладки делили 1 МиБ/с; снижение числа слотов с двух до одного приостанавливало более позднюю передачу в той же вкладке до явного возобновления. Пять файлов по 4 МиБ скачаны обратно и совпали побайтно. Прошли четыре теста. До выдачи прав на тестовый канал сервер возвращал PermissionsClientInsufficient; стенд остановлен.
|
||||
|
||||
Windows, база `aff60b9`: панель прав сохраняет обе категории и действия создания при обновлении одного списка. На двух гостевых вкладках beta14 проверены имена, ID обычных групп и действия меню по независимым ответам сервера. Прошли семь адресных тестов; обновление после изменения группы проверено на тестовых ответах, без записи на сервер.
|
||||
|
||||
Windows, база `8e9f28c`: форма журнала принимает число строк, позицию, порядок и флаг экземпляра. На beta14 проверены отмена, ошибки границ, видимый отказ гостю с сохранением полей и отклонение формы прежней вкладки. Прошли пять нативных тестов и тест stdio на границу позиции; содержимое журнала в отчёт не выводилось. Положительный ответ авторизованному пользователю на живом сервере не проверен.
|
||||
|
||||
Windows, база `5e73b78`: закрыт `command:server_info`. На двух вкладках beta14 панель показала имя и приветствие из отдельных ответов сервера, а действие редактирования сохранило нужную сессию и UID. Проверены закрытие панели и отбрасывание устаревших результатов в модели; пустой, неоднозначный и чужой ответ не открывает редактор. Прошли четыре нативных теста и тест ядра на аргументы. Серверные настройки не менялись.
|
||||
|
||||
Windows, база `cebac97`: форма переноса в защищённый канал проверяет пароль до отправки. На приватном beta14 поле открылось пустым, неверные значения остались с ошибкой, отмена не переместила участника. Отдельно проверена передача в команду пароля длиной 1024 байта с пробелами по краям. Прошли три нативных проверки и тест stdio. Перенос с разрешением сервера не подтверждён.
|
||||
|
||||
Windows, база `534f9b5`: после ответа на перенос участника проверяется исходная сессия, но не прежнее местоположение участника. Тест с обновлением списка до обработки ответа подтвердил, что повторная отправка запрещена, подтверждение принимается, а после замены сессии отклоняется. Прошли четыре адресных теста. Это проверка порядка событий, не успешного переноса на живом сервере.
|
||||
|
||||
Windows, база `baea1f7`: команда переноса участника привязана к исходной сессии, UID, номеру участника и каналу назначения. На двух гостях beta14 проверены отсутствие действия в общем канале, форма без пароля для открытого канала, отмена, серверный отказ и отклонение устаревшего подтверждения. Прошли четыре нативных теста и проверка stdio для границ ID. Успешный перенос с правами не подтверждён.
|
||||
|
||||
Windows, база `d687e35`: форма переименования серверной и канальной групп показывает имя выбранной строки. Пробелы по краям удаляются, пустое и неизменённое имена не отправляются, изменённое имя сохраняет исходный ID и сессию в команде формы. Прошли три теста нативного клиента. Запись группы на живом сервере не проверялась.
|
||||
|
||||
Windows, база `6f1ffc3`: список клиентов, поиск и пагинация проверяют номер запроса, окно, сессию и UID сервера. Тест модели подтвердил отбрасывание ответов в обратном порядке, после «Назад» и после замены сервера. Прошли пять проверок, включая панель гостя beta14. Положительный ответ на поиск от сервера с разрешённым доступом не подтверждён.
|
||||
|
||||
Windows, база `c3f3c43`: исправлен устаревший тест байтового лимита поиска. Нативная панель передаёт 255 символов без усечения, 256-й отклоняется. На beta14 открытие базы клиентов из меню сервера вернуло гостю PermissionsClientInsufficient; окно показало отказ без строк и без активного поиска. Три теста прошли; успешные list/find на сервере не подтверждены.
|
||||
|
||||
Windows, база `8072e6f`: для шаблона поиска по базе клиентов (255 символов) и UID административных запросов (128) ядро проверяет длину в символах Unicode. Три теста ядра и тест нативного поиска прошли; stdio отклонил пустую строку, управляющий символ и превышение на один символ до подключения. Живые ответы базы клиентов не проверялись.
|
||||
|
||||
Windows, база `d1b611a`: ядро и поля создания/переименования групп считают длину имени в символах Unicode, предел 128. Прошли два теста ядра и один тест форм. В stdio допустимое многобайтное имя дошло до not_connected; превышение предела и перевод строки дали bad_request. Изменение реальных серверных групп не проверялось.
|
||||
|
||||
Windows, база `1213468`: административные ID и смещение server_log, порядок каналов и семь числовых свойств server_edit ограничены по эталонному контракту. На границе 2^53−1 проверка stdio дошла до not_connected, а 2^53 отклонено до соединения. Прошли четыре теста ядра и три теста нативного клиента. Серверные квоты и группы на живом сервере не менялись.
|
||||
|
||||
Windows, база `bff5c33`: проверено поле `channel_codec_quality` в обеих формах. Beta14 вернул 5 после создания и 7 после редактирования того же канала. Значения 11 и −1 остались в форме с ошибкой; отмена изменения на 3 оставила на сервере 7. Прошли три адресных теста, звук не измерялся.
|
||||
|
||||
Windows, база `90bcf5d`: закрыт `admin-property:channel_edit.channel_name`. Форма удержала имя длиной 41 символ с ошибкой; отмена сохранила прежнее имя. Новое имя длиной 40 символов подтверждено в списке beta14 по прежнему ID, в дереве Slint и при повторном открытии редактора. Тема канала и имя лобби не изменились. Три адресных теста прошли.
|
||||
|
||||
Windows, база `a0c3318`: закрыт `preload:filesChooseUpload`. Диалог отправки файлов канала поддерживает множественный выбор. Пять проверок подтвердили точные имена и размеры, отмену, отказ для устаревшей сессии и для 101 файла, а также очистку временных копий при изменении источника. Файлы не отправлялись на сервер; мобильные диалоги не менялись.
|
||||
|
||||
Windows, база `49c747e`: закрыты `file-setting:alwaysAsk` и `file-setting:approvedDownloadDir`. После перезапуска проверены отмена выбора папки и отклонение выбора для прежней сессии. Первая вкладка скачала файл в разовую папку, вторая после выключения запроса использовала сохранённую; байты обеих копий проверены. Первоначальный групповой запуск получил ConnectFailedBanned до проверки второго сценария; адресный тест с интервалом между подключениями прошёл на том же beta14 без изменения прав и ограничений.
|
||||
|
||||
Windows, база `5f71304`: при проверке свободного слота ядро считает только активные передачи нужного направления и канала до заданного лимита, без построения и сортировки списка. Прошли тесты выбора следующей передачи и порядка паузы/возобновления; производительность не измерялась.
|
||||
|
||||
Windows, база `37552c2`: закрыт `file-setting:downloadSlots`. После перезапуска две вкладки начали три загрузки на классическом beta14. Уменьшение числа слотов с двух до одного через Slint приостановило более позднюю загрузку первой вкладки; после завершения остальных она оставалась на паузе до явного возобновления. Все три файла совпали с исходными байтами. Три адресных теста прошли; uploadSlots в этом сценарии не проверялся.
|
||||
|
||||
Windows, база `b41b2d7`: закрыты `file-setting:limitDownload` и `file-setting:downloadMiB`. Две вкладки после перезапуска одновременно скачали по 4 МиБ на классическом beta14. Проверены общий лимит 1 МиБ/с с допуском на блоки и выборку, а также точные байты обеих копий. Прошли три теста; скорость одновременной отправки не измерялась.
|
||||
|
||||
Windows, база `e1a07a2`: форма переименования файла открывается с текущим именем; отмена и подтверждение того же имени оставили список сервера неизменным. На классическом beta14 создание папки во временном канале вернуло видимый PermissionsClientInsufficient, повторный file_list пуст. Прошли три проверки. Успешные file_mkdir, file_rename и file_delete не подтверждены; права гостя не менялись.
|
||||
|
||||
Windows, база `a6684d3`: на двух гостях beta14 просмотр второй вкладки не менял разрешение первой. При передаче микрофона с недоступным выходом ошибка устройства видна, разрешения отозваны и ни одно аудиоустройство не запущено. Исправлены преждевременные флаги активности, первичное применение маршрута уведомлений и ложная ошибка отсутствующего разрешения у заглушённой вкладки. Прошли семь проверок. Положительная передача PCM при смене владельца в живом окне не проверена.
|
||||
|
||||
Windows, база `3396dcb`: закрыт `preference:lastAddress`. Вход из формы Winit подтверждён списком гостей beta14. Ошибка отсутствующего выхода видна и не мешает запомнить адрес, после перезапуска поле восстановлено. Две адресные проверки прошли, запуска аудиоустройств не было. Смена владельца микрофона между живыми вкладками остаётся открытой.
|
||||
|
||||
Windows, база `b684eca`: исправлено восстановление сохранённого адреса в форме подключения первой пустой вкладки. Тест Slint на двух запусках подтвердил отмену редактирования, отказ при отключённой сети, отсутствие записи при отказе и пустое поле второй вкладки. На протяжении теста не было активных серверов или запуска аудио. Успешную запись lastAddress через форму на beta14 и полную проверку command:connect не заявляем.
|
||||
|
||||
Windows, база `be3654f`: закрыт `feature:chat.central_matrix` как исключение. В открытом серверном чате ссылка `matrix:` неактивна, а `https://matrix.to/` вызывает подтверждение внешней ссылки; отмена сохраняет адресата и черновик. Два теста Slint прошли в отдельных процессах, без сети и внешнего браузера. Серверные комнаты Matrix этим не реализованы.
|
||||
|
||||
Windows, база `a8fc57c`: проверены исключения `feature:myts.account_cloud` и `feature:remote_apps` в настройках Slint с одноразовым профилем. Попытка включить облачные личные сообщения оставила клиент без входа и без соединения; пустой Chats не создал беседу при попытке отправки. Прошли три теста, включая отдельный сценарий объявления серверного Matrix. Для `feature:chat.central_matrix` не проверен переход по адресу комнаты при открытой серверной беседе.
|
||||
|
||||
Windows, база `149bad2`: закрыт `feature:whisper.block_hotkey` как проверенное исключение. Три режима блокировки из TS6 не регистрируются и не обрабатывают нажатие; действительная привязка ответа и исходные байты профиля v2 сохранены. Причина отражена в диагностике. Прошли три теста загрузки профилей и диспетчеризации, без глобальной регистрации в Windows.
|
||||
|
||||
Windows, база `9c0ddd4`: обработчик «Ответить на шёпот» передаёт ядру номер и UID именно того подключения, которое прислало шёпот. Два теста прошли: при двух подключениях с одним UID выбран только отправитель; при смене владельца номера до отправки ядро вернуло `no_targets`. Отказ и событие приёма сохранили ожидаемые уведомления. Проверка использовала тестовый список участников, без системной клавиши и сети.
|
||||
|
||||
Публикация: повторный push обновил `origin/feature/desktop-parity` с `b685597` до `20240c1`, включая исправления статуса командира и истории шёпота. Отказ аутентификации ниже относится к первой попытке.
|
||||
|
||||
Windows, база `d145043`: история шёпота использует UID отправителя на момент приёма; замена клиента с тем же номером проверена нативным тестом. На закрытом beta14 `duplex_qa --whisper` подтвердил получение с UID, отсутствие звука и события при запрете, возврат приёма и 3/3 отключения. Отдельно прошли тест настройки на двух вкладках, три теста ядра и четыре нативных теста. Системную клавишу ответа не нажимали. Стенд остановлен; push в feature/desktop-parity отклонён при аутентификации.
|
||||
|
||||
Windows, база `d9570f3`: закрыт `preference:channelCommanderAsLamp` по отрисовке Slint и восстановлению настройки. Для `client-action:commander` проверены меню собственной строки, отказ гостю на beta14 и устаревшее подтверждение; положительное изменение флага не подтверждено. Прошли четыре нативные и две проверки ядра. Стенд остановлен.
|
||||
|
||||
Windows, база `b266f4f`: закрыты `preload:setClientVolume` и `client-action:volume`. На beta14 проверены движение ползунка, сохранение при отпускании, локальный mute, переподключение и сброс. Прошли 12 нативных и три проверки ядра. Два источника Opus проверялись отдельно в микшере, без физических устройств. Стенд остановлен.
|
||||
|
||||
Windows, база `62bb67b`: закрыт `command:client_context`. На beta14 доступность действий и групп в меню обоих клиентов совпала с ответами ядра. Повторное открытие и устаревшие ответы проверены отдельно. Прошли пять нативных и две проверки ядра. Права не менялись; стенд остановлен.
|
||||
|
||||
Windows, база `256e10a`: закрыт `client-action:poke`. На beta14 отказ ParameterInvalidSize сохранил черновик; исправленный текст дошёл с точным UID отправителя. Отмена, превышение 1024 байт и смена адресата не привели к доставке. Прошли пять нативных тестов и тест stdio; стенд остановлен.
|
||||
|
||||
Windows, база `89a2b21`: закрыт `client-action:connection_info`. На beta14 проверено отображение статистики другого участника и своей после переподключения. Единицы измерения и точные 64-битные счётчики проверены отдельно. Прошли семь нативных и три проверки ядра; стенд остановлен.
|
||||
|
||||
Windows, база `0b4a707`: закрыт `command:client_info`. Карточка Slint привязана к запросу, вкладке, номеру клиента и UID; частичные ответы не стирают ранее полученные поля. Прошли десять нативных проверок, включая два сценария на beta14, и два теста ядра. Стенд остановлен.
|
||||
|
||||
Windows, база `c80219b`: закрыты `command:talk_power` и `feature:client.away_talkpower`. На beta14 проверены ручная выдача и отзыв без заявки, выдача из очереди, устаревшая заявка и отказ обычному гостю. После интервала между сценариями четыре нативных теста прошли; отдельно прошла проверка stdio. Физический звук не использовался, ограничения сервера не менялись; стенд остановлен.
|
||||
|
||||
Windows, база `380e9d4`: проверены `command:set_away` и `command:talk_request`. На beta14 обе вкладки увидели изменения статуса и запрос права голоса, включая его отзыв. Явный null и неверные сообщения отклоняются до подключения; прошли тест stdio и тест протокольных команд. Физический звук не использовался; стенд остановлен.
|
||||
|
||||
Windows, база `389e26d`: закрыт `command:disconnect`. На beta14 отключение через меню просмотренной вкладки удалило выбранного гостя из списка сервера, вторая вкладка сохранила подключение и роль владельца микрофона. Прошли живой тест и отдельная проверка передачи разрешения между вкладками. Физический звук не использовался. Вход через форму Slint не проверен; стенд остановлен.
|
||||
|
||||
Windows, база `f41e064`: менеджер вкладок проверяет запрос до изменения маршрута микрофона. Неверные connect/disconnect оставили действительными прежнюю сессию, владельца и разрешение; ядро приняло следующий сгенерированный PCM-кадр с тем же разрешением. Прошли 20 тестов ядра и 13 тестов менеджера. Физические устройства и переключение микрофона через Slint между живыми подключениями не проверялись.
|
||||
|
||||
Windows, база `c12cf21`: ограничения полей connect/disconnect сверены с историческим валидатором. Ядро отклоняет неверные строки и UID до подключения. Прошли 18 тестов протокола и профиля и один тест stdio. Проверка двух вкладок с переключением микрофона из Slint остаётся открытой.
|
||||
|
||||
Windows, база `6bf4de7`: закрыт `current-contract:snapshot-partial`. Частичный отчёт перечисляет подтверждённые изменения без значений свойств и разрешений. Отказ и отмена загрузки иконки проверены на уровне сервиса. На beta14 режим Skip показал один пропуск и ноль изменений. Прошли 32 теста; стенд остановлен.
|
||||
|
||||
Windows, база `75514f1`: закрыт `preload:snapshotApply`. На beta14 два файла с одинаковым ID каталога не поделили кнопки Apply/Cancel. Подтверждение UID с режимом Skip дало один пропуск, ноль изменений и прежний список каналов. Проверки частичных изменений и отмены выполнялись на уровне сервиса. Прошли 29 тестов; стенд остановлен.
|
||||
|
||||
Windows, база `5f3cf5f`: закрыт `preload:snapshotExport`. Частичный экспорт показывает имя сохранённого файла рядом с предупреждением. Прошли четыре проверки, включая Save/Open на beta14; в живом снимке один канал и одна ошибка чтения прав. Полный привилегированный экспорт всех разделов на сервере не выполнялся. Стенд остановлен.
|
||||
|
||||
Windows, база `1796838`: закрыт `preload:snapshotCancel` по шести проверкам сервиса и состояния интерфейса. Ранняя отмена не отправила запросов и не создала файл. Частичный отчёт сохранил ID уже созданного канала, дочерний канал не создавался. Живой сервер не изменялся.
|
||||
|
||||
Windows, база `e47a81d`: закрыт `preload:onSnapshotProgress`. На beta14 последнее событие задания сообщило 2/2 обработанных шага, один канал и одну ошибку прав. Прошли 20 проверок прогресса, отмены, смены сессии и итогового отчёта. Стенд остановлен; на живом сервере выполнялись только экспорт и открытие файла.
|
||||
|
||||
Windows, база `160ba55`: закрыт `preload:snapshotOpen`. Корректный файл открыт через системный диалог; неверный формат и файл свыше 32 МиБ не получили токена. Для обычных файлов размер проверяется до чтения содержимого. Прошли четыре проверки выбора, декодера и смены сессии.
|
||||
|
||||
Windows, база `c912eb3`: живой тест экспорта и открытия снимка прошёл. Отмена Save не оставила файла; выбранный JSON содержал один постоянный канал из реального списка beta14. Отчёт частичный: одна ошибка чтения прав канала. После Open панель показала правильные каталог и UID сервера. Импорт не применялся; стенд остановлен.
|
||||
|
||||
Windows, база `89cf170`: отмена предпросмотра снимка отзывает токен выбранного файла. Запоздалое подтверждение не отправило команду изменения сервера; повторный выбор и новое подтверждение применили изменение один раз. Прошли 12 тестов сервиса снимков. Проверка использовала тестовый обработчик команд, не живой сервер.
|
||||
|
||||
Windows, база `89cf170`: экспорт проверяет связи родителя и предшественника до запросов свойств. Потерянные узлы, циклы и неоднозначный порядок не превращаются в неполный снимок с пометкой об успехе. Прошли 11 тестов сервиса; живой экспорт через системный диалог этим прогоном не проверен.
|
||||
|
||||
Windows, база `4fee4c0`: экспорт снимка сверяет ID единственной строки свойств с ID экспортируемого канала. При неверном ответе отчёт частичный; соседний канал сохранён со своим описанием. Прошли 10 тестов сервиса снимков. Системный диалог экспорта не проверялся.
|
||||
|
||||
Windows, база `061bb2d`: закрыт `command:channel_info`. На beta14 из меню временного канала Slint прочитаны имя, тема и многострочное описание; при выборе лобби прежние свойства не остались. Шесть нативных тестов и одна отдельная проверка stdio прошли. Стенд остановлен.
|
||||
|
||||
Windows, база `96d9c45`: проверен `preference:highlightContacts` в Slint после двух перезапусков. Подсветка строки следует за UID, а не номером клиента. Прошли две проверки контактов на изолированном профиле и синтетическом списке участников.
|
||||
|
||||
Windows, база `2e45637`: восемь автономных проверок контактов прошли. Форма Slint сохраняет UID, имя и псевдоним после перезапуска; отмена удаления сохраняет запись, подтверждённое удаление переживает следующий запуск. В меню доступно только актуальное действие игнорирования, устаревшая команда удалённого контакта не меняет список. Сеть, устройства и буфер обмена не использовались.
|
||||
|
||||
Windows, база `b7635de`: показ и копирование папки загрузки используют одно сохранённое значение. Три автономные проверки прошли: пустой и сохранённый путь, отказ Slint и платформы при запрещённом доступе к буферу. Системный буфер не трогали. Из трёх сетевых сценариев два прошли, третий остановлен на входе с TS 3329; стенд выключен. Положительная запись в системный буфер не подтверждена.
|
||||
|
||||
Windows, база `de99c5f`: файловый браузер учитывает запрет переименования для «Переместить» и запрет просмотра или скачивания для «Скачать папку». Четыре теста модели меню прошли. Проверка отображения разрешений не заменяет живое выполнение mkdir/rename/delete; эти команды остаются открытыми.
|
||||
|
||||
Windows, база `b4e084d`: закрыт `command:file_fetch_image` для классического beta14. Проверены байты и отрисовка PNG в окне Slint, а также отбрасывание устаревших результатов после переподключения. Ограничения размеров проверяются до декодирования растра. Прошли четыре нативных проверки и тест stdio. Стенд остановлен.
|
||||
|
||||
Windows, база `c6cb353`: проверены `file_pause`, `file_resume` и `file_cancel` из панели Slint на классическом beta14. Отмена частично скачанного файла не оставила ни результата, ни временного файла; продолжение второй передачи дало точные 4 МиБ. Прошли живой тест, проверка границ ID через stdio и четыре теста ядра. Стенд остановлен.
|
||||
|
||||
Windows, база `67b2fc6`: для `preload:filesDownload` и `main-only-command:file_download` подтверждены скачивание и прогресс на beta14, отмена перезаписи и устаревшего выбора папки. Три отдельные проверки прошли для ошибки StorageFull после частичной записи, отмены копирования и повторного события после ошибки экспорта. Реальный том не заполнялся.
|
||||
|
||||
Windows, база `a3ee6cc`: после скачивания из файлового браузера beta14 повторно открытая панель передач показала 46 B / 46 B. Переподключение той же вкладки оставило пустой список в ядре и в Slint. Адресный тест прошёл; стенд остановлен.
|
||||
|
||||
Windows, база `8d4daf4`: закрыт `command:file_list` для классического хранилища. Меню канала Slint открыло список на beta14, размер строки совпал с 46 байтами файла, скачивание из этой строки дало точное содержимое. Прошли два сценария Slint и тест stdio для границы ID. Стенд остановлен.
|
||||
|
||||
Windows, база `e25263e`: закрыт `preload:filesRelease` на уровне файлового сервиса. Подсказка последней папки хранит только путь. После release повторная загрузка с этим токеном отклонена без команды ядру и без изменения прежнего файла. Активная передача удерживает собственное разрешение до завершения. Прошли 13 тестов файлового сервиса.
|
||||
|
||||
Windows, база `ba6cae3`: проверен `preload:filesSettings`. После перезапуска в Slint восстановились папка, запрос пути, слоты 8/2 и лимиты 1,5/2,5 МиБ/с. Прошли пять тестов, включая скачивание с beta14 и проверку распределения настроек между двумя тестовыми сессиями ядра. Сетевая скорость одновременно работающих клиентов не измерялась. Стенд остановлен.
|
||||
|
||||
Windows, база `e7951f1`: закрыт `preload:filesChooseDownloadDir`. Разовый выбор папки не переживает переподключение той же вкладки. Новый выбор сохранил 46 байт, не изменив постоянную папку. Прошли три проверки на классическом beta14; стенд остановлен.
|
||||
|
||||
Windows, база `6712e6d`: проверен `preload:filesChooseDefaultDir`. Два теста Slint: после перезапуска гостевой клиент beta14 получил 46 ожидаемых байт в выбранную папку; отсутствующая папка вызвала ошибку без подстановки другого пути. Классический стенд получил исходный файл при создании; загрузка гостем на сервер не разрешена, S3 не проверен. Стенд остановлен.
|
||||
|
||||
Windows, база `9a518bd`: выбор папки записи проверен из настроек звука через системный диалог. Отмена и попытка записи через общие настройки путь не изменили; после двух перезапусков оба WAV экспортированы в выбранную папку. Прошли два теста; стенд beta14 остановлен. Мобильные диалоги не проверялись.
|
||||
|
||||
Windows, база `5916610`: проверены семь команд `recording_*`. Панель Slint запрашивает статус ядра; старый Stop не останавливает вторую запись. На beta14 сверены форма сигнала, длительность и WAV, сохранность первого файла и чистое состояние после переподключения. Прошли 11 нативных проверок и отдельный тест stdio на неверные аргументы. Физический звук не использовался; стенд остановлен.
|
||||
|
||||
Windows, база `dc3e596`: Preview/Start/Stop привязаны к конкретному выбору источника, а Live требует и ID, и подтверждения setup. Прошли восемь тестов, включая сгенерированный источник на beta14. Для полного `command:stream_setup` остаются системный выбор источника и видимый отказ в этом сценарии. Стенд остановлен.
|
||||
|
||||
Windows, база `1fe05c0`: закрыт `command:stream_signal`. Два локальных WebRTC-пира проверили ранний ICE, порядок ответа, откат SDP и смену ICE-соединения по декодированным кадрам. Четыре отдельные регрессии и 16 тестов протокола прошли. Нулевой ID участника отклоняется до отправки; поиск по всему каналу без ID сохранён. Официальный клиент не участвовал.
|
||||
|
||||
Windows, база `b685597`: закрыт `command:stream_join`. На приватном beta14 после нажатия «Смотреть» и допуска издателем проверены красные пиксели в карточке Slint и тон 1 кГц на декодере выбранного зрителя. Отмена до допуска и действие отключённого зрителя не запустили просмотр на другой вкладке. Прошли два теста; стенд остановлен. Физические устройства и официальный клиент не проверялись.
|
||||
|
||||
Windows, база `59a2878`: закрыт `command:stream_list`. При открытии раздела клиент запрашивает потоки своего канала; параллельный запрос выбранного участника не отменяется. На beta14 прошли общий и адресный поиск, а также открытие списка из Slint; всего в адресном наборе нативного клиента прошли девять тестов. SFU проверен на тестовом объявлении. Стенд остановлен.
|
||||
|
||||
Windows, база `8630542`: закрыт `command:stream_leave`. На beta14 добровольный выход освободил пир и кадры выбранного зрителя, не прервав видео у другого. Повторный выход по старому объекту не закрыл новый просмотр. Прошли живой тест и две регрессии для задержанного подтверждения и закрытия окна. Источник сгенерирован; стенд остановлен.
|
||||
|
||||
Windows, база `039af3f`: закрыт `command:stream_remove`. При двух допущенных зрителях на beta14 исключение по имени в карточке Slint отключило только выбранного: второй продолжил получать новые синие кадры. UID проверен по двум серверным спискам. Два отдельных теста подтвердили защиту от повторной выдачи номера. Стенд остановлен.
|
||||
|
||||
Windows, база `8004c01`: закрыт `command:stream_stop`. На beta14 Stop из карточки Slint завершил выбранную публикацию во время передачи видео. Источник отклонил следующий кадр, просмотр завершился без оставшегося кадра, повторный поиск с обеих вкладок не обнаружил поток. Физический захват не использовался; стенд остановлен.
|
||||
|
||||
Windows, база `f7601e7`: закрыт `command:stream_respond`. На beta14 издатель разрешил просмотр первому зрителю и отказал второму. После отказа первый зритель получил три новых зелёных кадра без переподключения. Первоначальный запуск остановился на `ConnectFailedBanned` до проверки допуска; отдельный запуск с интервалом между подключениями прошёл на том же стенде без изменения серверных ограничений. Стенд остановлен.
|
||||
|
||||
Windows, база `402d8ff`: прошли два изолированных теста Slint на закрытом beta14. В `approved_beta14_viewer_receives_generated_video` зритель дождался допуска, издатель разрешил просмотр из карточки Slint, после ответа WebRTC зритель получил три красных кадра. Выход зрителя очистил список допущенных. Использован сгенерированный источник; звук, третья вкладка зрителя и официальный клиент не проверялись.
|
||||
|
||||
Windows, база `1e2856e`: `duplex_qa --stream-lifecycle` подтвердил на закрытом beta14 доставку заявки издателю и отказа без SDP зрителю. После отказа наблюдатель заново нашёл тот же поток; обновление, остановка и оба отключения прошли. Положительное решение и передача медиа этим сценарием не проверены.
|
||||
|
||||
Windows, база `f563d2b`: редактор действующей публикации Slint привязан к ID потока и UID издателя. В тесте на beta14 отмена сохранила исходное имя, после сохранения вторая вкладка подтвердила новое имя, битрейт 2700 и лимит 4 у того же потока. Прошёл также тест карточки без WebRTC. Источник сгенерирован; смена устройства или аудиозахвата не проверялась.
|
||||
|
||||
Windows, база `e52db5b`: на beta14 наблюдатель перечитал имя, битрейт, лимит зрителей и признак аудио у того же потока после подтверждения `stream_update`. В нативном издателе прошли проверки отложенного подтверждения, отказа, ограничений доступа и отключения во время запроса (24 теста сигнализации, отдельно 2 теста ядра). Проверен снимок состояния издателя, не видимое окно настроек и не фактическая скорость передачи.
|
||||
|
||||
Windows, база `c27a425`: на beta14 прошёл `duplex_qa --stream-lifecycle`. Наблюдатель подтвердил регистрацию и остановку потока по ID; без `reason=1` сервер отвергал остановку с TS 1542. Оба отключения подтверждены. Отдельно прошли тест сериализации ядра и две проверки нативного поиска. Подключение зрителя и медиа через эту сигнализацию пока не проверены.
|
||||
|
||||
Windows, база `f0ed160`: тест `decoded_tone_and_moving_video_on_local_peers` прошёл на двух нативных WebRTC-пирах. После декодера тон 1 кГц обнаружен в 43 из 46 блоков; одновременно показаны 12 кадров с возрастающим счётчиком. Аудиовыход закрыт, TeamSpeak-сигнализация и официальный клиент не использовались.
|
||||
|
||||
Windows, база `6053e8b`: `webrtc_smoke` прошёл с локальным архивом WebRTC. Из 14 отправленных кадров libvpx декодировал 14, на выходе проверены 7 красных и 6 зелёных кадров. Источник после остановки отклонил новый кадр, callback вызван один раз. Это два локальных пира без TeamSpeak-сервера, физического захвата и передачи аудио.
|
||||
|
||||
Windows, база `5933297`: остановка зарегистрированной публикации по своему `clid` освобождает источник сразу. До получения ID начало и остановка обрабатываются в порядке получения; события старого издателя не перенаправляются новому. Прошли 22 теста каталога и сигнализации с тестовыми источниками. Реальный захват и передача на сервер не проверялись.
|
||||
|
||||
Windows, база `5e646fc`: подтверждение и отклонение заявки на просмотр сверяют UID из меню до изменения очереди. Проверка повторной выдачи номера подтвердила, что оба устаревших действия сохраняют заявку нового зрителя, а подтверждение по актуальному UID работает. Прошли 19 тестов сигнализации; живой обмен WebRTC в этом прогоне не проверялся.
|
||||
|
||||
Windows, база `aa88f78`: ручное исключение зрителя передаёт UID из выбранного пункта меню и сверяет его до локального исключения и перед отправкой. Прошли 19 тестов сигнализации: устаревшее действие не заблокировало нового зрителя, а актуальное действие сработало. Это проверка издателя с тестовым пиром, не живой серверный прогон.
|
||||
|
||||
Windows, база `85e559d`: при смене приватности издатель закрывает отозванные соединения до сетевого ожидания и повторно сверяет UID перед отправкой. Тест подтвердил, что новый владелец переиспользованного номера не получает команду удаления, а трансляция не останавливается. Прошли 18 тестов сигнализации с тестовыми пирами; сквозная проверка через живой сервер остаётся открытой.
|
||||
|
||||
Windows, база `6fea1a8`: хаб немедленно завершает просмотры указанного автора при `notifystreamstopped` без ID потока. Тест проверил два просмотра одного автора, независимый просмотр другого автора и повторное открытие потока с тем же ID. Прошли 19 тестов каталога и сигнализации; реальные медиапотоки не использовались.
|
||||
|
||||
Windows, база `5417970`: просмотрщик больше не принимает некорректный тип `clid` за отсутствие адресата. Прошли 16 тестов сигнализации: неверные адресаты не создали пир и не завершили ожидание; следующий корректный ответ был принят. Это проверка состояний на тестовых пирах, не передача видеопотока.
|
||||
|
||||
Windows, база `dfb60d7`: отказ ядра при отправке локального ICE-кандидата после ответа переводит просмотрщик в Failed с причиной, закрывает пир и вызывает выход один раз. Прошли 15 тестов сигнализации с тестовыми пирами. Реальная передача видео в этом прогоне не проверялась.
|
||||
|
||||
Windows, база `335466b`: исходящие `stream_signal` и текст `stream_join` проверяются по схеме исторического клиента. Прошли четыре проверки ядра и два теста нативной сигнализации. Реальные WebRTC-пиры, изображение и звук этим прогоном не проверялись.
|
||||
|
||||
Windows, база `6ac0967`: семь тестов прошли для `chatUse24hTime` и связанных строк истории. Формат 12/24 ч меняется у загруженного сообщения и в журнале событий; после перезапуска исходная метка времени сохранена. Журнал проверен на русском и английском с тестовыми событиями.
|
||||
|
||||
Windows, база `4244adf`: расширенный тест чата на закрытом beta14 подтвердил видимый отказ гостю в серверном чате и сохранение черновика после ухода с вкладки и возврата. Личное и канальное сообщения доставлены. Успешную широковещательную отправку этот прогон не доказывает. Отдельно прошли три проверки валидации ядра.
|
||||
|
||||
Windows, база `390261e`: прошёл `send_text_delivers_exact_private_and_channel_messages_on_beta14`. Две временные identity проверили личную и канальную доставку из редактора Slint, единственное эхо у отправителя и сохранение слишком длинного черновика. Отправка в серверный чат этим прогоном не проверена.
|
||||
|
||||
Windows, база `2af19bc`: прошёл `protected_channel_join_from_tab_keeps_lobby_until_password_accepted` на закрытом beta14. Подтверждены выбор без перехода, отмена, видимый отказ при неверном пароле и переход по верному паролю на обеих вкладках. Закрыт `command:join_channel`.
|
||||
|
||||
Windows, база `0ef6447`: два теста ядра подтвердили отказ для `join_channel(0)` до проверки подключения. Тест Slint подтвердил выбор действия подписки и защиту от устаревшего пункта меню. На beta14 четыре переключения подписок подтверждены снимками после явного сброса автоподписки; без сброса первый вызов получил подтверждение без нового снимка. Второго чужого канала не было. Подробности в FEATURE_COMPATIBILITY.md.
|
||||
|
||||
Windows, база `c0835c6`: четыре адресных теста чата прошли с изолированными событиями. Подтверждены `chatOpenIncoming`, `chatIgnoredUsers` и `chatShowModerationEvents`. Исправлены фильтрация уже полученных событий модерации и игнорирование сообщения без явного UID, когда отправитель известен из списка участников. Сетевой обмен в этих тестах не проверялся.
|
||||
|
||||
Windows, база `20e6008`: прошли два отдельных теста настроек Slint. Audio PTT сохраняет состояние после перезапуска и при ошибке записи. Whispers на двух подключённых вкладках beta14 подтвердил три смены режима и сохранение последнего. Прямого чтения политики из каждого ядра нет; обмен аудио через эти вкладки и физические клавиши не проверялись.
|
||||
|
||||
На Windows прошёл расширенный `bookmark_sidebar_and_local_contact_reopen_without_network`: перенос непустой папки через форму, проверка вложенных ID после перезапуска, отмена и подтверждение удаления. Для локальных предпочтений подтверждены `savedServers`, `bookmarkOrder` и `bookmarkFolders`; подключение по закладке и хранилище паролей сюда не входят.
|
||||
|
||||
Windows, база `8a98e3d`: `duplex_qa --whisper` прошёл на закрытом beta14. При отключении отправитель передавал шёпот; после его переподключения старая метка не дала звука или события, обычный голос доставлен. Все три отключения подтверждены, стенд остановлен. Получатель не менялся, физический звук не использовался.
|
||||
|
||||
Windows, база `90c28ee`: для личного адреса шёпота требуется непустой UID из списка участников. Участник без UID не добавляется по временному номеру даже при раскрытии сохранённого канала; адрес самого канала сохраняется. Регрессия: `unidentified_clients_are_not_individual_whisper_targets`. Живое повторное использование номера не проверено.
|
||||
|
||||
Windows, база `533b2b2`: ядро обрабатывает все строки `notifytokenadd` до подтверждения. Пустая строка не затирает полученный ключ, повтор одного значения допустим, два разных значения не выдаются как успешный результат. Три адресных теста ядра прошли с тестовыми значениями. Живая выдача ключей и проверка формы остаются открытыми.
|
||||
|
||||
Windows, база `509bbb8`: тест `participant_info_menu_rejects_a_previous_session_target` прошёл через меню Slint на loopback beta14. В двух последовательных сессиях показаны версия и платформа своего участника; при отключении старые сведения очищены. После подключения второй identity действие из первой сессии получило видимую ошибку `target_changed`. Стенд остановлен. Разрыв соединения до прихода ответа в этом тесте не моделировался.
|
||||
|
||||
Windows, база `c849105`: `client_info` сверяет номер и UID участника до отправки и при подтверждении. На beta14 `channel_admin_qa --client-info` получил версию и платформу; подстановка другого UID отклонена локально. Три теста ядра и один тест нативного клиента прошли. Стенд остановлен; повторное использование номера при ожидании ответа проверено тестом ядра, а не живым переподключением.
|
||||
|
||||
Windows, база `60d1953`: отдельный режим `channel_admin_qa --client-database-id` собран и запущен на loopback beta14. Поиск по UID вернул одну строку с точным UID гостя и положительным ID базы. Независимый поиск по нику получил TS 2568, сценарий завершился кодом 1. Сервер подтвердил отключение, ядро завершено, временный профиль удалён, стенд остановлен. Полная сверка и проверка через UI остаются открытыми.
|
||||
|
||||
Windows, база `25575d1`: ядро сопоставляет `client_database_id` с точным UID в уведомлении и требует один положительный ID базы. Три адресных теста прошли; живой поиск через интерфейс в этом прогоне не проверялся.
|
||||
|
||||
Windows, база `d841530`: для `group_add` ядро исключает ранее известные ID групп нужной категории и сверяет имя и тип ответа. Проверены нулевой ID, повтор одного нового ID и неоднозначный ответ. Прошли три теста ядра и два теста импорта снимков. Создание серверной или канальной группы на живом стенде этим прогоном не подтверждено.
|
||||
|
||||
Windows, база `643d0e4`: поиск в браузере файлов фильтрует загруженные имена, сохраняет переход к родителю и сбрасывается при смене каталога. Тест Slint проверил обновление списка, регистр кириллицы и цель контекстного меню. Прошли три адресных теста; сетевой обмен файлами не проверялся.
|
||||
|
||||
Windows, база `3a8e15e`: поиск и перелистывание базы клиентов используют тот же контекст прав, что и первая страница. Три адресных теста прошли, включая сохранение смещения, строки поиска, ID записи и сессии. Живой запрос базы и удаление записи не проверялись.
|
||||
|
||||
Windows, база `d5ba657`: в списках прав ядро учитывает каждый явно указанный ID и не смешивает строки разных групп при смене ID внутри пакета. Три адресных теста прошли, включая продолжение списка в следующем пакете. Это проверка разбора протокола, не живое изменение прав.
|
||||
|
||||
Windows, база `e9f375c`: проверен `command:rename` на двух временных identity и локальном beta14. Форма сохранила занятый ник после отказа и закрылась после успешной повторной отправки. Оба списка участников показали новое имя с прежним серверным UID, а после открытия профиля изменился только ник нужной локальной identity. Тест `nickname_refusal_keeps_draft_and_retry_updates_only_own_identity` прошёл; стенд остановлен.
|
||||
|
||||
Windows, база `f804bef`: сворачивание скрывает непосредственных участников, сохраняется в `collapsedChannels` по адресу сервера и не скрывает подканалы. Три адресных теста прошли: Slint с двумя перезапусками и повтором номера канала на другом адресе, атомарность сохранения и регрессия порядка и размеров дерева. Проверены EN/dark и RU/light на снимках тестовых серверов.
|
||||
|
||||
Windows, база `3db0766`: для `showClientsBeforeChannels` проверены координаты участника и подканала в одном дереве до и после переключения, а также после перезапуска. Плотность не изменила порядок; смена порядка не изменила высоту строк и выбранный канал. Тест `tree_style_resizes_only_client_rows_and_survives_restart` прошёл для EN/dark и RU/light.
|
||||
|
||||
Windows, база `faf9f95`: выбор `treeStyle` в настройках оформления теперь меняет строки участников в дереве Slint. Прошёл `tree_style_resizes_only_client_rows_and_survives_restart`: 40 и 28 px для участника, 44 px для канала в обоих режимах; выбранный канал сохранился. Проверены EN/dark и RU/light с повторным запуском. Это измерение отображённых строк тестового сервера, не полное визуальное сравнение клиента.
|
||||
|
||||
Windows, база `2c8a47d`: исправлен статус трёх режимов скрытия в панели задач и описание микрофона после разблокировки. Тест `taskbar_capability_tracks_the_selected_hide_mode` прошёл в отдельном окне Windows с временным профилем. Реальная блокировка, физические горячие клавиши и скрытие в трее не проверялись. Семь статических сверок TS6 по уведомлениям, чату, оформлению, приватности, клавишам и ОС записаны в FEATURE_COMPATIBILITY.md. Триггер речи при выключенном микрофоне остаётся открытым.
|
||||
|
||||
Windows, база `2e3b271`: тест `recording_panel_exports_a_paused_and_resumed_master` прошёл после двух перезапусков с одним временным профилем. Master выбран в настройках; режим 4 отклонён, отмена Multitrack не создала файлов и не изменила выбор. На beta14 записан и экспортирован Master с одной паузой. Стенд остановлен. Системный выбор каталога этой проверкой не покрыт.
|
||||
|
||||
Windows, база `7729f26`: форма начала записи выбирает режим без произвольного имени папки. Клиент передаёт локальную метку времени, при недоступном часовом поясе ядро использует UTC. Тест `recording_panel_exports_a_paused_and_resumed_master` прошёл в настоящем окне Winit/Slint на локальном beta14: старт, дорожка Master, пауза, продолжение, остановка, экспорт, одна пауза в манифесте и совпадение размера WAV с числом кадров. Временная папка была заранее разрешена. Качество физического входа и системный picker не проверялись; стенд остановлен.
|
||||
|
||||
Windows, база `d59bebd`: отпускание ползунка и подтверждение формы сохраняют громкость следующего просмотра в `streamVolume`; во время движения меняется только текущий просмотр. Проверены события Slint, чтение 0%, 43% и 100% после повторного открытия временного профиля и изолированный микшер. Четыре адресных теста прошли. Живой WebRTC и физический аудиовыход не проверялись.
|
||||
|
||||
Windows, база `d5b9541`: ползунок и форма громкости трансляции используют диапазон проигрывателя 0–100%. Нажатие в середине видимого ползунка Slint передало выбранному просмотру примерно 0,5. Три адресных теста интерфейса, проигрывателя и микшера прошли. Сохранение после перезапуска и живое воспроизведение WebRTC не проверялись.
|
||||
|
||||
Windows, база `8a8f52d`: карточка потока режима 2 показывает ограничение SFU и убирает просмотр; медиасервис не отправляет P2P join для такого объявления. Отдельный P2P-поток того же участника остаётся доступен. Прошли тест карточек Slint и тест команд сигнализации. Живой SFU и сборка с WebRTC этим прогоном не проверялись.
|
||||
|
||||
Windows, база `89a930d`: уведомление об изменении описания канала сбрасывает устаревший текст в кеше и ожидающем ответе только для указанного канала. Четыре теста ядра прошли. Живой тест Slint на beta14 подтвердил многострочное редактирование, отмену, очистку и повторное чтение пустой строки. Гостевое создание с описанием отклонено; отдельный быстрый прогон редактирования получил ClientIsFlooding, а с интервалом стенда завершился успешно. Сверки файловых протоколов, Matrix и потоков зафиксированы в FEATURE_COMPATIBILITY.md.
|
||||
|
||||
2026-11-27, Windows, база `0354a6f`: настройки микрофона, воспроизведения и уведомлений показывают недоступное сохранённое устройство только после получения каталога. Возврат устройства восстанавливает имя без запроса смены маршрута. Два адресных теста прошли, включая представление Slint; физический hot-plug и работа активного потока не проверялись.
|
||||
|
||||
2026-11-27, Windows, база `010e6b4`: ссылки `ts3file://` с IPv6 из браузера файлов распознаются в чате. Прошли три теста, включая кодирование и чтение пути и UID; сетевую загрузку не проверяли. Сверки voice.dsp/devices/3d, whisper.all/receive_mode_transport/block_hotkey и chat.ts3file_links записаны в FEATURE_COMPATIBILITY.md отдельно от исполнения на оборудовании.
|
||||
|
||||
2026-11-27, Windows, база `a25bd6b`: исправлен отказ гостю beta14 при создании обычного канала через Slint. Форма не отправляет нетронутые необязательные поля; кодек и шифрование имеют явный выбор серверного значения. Через headless Slint и реальный beta14 проверены имя и тема при создании и тема при редактировании, ошибки длины, отмена и чтение после сохранения. Живой тест и пять адресных тестов свойств прошли, стенд остановлен. Смена сессии до ответа и физическое отображение не проверялись. Сверки TS6 server.admin, chat.server_plain_send и chat.history_local записаны в FEATURE_COMPATIBILITY.md отдельно от приёмки.
|
||||
|
||||
2026-11-27, Windows, `e6a8d2f`: живой `channel_admin_qa` подтвердил ID нового временного корневого канала на beta14, чтение свойств, изменение темы и обоих лимитов, отклонение устаревшего поколения и недопустимого качества. Первому запуску стенда не хватило времени, подключение не состоялось; повтор со стендом, удерживаемым до конца теста, прошёл. Вложение в родителя отклонено (TS 2568), наследование не подтверждено. Канал автоматически удалён после выхода, профиль удалён, стенд остановлен. Это проверка IPC; сценарий через видимый интерфейс остаётся открытым.
|
||||
|
||||
Windows, база `95ebf37`: подтверждение создания канала сопоставляется с автором, именем и родителем. Отсутствие однозначного положительного ID после принятия команды возвращает ошибку с `created: true`. Повтор одного ID допустим. Прошли три адресных теста ядра и нативный тест `post_create_icon_uses_only_acknowledged_child_id`; живой сервер в этой проверке не участвовал.
|
||||
|
||||
Windows, база `b3f73c3`: ядро сверяет ненулевой `channel_order` при создании и редактировании канала с текущим деревом перед отправкой. Удалённый или перемещённый в другую ветку сосед и ссылка редактируемого канала на себя отклоняются. Четыре адресных теста ядра прошли; сетевой запрос и ответ сервера в этом прогоне не проверялись.
|
||||
|
||||
Windows, база `3c828e3`: при создании канала смена родителя очищает позицию и ограничивает список предшественников его детьми. Тест Slint проверил три команды для родителя 8: без `channel_order`, с явным 0 и с ID 13 второго одноимённого соседа. Прошли шесть адресных тестов. Применение этих команд сервером в этом прогоне не проверялось.
|
||||
|
||||
Windows, база `8930007`: завершена сверка `channel.crud` с установленным TS6. Ядро возвращает `{"changed":false}` без сетевой команды только при совпадении родителя и явного предшественника. Три адресных теста прошли. Положительный ответ сервера на перенос и удаление этой сверкой не подтверждён.
|
||||
|
||||
Windows, база `9b19e96`: ядро перед отправкой `channel_move` проверяет, что предшественник всё ещё принадлежит выбранному родителю и новая ветка не замыкает цикл. Три адресных теста прошли, включая исчезновение или перемещение предшественника, перенос родителя в исходное поддерево и допустимую первую позицию. Серверное подтверждение переноса в этот прогон не входило.
|
||||
|
||||
Windows, база `cc3cb27`: диалог переноса канала показывает текущего родителя и предшественника. При смене родителя предлагает первую позицию и только соседние каналы. Тест Slint выбрал второй из двух одноимённых каналов и получил `channel_id=42, parent_id=8, order=13`. Шесть адресных тестов прошли. Это проверка формы и аргументов команды, не подтверждение перемещения на сервере.
|
||||
|
||||
Windows, база `be1d308`: сценарий `channel_admin_qa --channel-order` собран и запущен с актуальным диагностическим ядром. Гость beta14 получил TS 2568 на `channel_create` с явной позицией. Проверка порядка завершилась кодом 1; отключение подтверждено сервером, временный профиль удалён, стенд остановлен с кодом 0. Живой результат изменения порядка не установлен.
|
||||
|
||||
Windows, база `981c486`: ответы `channel_list` и `channel_info` берут родителя и предыдущий соседний канал из актуальной модели дерева. Адресный тест `channel_readback_uses_current_sibling_position_and_retains_extra_fields` прошёл: сохранены дополнительные свойства, позиция обновлена, удалённый канал не возвращается. Живое перемещение и показ позиции в окне в этом прогоне не проверялись.
|
||||
|
||||
Windows, база `827f2c3`: окно сервера показывает название Speex/CELT по текущему каналу открытой вкладки. Прошли `codec_warning_follows_joined_channel_on_viewed_tab` и `legacy_codecs_neither_select_an_encoder_nor_enter_the_mix`. Снимки для окна тестовые; пункт живого входа в legacy-канал остаётся открытым.
|
||||
|
||||
Windows, база `ced85a3`: при отзыве захвата менеджер один раз инвалидирует каждое затронутое ядро; инвалидация сама ставит маркер конца реплики. Два теста нативного менеджера и три теста очереди и буфера VAD прошли. Запоздалое подтверждение не восстановило отозванный маршрут, новое подтверждение разрешило следующий кадр. Это проверка встроенного ядра, не измерение сетевого или акустического окончания реплики.
|
||||
|
||||
Windows, база `2a0a95f`: исправлен повторный `set_transmit direct`. Тест `transmit_mode_invalidates_frames_only_on_detector_change` прошёл через встроенное ядро: повтор direct сохранил допуск кадра, смена direct/VAD в обе стороны отозвала старый допуск. Сеть и физические устройства в этом тесте не использовались.
|
||||
|
||||
Windows, `0e6bfb7`: завершена сверка `voice.transmit_modes` с настройками установленного TS6. Пять адресных тестов ядра прошли на PCM. Проверены открытие по речи, порог громкости, гибридный режим, смена детектора и сброс накопленных кадров. Это не измерение задержки PTT по сети и не проверка на официальном клиенте.
|
||||
|
||||
Windows, база `f1e7d8d`: исправлен выбор задержки отпускания PTT в Audio. Значение 500 мс сохраняется при отключении и после двух перезапусков; 250 мс отклоняется без изменения настроек. Отключение и смена профиля отменяют ожидающий таймер. Прошли четыре адресных теста; задержка слышимого звука у удалённого участника не измерялась.
|
||||
|
||||
Windows, база `afac6cf`: прошёл изолированный тест `talk_request_draft_rejects_invalid_length_and_replaced_session`. Форма отклонила сообщение из 51 символа и не отправила допустимый черновик после замены сессии вкладки. Живой прогон переподключения не принят: сервер вернул `ClientIsFlooding`. Стенд остановлен; успешные проверки заявки, выдачи и отзыва из предыдущих прогонов остаются отдельными результатами.
|
||||
|
||||
Windows, база `20a36d0`: после получения отзыва заявки действие «Дать слово» проверяет актуальные ID, UID, канал и наличие запроса. Тест `talk_request_form_and_withdrawal_reach_peer` на beta14 прошёл: старое действие вернуло `target_changed`, в обоих списках право слова осталось выключенным. Отзыв после отправки команды и серверный отказ по правам в этом прогоне не проверялись.
|
||||
|
||||
Windows, база `2780adc`: поле сообщения в заявке на слово теперь необязательное. Живой тест `talk_request_form_and_withdrawal_reach_peer` прошёл на beta14 в канале с порогом 50: обе сессии увидели пустую заявку и её отзыв, затем заявку с текстом, выдачу и снятие права слова. Физическая клавиша, отказ в правах и переподключение во время выдачи не проверялись.
|
||||
|
||||
Windows, база `3daa2fd`: живой тест `away_message_reaches_both_loopback_sessions` прошёл с переподключением первой вкладки во время ввода. Обе копии списка участников показали новую сессию онлайн и подтверждённое сообщение у второй. Устаревшая цель показана как ошибка; рассылка остальным не прерывается. Публикация предыдущего коммита не прошла аутентификацию origin.
|
||||
|
||||
2026-11-27, Windows, база `220119e`: исправлена рассылка статуса «Отойти с сообщением» из одной формы по сессиям, подключённым на момент вызова. Тест `away_message_reaches_both_loopback_sessions` прошёл на закрытом TS6 beta14: обе вкладки увидели у обоих участников online после отмены и одинаковое away-сообщение после подтверждения. Проверялось событие горячей клавиши, не физический аккорд; стенд остановлен.
|
||||
|
||||
2026-11-27, Windows, база `4dd514e`: список запросов слова сортируется от новых к старым, как в установленном TS6. Горячая клавиша выбирает самую раннюю действующую заявку другого участника своего канала. Адресный тест прошёл, включая отмену заявки и отсутствие текущего канала. Выдача прав на живом сервере в этом прогоне не проверялась.
|
||||
|
||||
2026-11-27, Windows, база `764e3dc`: Alt+щелчок по регулятору собеседника возвращает 0 дБ, сохраняя заглушение. Тест `speaker_gain_drag_cancel_and_reset` прошёл в отрисованном окне, включая отпускание Alt до кнопки мыши. Расширенная проверка на живом собеседнике остаётся открытой.
|
||||
|
||||
2026-11-27, Windows, база `49b9ce5`: диалог локальной громкости получил ползунок со шкалой TS6. Тест отрисованного окна проверил перетаскивание, отмену, повторное открытие и сброс на 0 дБ со снятием заглушения после подтверждения. Проверены все 421 значения шкалы; три адресных теста прошли. Подключённый собеседник и физический выход не использовались.
|
||||
|
||||
2026-11-27, Windows, база `abdcbf1`: при загрузке локальной громкости ошибочный UID больше не блокирует применение корректных записей. Хранилище сообщает о пропуске и не переписывает файл при чтении. Прошли пять тестов хранилища и два теста ядра, включая повторное использование числового ID и смешивание декодированного звука двух участников. Экранный регулятор и физический выход не проверялись.
|
||||
|
||||
2026-11-27, Windows, база `373bd3d`: возврат на вкладку с уже действующим разрешением на захват не прерывает передачу при включённом автопереключении. Три теста прошли со встроенными ядрами: передача владения, восстановление прежнего владельца и отказ устаревшему ответу. Состояния подключения моделировались, физический микрофон и два живых сервера не проверялись.
|
||||
|
||||
2026-11-27, Windows, база `a215ceb`: выбор файлового протокола использует полное объявление возможностей; текст файловой диагностики по-прежнему ограничен 1024 символами. Новое initserver сбрасывает прежние свойства сервера, частичное обновление сохраняет отсутствующие поля. Прошли шесть тестов ядра. Живая проверка двух вкладок и владельца микрофона не входила в этот прогон.
|
||||
|
||||
2026-11-27, Windows, база `ab3508c`: проверен `preload:openLogs` на странице сведений об установке. При отсутствии logs показано объяснение без кнопки, при наличии Проводник подтвердил точный каталог временного профиля. Тест about_workflows подтвердил отказ прямого вызова в изолированном режиме. Содержимое журналов не читалось, мобильный экспорт не проверялся.
|
||||
|
||||
2026-11-27, Windows, база `4fb47fb`: для каждого установленного пакета тем в Appearance доступна его папка. Проводник подтвердил каталог пакета и общий каталог extensions по отдельности. В изолированном режиме обе операции получили os_actions_disabled; адресный тест выбора, перезапуска и удаления темы прошёл. Мобильное открытие не проверялось.
|
||||
|
||||
2026-11-27, Windows, база `bab7c93`: добавлены шесть расширенных настроек звука для переноса и исключения в канал, серверных групп и отказа в правах. В старых профилях прежний выбор действует до изменения отдельного события. Прошли 15 адресных тестов; UI Automation обнаружил все шесть элементов выбора в запущенном приложении. PCM проверен на изолированном выходе, физическое воспроизведение не проверялось. Для предупреждения о речи при выключенном микрофоне по-прежнему нет проверки с настоящим источником речи.
|
||||
|
||||
2026-11-27, Windows, база `2b176cc`: исправлены исходные каналы при групповом входе клиентов и уведомления о переходах между подписанными и неподписанными каналами. Прошли семь тестов событий и снимков ядра и пять тестов нативного обработчика. Проверены журнал и выбор WAV по событиям; живой сервер, физическое воспроизведение и кнопки прослушивания не проверялись.
|
||||
|
||||
2026-11-27, Windows: после базы `582fe2d` исправлено отображение связанных закладок в Details. Адресный тест `reattached_identity_details_keep_nondefault_uid_and_its_bookmarks` прошёл: вложенная закладка без UID следует за текущей идентичностью по умолчанию без изменения записи. SHA-256 эталонного TS6 и смещения записаны в FEATURE_COMPATIBILITY.md. Эталон повторяет подключение при достижении требуемого уровня; для TeamsPeach этот переход остаётся непроверенным.
|
||||
|
||||
Windows, feature:identity.security_level_improve: структурированный отказ connect_failed с required_security_level показывает действие для UID неудачной попытки. Переход открывает Details этой идентичности и подставляет требуемый уровень; улучшение и повторное подключение не запускаются автоматически. Три адресных теста прошли, включая отказ уровня 31 для недефолтного UID, отклонение устаревшего действия после перезапуска вкладки и изоляцию старой отмены поиска. Проверка перехода использовала событие отказа в тестовом runtime; живой сервер с повышенным порогом в этом прогоне не использовался.
|
||||
|
||||
На `4ca8678` выполнен также живой прогон: изолированный TS6 beta14 подтвердил через `serverinfo` требуемый уровень 31; при тесте Query был выключен, сервер слушал только loopback. Windows-клиент подключался недефолтной идентичностью уровня 9. После отказа кнопка открыла в настройках именно её с целью 31. Состав публичного хранилища, уровень и UID по умолчанию остались прежними. Тестовый профиль удалён, стенд завершился с кодом 0. Поиск до уровня 31 и успешное переподключение не проверялись.
|
||||
|
||||
Windows, feature:onboarding.offline: проверены пустой каталог и ранее инициализированный профиль без идентичностей. В обоих случаях выбор светлой темы дошёл до окна Slint и сохранился с тем же UID после перезапуска. Принудительная ошибка записи настроек оставила форму открытой и хранилище идентичностей пустым. Повторная отправка после устранения ошибки создала единственную идентичность. Два адресных теста прошли с выключенными сетью и физическим аудио.
|
||||
|
||||
Windows, preload:onIdentitiesChanged: в тесте reattached_identity_details_keep_nondefault_uid_and_its_bookmarks новая привязка окна сохранила выбранный недефолтный UID при одинаковых именах двух идентичностей. В Details показана связанная с ним закладка; изменение ника затронуло только выбранный UID. При выборе другой идентичности чужая закладка не показывалась. Прошли оба теста смены окна; работа выполнялась на временных профилях без сети.
|
||||
|
||||
Windows, preload:onIdentityProgress: тест old_cancel_cannot_stop_or_relabel_a_new_identity_search прошёл в нативном окне с одним временным UID. После отмены поиска с целью 99 начат поиск с целью 100. Старая команда отмены не остановила второй поиск: его счётчик продолжил расти, а отображаемый уровень и цель относились к новой задаче. Отмена из текущего окна завершила работу, сохранённая позиция совпала с итоговым результатом. Сеть и физические устройства не использовались.
|
||||
|
||||
Windows, preload:exportIdentity: проверена отмена на обоих этапах в отдельном временном профиле. После Cancel в предупреждении о приватном ключе системный Save не открылся. В двух отдельных диалогах Save введены путь существующего файла и путь нового INI; после Cancel содержимое существующего файла и состав каталога не изменились. Успешный перенос и совпадение UID проверены ранее. Тестовое окно закрыто, профиль и каталог удалены.
|
||||
|
||||
Windows, preload:importIdentity: системный диалог выбора INI проверен на новой идентичности, повторном импорте и повреждённом файле. Окно показало «добавлено 1, уже в профиле 0», затем «0, 1»; повреждённый INI дал видимую ошибку, публичные данные и UID по умолчанию не изменились. Два теста ядра прошли: дубликаты не занимают места при лимите 256, пакет с лишним новым UID не записывается частично. Оба временных профиля и тестовые INI удалены.
|
||||
|
||||
Windows, identity-action:export/import: в двух временных профилях проверен перенос через настоящие системные диалоги. После предупреждения о приватном ключе исходный клиент сохранил INI; второй клиент импортировал его и после перезапуска вернул оба публичных UID с прежним UID по умолчанию. Ключи в вывод не попадали; оба профиля и INI удалены. Пять адресных тестов прошли, включая ошибку после частичной записи при замене старой копии. Desktop экспортирует из памяти через закрытый временный файл в выбранном каталоге. Мобильные провайдеры и восстановление после отключения питания не проверялись.
|
||||
|
||||
Windows, identity-action:delete: в окне Slint удалена одна из двух тестовых идентичностей с одинаковым именем после подтверждения точного UID. Выбор удалённого UID сброшен; окно показало оставшуюся идентичность, изменение её ника сохранилось при полном перезапуске. После перезапуска в хранилище остался только исходный UID по умолчанию. Два адресных теста прошли, включая проверку общего профиля двух вкладок. Отказ удаления используемого UID покрыт отдельной проверкой pc5232-identity-cancel-02.
|
||||
|
||||
Windows, локальный профиль: тест offline_profile_is_shared_by_tabs_but_not_by_detached_editors прошёл через форму первого запуска и Details при двух открытых вкладках. До создания профиля попытка открыть соединение отклонена. Обе вкладки показали изменённый ник, оба ядра вернули его и один UID через profile_get. После смены окна старый редактор не изменил профиль и не получил новое значение; после полного перезапуска сохранились ник, UID и единственная идентичность. Подключённый к серверу rename и отказ сервера этим тестом не проверялись.
|
||||
|
||||
Windows, preload:onCoreStatus: менеджер публикует Starting перед созданием нового worker при перезапуске. Вкладка показывает состояние неработающего ядра и не предлагает подключение до Ready. Три адресных теста прошли. На уровне менеджера занятие временного слота дало Failed и Disconnected, соседняя вкладка ответила на profile_get, снятие блокировки позволило восстановить Ready. В отдельном тесте окна Slint выбор со старым SessionKey после перезапуска дал target_changed, цикл приложения продолжил работать, соседняя вкладка выбиралась и отвечала. Быстрое промежуточное Starting не измерялось как отдельный отрисованный кадр.
|
||||
|
||||
Windows, голосовое ядро: собственное событие ClientChannel с изменившимся каналом отзывает очередь и разрешение отправки ранее захваченных кадров, после чего снимок публикуется без обычной задержки. Три адресных теста teamspeach-core прошли: проверены собственный и чужой перенос, повторное уведомление без смены канала, блокировка отправки со старым разрешением и приём кадра с новым. Физический микрофон и сетевой переход не проверялись.
|
||||
|
||||
Windows: contact_sort_uses_saved_mode_after_two_restarts проверил сортировку из настройки Chats. В негруппированном списке локальный псевдоним Alpha (офлайн) был выше Zulu (онлайн) при алфавитном порядке. После отключения настройки и двух перезапусков первым отображался онлайн-контакт Zulu. Присутствие взято из тестового снимка сервера; облачные сервисы не использовались. Вместе с проверкой независимого раскрытия групп прошли два теста.
|
||||
|
||||
Windows: настройки показа и группировки офлайн-контактов проверены через элементы Slint на трёх запусках. Отключение показа скрывает контакты без непрочитанных сообщений и сам элемент группировки, не сбрасывая выбор. При повторном включении показан локальный псевдоним, затем отдельная офлайн-группа при включении группировки. Три адресных теста прошли, включая исключение для непрочитанных сообщений.
|
||||
|
||||
Windows: свёрнутая группа контактов показывает суммарное число непрочитанных личных сообщений. В тесте contact_disclosures_restore_online_and_offline_independently проверено доступное имя заголовка Online Contacts (1) и сохранение непрочитанного у контакта после выхода с сервера. Использовались события тестового сервера без сети и аудио.
|
||||
|
||||
Windows: список контактов суммирует непрочитанные личные сообщения по UID на всех серверных вкладках из состояния уведомлений. Три адресных теста прошли: контакт с непрочитанным сообщением виден после ухода с сервера даже без открытой переписки; чтение на одном сервере не снимает счётчик другого. Проверка использовала тестовые события без сети и аудио.
|
||||
|
||||
Windows, контакты: заголовки онлайн- и офлайн-групп независимо сохраняют состояние раскрытия. В тесте Slint два контакта распределены по снимку тестового сервера; нажатия и два перезапуска сохранили видимость правильной группы и активную вкладку, без запуска аудио. Также прошёл интеграционный сценарий добавления, переименования, отклонения ошибочных правок и удаления локального контакта. Облачное присутствие не использовалось.
|
||||
|
||||
Windows: заголовок списка закладок сохраняет savedServersCollapsed. В окне Slint проверены сворачивание указателем, отсутствие строк после перезапуска и повторное открытие с сохранённой закладкой во всех сочетаниях EN/RU и светлой/тёмной темы. Выбранная вкладка и владелец ввода не менялись. Два теста боковой панели прошли.
|
||||
|
||||
Windows: ширины sidebarWidth и serverPaneWidth теперь сохраняются целыми числами; старые значения в виде 280.0/470.0 также восстанавливаются. Перетаскивание серверной панели ограничено максимумом хранилища (1600 px). Тест desktop_pane_drags_remain_visible_and_persist_across_restart прошёл для EN/RU и тёмной/светлой темы: проверены геометрия после указателя и перезапуска, сужение с 2600 до 1024 px без потери сохранённой ширины и неизменность активной вкладки и владельца ввода. Профили были отключены от серверов.
|
||||
|
||||
Сверка themes.extensions с TS6 5232: подтверждены ключ идентификатор//вариант, сброс отсутствующего выбора, кэш 300 секунд и сортировка вариантов по имени. Сортировка исправлена в нативном списке; тест Slint с обратным порядком в манифесте прошёл на Windows. Ограничение Slint поддерживаемыми токенами CSS сохраняется.
|
||||
|
||||
Кодеки на Windows: прошли `legacy_codecs_neither_select_an_encoder_nor_enter_the_mix` и `encode_decode_mix_roundtrip_both_codecs`. Для Speex NB/WB/UWB и CELT Mono проверены отсутствие выбранного TX-кодека и отклонение входящих пакетов с указанием исходного кодека, без активных говорящих и без PCM в микшере. Сброс приёмника позволяет снова сообщить об ошибке того же client ID. Это модульная проверка, не вход в legacy-канал и не измерение исходящих сетевых пакетов; `current-contract:speex-celt` остаётся открытым.
|
||||
|
||||
Windows: проверен импорт ZIP темы через реальный системный диалог. Вариант появился в списке и остался выбранным после Reload, хеш установленного CSS совпал с исходным. Неизвестный селектор показан как проигнорированный; второй пакет с внешним @import отклонён до установки. Два теста ядра обработки тем в teamspeach-native подтвердили отказ для внешних ресурсов и выходящих за каталог путей. Это результат Windows для поддерживаемого подмножества, не совместимость с произвольным CSS.
|
||||
|
||||
Windows, список тем: после Reload в работающем клиенте видны название пакета, два его варианта и ошибка соседнего некорректного пакета. Ссылки показаны один раз на пакет. Адресный тест Slint подтвердил предпросмотр без изменения userStyle, сохранение оформления при выборе и возврат стандартной темы при удалении. Проверка не охватывает системный диалог импорта ZIP.
|
||||
|
||||
Windows: проверен `preload:openThemeLink`. Временный пакет темы объявлял домашнюю страницу, документацию, репозиторий и почту. У каждой кнопки Windows UI Automation наблюдала диалог с соответствующим полным адресом и отменила переход, включая доверенный домен и mailto. Во втором профиле без homepage и docsUrl обе кнопки отсутствовали. Внешнее приложение для проверки не запускалось.
|
||||
|
||||
Проверка ссылок из настроек: в двух временных профилях один и тот же URL репозитория темы получил предупреждение о вредоносном домене при наличии домена в локальном кэше и обычное подтверждение при отсутствии списка. Точный URL остался виден; в обоих диалогах нажата отмена. Восемь тестов политики privacy прошли, включая отклонение некорректных DNS-имён и сохранение обычного подтверждения для IPv4/IPv6. Внешнюю страницу не открывали.
|
||||
|
||||
Windows, Privacy → Manage trusted sites: добавлен статус локального списка фишинговых доменов. В двух временных профилях при недоступном обновлении Windows UI Automation показала отдельно отсутствие списка и использование сохранённой копии. Восемь тестов сервиса privacy прошли, включая успешное обновление и сохранение предыдущего списка при ошибке. Статус источника не является вердиктом безопасности для отдельной ссылки.
|
||||
|
||||
Темы Windows: после удаления выбранного пакета Reload теперь выводит его имя и сообщает о возврате стандартной темы. Проверено в отдельном окне через UI Automation. Тест `selected_variant_survives_restart_and_restores_stock_on_removal` прошёл: после перезапуска сохранились цвет отрисованных пикселей, семейство Consolas и размер 19 px; после удаления пакета восстановлены стандартные значения, исходный CSS не изменился. Это не проверка импорта ZIP или загрузки шрифтов из пакета.
|
||||
|
||||
Локальный `main` синхронизирован с `origin/main` (`05e8d34`); `feature/mobile-port` обновлена до `da1f867`, без слияния в desktop. Для ПК выборочно перенесены обработка ошибок команды без остановки входящего звука и различение просроченного кадра и отзыва разрешения на микрофон. Изменения нативного аудиотракта не требуют отката обновлённых зависимостей.
|
||||
|
||||
После переноса четырёх адресных проверок `teamspeach-native` на `x86_64-pc-windows-msvc` (`--no-default-features`, цели `--lib --test audio_binding --test connections`) прошли все четыре: отклонение отдельного кадра, остановка только отозванного источника, отсутствие захвата без разрешения и сохранение входящего звука при нетерминальной ошибке. Физический микрофон и сервер не использовались.
|
||||
|
||||
Исправлена гонка ручного выхода с `DisconnectedTemporarily` в `core/src/session.rs`: вместо автопереподключения с потерей ID запроса ядро закрывает транспорт и отвечает `clean: false`. Windows-тест `server_stop_reconnects_only_without_an_explicit_disconnect` прошёл: `Serverstop` без запроса оставляет reconnect, после запроса выдаёт один ответ и состояние `disconnected`. В сетевой проверке исправленного stdio-ядра использованы временные профили, вход и выход звука отключены. `10.10.10.160:9987` и `voice.teamspeak.com:9987` прошли `connecting → connected → disconnecting → disconnected`, процессы завершились с кодом 0. Результат `disconnect`: соответственно `clean: true` и `clean: false`; причина отсутствия подтверждения на публичном сервере не установлена. Серверы не останавливались, голос не проверялся.
|
||||
|
||||
По последующему указанию владельца обновление библиотек и инструментов ПК предшествует исправлению ядра. На `main` обновлены Rust 1.100.0, Slint 1.19.1/Skia m157.2, привязки WebRTC 0.4.2/0.3.55 и Sonora 0.3.0 с переносом локальных патчей. На Windows `cargo test --locked -p teamspeach-core -p teamspeach-denoise --lib`: ядро 207 passed / 1 ignored, DSP 18 passed. Это не приёмка окна или связи. Установленный клиент и профиль не изменялись.
|
||||
|
||||
`xtask deps` и `xtask build --target x86_64-pc-windows-msvc` завершились успешно: Windows release EXE со стандартными Skia и WebRTC, без test-harness. Отдельно прошёл `cargo check --locked -p teamspeach-native --no-default-features` для Windows x64. Это новая проверка сборки, но не ручная приёмка голоса или установленной версии.
|
||||
|
||||
## Проверка паритета ПК с TeamSpeak 6.0.0.5232, 2026-11-26
|
||||
|
||||
- Актуальный визуальный эталон — **TeamSpeak 6.0.0.5232**; 6.0.0.5163 и его значения смещений —
|
||||
исторический источник. [Карта эталона](evidence/official-parity/visual-source-map.md) содержит
|
||||
SHA-256 обоих бандлов из четырёх манифестов, точные команды и пути reference/native/compare.
|
||||
Снимки сделаны с общей синтетической сценой, не с аккаунта или пользовательского профиля.
|
||||
- Dark/light × EN/RU, 1280×800: основной вид с чатом канала, личный чат, контекстное меню,
|
||||
настройки Audio и Appearance. В каждом из двух прогонов 20/20 нативных сцен отрисованы;
|
||||
строгий результат каждого — **0 passed / 20 failed / 0 blocked** (`target/evidence/compare-5232-pc-02/parity-report.json`
|
||||
и `target/evidence/compare-5232-pc-03/parity-report.json`). Исключения продукта (свой бренд,
|
||||
отсутствие myTeamSpeak/homebase и Remote Apps) не маскируются при сравнении всего кадра.
|
||||
- Отдельный `target/evidence/pc5232-functional-04/result.json`: 8 проверок и 28 снимков, включая
|
||||
12 разделов настроек, EN/RU, dark/light, ширины 390/800/1280, PTT при фокусе текста, безопасный
|
||||
rich chat, отказ захвата и перезапуск временного профиля. Без сети, действий ОС и реальных устройств.
|
||||
- Уведомления и настройки передачи файлов: на Windows прошли 2 теста ядра `disconnect_tests`,
|
||||
49 выбранных библиотечных тестов `teamspeach-native` и 4 интеграционных теста
|
||||
`notification_preferences`. Старый звуковой параметр `group_status` сохранён, переключатель
|
||||
категории Status работает независимо. `target/evidence/pc5232-notification-03/result.json`:
|
||||
успешный изолированный прогон, 32 снимка. Global Private Chat, Global Group Chat, Incoming call
|
||||
и Outgoing call остались недоступны после попыток активации указателем и через accessibility;
|
||||
каждый снят отдельно. Сохранённые настройки и уже открытая отключённая вкладка не изменились,
|
||||
активных сеансов и физического аудио не было.
|
||||
- Проверку по критерию индивидуально доступного Listen и звуковой политики прошёл 51 из 58 случаев:
|
||||
у шести нет своего варианта Listen, для речи при выключенном микрофоне нет реального речевого
|
||||
триггера. Локальный журнал на тестовых событиях принял 501 событие без звука, сохранил 500 и
|
||||
показал последние 200. Переключение и закрытие вкладок не смешивают сеансы; это не серверный
|
||||
`Server Log`. Для файлов проверены шаговые кнопки, общий с ручным вводом шаг и границы,
|
||||
сохранение настроек после повторного открытия и отклонение недопустимых значений. Это не
|
||||
сквозная приёмка файловых операций, установленной сборки или официального клиента; статусы
|
||||
718 требований в `native/compatibility.json` не менялись.
|
||||
- Последующая Windows release-сборка (`xtask build`, Skia + WebRTC) успешно слинкована; запуск `teamspeach.exe --version` вернул `TeamsPeach 0.1.7 (Rust + Slint)`. Это сборка из рабочего дерева, не установка или приёмка на физической гарнитуре.
|
||||
- В `target/evidence/pc5232-identity-cancel-02/result.json` проверены создание, выбор по UID при одинаковых именах, сохранение ключа, уровня, закладки и ника после перезапуска, отказ удаления используемой идентичности и отмена экспорта из меню указателем и клавиатурой. Отмена активного поиска подтверждена за 172 мс и за 180 мс после перезапуска; второй поиск продолжился с контрольной точки первого. Отдельно прошли `about_workflows` и `bookmark_contact_workflows` (3 теста). Это не подтверждение экспорта через системный диалог, изменения ника на сервере или визуального паритета.
|
||||
- Административные формы: 9 адресных Windows-тестов (`admin_editor_`, `server_edit_`, `channel_admin_tests`) прошли. `channel_admin_qa` с отдельным beta14 подтвердил создание временного канала, смену темы без изменения имени/качества кодека, отказ по неверному качеству и старому поколению, чтение обычного и семейного лимита. `channel_flag_maxfamilyclients_inherited` у корневого канала не прислан; перенос под родителя гостю запрещён (TS 2568). Канал исчез после выхода; сервер подтвердил отключение. Рабочий сервер не менялся.
|
||||
- Отдельно два CLI-клиента ядра через изолированный официальный beta 14 одновременно передали
|
||||
по 100 кадров с тонами 500/900 Гц: 99/101 и 100/101 декодированных кадров совпали по спектру и
|
||||
идентификатору отправителя; оба клиента отключились штатно. Реальных устройств и официального клиента
|
||||
в этой проверке не было.
|
||||
- `cargo run --locked -p teamspeach-core --example duplex_qa` с QA-ядром и изолированным beta 14 на
|
||||
localhost: A→B и B→A по 45 кадров, начало через 14 и 21 мс соответственно, 864 мс одновременной
|
||||
передачи. Проверены отпускание PTT, mute, отказ после отключения и новый сеанс при повторном
|
||||
подключении; 3/3 штатных выхода. Отдельно прошли 112 тестов `media::audio` на Windows, в том числе
|
||||
задержка захвата более 200 мс при активном воспроизведении и замена разрешения на захват. Эти
|
||||
воспроизводимые тесты подтверждают исправление пути `Audio worker stalled` в коде; сценарий на
|
||||
реальном WASAPI-устройстве независимо не наблюдался, готовность сборки и приёмка не подтверждены.
|
||||
- Два CLI-клиента прошли `duplex_qa -- --whisper` на закрытом beta14; 15 тестов ядра с фильтром `whisper` прошли. Проверены разрешение и запрет приёма, восстановление приёма и отбрасывание устаревшего кадра без передачи в обычный канал. Стенд остановлен. Проверка не включает окно настроек, системный ввод или физическое аудио.
|
||||
- Чат на изолированном beta14: два CLI-клиента получили подтверждения и точный текст для текущего канала и личного сообщения с проверкой ID и серверного UID. Несовпадающий UID дал `target_changed`, четыре недопустимых набора аргументов дали `bad_request`; общесерверный текст гостю запрещён (TS 2568). Оба клиента отключились штатно. Отдельный тест Slint `concurrent_tabs_keep_separate_drafts_and_pending_sends` подтвердил независимость черновиков двух вкладок при одинаковой истории и ответах в обратном порядке. Это не проверка установленного клиента и не доказательство доставки в произвольный канал.
|
||||
- После перехода обоих CLI-клиентов из лобби во временный канал beta14 ядро отклонило `send_text` с прежним `expected_channel_id` (`target_changed`). Сообщение с текущим ID сервер подтвердил, второй клиент получил только контрольный текст. Оба клиента отключились штатно, стенд остановлен. Прошли два теста валидации протокола и два теста нативного клиента на устаревший канал и независимость черновиков. Проверка относится к известному ядру каналу перед отправкой, не к доставке в произвольный канал.
|
||||
- При пересечении загрузки последней страницы и записи входящего сообщения окно не добавляет повторно строку, которая уже вошла в страницу. На Windows прошли `latest_page_and_live_append_show_each_record_once`, `restart_pagination_and_scope_isolation` (641 запись, два повторных открытия) и `interrupted_and_damaged_lines_keep_indices`.
|
||||
- `preload:chatHistoryPage`: в Slint кнопка «Ранее» открыла записи 5–104, затем 0–4; «Последние» вернула 105–204. Проверены индекс и текст каждой записи, личная запись не попала в историю канала. Тест `older_and_latest_buttons_page_only_the_selected_history` прошёл на Windows: файлы истории и приложение реальные, список участников тестовый, без сети и запуска аудиоустройств.
|
||||
- `preload:chatHistoryList` и `preload:chatHistorySetOpen`: закрытие фоновой личной вкладки оставило выбранный чат и его черновик на месте. После повторного открытия и перезапуска runtime сохранились подпись собеседника и его прежнее сообщение. Разговоры другой идентичности и другого сервера не появились. Девять оконных тестов Slint прошли вместе на Windows; каждый использовал отдельный процесс для платформы Slint. Профили временные, список участников тестовый, без сети и физических аудиоустройств.
|
||||
- `preload:chatHistoryAppend`: тест `private_history_tabs_restore_labels_and_preserve_the_selected_draft` прошёл на Windows с входящими личными сообщениями и эхом собственной отправки, поданными как события `text`. После двух перезапусков runtime проверены точный текст, UID автора, признак собственной отправки и отсутствие дубликатов. Другие разговоры, идентичности и серверы сохранили только свои записи. События синтетические; запись и повторное чтение выполнены реальным хранилищем.
|
||||
- Запись: `recording_finalized` с `ok:false` не разрешает экспорт. Панель показывает ошибку, скрывает «Показать» и позволяет явно начать новую запись. Проверено, что существующий файл назначения и неполный файл в staging не меняются. На Windows прошли 4 адресных теста нативного клиента и 4 теста ядра: пауза/продолжение, длина WAV, waveform и ошибка записи. Полный сценарий через системный выбор каталога и установленный UI не проверялся.
|
||||
- На изолированном beta14 проверены команды ядра `recording_start` (режим 3), pause/resume, info/status, waveform и stop с ожиданием `recording_finalized`. На паузе счётчик остался на 42 240 кадрах; в итоговой мастер-дорожке 84 480 кадров. Обнаружено по 25 блоков по 20 мс на 650 и 1300 Гц до и после паузы; тон 1000 Гц, поданный на паузе, отсутствовал. Сумма PCM по дорожкам, `session.json` и событие завершения совпали: 324 480 байт без заголовков WAV. Сервер подтвердил отключение. Это проверка CLI и файлов, не системного выбора каталога или физического микрофона.
|
||||
- Доступ к каталогу записи теперь сохраняется после ответа `recording_stop`: его освобождает `recording_finalized` для соответствующего пути либо подтверждённая остановка ядра. На Windows семь тестов прошли, включая смену каталога после Stop, позднее событие другой записи и перезапуск worker. Это проверка lifetime разрешений; системные разрешения Android/iOS не проверялись.
|
||||
- Панель записи показывает «Завершение записи» между `Stop` и результатом writer. Тест `failed_recording_finalization_does_not_authorize_export` прошёл на Windows: проверены кнопки паузы и продолжения, отсутствие действий записи и экспорта при финализации и игнорирование позднего ответа `recording_info`. Проверка использует модель панели, не системный диалог выбора каталога.
|
||||
- При экспорте нескольких файлов записи все замены подтверждаются до первого копирования. Финализация запускает экспорт в задаче приложения, чтобы цикл событий мог показать диалог и обработать ответ. На Windows прошли три адресных теста, включая `cancel_second_recording_overwrite_keeps_all_destination_files`: после подтверждения первого файла и отмены второго исходные и целевые файлы не изменились. Это не гарантия группового отката при ошибке ввода-вывода во время копирования.
|
||||
- `finalized_recording_exports_wav_and_manifest_byte_for_byte` прошёл на Windows с `--ignored`: штатный рекордер записал пять блоков по 960 кадров; до уведомления о финализации каталог экспорта отсутствовал. После него Windows-адаптер опубликовал `00 master.wav` и `session.json`, оба побайтно совпали с оригиналами. В WAV 9 600 байт PCM и 44 байта заголовка. Профиль и каталоги временные, сеть отключена; системный выбор каталога и физическое аудио не проверялись.
|
||||
- При переполнении очереди WAV блок сохраняется тишиной; теперь соответствующий пик `recording_waveform` также нулевой. На Windows прошли `slow_disk_drops_whole_ticks_truthfully_and_keeps_alignment` (сверка каждого пика с PCM итогового WAV) и `waveform_reports_peaks_per_tick` (обычный сигнал). Это проверка ядра без устройств.
|
||||
- Панель записи Rust/Slint показывает последние 64 блока формы сигнала отдельно для каждой дорожки. Канонический путь staging берётся из разрешения, переданного ядру; чужая или повторная финализация не разрешает экспорт текущей записи. На Windows шесть адресных тестов `teamspeach-native` прошли с `test-harness`: выравнивание пиков, поздний ответ после закрытия панели, пиксели двух дорожек Slint при обновлении и удалении, отказ финализации, отмена замены и побайтный экспорт WAV/манифеста. Эталон inline-дорожек микшера: 5232 `main.js` (байты 4465339, 4469377, 4474782), `main.css` (652446). Это не попиксельное сравнение всего микшера; физические устройства и системный диалог в этих тестах не использовались.
|
||||
- Серверный `MATRIXCHAT`: в обычном серверном чате показано пояснение о неподдерживаемых комнатах при `server.features.chat=true`. Windows `smoke::chat::` (4 теста) проверил появление и исчезновение сообщения при смене объявления, доступность ввода и отсутствие диалога входа. Контракты `current-contract:matrix-not-account` и `feature:chat.server_matrix` проверены только в части явного ограничения. Сеанс Matrix не устанавливался.
|
||||
- `current-contract:profile-import`: на Windows прошли 8 адресных сервисных проверок и 3 проверки диалогов, включая отмену пароля импортированной закладки на первом запуске и после двух перезапусков. Устранено повторное открытие отменённого запроса из запоздалого снимка. Проверены неизменность маркера пароля, UID, истории и порядка закладок; профиль владельца не использовался.
|
||||
- Проверены лимиты файлов: 4 адресных Windows-теста нативного планировщика подтвердили распределение между двумя вкладками после перезапуска сервиса и сохранение прежних настроек при отказе. На уровне ядра `download_rate_limit_paces_real_bytes_and_can_be_disabled` и `upload_sends_exact_bytes_and_sees_server_close` проверили реальные байты через TCP loopback при 1 МиБ/с. Для upload приёмник проверяет пять блоков по 64 КиБ, порог 240 мс, целостность и закрытие пишущей стороны. `transfer_slots_are_counted_per_channel_and_direction` проверил независимость очередей каналов и направлений. Одновременные сетевые передачи на двух серверных вкладках не выполнялись.
|
||||
- Автоподключение перебирает закладки в порядке боковой панели, включая вложенные папки, вместо исходного порядка массива `savedServers`. Семь тестов `services::bookmarks::tests::` прошли на Windows, включая перестановку папки перед ранее созданной корневой закладкой. Проверены порядок обхода и сборка вызывающего runtime; сетевой автозапуск двух серверов в этом тесте не выполнялся.
|
||||
- Отдельная проверка на `76795c6`: запущен собранный Windows `teamspeach.exe` с временным профилем и двумя защищёнными закладками на loopback. Через Windows UI Automation в основном окне `TeamsPeach` отменены запросы `QA Nested`, затем `QA Outside`, хотя `savedServers` содержал обратный порядок. За 600 мс после второй отмены запрос не повторился. `bookmark_sidebar_and_local_contact_reopen_without_network` отдельно подтвердил порядок после перезапуска, копию сразу после оригинала, отмену/подтверждение удаления поддерева и отсутствие запуска аудио в изолированном runtime. Не проверялась успешная авторизация на двух серверах.
|
||||
- Сопоставлены `myts.account_cloud`, `remote_apps`, `privacy.analytics` и `dev.options` с установленным JS-бандлом TS6 5232 (SHA-256 совпал с visual source map). В обычном Windows-окне открыты Settings → Privacy → More Information: объяснение диагностики доступно, режима сбора выбрать нельзя. У Account, Remote Apps и Developer Options нет категории. Это проверка интерфейса; не измерялись сетевые запросы. UI Automation в этой сборке не предоставила Invoke для кнопки Privacy; переход проверен указателем.
|
||||
- Нативная проверка `whisper-settings`: `target/evidence/pc5232-whisper-settings-03/result.json` и 5 кадров. Подтверждены `deny_all`, сохранение списков после перезапуска runtime, предупреждения для повреждённого файла и файла новой версии, отсутствие запуска аудио. `whisper_list_workflows` проверил отмену и подтверждение удаления, сохранность несвязанных сочетаний и восстановление при ошибке записи. В About возврат фокуса к лицензии и выпуску проверен повторной активацией через Enter. Эти проверки не подтверждают визуальное совпадение с официальным клиентом.
|
||||
- `preload:setWhisperReceiveMode`: `target/evidence/pc5232-whisper-settings-05/result.json` подтверждает выбор `allow_all`, затем `deny_all` указателем в Slint. Для обоих режимов показанное значение совпало с `whisper.json`, после перезапуска runtime сохранился `deny_all`. Отдельно `target/evidence/pc5232-identity-choice-01/result.json` прошёл с тем же исправленным компонентом выбора. Доставка звука проверялась отдельным CLI-сценарием, не из этого окна.
|
||||
- Профили горячих клавиш: адресный тест Slint и тест хранилища прошли на Windows. Создание второго профиля не меняет активный; имя длиннее 64 символов отклоняется. После подтверждённого удаления неактивного профиля редактор сразу показывает активный; его UUID, новое имя и локальная привязка F8 сохранились после перезапуска runtime. Системные сочетания не регистрировались.
|
||||
- `preload:activateKeybindProfile`: при смене активного профиля удерживаемый PTT завершился без таймера; обычное отпускание в том же тесте сохранило настроенную задержку 500 мс. После активации старый F8 не срабатывал, новый F9 управлял push-to-mute, выбранный профиль сохранился после перезапуска runtime. Прошли 12 адресных тестов Windows с синтетическим вводом; физическая передача звука не проверялась.
|
||||
- Точное совпадение: флажок Slint переключён через действие доступности. Локальный обработчик принимал Ctrl+F8 в обоих режимах, Ctrl+Shift+F8 только без точного совпадения; после перезапуска runtime настройка сохранилась. Два адресных теста прошли, включая ограничение числа вариантов регистрации. Системный backend Windows не регистрировал сочетания в этом сценарии; `preload:setKeybindExact` остаётся открытым.
|
||||
- `current-contract:speex-celt` не закрыт: изолированный beta14 отклонил обе попытки создания временного канала с `channel_codec=0` (Speex Narrowband) и `3` (CELT Mono), TS 1538 `ParameterInvalid`. Вход в такой канал и отсутствие TX не проверены; гостевой клиент отключился штатно, стенд остановлен.
|
||||
- Windows, вкладки: 5 адресных тестов библиотеки и 7 интеграционных из `connections` и `audio_binding` прошли. Восемь отдельных ядер созданы менеджером без сети; в окне Slint вкладки `c1`–`c8` выбирались указателем без смены владельца ввода и без запуска аудио. Девятый запрос отклонён с видимой ошибкой. Отказ закрыть последнюю вкладку не снимает PTT/whisper; при принятом закрытии или перезапуске очередь аудио старой сессии отзывается. Сетевой диалог, физический микрофон и подключение к официальному клиенту не проверялись.
|
||||
- Два дополнительных теста менеджера: между сменой владельца ввода A→B и обработкой подтверждения B нет активного разрешения на захват, старая эпоха A недействительна, просмотр C не меняет владельца; после подтверждения кадр принимает только B. При повторном использовании слота запоздавшие события закрытой вкладки не меняют подписку, новая вкладка отвечает на `profile_get`. Ядра и очереди реальные, сетевое состояние тестовое, физический ввод не запускался.
|
||||
- При неудачном перезапуске worker состояние вкладки публикуется как `Failed` до ответа, а не как штатное `Stopped`. Проверено реальной блокировкой временного слота: соседнее ядро продолжило отвечать, после снятия блокировки повторный запуск вернул `Ready`. Это проверка менеджера, не сценарий перезапуска через установленный UI с незавершённым запросом.
|
||||
- `preload:restartCore`: три адресных теста прошли. В окне Slint перезапуск через контекстное меню отключённой вкладки показал подтверждение с её именем. Менеджер отдельно отбросил задержанный ответ прежнего ядра после перезапуска; соседняя вкладка продолжала отвечать. Проверка была изолированной, без сети и физических устройств.
|
||||
- На изолированном официальном beta 14 ядро получило только пустой S3-каталог в режиме чтения.
|
||||
Отдельный PUT/list/GET напрямую в хранилище не доказывает передачу или изменение файлов через
|
||||
TeamSpeak. Открыты визуальный паритет, положительные S3-операции через TeamSpeak, HTTPFT,
|
||||
серверные Matrix/SFU, двусторонний голос с официальным клиентом и приёмка установленной версии
|
||||
этой сборки. Эти результаты не меняют принятую ранее базу 0.1.7 и не заменяют проверки Android/iOS
|
||||
на устройствах. [Подробности](../FEATURE_COMPATIBILITY.md#current-windows-account-free-checkpoint-2026-11-26).
|
||||
|
||||
## Принятая Windows-база и мобильная ветка
|
||||
|
||||
- Пользователь явно подтвердил в форме: **проверил подключение, вход в канал и голос в обе стороны, принимает установленную Windows 0.1.7 и разрешает baseline/push**. Desktop acceptance gate снят; это ручная приёмка владельца, не новый автоматический тест.
|
||||
- До обновления стоял **0.1.4 Electron**; теперь принят **0.1.7 Rust/Slint**. `main` сохраняет проверенную базу, Android/iOS дорабатываются в `feature/mobile-port`; изменения desktop-поведения требуют отдельного запроса, общий core/DSP/services — desktop regression checks. Ниже сохранена хронология сборки; прежние запреты push относятся к этапу до приёмки.
|
||||
- **Push main и desktop-baseline успешен**: пользователь ввёл credentials в отдельном обычном PowerShell, команда с отключённым для одного запуска credential helper завершилась exit0. `git ls-remote` подтвердил main и peeled tag на `05e8d34bcf0e24a44f76e65220293c45b6821798`. Прежний GCM auth/transport blocker обойдён, не объявлен исправленным; credentials ассистент не читал и команда их не сохраняла. По уточнению пользователя `feature/mobile-port` оставлена локально, на remote её нет; для CI по этой ветке позже потребуется отдельный push. Релиз/установщик не опубликован.
|
||||
- До изменения установки сохранён побайтово проверенный rollback: `%LOCALAPPDATA%/Programs/TeamsPeach.rollback-20261110-223748`, 78 файлов. При установке native исходный каталог также целиком переименован в `TeamsPeach.pre-native-20261111-111816`. Пользовательские профили/identity/настройки вне installation directory не читались и не изменялись.
|
||||
- Full native artifacts отсутствовали. Guarded serial `xtask deps` Windows x64 прошёл исправленную MSVC activation, pinned SDK/depot_tools/WebRTC checkout и gclient sync. OEM/UTF-8 ошибка устранена child `chcp 65001`; отдельный real-vcvarsall smoke сохранил синтетическую кириллицу. Следующий blocker — CRLF checkout checksum-pinned patches: добавлен `.gitattributes`, все три патча восстановлены как LF и точные SHA256 проверены без изменения lock. Повторный provisioning отказал до старта по локальному RAM guard (exit125); полный build/package/runtime **не выполнен**, установка 0.1.4 нетронута.
|
||||
- После успешной сборки: isolated native smoke → production package/verify → установка с сохранённым rollback → ручная приёмка владельца. После подтверждения фиксировать desktop-baseline; mobile-specific изменения изолировать, shared core/services не менять без desktop regression проверки.
|
||||
@@ -546,6 +79,40 @@ Windows, Privacy → Manage trusted sites: добавлен статус лок
|
||||
- Native **0.1.7 установлен** в `%LOCALAPPDATA%/Programs/TeamsPeach`: NSIS exit0, SHA256 всех 76 payload files совпали, установленный `--version` вывел `TeamsPeach 0.1.7 (Rust + Slint)`, `--help` не содержит test-harness. Старый Electron uninstall key экспортирован в `target/desktop-acceptance/legacy-uninstall-registration.reg` и удалён после установки; исходный каталог сохранён, пользовательский профиль не тронут.
|
||||
- Реальное окно установленного production exe проверено с новым временным `TEAMSPEACH_PROFILE_DIR` и закрыто штатно exit0; профиль удалён. Снимок: `target/desktop-acceptance/installed-native-window.png`. Подключение/голос затем проверил и принял владелец; миграция пользовательского профиля отдельно не подтверждена. Следующий этап — Android CI/device проверки в мобильной ветке. Baseline tag не является release tag `v*`; публикация установщика не выполняется.
|
||||
|
||||
## Read-only Android CI preflight, 2026-11-11
|
||||
|
||||
- **Сверено:** `feature/mobile-port`, HEAD `82334f8a8bf25be6b594d013eb30f55f25c8c7bb`; исходное рабочее дерево чистое (staged/unstaged/untracked отсутствуют в `git status`). Локальные `main`, `origin/main` и peeled baseline tag — `05e8d34bcf0e24a44f76e65220293c45b6821798`; отличие HEAD от baseline — только этот handoff. `mobile-build.local.md` прочитан, исключение из Git подтверждено; локальные ограничения не перенесены в CI.
|
||||
- **Live Gitea:** публичный [branches API](https://git.eeee.moe/api/v1/repos/TeamsPeach/client/branches) показывает только `main` на `05e8d34`; [Android Actions](https://git.eeee.moe/TeamsPeach/client/actions?workflow=android.yml&actor=0&status=0&branch=) показывает **0 workflow runs**. Workflow уже опубликован в baseline; мобильная ветка остаётся локальной. Actions UI доступен, но готовность artifact storage этим не доказана.
|
||||
- **Точный блокер доступа:** GET `/api/v1/repos/TeamsPeach/client/actions/runners` и `/actions/variables` вернули HTTP 401. Попытка открыть Actions через подписанный браузер не состоялась: relay connection timeout 30 s. `ssh://` сообщает, что настроенных hosts нет. Runner `teamspeach-android-linux-x64`, его online/labels/resources, установленные SDK/NDK/JDK/LLVM/Skia и наличие семи variables из README **неизвестны**; ни одна variable не объявлена отсутствующей без доступа. Credentials/tokens/profile не читались; Git auth не проверялся и не объявлен исправленным.
|
||||
- **Статически готово:** ручной ARM64 workflow с full Skia+WebRTC, source dependency provisioning, отдельными harness APK и unsigned production APK/AAB, package verification, revision/SHA256 receipts ([workflow](../.gitea/workflows/android.yml), job `android-arm64`; [variant recipe](../.gitea/build-android-variant.sh)). SDK API36/build-tools36.0.0/NDK28.2.13676358, JDK17+, LLVM/libclang, synced Skia+GN, local Gradle8.14.3 ZIP и bundletool должны существовать на runner до build dispatch; Rust1.96.0 и Android target также обязательны. Список variables — [README](../README.md):101–117. В dependency lock по-прежнему только Windows record; Android receipt должен появиться от реального `xtask deps`, не вручную.
|
||||
- **Дополнительные prerequisites:** runner execution environment должен поддерживать checkout@v4/upload-artifact@v3 и исходящие загрузки pinned WebRTC/depot_tools/CIPD, Cargo и Gradle dependencies. `xtask deps` использует отдельный upstream Gradle wrapper для prefixed JNI jar ([deps.rs](../xtask/src/deps.rs):605–615); локальный Gradle ZIP приложения не делает всю цепочку offline. Rust Android build выбирает DEPS-pinned NDK из WebRTC checkout ([build_native.rs](../xtask/src/build_native.rs):275–290), а установленный NDK28.2 проверяется workflow/Gradle. CI capacity и сетевой доступ не измерены; run-specific checkout/target/Gradle trees означают, что межзапусковой object-cache reuse этим workflow не настроен.
|
||||
- **Риск получения первого APK найден и затем исправлен локально:** исходный workflow загружал harness после полного цикла harness+production. В разрешённом продолжении порядок изменён на harness build/verify → harness upload → production build/verify → production upload ([workflow](../.gitea/workflows/android.yml), job `android-arm64`). Общий прежний recipe вынесен в `.gitea/build-android-variant.sh`; failure gates и receipts сохранены. Реальный CI upload ещё не проверен.
|
||||
- **Уточнение harness:** без smoke extras `smoke_request` возвращает `None`, а Android host выставляет `network_enabled=true` и `allow_os_actions=true` ([smoke.rs](../native/src/platform/android/smoke.rs):16–40; [android.rs](../native/src/platform/android.rs):61–85). Offline isolation относится к smoke-запуску, не ко всем запускам harness APK. Обычный запуск test APK — кандидат для первого разрешённого live voice proof на отдельном тестовом телефоне; это статический вывод, не phone/production acceptance. Application ID общий с production — не устанавливать поверх реального профиля.
|
||||
- **Граф:** `.ua/meta.json` и project metadata остаются working-tree snapshot от `5ce12714`, не текущий HEAD; прочитаны только нужные метаданные/узлы/связи. Архитектура не менялась, граф и auto-update не тронуты.
|
||||
- **Следующий порядок:** восстановить read-only доступ к runner/variables и получить фактический tool/resource inventory → согласовать только обнаруженное provisioning и точечные CI-изменения → отдельное разрешение на push `feature/mobile-port` и manual dispatch → проверить скачанный harness APK, revision/SHA256 и receipts → отдельно согласовать ARM64 API26+ телефон, disposable app data, сервер/канал и ПК-peer, затем install/launch/mic/Join ACK/двусторонний голос. iOS/macOS/Xcode/signing — отдельный незакрытый маршрут.
|
||||
- **Проверки этой сессии:** Git metadata, targeted source/docs/graph reads и публичные HTTP GET. Не запускались Cargo/Gradle/tests/build/package/CI/device/app, ничего не устанавливалось и не отправлялось. Изменены только handoff и точное уточнение harness в assessment; исходники, desktop, caches и локальная политика нетронуты. Исторические записи ниже о незакоммиченном CI относятся к прежнему этапу, не к состоянию этого preflight.
|
||||
|
||||
### Разрешённое продолжение: доступ к CI и точечная правка
|
||||
|
||||
- Пользователь разрешил браузерный вход и продолжение подготовки, повторно подтвердив, что Android LLVM/SDK/build должны находиться на удалённом CI, не на его Windows-ПК. Локальная политика, WSL, память и compiler settings не менялись.
|
||||
- Браузерный вход состоялся через уже установленный Chrome, без установки инструментов/расширений и без чтения пароля/cookies/tokens. Авторизованная страница repository Actions runners показала **ровно один доступный runner**: `monkeyRunner`, ID9, v0.2.13, глобальный, «Простаивает»; labels `ubuntu-latest`, `ubuntu-22.04`, `ubuntu-20.04`. **Нужного label `teamspeach-android-linux-x64` нет.** Repository variables page показала пустой список; семь требуемых переменных на уровне репозитория не настроены. Наследуемые organization variables и установленный host toolchain не проверены.
|
||||
- Авторизованный доступ к Gitea settings больше не блокер; **блокер запуска — отсутствие matching runner label и repository configuration**, а фактические SDK/NDK/JDK/LLVM/Skia, RAM/disk/network на host остаются неизвестны. Нельзя просто заменить runs-on на `ubuntu-latest`: это направит тяжёлую сборку в неподтверждённую среду. Нужен согласованный удалённый Linux execution environment и его inventory; Git auth отдельно не проверен.
|
||||
- Повторные обращения к браузеру давали detached Frame и открывали новые окна. Пользователь потребовал прекратить открывать Chrome, затем **уточнил разрешение: невидимый браузер допустим, видимые окна запрещены**. Продолжение выполнено с `headed:false`, вкладка закрыта после чтения. Пароли/cookies/tokens и пользовательский профиль приложения не читались.
|
||||
- Локальная CI-правка завершена: helper `bash -n`, syntax всех workflow run blocks, YAML parse, compile обоих embedded Python scripts и статический порядок стадий прошли. Python subprocess сначала не нашёл Bash в PATH; проверка выполнена через имеющийся shell tool, без установки. Это syntax/structure checks, **не Android build или CI/device proof**. Обновлён CHANGELOG; исходники приложения и desktop-поведение нетронуты, граф не обновлялся.
|
||||
- Пользователь подтвердил **Android-only на ближайшем этапе**: разработка на Windows, APK на удалённом Linux; WSL не возвращать. После проверки вариантов явно разрешены **push только `feature/mobile-port` и один диагностический CI run до 5 минут на существующем runner**, без установки, компиляции и чтения секретов. Main/релизы/телефон и тяжёлый build не входят в это разрешение.
|
||||
- В `android.yml` добавлен безопасный default `mode=inventory`: job `runner-inventory` на `ubuntu-latest`, без checkout/action downloads, только OS/CPU/RAM/disk/cgroup/tool/config inventory; значения variables не печатаются, Rust proxies не вызываются. `mode=build` — единственный путь к прежней тяжёлой job на выделенном Android label. YAML/Bash syntax и статические mode/timeout/job gates проверены; фактический remote run ещё предстоит. Runner resources и inherited organization variables пока неизвестны.
|
||||
|
||||
### Реальный runner inventory: run 4828, 2026-11-11
|
||||
|
||||
- **Push выполнен:** отдельный PowerShell с ручным вводом credentials, credential helper отключён только для команды; exit0. Публичный branches API подтвердил `feature/mobile-port=cb1d682dfb307ec41d73434ab40de5de0b30410e`, `main=05e8d34bcf0e24a44f76e65220293c45b6821798`. Credentials не читались, GCM не объявлен исправленным. Коммит включает диагностический режим, раннее сохранение harness и документы; запись фактического результата ниже добавлена локально после push.
|
||||
- **Единственный разрешённый dispatch выполнен:** [android-ci run 4828 / #62](https://git.eeee.moe/TeamsPeach/client/actions/runs/4828), [job runner-inventory 5423](https://git.eeee.moe/TeamsPeach/client/actions/runs/4828/jobs/5423) — **success, 1 s**; `android-arm64` — **skipped**. Выбрана `feature/mobile-port`; форма Gitea на default branch ещё не показывала input `mode`, поэтому сработал безопасный fallback inventory при отсутствии `mode=build`. Новых dispatch/re-run не выполнялось.
|
||||
- **Execution environment подтверждён setup log:** `monkeyRunner` v0.2.13 запускает job в контейнере `docker.gitea.com/runner-images:ubuntu-latest`. Docker pull проверил существующий image как up-to-date; это инфраструктура удалённого CI, не Docker/WSL на Windows. Диагностический step не скачивал SDK/dependencies и не устанавливал инструменты. Наличие инструментов на физическом host из этих данных не следует: измерено окружение job.
|
||||
- **Ресурсы, видимые job:** Linux x86_64, 32 CPU; `/proc/meminfo`: MemTotal 129429464 KiB, MemAvailable 30306932 KiB (≈28,9 GiB); workspace Available 21965056 KiB (≈20,95 GiB) из 64 GiB. Cgroup v2 `memory.max=max`, `memory.swap.max=max`, `cpu.max=max 100000` в видимом scope; это не гарантия отсутствия ancestor/shared-host limits. Linux Committed_AS превышал CommitLimit; не трактовать эти Linux показатели как Windows Job Object guard или обещание безопасной build capacity. Достаточность свободного диска для холодного WebRTC+Skia build не подтверждена.
|
||||
- **Фактические tools:** git/python3/pkg-config/ar/sh/node найдены в PATH. cargo/rustc/rustup, cmake/ninja, clang/clang++, llvm-strip/llvm-readelf, java/javac/jar/keytool/jarsigner, zipalign/aapt2/apksigner/sdkmanager — **missing-from-PATH**, не утверждение об отсутствии на всём host. Rust1.96.0 не найден в обычном rustup-home. SDK/Skia roots не настроены, поэтому их установки остаются неизвестными, а не просканированными как отсутствующие.
|
||||
- **Все семь variables действительно unset в CI-контексте:** `ANDROID_SDK_ROOT`, `ANDROID_JAVA_HOME`, `NATIVE_LLVM_HOME`, `NATIVE_LIBCLANG_PATH`, `NATIVE_SKIA_SOURCE_DIR`, `ANDROID_GRADLE_DISTRIBUTION`, `ANDROID_BUNDLETOOL`. Унаследованные runner env roots Android/JAVA/LLVM/libclang/Skia тоже unset. Пустой repository UI больше не единственное основание этого вывода.
|
||||
- **Точный следующий blocker:** общий runner работает, но его job image не предоставляет Android toolchain/configuration; matching Android label по-прежнему отсутствует. Нужна отдельно разрешённая подготовка Android execution image и build/cache storage на существующем удалённом runner, затем фактические paths/variables и dedicated label. Нельзя подменять этим изменением общий image других проектов или просто запускать heavy build на generic `ubuntu-latest`. Host access/административное provisioning не предоставлены; текущая авторизация покрывала только push и один inventory, не установку/сборку.
|
||||
- **Граница доказательства:** реальный read-only Linux CI pass, не Android compile/package/APK/device/voice acceptance. Windows acceptance/base, desktop-код, локальные compiler settings, caches, pagefile и WSL не менялись. Все последующие browser calls использовали `headed:false`; вкладки закрыты. iOS на этом этапе не исследовался и не собирался.
|
||||
|
||||
|
||||
## Текущий маршрут: Android в CI, Windows без WSL
|
||||
|
||||
|
||||
@@ -55,8 +55,6 @@ Remote URLs and `@import` are rejected, including escaped spellings; local refer
|
||||
|
||||
## Historical source observations
|
||||
|
||||
The installed 6.0.0.5232 bundle (SHA-256 in the visual source map) still resolves a variant by splitting its key at the first `//` (`getThemeForIdentifier`, byte 1165264), clears missing selections (`applyUserStyle`, 1164894), and caches installed metadata for 300 seconds unless forced (`refreshAvailableUserStyles`, 1165673). Its picker sorts variant names by JavaScript string order (getter following byte 4625402). The Windows Slint picker uses the same UTF-16 ordering; its rendered selection test includes variants declared in reverse order. The official client installs a stylesheet link, whereas the native client imports only supported values into Slint.
|
||||
|
||||
The installed TS6 6.0.0.5163 `html/client_ui/main.js` (SHA-256 `9d6bea2e…9b82c39`) supplied the original contract:
|
||||
|
||||
- `applyUserStyle` @1369504 inserted the selected stylesheet and reset missing selection to stock.
|
||||
|
||||
+2
-2
@@ -15,8 +15,8 @@ path = "src/lib.rs"
|
||||
# Native capture uses sonora AEC3, noise suppression and adaptive AGC2 together.
|
||||
# The standalone noise-only behavioral reference is compiled only for Rust tests.
|
||||
[dependencies]
|
||||
sonora.workspace = true
|
||||
sonora = "=0.2.0"
|
||||
|
||||
[dev-dependencies]
|
||||
sonora-ns.workspace = true
|
||||
sonora-ns = "=0.2.0"
|
||||
|
||||
+1
-5
@@ -3,9 +3,6 @@
|
||||
//! Sonora owns the split/filter/synthesis path. Never put 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.
|
||||
//! Both PCM boundaries use normalized `f32` in [-1, 1]. Sonora's `AudioBuffer`
|
||||
//! handles conversion to and from FloatS16 internally; scaling by 32768 at the
|
||||
//! wrapper boundary would double-convert and saturate ordinary microphone PCM.
|
||||
//!
|
||||
//! Sonora's integrated NS also enables its split-band high-pass filter. The test-only
|
||||
//! noise-only reference does not; waveform equivalence to that wrapper is not promised.
|
||||
@@ -27,7 +24,6 @@ pub struct CaptureSettings {
|
||||
/// `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.
|
||||
/// Uses Sonora's speech- and noise-aware gain and limiter, without fixed pre-gain.
|
||||
pub automatic_gain_control: bool,
|
||||
}
|
||||
|
||||
@@ -149,7 +145,7 @@ impl CaptureProcessor {
|
||||
})
|
||||
}
|
||||
|
||||
/// Analyze the actual, normalized post-gain playout PCM without modifying it.
|
||||
/// 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.
|
||||
|
||||
@@ -274,185 +274,3 @@ fn invalid_settings_never_construct_a_processor() {
|
||||
}), Err(CaptureError::InvalidNoiseSuppressionLevel(actual)) if actual == level));
|
||||
}
|
||||
}
|
||||
|
||||
fn stage_combinations() -> impl Iterator<Item = CaptureSettings> {
|
||||
[false, true].into_iter().flat_map(|echo_cancellation| {
|
||||
[None, Some(0), Some(1), Some(2), Some(3)].into_iter().flat_map(move |noise_suppression| {
|
||||
[false, true].into_iter().map(move |automatic_gain_control| CaptureSettings {
|
||||
echo_cancellation,
|
||||
noise_suppression,
|
||||
automatic_gain_control,
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalized_float_matches_integer_sonora_at_every_enabled_stage_boundary() {
|
||||
// Sonora's mono i16 path widens samples directly to FloatS16. Use matching
|
||||
// integer and normalized float inputs to detect missing or double scaling.
|
||||
const PCM16_SCALE: f32 = 32768.0;
|
||||
const DELAY_MS: i32 = 20;
|
||||
let quantize = |sample: f32| (sample * PCM16_SCALE).round() as i16;
|
||||
let normalize = |sample: i16| f32::from(sample) / PCM16_SCALE;
|
||||
for settings in stage_combinations() {
|
||||
let mut processor = CaptureProcessor::new(settings).unwrap();
|
||||
let stream = StreamConfig::new(48_000, 1);
|
||||
let mut integer = AudioProcessing::builder()
|
||||
.config(configuration(settings).unwrap())
|
||||
.capture_config(stream)
|
||||
.render_config(stream)
|
||||
.build();
|
||||
let mut seed = 0x71ab_2309;
|
||||
let mut render_history = [[0_i16; FRAME_SAMPLES]; 2];
|
||||
let mut render_output = [0_i16; FRAME_SAMPLES];
|
||||
let mut expected = [0_i16; FRAME_SAMPLES];
|
||||
let mut output_energy = 0.0;
|
||||
for frame in 0..120 {
|
||||
let render = if frame < 90 { noise(&mut seed, 0.15).map(quantize) } else { [0; FRAME_SAMPLES] };
|
||||
let delayed_render = &mut render_history[frame % 2];
|
||||
let input = match frame {
|
||||
0..=9 | 90..=119 => [0; FRAME_SAMPLES],
|
||||
10..=39 => harmonic(frame, 0.002).map(quantize),
|
||||
40..=69 => {
|
||||
// A matching echo 20 ms later makes reverse scaling observable in capture.
|
||||
let voice = harmonic(frame, 0.08);
|
||||
std::array::from_fn(|index| quantize(voice[index] + 0.5 * normalize(delayed_render[index])))
|
||||
}
|
||||
70..=79 => std::array::from_fn(|index| if index % 2 == 0 { i16::MAX } else { i16::MIN }),
|
||||
_ => [512; FRAME_SAMPLES],
|
||||
};
|
||||
*delayed_render = render;
|
||||
let mut actual = input.map(normalize);
|
||||
processor.process_render(&render.map(normalize), DELAY_MS).unwrap();
|
||||
integer.set_stream_delay_ms(DELAY_MS).unwrap();
|
||||
integer.process_render_i16(&render, &mut render_output).unwrap();
|
||||
processor.process_capture(&mut actual).unwrap();
|
||||
integer.process_capture_i16(&input, &mut expected).unwrap();
|
||||
assert_normalized(&actual);
|
||||
for (index, (&actual, &expected)) in actual.iter().zip(&expected).enumerate() {
|
||||
// The integer result rounds and saturates at +32767, not +32768.
|
||||
assert!(
|
||||
(actual * PCM16_SCALE - f32::from(expected)).abs() <= 1.0,
|
||||
"float/i16 scale mismatch: {settings:?}, frame {frame}, sample {index}: {actual} vs {expected}"
|
||||
);
|
||||
}
|
||||
output_energy += energy(&actual);
|
||||
}
|
||||
assert!(output_energy > 0.001, "pipeline discarded the entire probe: {settings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_and_sustained_silence_do_not_generate_audio_in_any_stage_combination() {
|
||||
for settings in stage_combinations() {
|
||||
let mut processor = CaptureProcessor::new(settings).unwrap();
|
||||
// Cross the AGC VAD's 1.5 s reset period as well as startup.
|
||||
for frame in 0..200 {
|
||||
processor.process_render(&[0.0; FRAME_SAMPLES], 0).unwrap();
|
||||
let mut silence = [0.0; FRAME_SAMPLES];
|
||||
processor.process_capture(&mut silence).unwrap();
|
||||
assert!(silence.iter().all(|&sample| sample == 0.0), "generated audio: {settings:?}, frame {frame}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agc_does_not_wind_up_in_silence_and_quiet_onset_does_not_clip() {
|
||||
let settings = CaptureSettings { automatic_gain_control: true, ..BYPASS };
|
||||
for silent_frames in [0, 1200] {
|
||||
let mut processor = CaptureProcessor::new(settings).unwrap();
|
||||
for frame in 0..silent_frames {
|
||||
let mut silence = [0.0; FRAME_SAMPLES];
|
||||
processor.process_capture(&mut silence).unwrap();
|
||||
assert!(silence.iter().all(|&sample| sample == 0.0), "generated audio before onset: frame {frame}");
|
||||
}
|
||||
let mut input_energy = 0.0;
|
||||
let mut output_energy = 0.0;
|
||||
let mut peak = 0.0_f32;
|
||||
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);
|
||||
peak = samples.iter().fold(peak, |peak, sample| peak.max(sample.abs()));
|
||||
output_energy += energy(&samples);
|
||||
}
|
||||
let gain_db = 10.0 * (output_energy / input_energy).log10();
|
||||
// Sonora starts at 15 dB of adaptive gain and changes it at 6 dB/s.
|
||||
assert!((6.0..18.0).contains(&gain_db), "{silent_frames} silent frames: {gain_db:.2} dB");
|
||||
assert!(peak < 0.05, "quiet onset became loud after {silent_frames} silent frames: {peak}");
|
||||
for frame in 0..50 {
|
||||
let mut silence = [0.0; FRAME_SAMPLES];
|
||||
processor.process_capture(&mut silence).unwrap();
|
||||
assert!(silence.iter().all(|&sample| sample == 0.0), "generated audio after onset: frame {frame}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_scale_impulses_and_polarity_steps_remain_bounded_and_decay_to_silence() {
|
||||
for settings in [
|
||||
CaptureSettings { automatic_gain_control: true, ..BYPASS },
|
||||
CaptureSettings { noise_suppression: Some(1), ..BYPASS },
|
||||
CaptureSettings::default(),
|
||||
] {
|
||||
let mut processor = CaptureProcessor::new(settings).unwrap();
|
||||
let mut transient_energy = 0.0;
|
||||
let mut tail_energy = 0.0;
|
||||
for frame in 0..400 {
|
||||
let mut samples = match frame {
|
||||
0 | 100 => {
|
||||
let mut impulse = [0.0; FRAME_SAMPLES];
|
||||
impulse[0] = if frame == 0 { 1.0 } else { -1.0 };
|
||||
impulse
|
||||
}
|
||||
1..=9 => [1.0; FRAME_SAMPLES],
|
||||
10..=19 => [-1.0; FRAME_SAMPLES],
|
||||
20..=29 => std::array::from_fn(|index| if index % 2 == 0 { 1.0 } else { -1.0 }),
|
||||
_ => [0.0; FRAME_SAMPLES],
|
||||
};
|
||||
processor.process_render(&[0.0; FRAME_SAMPLES], 0).unwrap();
|
||||
processor.process_capture(&mut samples).unwrap();
|
||||
// Full-scale input may engage Sonora's hard limiter. Bounded output
|
||||
// here does not imply the absence of clipping.
|
||||
assert_normalized(&samples);
|
||||
if frame < 120 {
|
||||
transient_energy += energy(&samples);
|
||||
} else if frame >= 300 {
|
||||
tail_energy += energy(&samples);
|
||||
}
|
||||
}
|
||||
assert!(transient_energy > 0.0, "pipeline muted the transient probe: {settings:?}");
|
||||
assert!(tail_energy < 1e-6, "transient persisted in silence: {settings:?}, energy {tail_energy}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integrated_noise_suppression_attenuates_dc_without_rail_clipping() {
|
||||
for level in 0..=3 {
|
||||
let settings = CaptureSettings { noise_suppression: Some(level), ..BYPASS };
|
||||
let mut processor = CaptureProcessor::new(settings).unwrap();
|
||||
let mut tail_energy = 0.0;
|
||||
let mut input_energy = 0.0;
|
||||
for frame in 0..200 {
|
||||
let mut samples = [0.1; FRAME_SAMPLES];
|
||||
if frame >= 150 {
|
||||
input_energy += energy(&samples);
|
||||
}
|
||||
processor.process_capture(&mut samples).unwrap();
|
||||
assert_normalized(&samples);
|
||||
assert!(samples.iter().all(|sample| sample.abs() < 1.0), "DC clipped: level {level}, frame {frame}");
|
||||
if frame >= 150 {
|
||||
tail_energy += energy(&samples);
|
||||
}
|
||||
}
|
||||
// Sonora's split-band HPF has finite DC rejection. Use its upstream
|
||||
// 47.3 dB criterion instead of requiring exact zeros at steady state.
|
||||
let attenuation_db = 10.0 * (input_energy / tail_energy).log10();
|
||||
assert!(
|
||||
attenuation_db >= 47.3,
|
||||
"insufficient integrated HPF/NS DC rejection at level {level}: {attenuation_db:.2} dB"
|
||||
);
|
||||
}
|
||||
}
|
||||
Vendored
+12
-12
@@ -1,29 +1,29 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"upstream_revision": "1632d47c1e77d0857f9145bd175134b348541e11",
|
||||
"upstream_revision": "a024d6ef8351add55be5e8b1d6cc35f555787660",
|
||||
"packages": [
|
||||
{
|
||||
"name": "sonora",
|
||||
"version": "0.3.0",
|
||||
"version": "0.2.0",
|
||||
"registry": "https://crates.io",
|
||||
"archive": "https://static.crates.io/crates/sonora/sonora-0.3.0.crate",
|
||||
"sha256": "d461e6c9ad112f8728919387a4bc5639fd28631f2070171efad38676e907edd8",
|
||||
"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": "Preserve the mono AGC2 stack channel descriptors and direct AudioBuffer::channel_mut(0) processing, avoiding the upstream reusable-buffer copy for mono. Multichannel uses the 0.3.0 reusable owned-buffer pipeline. Retains the mono-vs-identical-stereo signal equivalence test and standalone sonora-agc2 path patch."
|
||||
"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.3.0",
|
||||
"version": "0.2.0",
|
||||
"registry": "https://crates.io",
|
||||
"archive": "https://static.crates.io/crates/sonora-agc2/sonora-agc2-0.3.0.crate",
|
||||
"sha256": "501b5dd3f8bdc8c983dc64a131cef22a429f3ff879d6f0007b8bfe46ec7b96aa",
|
||||
"archive": "https://static.crates.io/crates/sonora-agc2/sonora-agc2-0.2.0.crate",
|
||||
"sha256": "9a93a9fa8373a33e61a7fb441d8a9e725ac6024079d2c77a845cf6abe1790b9f",
|
||||
"path_in_vcs": "crates/sonora-agc2",
|
||||
"modified_sources": [],
|
||||
"patch": "The former mono limiter descriptor-allocation patch is subsumed by upstream 0.3.0: generic channel views pass directly to compute_level_of_channels without collecting a Vec for either mono or multichannel. The public borrowed-slice entry point used by the local sonora mono path remains available."
|
||||
"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": "Official 0.3.0 registry archives, retaining upstream files and licenses; mono behavioral/performance patch rebased rather than dropped. Standalone sonora Cargo manifest and lock retain the local sonora-agc2 path patch.",
|
||||
"verification": "Source migration only. Retained local equivalence test and included upstream release tests; no builds, tests, formatters or cargo update executed by delegated worker. Parent runs verification after integration."
|
||||
"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."
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "1632d47c1e77d0857f9145bd175134b348541e11"
|
||||
"sha1": "a024d6ef8351add55be5e8b1d6cc35f555787660"
|
||||
},
|
||||
"path_in_vcs": "crates/sonora-agc2"
|
||||
}
|
||||
+109
-213
@@ -10,52 +10,24 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.11.1"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"
|
||||
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
|
||||
dependencies = [
|
||||
"bit-vec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-vec"
|
||||
version = "0.10.1"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269"
|
||||
dependencies = [
|
||||
"borsh",
|
||||
"serde",
|
||||
]
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
version = "2.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "borsh"
|
||||
version = "1.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
|
||||
dependencies = [
|
||||
"borsh-derive",
|
||||
"bytes",
|
||||
"cfg_aliases",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "borsh-derive"
|
||||
version = "1.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
@@ -68,55 +40,26 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck_derive"
|
||||
version = "1.12.1"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
|
||||
checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
|
||||
|
||||
[[package]]
|
||||
name = "chacha20"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core_detect"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
|
||||
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
@@ -130,7 +73,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta",
|
||||
"syn 2.0.119",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -151,16 +94,10 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rustc_version",
|
||||
"syn 2.0.119",
|
||||
"syn",
|
||||
"unicode-xid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
@@ -183,6 +120,18 @@ 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"
|
||||
@@ -191,31 +140,14 @@ checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
"r-efi 6.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
version = "0.2.189"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
@@ -223,12 +155,6 @@ version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -251,12 +177,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-crate"
|
||||
version = "3.5.0"
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"toml_edit",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -270,17 +196,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "proptest"
|
||||
version = "1.12.0"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
|
||||
checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"bit-vec",
|
||||
"bitflags",
|
||||
"chacha20",
|
||||
"core_detect",
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand_chacha",
|
||||
"rand_xorshift",
|
||||
"regex-syntax",
|
||||
"rusty-fork",
|
||||
@@ -303,6 +228,12 @@ 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"
|
||||
@@ -311,25 +242,38 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.3"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"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.10.1"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_xorshift"
|
||||
version = "0.5.0"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
|
||||
checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
|
||||
dependencies = [
|
||||
"rand_core",
|
||||
]
|
||||
@@ -351,9 +295,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.6"
|
||||
version = "1.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
@@ -380,39 +324,9 @@ version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-agc2"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"derive_more",
|
||||
@@ -426,9 +340,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-common-audio"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c05dfa300c14dc8498751ce2c5b87aad2acf1892d4f9d66b92ae2f372a83410"
|
||||
checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc"
|
||||
dependencies = [
|
||||
"derive_more",
|
||||
"sonora-simd",
|
||||
@@ -436,18 +350,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-fft"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec3529f2cf748f1acc85d9403ffa08a3fe69dec6bf22383910b3bd21aca2fd26"
|
||||
dependencies = [
|
||||
"sonora-simd",
|
||||
]
|
||||
checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012"
|
||||
|
||||
[[package]]
|
||||
name = "sonora-simd"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f939d8e63a2a0baa7555294d7b09c5e3d382f28358755b920e13ad527658c8fa"
|
||||
checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
]
|
||||
@@ -461,7 +372,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta-derive",
|
||||
"syn 2.0.119",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -472,7 +383,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -486,17 +397,6 @@ dependencies = [
|
||||
"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 = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -504,7 +404,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys",
|
||||
@@ -520,37 +420,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_edit"
|
||||
version = "0.25.19+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"toml_datetime",
|
||||
"toml_parser",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
|
||||
dependencies = [
|
||||
"winnow",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -572,7 +442,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -592,9 +462,9 @@ checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
@@ -611,6 +481,15 @@ 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"
|
||||
@@ -627,10 +506,27 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.5"
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
|
||||
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"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",
|
||||
]
|
||||
Vendored
+4
-8
@@ -13,7 +13,7 @@
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
name = "sonora-agc2"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
@@ -37,10 +37,6 @@ repository = "https://github.com/dignifiedquire/sonora"
|
||||
name = "sonora_agc2"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[test]]
|
||||
name = "published_signatures"
|
||||
path = "tests/published_signatures.rs"
|
||||
|
||||
[dependencies.bytemuck]
|
||||
version = "1"
|
||||
features = ["derive"]
|
||||
@@ -50,13 +46,13 @@ version = "2"
|
||||
features = ["debug"]
|
||||
|
||||
[dependencies.sonora-common-audio]
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-fft]
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-simd]
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.tracing]
|
||||
version = "0.1"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sonora-agc2"
|
||||
version = "0.3.0"
|
||||
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"]
|
||||
|
||||
@@ -122,19 +122,6 @@ impl AdaptiveDigitalGainController {
|
||||
|
||||
/// 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]]) {
|
||||
self.process_channels(info, frame);
|
||||
}
|
||||
|
||||
/// Analyzes `info`, updates the digital gain and applies it to a frame in owned buffers.
|
||||
pub fn process_owned_frame(&mut self, info: &FrameInfo, frame: &mut [Vec<f32>]) {
|
||||
self.process_channels(info, frame);
|
||||
}
|
||||
|
||||
fn process_channels<C: AsRef<[f32]> + AsMut<[f32]>>(
|
||||
&mut self,
|
||||
info: &FrameInfo,
|
||||
frame: &mut [C],
|
||||
) {
|
||||
debug_assert!(info.speech_level_dbfs >= -150.0);
|
||||
debug_assert!(!frame.is_empty());
|
||||
|
||||
@@ -187,7 +174,7 @@ impl AdaptiveDigitalGainController {
|
||||
.set_gain_factor(db_to_ratio(self.last_gain_db + gain_change_this_frame_db));
|
||||
}
|
||||
|
||||
self.gain_applier.apply_gain_to_channels(frame);
|
||||
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;
|
||||
|
||||
@@ -45,22 +45,14 @@ impl FixedDigitalLevelEstimator {
|
||||
/// 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] {
|
||||
self.compute_level_of_channels(frame)
|
||||
}
|
||||
|
||||
pub(crate) fn compute_level_of_channels<C: AsRef<[f32]>>(
|
||||
&mut self,
|
||||
frame: &[C],
|
||||
) -> [f32; SUB_FRAMES_IN_FRAME as usize] {
|
||||
let num_channels = frame.len();
|
||||
debug_assert!(num_channels > 0);
|
||||
debug_assert_eq!(frame[0].as_ref().len(), self.samples_in_frame as usize);
|
||||
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 {
|
||||
let channel = channel.as_ref();
|
||||
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];
|
||||
|
||||
+7
-19
@@ -12,20 +12,20 @@ fn gain_close_to_one(gain_factor: f32) -> bool {
|
||||
}
|
||||
|
||||
/// Clamps all samples in multi-channel signal to FloatS16 range.
|
||||
fn clip_signal<C: AsMut<[f32]>>(signal: &mut [C]) {
|
||||
fn clip_signal(signal: &mut [&mut [f32]]) {
|
||||
for channel in signal.iter_mut() {
|
||||
for sample in channel.as_mut().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<C: AsMut<[f32]>>(
|
||||
fn apply_gain_with_ramping(
|
||||
last_gain: f32,
|
||||
gain_at_end: f32,
|
||||
inverse_samples_per_channel: f32,
|
||||
signal: &mut [C],
|
||||
signal: &mut [&mut [f32]],
|
||||
) {
|
||||
// Do not modify the signal.
|
||||
if last_gain == gain_at_end && gain_close_to_one(gain_at_end) {
|
||||
@@ -35,7 +35,7 @@ fn apply_gain_with_ramping<C: AsMut<[f32]>>(
|
||||
// Gain is constant and different from 1.
|
||||
if last_gain == gain_at_end {
|
||||
for channel in signal.iter_mut() {
|
||||
for sample in channel.as_mut().iter_mut() {
|
||||
for sample in channel.iter_mut() {
|
||||
*sample *= gain_at_end;
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ fn apply_gain_with_ramping<C: AsMut<[f32]>>(
|
||||
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.as_mut().iter_mut() {
|
||||
for sample in channel.iter_mut() {
|
||||
*sample *= gain;
|
||||
gain += increment;
|
||||
}
|
||||
@@ -81,19 +81,7 @@ impl GainApplier {
|
||||
|
||||
/// Applies gain to the signal with linear ramping between frames.
|
||||
pub fn apply_gain(&mut self, signal: &mut [&mut [f32]]) {
|
||||
self.apply_gain_to_channels(signal);
|
||||
}
|
||||
|
||||
/// Applies gain to a signal in owned buffers with linear ramping between frames.
|
||||
pub fn apply_gain_to_owned_signal(&mut self, signal: &mut [Vec<f32>]) {
|
||||
self.apply_gain_to_channels(signal);
|
||||
}
|
||||
|
||||
pub(crate) fn apply_gain_to_channels<C: AsRef<[f32]> + AsMut<[f32]>>(
|
||||
&mut self,
|
||||
signal: &mut [C],
|
||||
) {
|
||||
let spc = signal.first().map_or(0, |ch| ch.as_ref().len()) as i32;
|
||||
let spc = signal.first().map_or(0, |ch| ch.len()) as i32;
|
||||
if spc != self.samples_per_channel {
|
||||
self.initialize(spc);
|
||||
}
|
||||
|
||||
+11
-17
@@ -53,14 +53,11 @@ fn compute_per_sample_subframe_factors(
|
||||
}
|
||||
}
|
||||
|
||||
fn scale_samples<C: AsRef<[f32]> + AsMut<[f32]>>(
|
||||
per_sample_scaling_factors: &[f32],
|
||||
signal: &mut [C],
|
||||
) {
|
||||
let samples_per_channel = signal.first().map_or(0, |ch| ch.as_ref().len());
|
||||
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.as_mut().iter_mut().zip(per_sample_scaling_factors) {
|
||||
for (sample, &factor) in channel.iter_mut().zip(per_sample_scaling_factors) {
|
||||
*sample = (*sample * factor).clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
}
|
||||
}
|
||||
@@ -94,19 +91,16 @@ impl Limiter {
|
||||
|
||||
/// Applies limiter and hard-clipping to the signal.
|
||||
pub fn process(&mut self, signal: &mut [&mut [f32]]) {
|
||||
self.process_channels(signal);
|
||||
}
|
||||
|
||||
/// Applies limiter and hard-clipping to a signal in owned buffers.
|
||||
pub fn process_owned_signal(&mut self, signal: &mut [Vec<f32>]) {
|
||||
self.process_channels(signal);
|
||||
}
|
||||
|
||||
fn process_channels<C: AsRef<[f32]> + AsMut<[f32]>>(&mut self, signal: &mut [C]) {
|
||||
let samples_per_channel = signal.first().map_or(0, |ch| ch.as_ref().len());
|
||||
let samples_per_channel = signal.first().map_or(0, |ch| ch.len());
|
||||
debug_assert!(samples_per_channel <= MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL);
|
||||
|
||||
let level_estimate = self.level_estimator.compute_level_of_channels(signal);
|
||||
// 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;
|
||||
|
||||
+3
-12
@@ -7,10 +7,10 @@ const FRAMES_PER_SECOND: i32 = 100;
|
||||
/// Update the noise floor every 5 seconds.
|
||||
const UPDATE_PERIOD_NUM_FRAMES: i32 = 500;
|
||||
|
||||
fn frame_energy<C: AsRef<[f32]>>(audio: &[C]) -> f32 {
|
||||
fn frame_energy(audio: &[&[f32]]) -> f32 {
|
||||
let mut energy = 0.0_f32;
|
||||
for channel in audio {
|
||||
let channel_energy: f32 = channel.as_ref().iter().map(|&s| s * s).sum();
|
||||
let channel_energy: f32 = channel.iter().map(|&s| s * s).sum();
|
||||
energy = energy.max(channel_energy);
|
||||
}
|
||||
energy
|
||||
@@ -76,17 +76,8 @@ 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 {
|
||||
self.analyze_channels(frame)
|
||||
}
|
||||
|
||||
/// Analyzes a 10 ms frame in owned buffers, like [`Self::analyze`].
|
||||
pub fn analyze_owned_frame(&mut self, frame: &[Vec<f32>]) -> f32 {
|
||||
self.analyze_channels(frame)
|
||||
}
|
||||
|
||||
fn analyze_channels<C: AsRef<[f32]>>(&mut self, frame: &[C]) -> f32 {
|
||||
debug_assert!(!frame.is_empty());
|
||||
let samples_per_channel = frame[0].as_ref().len();
|
||||
let samples_per_channel = frame[0].len();
|
||||
|
||||
// Detect sample rate changes.
|
||||
let sample_rate_hz = samples_per_channel as i32 * FRAMES_PER_SECOND;
|
||||
|
||||
+2
-4
@@ -101,10 +101,8 @@ mod tests {
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes).unwrap();
|
||||
bytes
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| f32::from_le_bytes(*c))
|
||||
.chunks_exact(4)
|
||||
.map(|c| f32::from_le_bytes(c.try_into().unwrap()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -540,10 +540,8 @@ mod tests {
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes).unwrap();
|
||||
let floats: Vec<f32> = bytes
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| f32::from_le_bytes(*c))
|
||||
.chunks_exact(4)
|
||||
.map(|c| f32::from_le_bytes(c.try_into().unwrap()))
|
||||
.collect();
|
||||
|
||||
let mut offset = 0;
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
//! Checks that methods keep the signatures they had in sonora-agc2 0.2.0.
|
||||
|
||||
use sonora_agc2::adaptive_digital_gain_controller::{AdaptiveDigitalGainController, FrameInfo};
|
||||
use sonora_agc2::common::SUB_FRAMES_IN_FRAME;
|
||||
use sonora_agc2::fixed_digital_level_estimator::FixedDigitalLevelEstimator;
|
||||
use sonora_agc2::gain_applier::GainApplier;
|
||||
use sonora_agc2::limiter::Limiter;
|
||||
use sonora_agc2::noise_level_estimator::NoiseLevelEstimator;
|
||||
|
||||
// Generic signatures break 0.2.0 callers that take a function pointer, pass
|
||||
// an empty slice or mix buffer types in one slice literal.
|
||||
#[test]
|
||||
fn methods_keep_published_signatures() {
|
||||
let _: fn(&mut AdaptiveDigitalGainController, &FrameInfo, &mut [&mut [f32]]) =
|
||||
AdaptiveDigitalGainController::process;
|
||||
let _: fn(&mut FixedDigitalLevelEstimator, &[&[f32]]) -> [f32; SUB_FRAMES_IN_FRAME as usize] =
|
||||
FixedDigitalLevelEstimator::compute_level;
|
||||
let _: fn(&mut GainApplier, &mut [&mut [f32]]) = GainApplier::apply_gain;
|
||||
let _: fn(&mut Limiter, &mut [&mut [f32]]) = Limiter::process;
|
||||
let _: fn(&mut NoiseLevelEstimator, &[&[f32]]) -> f32 = NoiseLevelEstimator::analyze;
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "1632d47c1e77d0857f9145bd175134b348541e11"
|
||||
"sha1": "a024d6ef8351add55be5e8b1d6cc35f555787660"
|
||||
},
|
||||
"path_in_vcs": "crates/sonora"
|
||||
}
|
||||
+118
-120
@@ -4,9 +4,9 @@ version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
version = "1.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
@@ -112,9 +112,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
version = "2.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
@@ -142,13 +142,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck_derive"
|
||||
version = "1.12.1"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
|
||||
checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -165,9 +165,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.11.1"
|
||||
version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155"
|
||||
checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
@@ -175,9 +175,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
@@ -214,9 +214,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.7"
|
||||
version = "4.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
checksum = "d91e0c145792ef73a6ad36d27c75ac09f1832222a3c209689d90f534685ee5b7"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@@ -224,9 +224,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
version = "4.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
checksum = "f09628afdcc538b57f3c6341e9c8e9970f18e4a481690a64974d7023bd33548b"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -236,21 +236,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.7"
|
||||
version = "4.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
|
||||
checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.1"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
|
||||
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
@@ -260,9 +260,9 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.9"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"
|
||||
checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"memchr",
|
||||
@@ -284,9 +284,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cpal"
|
||||
version = "0.18.2"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1"
|
||||
checksum = "5f77b11176c37874be37e8d691c946e31b2b8c357abce9526f6a99eb469e1028"
|
||||
dependencies = [
|
||||
"alsa",
|
||||
"block2",
|
||||
@@ -314,9 +314,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
|
||||
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
@@ -358,9 +358,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.8"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
|
||||
checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"
|
||||
dependencies = [
|
||||
"crossbeam-epoch",
|
||||
"crossbeam-utils",
|
||||
@@ -368,18 +368,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-epoch"
|
||||
version = "0.9.21"
|
||||
version = "0.9.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
|
||||
checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.23"
|
||||
version = "0.8.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
|
||||
|
||||
[[package]]
|
||||
name = "crunchy"
|
||||
@@ -440,39 +440,39 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
version = "1.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.15"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
version = "0.3.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||
checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.34"
|
||||
version = "0.3.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||
checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.34"
|
||||
version = "0.3.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
@@ -511,9 +511,9 @@ checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
version = "2.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
@@ -552,7 +552,7 @@ dependencies = [
|
||||
"jni-sys 0.4.1",
|
||||
"log",
|
||||
"simd_cesu8",
|
||||
"thiserror 2.0.21",
|
||||
"thiserror 2.0.19",
|
||||
"walkdir",
|
||||
"windows-link",
|
||||
]
|
||||
@@ -600,9 +600,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.107"
|
||||
version = "0.3.103"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
|
||||
checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-util",
|
||||
@@ -611,21 +611,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.1"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
version = "0.2.189"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.35"
|
||||
version = "0.4.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "mach2"
|
||||
@@ -742,9 +742,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
|
||||
checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
|
||||
dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
@@ -866,9 +866,9 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
version = "0.3.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
|
||||
|
||||
[[package]]
|
||||
name = "plotters"
|
||||
@@ -900,15 +900,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.15.0"
|
||||
version = "1.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
|
||||
checksum = "3d20d5497ef88037a52ff98267d066e7f11fcc5e99bbfbd58a42336193aacec3"
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic-util"
|
||||
version = "0.2.8"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
|
||||
checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"
|
||||
dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
@@ -974,9 +974,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
version = "0.4.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
@@ -991,9 +991,9 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "ringbuf"
|
||||
version = "0.5.3"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b58b631e416dd7d84549d7e6a50f767e111f9b03e30d04f40072f6618f386aaf"
|
||||
checksum = "a158e09ede21a14b172ca6cdd6208386c6ae2cb6acef58d774368ef8c450dfa7"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
"portable-atomic",
|
||||
@@ -1057,14 +1057,14 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
version = "1.0.151"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
@@ -1112,13 +1112,13 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.16.4"
|
||||
version = "1.15.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
|
||||
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
|
||||
|
||||
[[package]]
|
||||
name = "sonora"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -1139,9 +1139,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-aec3"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2809c3fda13f71deac22d0ddb6c02c493f254d3da2afe59a7e256a8f15bcffe"
|
||||
checksum = "50280e31256d09f7838aff6715ed4b7640e514dc1092a1e14013c01e552380db"
|
||||
dependencies = [
|
||||
"sonora-common-audio",
|
||||
"sonora-fft",
|
||||
@@ -1150,7 +1150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-agc2"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"derive_more",
|
||||
@@ -1162,9 +1162,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-common-audio"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c05dfa300c14dc8498751ce2c5b87aad2acf1892d4f9d66b92ae2f372a83410"
|
||||
checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc"
|
||||
dependencies = [
|
||||
"derive_more",
|
||||
"sonora-simd",
|
||||
@@ -1172,27 +1172,24 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-fft"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec3529f2cf748f1acc85d9403ffa08a3fe69dec6bf22383910b3bd21aca2fd26"
|
||||
dependencies = [
|
||||
"sonora-simd",
|
||||
]
|
||||
checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012"
|
||||
|
||||
[[package]]
|
||||
name = "sonora-ns"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "31c0a62e78419a174dbf9c9c01943c1ecd8c298a68d15c4fb4906cb19f0428b9"
|
||||
checksum = "d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f"
|
||||
dependencies = [
|
||||
"sonora-fft",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-simd"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f939d8e63a2a0baa7555294d7b09c5e3d382f28358755b920e13ad527658c8fa"
|
||||
checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
]
|
||||
@@ -1216,9 +1213,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
version = "3.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -1236,11 +1233,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
version = "2.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"
|
||||
dependencies = [
|
||||
"thiserror-impl 2.0.21",
|
||||
"thiserror-impl 2.0.19",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1256,13 +1253,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
version = "2.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1286,18 +1283,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
version = "1.1.1+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
|
||||
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_edit"
|
||||
version = "0.25.19+spec-1.1.0"
|
||||
version = "0.25.13+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218"
|
||||
checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"toml_datetime",
|
||||
@@ -1307,9 +1304,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.5+spec-1.1.0"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
|
||||
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
|
||||
dependencies = [
|
||||
"winnow",
|
||||
]
|
||||
@@ -1377,9 +1374,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
@@ -1411,11 +1408,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.130"
|
||||
version = "0.2.126"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
|
||||
checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"rustversion",
|
||||
"wasm-bindgen-macro",
|
||||
"wasm-bindgen-shared",
|
||||
@@ -1423,9 +1421,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.130"
|
||||
version = "0.2.126"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
|
||||
checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
@@ -1433,31 +1431,31 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.130"
|
||||
version = "0.2.126"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
|
||||
checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"syn 2.0.119",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.130"
|
||||
version = "0.2.126"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
|
||||
checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-sys"
|
||||
version = "0.3.107"
|
||||
version = "0.3.103"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"
|
||||
checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
@@ -1615,27 +1613,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.5"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
|
||||
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.63"
|
||||
version = "0.8.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
|
||||
checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.63"
|
||||
version = "0.8.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
|
||||
checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
||||
Vendored
+7
-15
@@ -13,7 +13,7 @@
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
name = "sonora"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
@@ -61,14 +61,6 @@ required-features = ["examples"]
|
||||
name = "simple"
|
||||
path = "examples/simple.rs"
|
||||
|
||||
[[test]]
|
||||
name = "echo_canceller3_config"
|
||||
path = "tests/echo_canceller3_config.rs"
|
||||
|
||||
[[test]]
|
||||
name = "no_allocation"
|
||||
path = "tests/no_allocation.rs"
|
||||
|
||||
[[bench]]
|
||||
name = "pipeline"
|
||||
path = "benches/pipeline.rs"
|
||||
@@ -101,19 +93,19 @@ version = "0.5"
|
||||
optional = true
|
||||
|
||||
[dependencies.sonora-aec3]
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-agc2]
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-common-audio]
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-ns]
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.sonora-simd]
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies.tracing]
|
||||
version = "0.1"
|
||||
@@ -123,7 +115,7 @@ version = "0.8"
|
||||
features = ["html_reports"]
|
||||
|
||||
[dev-dependencies.sonora-fft]
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
|
||||
[dev-dependencies.tracing-subscriber]
|
||||
version = "0.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sonora"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
description = "WebRTC Audio Processing — pure Rust port with echo cancellation, noise suppression, and AGC"
|
||||
keywords = ["audio", "webrtc", "echo-cancellation", "noise-suppression", "agc"]
|
||||
categories = ["multimedia::audio"]
|
||||
|
||||
-64
@@ -111,69 +111,6 @@ fn bench_process_stream(c: &mut Criterion) {
|
||||
group.finish();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Issue #34: AEC3 with a silent render reference
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Render+capture pair cost with an active and with an exact-zero render
|
||||
/// reference. Without hardware flush-to-zero the recursive filters settle in
|
||||
/// the subnormal range once render goes silent and stay there, which costs a
|
||||
/// microcode assist per operation on x86 (10-50x per the report). The
|
||||
/// silent/active ratio is the figure to watch; it should stay near 1.
|
||||
fn bench_aec3_silent_render(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("aec3_render");
|
||||
let stream = StreamConfig::new(48000, 1);
|
||||
let n = stream.num_frames();
|
||||
let speech: Vec<f32> = (0..n).map(|i| (i as f32 * 0.01).sin() * 0.1).collect();
|
||||
let echo: Vec<f32> = speech.iter().map(|x| 0.5 * x).collect();
|
||||
let silence = vec![0.0f32; n];
|
||||
// About -60 dBFS deterministic noise on the capture side.
|
||||
let noise: Vec<f32> = (0..n)
|
||||
.map(|i| ((i * 7919 % 101) as f32 / 101.0 - 0.5) * 2e-3)
|
||||
.collect();
|
||||
let mut out = vec![0.0f32; n];
|
||||
let mut render_out = vec![0.0f32; n];
|
||||
|
||||
for (name, render, capture) in [
|
||||
("48k_mono_active", &speech, &echo),
|
||||
("48k_mono_silent", &silence, &noise),
|
||||
] {
|
||||
let config = Config {
|
||||
echo_canceller: Some(EchoCanceller::default()),
|
||||
..Default::default()
|
||||
};
|
||||
let mut apm = AudioProcessing::builder()
|
||||
.config(config)
|
||||
.capture_config(stream)
|
||||
.render_config(stream)
|
||||
.build();
|
||||
// 1 s with active render and echo, then 6 s of the measured
|
||||
// condition so the filter states have settled before timing. Without
|
||||
// flush-to-zero, the slowest state (the low-render detector's average
|
||||
// power) turns subnormal about 4 s into the silent condition.
|
||||
for _ in 0..100 {
|
||||
apm.process_render_f32(&[&speech], &mut [&mut render_out])
|
||||
.unwrap();
|
||||
apm.process_capture_f32(&[&echo], &mut [&mut out]).unwrap();
|
||||
}
|
||||
for _ in 0..600 {
|
||||
apm.process_render_f32(&[render], &mut [&mut render_out])
|
||||
.unwrap();
|
||||
apm.process_capture_f32(&[capture], &mut [&mut out])
|
||||
.unwrap();
|
||||
}
|
||||
group.bench_function(name, |b| {
|
||||
b.iter(|| {
|
||||
apm.process_render_f32(&[black_box(render)], &mut [&mut render_out])
|
||||
.unwrap();
|
||||
apm.process_capture_f32(&[black_box(capture)], &mut [&mut out])
|
||||
.unwrap();
|
||||
});
|
||||
});
|
||||
}
|
||||
group.finish();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Component benchmarks
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -267,7 +204,6 @@ fn bench_sinc_resampler(c: &mut Criterion) {
|
||||
criterion_group!(
|
||||
benches,
|
||||
bench_process_stream,
|
||||
bench_aec3_silent_render,
|
||||
bench_noise_suppressor,
|
||||
bench_pffft,
|
||||
bench_sinc_resampler,
|
||||
|
||||
+26
-27
@@ -43,10 +43,6 @@ pub(crate) struct AudioBuffer {
|
||||
output_resamplers: Vec<PushSincResampler>,
|
||||
downmix_by_averaging: bool,
|
||||
channel_for_downmixing: usize,
|
||||
/// Working buffer for downmixing and sample format conversion in the
|
||||
/// `copy_*` methods. It is sized at construction for the longer of the
|
||||
/// input and output frames so that processing a frame does not allocate.
|
||||
scratch: Vec<f32>,
|
||||
}
|
||||
|
||||
impl AudioBuffer {
|
||||
@@ -124,7 +120,6 @@ impl AudioBuffer {
|
||||
output_resamplers,
|
||||
downmix_by_averaging: true,
|
||||
channel_for_downmixing: 0,
|
||||
scratch: vec![0.0; input_num_frames.max(output_num_frames)],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,8 +227,9 @@ impl AudioBuffer {
|
||||
let resampling_needed = self.input_num_frames != self.buffer_num_frames;
|
||||
|
||||
if downmix_needed {
|
||||
let downmixed_data: &[f32] = if self.downmix_by_averaging {
|
||||
let downmix = &mut self.scratch[..self.input_num_frames];
|
||||
let mut downmix = vec![0.0f32; self.input_num_frames];
|
||||
|
||||
if self.downmix_by_averaging {
|
||||
let scale = 1.0 / self.input_num_channels as f32;
|
||||
for (i, d) in downmix.iter_mut().enumerate() {
|
||||
let mut value = stacked_data[0][i];
|
||||
@@ -242,7 +238,14 @@ impl AudioBuffer {
|
||||
}
|
||||
*d = value * scale;
|
||||
}
|
||||
downmix
|
||||
} else {
|
||||
downmix.copy_from_slice(
|
||||
&stacked_data[self.channel_for_downmixing][..self.input_num_frames],
|
||||
);
|
||||
}
|
||||
|
||||
let downmixed_data = if self.downmix_by_averaging {
|
||||
&downmix
|
||||
} else {
|
||||
&stacked_data[self.channel_for_downmixing][..self.input_num_frames]
|
||||
};
|
||||
@@ -315,14 +318,10 @@ impl AudioBuffer {
|
||||
let buf_frames = buffer.num_frames();
|
||||
if resampling_needed {
|
||||
for i in 0..self.num_channels {
|
||||
// Resample straight into the destination channel instead of a
|
||||
// temporary vector, so this real-time path does not allocate.
|
||||
// This fills the whole destination only because the resampler
|
||||
// produces exactly `buf_frames` samples per call.
|
||||
let src = self.data.bands(i);
|
||||
let written = self.output_resamplers[i]
|
||||
.resample(src, &mut buffer.channel_mut(i)[..buf_frames]);
|
||||
debug_assert_eq!(written, buf_frames);
|
||||
let mut temp = vec![0.0f32; buf_frames];
|
||||
self.output_resamplers[i].resample(src, &mut temp);
|
||||
buffer.channel_mut(i)[..buf_frames].copy_from_slice(&temp);
|
||||
}
|
||||
} else {
|
||||
for i in 0..self.num_channels {
|
||||
@@ -363,13 +362,13 @@ impl AudioBuffer {
|
||||
if self.input_num_channels == 1 {
|
||||
// Mono to mono.
|
||||
if resampling_required {
|
||||
let float_buffer = &mut self.scratch[..self.input_num_frames];
|
||||
let mut float_buffer = vec![0.0f32; self.input_num_frames];
|
||||
audio_util::s16_to_float_s16_slice(
|
||||
&interleaved_data[..self.input_num_frames],
|
||||
float_buffer,
|
||||
&mut float_buffer,
|
||||
);
|
||||
let ch0 = self.data.bands_mut(0);
|
||||
self.input_resamplers[0].resample(float_buffer, ch0);
|
||||
self.input_resamplers[0].resample(&float_buffer, ch0);
|
||||
} else {
|
||||
let ch0 = self.data.bands_mut(0);
|
||||
audio_util::s16_to_float_s16_slice(
|
||||
@@ -379,7 +378,7 @@ impl AudioBuffer {
|
||||
}
|
||||
} else {
|
||||
// Multi-channel to mono (downmix).
|
||||
let downmixed = &mut self.scratch[..self.input_num_frames];
|
||||
let mut downmixed = vec![0.0f32; self.input_num_frames];
|
||||
|
||||
if self.downmix_by_averaging {
|
||||
for (j, sample) in downmixed.iter_mut().enumerate().take(self.input_num_frames)
|
||||
@@ -400,15 +399,15 @@ impl AudioBuffer {
|
||||
|
||||
if resampling_required {
|
||||
let ch0 = self.data.bands_mut(0);
|
||||
self.input_resamplers[0].resample(downmixed, ch0);
|
||||
self.input_resamplers[0].resample(&downmixed, ch0);
|
||||
} else {
|
||||
self.data.bands_mut(0)[..self.input_num_frames].copy_from_slice(downmixed);
|
||||
self.data.bands_mut(0)[..self.input_num_frames].copy_from_slice(&downmixed);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Multi-channel, deinterleave.
|
||||
if resampling_required {
|
||||
let float_buffer = &mut self.scratch[..self.input_num_frames];
|
||||
let mut float_buffer = vec![0.0f32; self.input_num_frames];
|
||||
for i in 0..self.num_channels {
|
||||
// Deinterleave channel i.
|
||||
for (j, sample) in float_buffer
|
||||
@@ -419,7 +418,7 @@ impl AudioBuffer {
|
||||
*sample = interleaved_data[j * self.input_num_channels + i] as f32;
|
||||
}
|
||||
let ch = self.data.bands_mut(i);
|
||||
self.input_resamplers[i].resample(float_buffer, ch);
|
||||
self.input_resamplers[i].resample(&float_buffer, ch);
|
||||
}
|
||||
} else {
|
||||
for i in 0..self.num_channels {
|
||||
@@ -445,11 +444,11 @@ impl AudioBuffer {
|
||||
let resampling_required = self.buffer_num_frames != self.output_num_frames;
|
||||
|
||||
if self.num_channels == 1 {
|
||||
let float_buffer = &mut self.scratch[..self.output_num_frames];
|
||||
let mut float_buffer = vec![0.0f32; self.output_num_frames];
|
||||
|
||||
if resampling_required {
|
||||
let ch0 = self.data.bands(0);
|
||||
self.output_resamplers[0].resample(ch0, float_buffer);
|
||||
self.output_resamplers[0].resample(ch0, &mut float_buffer);
|
||||
} else {
|
||||
float_buffer.copy_from_slice(&self.data.bands(0)[..self.output_num_frames]);
|
||||
}
|
||||
@@ -471,9 +470,9 @@ impl AudioBuffer {
|
||||
} else {
|
||||
if resampling_required {
|
||||
for i in 0..self.num_channels {
|
||||
let float_buffer = &mut self.scratch[..self.output_num_frames];
|
||||
let mut float_buffer = vec![0.0f32; self.output_num_frames];
|
||||
let ch = self.data.bands(i);
|
||||
self.output_resamplers[i].resample(ch, float_buffer);
|
||||
self.output_resamplers[i].resample(ch, &mut float_buffer);
|
||||
for (k, sample) in float_buffer.iter().enumerate().take(self.output_num_frames)
|
||||
{
|
||||
interleaved_data[k * config_num_channels + i] =
|
||||
|
||||
+1
-42
@@ -10,7 +10,7 @@ use std::error;
|
||||
use std::fmt;
|
||||
|
||||
use crate::audio_processing_impl::AudioProcessingImpl;
|
||||
use crate::config::{Config, EchoCanceller3Config, PlayoutAudioDeviceInfo, RuntimeSetting};
|
||||
use crate::config::{Config, PlayoutAudioDeviceInfo, RuntimeSetting};
|
||||
use crate::stats::AudioProcessingStats;
|
||||
use crate::stream_config::StreamConfig;
|
||||
/// Errors returned by audio processing operations.
|
||||
@@ -313,7 +313,6 @@ pub struct AudioProcessingBuilder {
|
||||
capture_config: StreamConfig,
|
||||
render_config: StreamConfig,
|
||||
echo_detector: bool,
|
||||
echo_canceller3_config: Option<EchoCanceller3Config>,
|
||||
}
|
||||
|
||||
impl Default for AudioProcessingBuilder {
|
||||
@@ -323,7 +322,6 @@ impl Default for AudioProcessingBuilder {
|
||||
capture_config: DEFAULT_STREAM_CONFIG,
|
||||
render_config: DEFAULT_STREAM_CONFIG,
|
||||
echo_detector: false,
|
||||
echo_canceller3_config: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -363,24 +361,9 @@ impl AudioProcessingBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Use this AEC3 configuration instead of the default one (matching C++
|
||||
/// `EchoCanceller3Factory(config)`). Only takes effect when
|
||||
/// [`Config::echo_canceller`] is enabled; its `transparent_mode` still
|
||||
/// overrides `echo_removal_control.transparent_mode`. The configuration
|
||||
/// is validated (clamped to valid ranges) when the echo canceller is
|
||||
/// created. It applies to mono and multichannel render alike, as with
|
||||
/// C++ `EchoCanceller3Factory(config)`.
|
||||
pub fn echo_canceller3_config(mut self, config: EchoCanceller3Config) -> Self {
|
||||
self.echo_canceller3_config = Some(config);
|
||||
self
|
||||
}
|
||||
|
||||
/// Build the [`AudioProcessing`] instance.
|
||||
pub fn build(self) -> AudioProcessing {
|
||||
let mut inner = AudioProcessingImpl::with_config(self.config);
|
||||
if let Some(config) = self.echo_canceller3_config {
|
||||
inner.set_echo_canceller3_config(config);
|
||||
}
|
||||
|
||||
if self.echo_detector {
|
||||
inner.set_echo_detector();
|
||||
@@ -430,30 +413,6 @@ impl AudioProcessingBuilder {
|
||||
/// - Call `apply_config` from any thread, but never concurrently with
|
||||
/// `config()`.
|
||||
///
|
||||
/// # Floating-point environment
|
||||
///
|
||||
/// Like upstream WebRTC, each `process_*` call sets hardware flush-to-zero
|
||||
/// for its duration on x86/x86_64 with SSE (MXCSR FTZ and DAZ) and on
|
||||
/// aarch64 with NEON (FPCR.FZ), and restores the calling thread's previous
|
||||
/// setting before it returns, also when it panics. While a call runs,
|
||||
/// subnormal input samples are read as zero, and any code the call reaches
|
||||
/// on this thread runs in that mode too: `tracing` subscribers, the global
|
||||
/// allocator and the panic hook. In that mode a comparison with a subnormal
|
||||
/// operand can change its result; for example, `x > 0.0` is false for the
|
||||
/// smallest positive subnormal `x`. On Linux and other platforms where a new
|
||||
/// thread inherits the floating-point environment, a thread started during
|
||||
/// the call (for example by a subscriber or the allocator) keeps
|
||||
/// flush-to-zero for its whole life; only the calling thread is restored.
|
||||
/// Changing the floating-point environment is formally undefined behavior in
|
||||
/// Rust, and upstream's `DenormalDisabler`, nih-plug and the `no_denormals`
|
||||
/// crate also change it; sonora sets flush-to-zero only on the calling thread
|
||||
/// and restores that thread's setting when each call returns (threads started
|
||||
/// during the call can inherit it; see above), and the audio pipeline has no
|
||||
/// subnormal-sensitive logic. All other targets do not flush, for example
|
||||
/// 32-bit ARM, `arm64ec`, wasm, x86 without SSE (i586) and aarch64 without
|
||||
/// NEON (soft-float). There, near-silent input can make processing slower on
|
||||
/// hardware with a subnormal penalty.
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// 1. Create an instance via [`AudioProcessing::builder()`] or
|
||||
|
||||
+6
-64
@@ -11,7 +11,6 @@ use crate::audio_buffer::AudioBuffer;
|
||||
use crate::audio_converter::AudioConverter;
|
||||
use crate::capture_levels_adjuster::CaptureLevelsAdjuster;
|
||||
use crate::config::{Config, DownmixMethod, NoiseSuppressionLevel, RuntimeSetting};
|
||||
use crate::denormal_disabler::DenormalDisabler;
|
||||
use crate::echo_canceller3::EchoCanceller3;
|
||||
use crate::gain_controller2::{
|
||||
Agc2AdaptiveDigitalConfig, Agc2Config, Agc2InputVolumeControllerConfig, FixedDigitalConfig,
|
||||
@@ -166,8 +165,6 @@ pub(crate) struct AudioProcessingImpl {
|
||||
capture_input_rms: RmsLevel,
|
||||
capture_output_rms: RmsLevel,
|
||||
capture_rms_interval_counter: usize,
|
||||
// AEC3 tuning given to the builder; the default configuration if `None`.
|
||||
echo_canceller3_config: Option<EchoCanceller3Config>,
|
||||
}
|
||||
|
||||
impl AudioProcessingImpl {
|
||||
@@ -196,20 +193,11 @@ impl AudioProcessingImpl {
|
||||
capture_input_rms: RmsLevel::new(),
|
||||
capture_output_rms: RmsLevel::new(),
|
||||
capture_rms_interval_counter: 0,
|
||||
echo_canceller3_config: None,
|
||||
};
|
||||
if !DenormalDisabler::is_supported() {
|
||||
tracing::info!("Denormal disabler unsupported");
|
||||
}
|
||||
apm.initialize();
|
||||
apm
|
||||
}
|
||||
|
||||
/// Sets the AEC3 configuration used when the echo canceller is created.
|
||||
pub(crate) fn set_echo_canceller3_config(&mut self, config: EchoCanceller3Config) {
|
||||
self.echo_canceller3_config = Some(config);
|
||||
}
|
||||
|
||||
/// Installs the residual echo detector (opt-in).
|
||||
///
|
||||
/// Must be called before `initialize()`.
|
||||
@@ -334,7 +322,6 @@ impl AudioProcessingImpl {
|
||||
/// Processes a capture audio frame.
|
||||
///
|
||||
/// `src` and `dest` are deinterleaved float channel slices, one per channel.
|
||||
#[inline(never)]
|
||||
pub(crate) fn process_stream(
|
||||
&mut self,
|
||||
src: &[&[f32]],
|
||||
@@ -342,12 +329,6 @@ impl AudioProcessingImpl {
|
||||
output_config: &StreamConfig,
|
||||
dest: &mut [&mut [f32]],
|
||||
) {
|
||||
// SAFETY: the pipeline tolerates flushed subnormals; upstream runs it
|
||||
// under the same guard (audio_processing_impl.cc, DenormalDisabler).
|
||||
// Foreign code in the window (tracing subscribers, the allocator, the
|
||||
// panic hook) is documented on `AudioProcessing`. `#[inline(never)]`
|
||||
// keeps caller code from being inlined into the window.
|
||||
let _denormal_disabler = unsafe { DenormalDisabler::new() };
|
||||
self.maybe_initialize_capture(input_config, output_config);
|
||||
|
||||
let capture_audio = self.capture.capture_audio.as_mut().unwrap();
|
||||
@@ -372,7 +353,6 @@ impl AudioProcessingImpl {
|
||||
/// Processes a reverse (render / far-end) audio frame.
|
||||
///
|
||||
/// `src` and `dest` are deinterleaved float channel slices, one per channel.
|
||||
#[inline(never)]
|
||||
pub(crate) fn process_reverse_stream(
|
||||
&mut self,
|
||||
src: &[&[f32]],
|
||||
@@ -380,12 +360,6 @@ impl AudioProcessingImpl {
|
||||
output_config: &StreamConfig,
|
||||
dest: &mut [&mut [f32]],
|
||||
) {
|
||||
// SAFETY: the pipeline tolerates flushed subnormals; upstream runs it
|
||||
// under the same guard (audio_processing_impl.cc, DenormalDisabler).
|
||||
// Foreign code in the window (tracing subscribers, the allocator, the
|
||||
// panic hook) is documented on `AudioProcessing`. `#[inline(never)]`
|
||||
// keeps caller code from being inlined into the window.
|
||||
let _denormal_disabler = unsafe { DenormalDisabler::new() };
|
||||
self.maybe_initialize_render(input_config, output_config);
|
||||
self.analyze_reverse_stream_locked(src, input_config);
|
||||
|
||||
@@ -413,7 +387,6 @@ impl AudioProcessingImpl {
|
||||
}
|
||||
|
||||
/// Processes a capture audio frame (int16, interleaved).
|
||||
#[inline(never)]
|
||||
pub(crate) fn process_stream_i16(
|
||||
&mut self,
|
||||
src: &[i16],
|
||||
@@ -421,12 +394,6 @@ impl AudioProcessingImpl {
|
||||
output_config: &StreamConfig,
|
||||
dest: &mut [i16],
|
||||
) {
|
||||
// SAFETY: the pipeline tolerates flushed subnormals; upstream runs it
|
||||
// under the same guard (audio_processing_impl.cc, DenormalDisabler).
|
||||
// Foreign code in the window (tracing subscribers, the allocator, the
|
||||
// panic hook) is documented on `AudioProcessing`. `#[inline(never)]`
|
||||
// keeps caller code from being inlined into the window.
|
||||
let _denormal_disabler = unsafe { DenormalDisabler::new() };
|
||||
self.maybe_initialize_capture(input_config, output_config);
|
||||
|
||||
let capture_audio = self.capture.capture_audio.as_mut().unwrap();
|
||||
@@ -462,7 +429,6 @@ impl AudioProcessingImpl {
|
||||
}
|
||||
|
||||
/// Processes a reverse (render / far-end) audio frame (int16, interleaved).
|
||||
#[inline(never)]
|
||||
pub(crate) fn process_reverse_stream_i16(
|
||||
&mut self,
|
||||
src: &[i16],
|
||||
@@ -470,12 +436,6 @@ impl AudioProcessingImpl {
|
||||
output_config: &StreamConfig,
|
||||
dest: &mut [i16],
|
||||
) {
|
||||
// SAFETY: the pipeline tolerates flushed subnormals; upstream runs it
|
||||
// under the same guard (audio_processing_impl.cc, DenormalDisabler).
|
||||
// Foreign code in the window (tracing subscribers, the allocator, the
|
||||
// panic hook) is documented on `AudioProcessing`. `#[inline(never)]`
|
||||
// keeps caller code from being inlined into the window.
|
||||
let _denormal_disabler = unsafe { DenormalDisabler::new() };
|
||||
self.maybe_initialize_render(input_config, output_config);
|
||||
|
||||
let render_audio = self.render.render_audio.as_mut().unwrap();
|
||||
@@ -723,11 +683,10 @@ impl AudioProcessingImpl {
|
||||
.capture_multi_band_processing_active(ec_active)
|
||||
{
|
||||
// Copy the multi-band processed audio to the fullband buffer.
|
||||
self.capture
|
||||
.capture_audio
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.copy_to_buffer(fullband);
|
||||
// Temporarily take capture_audio to avoid double &mut borrow.
|
||||
let mut capture = self.capture.capture_audio.take().unwrap();
|
||||
capture.copy_to_buffer(fullband);
|
||||
self.capture.capture_audio = Some(capture);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1318,26 +1277,9 @@ impl AudioProcessingImpl {
|
||||
let num_render_channels = self.num_reverse_channels();
|
||||
let num_capture_channels = self.num_proc_channels();
|
||||
|
||||
// The default path stays exactly as before; only a caller's tuning
|
||||
// is validated (clamped to valid ranges).
|
||||
let mut config = match &self.echo_canceller3_config {
|
||||
Some(custom) => {
|
||||
let mut custom = custom.clone();
|
||||
if !custom.validate() {
|
||||
tracing::warn!("Invalid EchoCanceller3Config; clamped to valid ranges");
|
||||
}
|
||||
custom
|
||||
}
|
||||
None => EchoCanceller3Config::default(),
|
||||
};
|
||||
let mut config = EchoCanceller3Config::default();
|
||||
config.echo_removal_control.transparent_mode = ec.transparent_mode;
|
||||
// Like C++ `AudioProcessingImpl::InitializeEchoController`: the default
|
||||
// multichannel config is used only when the caller set no config. A
|
||||
// caller's config applies to mono and multichannel render alike.
|
||||
let multichannel_config = match self.echo_canceller3_config {
|
||||
Some(_) => None,
|
||||
None => Some(EchoCanceller3Config::create_default_multichannel_config()),
|
||||
};
|
||||
let multichannel_config = Some(EchoCanceller3Config::create_default_multichannel_config());
|
||||
|
||||
self.submodules.echo_controller = Some(EchoCanceller3::new(
|
||||
config,
|
||||
|
||||
Vendored
+2
-4
@@ -173,7 +173,8 @@ impl Default for HighPassFilter {
|
||||
/// Echo canceller (AEC3) settings.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EchoCanceller {
|
||||
/// Enforce the highpass filter to be on (default: true).
|
||||
/// Enforce the highpass filter to be on (default: true). Has no effect
|
||||
/// in mobile mode.
|
||||
pub enforce_high_pass_filtering: bool,
|
||||
/// Which transparent mode algorithm to use (default: `Legacy`).
|
||||
///
|
||||
@@ -194,9 +195,6 @@ impl Default for EchoCanceller {
|
||||
|
||||
pub use sonora_aec3::config::TransparentModeType;
|
||||
|
||||
/// Full AEC3 tuning, for [`AudioProcessingBuilder::echo_canceller3_config`](crate::AudioProcessingBuilder::echo_canceller3_config).
|
||||
pub use sonora_aec3::config::EchoCanceller3Config;
|
||||
|
||||
/// Background noise suppression settings.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NoiseSuppression {
|
||||
|
||||
-640
@@ -1,640 +0,0 @@
|
||||
//! Scoped hardware flush-to-zero for the processing entry points.
|
||||
//!
|
||||
//! Mirrors WebRTC's `DenormalDisabler` (`rtc_base/denormal_disabler.{h,cc}`),
|
||||
//! which `AudioProcessingImpl` places at every stream entry point. Several
|
||||
//! recursive filters in the pipeline (the two-band QMF all-pass states, the
|
||||
//! AEC3 decimator biquads, the reverb models) never decay to zero on silent
|
||||
//! input under IEEE gradual underflow: they settle in a limit cycle a few
|
||||
//! ulps above zero, in the subnormal range. On x86 every arithmetic operation
|
||||
//! on a subnormal operand takes a microcode assist, which made AEC3 10-50x
|
||||
//! slower while the render reference was silent (issue #34). Upstream hides
|
||||
//! this with FTZ/DAZ; so does this guard.
|
||||
|
||||
use core::marker::PhantomData;
|
||||
|
||||
/// Sets hardware flush-to-zero for the current thread while alive.
|
||||
///
|
||||
/// - x86 / x86_64 with SSE: MXCSR.FTZ (bit 15) and MXCSR.DAZ (bit 6).
|
||||
/// - aarch64 with NEON: FPCR.FZ (bit 24), which flushes inputs and outputs.
|
||||
/// - Everything else is a no-op, including all 32-bit ARM targets
|
||||
/// (`armv7-linux-androideabi`), `arm64ec`, wasm32, i586 and Miri. Upstream
|
||||
/// also flushes on 32-bit ARM (FPSCR.FZ); this port does not yet.
|
||||
///
|
||||
/// Like upstream, the guard changes the register only if the bits are not
|
||||
/// already all set, and restores the saved word only if it changed it, so
|
||||
/// nested guards are harmless and a caller that already runs with FTZ keeps
|
||||
/// it.
|
||||
#[derive(Debug)]
|
||||
#[must_use = "denormals are only disabled while the guard is alive"]
|
||||
pub(crate) struct DenormalDisabler {
|
||||
/// Control word read by `new`; `Some` only if `new` changed the register.
|
||||
saved: Option<imp::Word>,
|
||||
/// FP control registers are per thread, so the guard is `!Send + !Sync`.
|
||||
_not_send: PhantomData<*const ()>,
|
||||
}
|
||||
|
||||
impl DenormalDisabler {
|
||||
/// Sets the flush-to-zero bits for the current thread.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Rust assumes the default floating-point environment: RFC 3514 makes
|
||||
/// any change to it undefined behavior, and the `core::arch` MXCSR
|
||||
/// documentation calls a changed DAZ bit "immediate Undefined Behavior".
|
||||
/// Until the guard drops, everything that runs on this thread sees
|
||||
/// subnormal inputs and results as zero. That includes code sonora does
|
||||
/// not control: `tracing` subscribers, the global allocator and the panic
|
||||
/// hook (which runs before unwinding drops the guard). On Linux and other
|
||||
/// platforms where a new thread inherits the floating-point environment,
|
||||
/// a thread that such code starts before the guard drops keeps
|
||||
/// flush-to-zero for its whole life; `Drop` restores only this thread. A
|
||||
/// comparison with a subnormal operand can change its result (`x > 0.0`
|
||||
/// is false for `x = f32::from_bits(1)`). LLVM may also move float
|
||||
/// operations across the guard boundary: the `asm!` blocks order only
|
||||
/// memory the compiler cannot prove private, so arithmetic on values in
|
||||
/// registers, on the stack, or behind a `&` or `&mut` can run on either
|
||||
/// side. Compile-time float results can also differ from run-time ones
|
||||
/// in the subnormal range. The caller must run only code that tolerates
|
||||
/// all of this. The audio pipeline has no subnormal-sensitive logic, and
|
||||
/// upstream runs the same algorithms with the same bits set.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn new() -> Self {
|
||||
#[cfg(test)]
|
||||
if tests::BYPASS.get() {
|
||||
return Self {
|
||||
saved: None,
|
||||
_not_send: PhantomData,
|
||||
};
|
||||
}
|
||||
let before = imp::read();
|
||||
let saved = if imp::denormals_enabled(before) {
|
||||
// SAFETY: the caller accepts the non-default FP environment (see
|
||||
// the function contract). The written word differs from `before`
|
||||
// only in the defined FTZ/DAZ bits.
|
||||
unsafe { imp::write(imp::with_ftz(before)) };
|
||||
Some(before)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Self {
|
||||
saved,
|
||||
_not_send: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if this target has a hardware flush-to-zero path.
|
||||
/// Mirrors upstream `DenormalDisabler::IsSupported()`.
|
||||
pub(crate) const fn is_supported() -> bool {
|
||||
imp::SUPPORTED
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DenormalDisabler {
|
||||
#[inline]
|
||||
fn drop(&mut self) {
|
||||
if let Some(word) = self.saved {
|
||||
// SAFETY: restores the exact word read in `new`, on the same
|
||||
// thread (the guard is `!Send`), which returns the caller to its
|
||||
// own environment. Runs during unwinding too.
|
||||
unsafe { imp::write(word) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
not(miri),
|
||||
any(target_arch = "x86", target_arch = "x86_64"),
|
||||
target_feature = "sse"
|
||||
))]
|
||||
mod imp {
|
||||
use core::arch::asm;
|
||||
|
||||
pub(super) type Word = u32;
|
||||
pub(super) const SUPPORTED: bool = true;
|
||||
/// MXCSR.FTZ (bit 15) | MXCSR.DAZ (bit 6); upstream `kDenormalBitMask`.
|
||||
const MASK: Word = 0x8040;
|
||||
|
||||
pub(super) const fn denormals_enabled(word: Word) -> bool {
|
||||
word & MASK != MASK
|
||||
}
|
||||
|
||||
pub(super) const fn with_ftz(word: Word) -> Word {
|
||||
word | MASK
|
||||
}
|
||||
|
||||
/// Test-only: FTZ set and DAZ clear, a word the guard must still change
|
||||
/// and whose FTZ bit a sloppy restore would drop.
|
||||
#[cfg(test)]
|
||||
pub(super) const fn non_default_word(word: Word) -> Word {
|
||||
(word | 0x8000) & !0x0040
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(super) fn read() -> Word {
|
||||
let mut csr: Word = 0;
|
||||
// SAFETY: `stmxcsr` stores MXCSR into the 4 bytes at `p`, a live
|
||||
// local. It changes no register and no flag. Never `pure`: the value
|
||||
// depends on hidden state.
|
||||
unsafe {
|
||||
asm!(
|
||||
"stmxcsr [{p}]",
|
||||
p = in(reg) &raw mut csr,
|
||||
options(nostack, preserves_flags),
|
||||
);
|
||||
}
|
||||
csr
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
///
|
||||
/// `csr` must be a word read by `read`, optionally with `MASK` set, and
|
||||
/// the caller must accept the resulting FP environment.
|
||||
#[inline(always)]
|
||||
pub(super) unsafe fn write(csr: Word) {
|
||||
// SAFETY: `ldmxcsr` reads the 4 bytes at `p`, a live local. It
|
||||
// rewrites the MXCSR exception flags, so `preserves_flags` is not
|
||||
// claimed. No `nomem`/`readonly`: the block also orders memory the
|
||||
// compiler cannot prove private (not data behind a `&mut`).
|
||||
unsafe {
|
||||
asm!("ldmxcsr [{p}]", p = in(reg) &raw const csr, options(nostack));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(not(miri), target_arch = "aarch64", target_feature = "neon"))]
|
||||
mod imp {
|
||||
use core::arch::asm;
|
||||
|
||||
pub(super) type Word = u64;
|
||||
pub(super) const SUPPORTED: bool = true;
|
||||
/// FPCR.FZ (bit 24).
|
||||
const MASK: Word = 1 << 24;
|
||||
|
||||
pub(super) const fn denormals_enabled(word: Word) -> bool {
|
||||
word & MASK != MASK
|
||||
}
|
||||
|
||||
pub(super) const fn with_ftz(word: Word) -> Word {
|
||||
word | MASK
|
||||
}
|
||||
|
||||
/// Test-only: FPCR.DN (bit 25) set, a bit the guard does not own and a
|
||||
/// restore to a fixed default word would drop. (Clearing FZ from the
|
||||
/// saved word cannot lose anything here: `new` saves only words with FZ
|
||||
/// clear.)
|
||||
#[cfg(test)]
|
||||
pub(super) const fn non_default_word(word: Word) -> Word {
|
||||
word | (1 << 25)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(super) fn read() -> Word {
|
||||
let fpcr: Word;
|
||||
// SAFETY: reads FPCR into a general register. FPCR holds no NZCV or
|
||||
// FPSR state, so no flag changes.
|
||||
unsafe {
|
||||
asm!("mrs {}, fpcr", out(reg) fpcr, options(nomem, nostack, preserves_flags));
|
||||
}
|
||||
fpcr
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
///
|
||||
/// The caller must accept the resulting FP environment.
|
||||
#[inline(always)]
|
||||
pub(super) unsafe fn write(fpcr: Word) {
|
||||
// SAFETY: writes FPCR from a general register; NZCV and FPSR are
|
||||
// untouched. No `nomem`: the block also orders memory the compiler
|
||||
// cannot prove private (not data behind a `&mut`).
|
||||
unsafe {
|
||||
asm!("msr fpcr, {}", in(reg) fpcr, options(nostack, preserves_flags));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
all(
|
||||
not(miri),
|
||||
any(target_arch = "x86", target_arch = "x86_64"),
|
||||
target_feature = "sse"
|
||||
),
|
||||
all(not(miri), target_arch = "aarch64", target_feature = "neon"),
|
||||
)))]
|
||||
mod imp {
|
||||
// `u32`, not `()`: a unit word trips clippy `let_unit_value`/`unit_arg`.
|
||||
pub(super) type Word = u32;
|
||||
pub(super) const SUPPORTED: bool = false;
|
||||
|
||||
pub(super) const fn denormals_enabled(_word: Word) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) const fn with_ftz(word: Word) -> Word {
|
||||
word
|
||||
}
|
||||
|
||||
/// Test-only: there is no register, so the word stays as it is.
|
||||
#[cfg(test)]
|
||||
pub(super) const fn non_default_word(word: Word) -> Word {
|
||||
word
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(super) fn read() -> Word {
|
||||
0
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
///
|
||||
/// Always safe; `unsafe` only to match the supported variants.
|
||||
#[inline(always)]
|
||||
pub(super) unsafe fn write(_word: Word) {}
|
||||
}
|
||||
|
||||
// Every test whose result depends on the target asserts it against
|
||||
// `is_supported()` instead of skipping unsupported targets; the other tests
|
||||
// hold on every target. On a no-op target the tests therefore check that the
|
||||
// guard really is a no-op, nothing shows as passed without running, and the
|
||||
// target predicates exist only once (in `imp`).
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
use std::collections::BTreeMap;
|
||||
use std::f32::consts::PI;
|
||||
use std::hint::black_box;
|
||||
use std::panic;
|
||||
|
||||
use super::{DenormalDisabler, imp};
|
||||
use crate::config::EchoCanceller;
|
||||
use crate::{AudioProcessing, Config, StreamConfig};
|
||||
|
||||
thread_local! {
|
||||
/// Test-only: makes `DenormalDisabler::new` a no-op on this thread,
|
||||
/// so the regression test can run a control without the guard.
|
||||
pub(super) static BYPASS: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
/// `MIN_POSITIVE / 123.125` is subnormal under IEEE and zero under FTZ.
|
||||
/// `black_box` keeps LLVM from folding it at compile time, where the FTZ
|
||||
/// bit is invisible.
|
||||
fn runtime_division_is_subnormal() -> bool {
|
||||
(black_box(f32::MIN_POSITIVE) / black_box(123.125f32)).is_subnormal()
|
||||
}
|
||||
|
||||
/// `2^-149 * 2^100` is `2^-49` (normal) under IEEE; DAZ reads the
|
||||
/// subnormal input as zero.
|
||||
fn subnormal_input_reads_as_zero() -> bool {
|
||||
black_box(f32::from_bits(1)) * black_box(2.0f32.powi(100)) == 0.0
|
||||
}
|
||||
|
||||
fn guard() -> DenormalDisabler {
|
||||
// SAFETY: test code; tolerates flushed subnormals.
|
||||
unsafe { DenormalDisabler::new() }
|
||||
}
|
||||
|
||||
/// Every test assumes it starts in Rust's default FP environment. If a
|
||||
/// platform starts threads with FTZ set, fail here, loudly, rather than
|
||||
/// in a confusing later assertion.
|
||||
fn assert_ieee_default() {
|
||||
assert!(
|
||||
runtime_division_is_subnormal() && !subnormal_input_reads_as_zero(),
|
||||
"precondition: the test thread must start in the IEEE default FP environment"
|
||||
);
|
||||
}
|
||||
|
||||
/// Upstream parity (`ZeroDenormals`): subnormal results become zero
|
||||
/// inside the guard. This is the FTZ half of the fix.
|
||||
#[test]
|
||||
fn guard_flushes_subnormal_results() {
|
||||
assert_ieee_default();
|
||||
let _g = guard();
|
||||
assert_eq!(
|
||||
!runtime_division_is_subnormal(),
|
||||
DenormalDisabler::is_supported()
|
||||
);
|
||||
}
|
||||
|
||||
/// Subnormal *inputs* must read as zero too (x86 DAZ; FPCR.FZ covers
|
||||
/// inputs on aarch64). Without DAZ, x86 still takes a microcode assist for
|
||||
/// every subnormal operand the caller feeds in; the FTZ test above cannot
|
||||
/// tell 0x8000 from 0x8040.
|
||||
#[test]
|
||||
fn guard_treats_subnormal_inputs_as_zero() {
|
||||
assert_ieee_default();
|
||||
let _g = guard();
|
||||
assert_eq!(
|
||||
subnormal_input_reads_as_zero(),
|
||||
DenormalDisabler::is_supported()
|
||||
);
|
||||
}
|
||||
|
||||
/// Upstream parity (`RestoreDenormalsEnabled`): a leaked FTZ bit would
|
||||
/// silently change the numerics of unrelated code on the caller's thread.
|
||||
#[test]
|
||||
fn guard_restores_caller_environment() {
|
||||
assert_ieee_default();
|
||||
{
|
||||
let _g = guard();
|
||||
}
|
||||
assert_ieee_default();
|
||||
}
|
||||
|
||||
/// The guard promises to restore the exact word it read: not the default
|
||||
/// word, and not that word with the flush bits cleared. From the default
|
||||
/// word all three are equal, so start from a word the guard must change
|
||||
/// and that a sloppy restore would lose: FTZ without DAZ on x86 (a caller
|
||||
/// that chose FTZ only), FPCR.DN on aarch64.
|
||||
#[test]
|
||||
fn guard_restores_non_default_word_exactly() {
|
||||
assert_ieee_default();
|
||||
let default = imp::read();
|
||||
let start = imp::non_default_word(default);
|
||||
// SAFETY: test code; tolerates flushed subnormals and default NaNs.
|
||||
// The default word is written back before any assertion can panic.
|
||||
unsafe { imp::write(start) };
|
||||
let inside = {
|
||||
let _g = guard();
|
||||
imp::read()
|
||||
};
|
||||
let after = imp::read();
|
||||
// SAFETY: as above; this is the word the thread started with.
|
||||
unsafe { imp::write(default) };
|
||||
assert_eq!(
|
||||
inside != start,
|
||||
DenormalDisabler::is_supported(),
|
||||
"guard did not change {start:#x}"
|
||||
);
|
||||
assert_eq!(after, start, "restored {after:#x}, expected {start:#x}");
|
||||
assert_ieee_default();
|
||||
}
|
||||
|
||||
/// Upstream's nesting rule: a nested guard, or a caller that already set
|
||||
/// FTZ, must keep the outer state after the inner guard drops.
|
||||
#[test]
|
||||
fn nested_guard_keeps_outer_state() {
|
||||
assert_ieee_default();
|
||||
let _outer = guard();
|
||||
{
|
||||
let _inner = guard();
|
||||
}
|
||||
assert_eq!(
|
||||
!runtime_division_is_subnormal(),
|
||||
DenormalDisabler::is_supported()
|
||||
);
|
||||
}
|
||||
|
||||
/// Upstream parity (`DoNotZeroInfNan`): FTZ must not touch Inf or NaN.
|
||||
#[test]
|
||||
fn guard_keeps_inf_and_nan() {
|
||||
assert_ieee_default();
|
||||
let _g = guard();
|
||||
assert!((black_box(f32::MAX) * black_box(2.0f32)).is_infinite());
|
||||
assert!(black_box(-1.0f32).sqrt().is_nan());
|
||||
}
|
||||
|
||||
/// The C API catches panics and the caller's thread carries on, so the
|
||||
/// environment must be restored during unwinding as well.
|
||||
#[test]
|
||||
fn guard_restores_on_unwind() {
|
||||
assert_ieee_default();
|
||||
let r = panic::catch_unwind(|| {
|
||||
let _g = guard();
|
||||
panic!("unwind through the guard");
|
||||
});
|
||||
assert!(r.is_err());
|
||||
assert_ieee_default();
|
||||
}
|
||||
|
||||
fn ec_48k_mono() -> AudioProcessing {
|
||||
let config = Config {
|
||||
echo_canceller: Some(EchoCanceller::default()),
|
||||
..Default::default()
|
||||
};
|
||||
let stream = StreamConfig::new(48_000, 1);
|
||||
AudioProcessing::builder()
|
||||
.config(config)
|
||||
.capture_config(stream)
|
||||
.render_config(stream)
|
||||
.build()
|
||||
}
|
||||
|
||||
/// Calls each public processing entry point once and returns after each
|
||||
/// call so the caller can inspect the thread's FP environment.
|
||||
fn for_each_process_call(apm: &mut AudioProcessing, mut check: impl FnMut(&str)) {
|
||||
let n = 480;
|
||||
let src = vec![0.01f32; n];
|
||||
let mut dst = vec![0.0f32; n];
|
||||
let src_i16 = vec![100i16; n];
|
||||
let mut dst_i16 = vec![0i16; n];
|
||||
apm.process_render_f32(&[&src], &mut [&mut dst]).unwrap();
|
||||
check("process_render_f32");
|
||||
apm.process_capture_f32(&[&src], &mut [&mut dst]).unwrap();
|
||||
check("process_capture_f32");
|
||||
apm.process_render_i16(&src_i16, &mut dst_i16).unwrap();
|
||||
check("process_render_i16");
|
||||
apm.process_capture_i16(&src_i16, &mut dst_i16).unwrap();
|
||||
check("process_capture_i16");
|
||||
}
|
||||
|
||||
/// sonora must hand the caller's thread back in the environment it
|
||||
/// found, through the real API: IEEE for a default caller, and FTZ kept
|
||||
/// for a caller (such as a DAW audio thread) that already set it.
|
||||
#[test]
|
||||
fn process_calls_leave_caller_environment_unchanged() {
|
||||
assert_ieee_default();
|
||||
let mut apm = ec_48k_mono();
|
||||
for_each_process_call(&mut apm, |call| {
|
||||
assert!(runtime_division_is_subnormal(), "{call} leaked FTZ");
|
||||
assert!(!subnormal_input_reads_as_zero(), "{call} leaked DAZ");
|
||||
});
|
||||
let _caller_ftz = guard();
|
||||
for_each_process_call(&mut apm, |call| {
|
||||
assert_eq!(
|
||||
!runtime_division_is_subnormal(),
|
||||
DenormalDisabler::is_supported(),
|
||||
"{call} cleared the caller's FTZ"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Counts nonzero values below `f32::MIN_POSITIVE` per state field in the
|
||||
/// pretty `Debug` dump of the whole processor (every state struct derives
|
||||
/// `Debug`). Keys are the field path, e.g.
|
||||
/// `inner.render.render_audio.splitting_filter.state.analysis_state1`.
|
||||
///
|
||||
/// The scan cannot tell `f32` from `f64` fields, so it also counts `f64`
|
||||
/// values below that bound (normal `f64`s, untouched by FTZ), and some
|
||||
/// state is `f64`, such as `echo_return_loss` in the stored statistics.
|
||||
/// That can only add counts: it can fail the guarded run, with the field
|
||||
/// named in the message, but cannot hide an `f32` subnormal.
|
||||
fn subnormals_by_field(apm: &AudioProcessing) -> BTreeMap<String, usize> {
|
||||
let dump = format!("{apm:#?}");
|
||||
let mut stack: Vec<Option<&str>> = Vec::new();
|
||||
let mut counts = BTreeMap::new();
|
||||
for line in dump.lines() {
|
||||
let body = line.trim_start();
|
||||
stack.truncate((line.len() - body.len()) / 4);
|
||||
let field = body.split_once(": ").map(|(name, _)| name).filter(|name| {
|
||||
name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
|
||||
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
|
||||
});
|
||||
stack.push(field);
|
||||
let n = body
|
||||
.split(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '-' | '+')))
|
||||
.filter_map(|t| t.parse::<f64>().ok())
|
||||
.filter(|v| *v != 0.0 && v.abs() < f64::from(f32::MIN_POSITIVE))
|
||||
.count();
|
||||
if n > 0 {
|
||||
let key: Vec<&str> = stack.iter().flatten().copied().collect();
|
||||
*counts.entry(key.join(".")).or_insert(0) += n;
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Deterministic speech-like source: LCG noise with a 4 Hz envelope.
|
||||
fn speech_like(frame: usize, n: usize, out: &mut [f32]) {
|
||||
let mut seed = (frame as u32).wrapping_mul(2_654_435_761).wrapping_add(1);
|
||||
for (i, s) in out.iter_mut().enumerate().take(n) {
|
||||
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
let noise = (seed >> 8) as f32 / (1u32 << 24) as f32 - 0.5;
|
||||
let t = (frame * n + i) as f32 / 48_000.0;
|
||||
let env = 0.5 + 0.5 * (2.0 * PI * 4.0 * t).sin();
|
||||
*s = 0.2 * env * noise;
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames (10 ms) of 1 s speech-like render and echo.
|
||||
const SPEECH_END: usize = 100;
|
||||
/// Then exact-zero render (the reported case) with capture noise at about
|
||||
/// -75 dBFS RMS and -66 dBFS peak, until checkpoint A.
|
||||
const CHECKPOINT_A: usize = 300;
|
||||
/// Then exact-zero render and capture, until checkpoint B. The latest
|
||||
/// onset in the control (`y2_smoothed`, about frame 650) leaves a margin
|
||||
/// of 150 frames; keep one if either moves.
|
||||
const CHECKPOINT_B: usize = 800;
|
||||
|
||||
/// Runs the issue #34 scenario through the f32 or i16 API and returns the
|
||||
/// subnormal state per field at checkpoints A and B.
|
||||
fn silent_render_scenario(use_i16: bool) -> [BTreeMap<String, usize>; 2] {
|
||||
let mut apm = ec_48k_mono();
|
||||
let n = 480;
|
||||
let mut render = vec![0.0f32; n];
|
||||
let mut capture = vec![0.0f32; n];
|
||||
let mut out = vec![0.0f32; n];
|
||||
let mut render_out = vec![0.0f32; n];
|
||||
let mut out_i16 = vec![0i16; n];
|
||||
let to_i16 = |x: &[f32]| -> Vec<i16> { x.iter().map(|v| (v * 32767.0) as i16).collect() };
|
||||
let mut checkpoint_a = BTreeMap::new();
|
||||
for frame in 0..CHECKPOINT_B {
|
||||
if frame < SPEECH_END {
|
||||
speech_like(frame, n, &mut render);
|
||||
for (c, r) in capture.iter_mut().zip(&render) {
|
||||
*c = 0.5 * r;
|
||||
}
|
||||
} else if frame < CHECKPOINT_A {
|
||||
render.fill(0.0);
|
||||
speech_like(frame, n, &mut capture);
|
||||
for c in &mut capture {
|
||||
*c *= 0.005;
|
||||
}
|
||||
} else {
|
||||
render.fill(0.0);
|
||||
capture.fill(0.0);
|
||||
}
|
||||
if use_i16 {
|
||||
apm.process_render_i16(&to_i16(&render), &mut out_i16)
|
||||
.unwrap();
|
||||
apm.process_capture_i16(&to_i16(&capture), &mut out_i16)
|
||||
.unwrap();
|
||||
} else {
|
||||
apm.process_render_f32(&[&render], &mut [&mut render_out])
|
||||
.unwrap();
|
||||
apm.process_capture_f32(&[&capture], &mut [&mut out])
|
||||
.unwrap();
|
||||
}
|
||||
if frame + 1 == CHECKPOINT_A {
|
||||
checkpoint_a = subnormals_by_field(&apm);
|
||||
}
|
||||
}
|
||||
[checkpoint_a, subnormals_by_field(&apm)]
|
||||
}
|
||||
|
||||
/// Recursive states that settle in the subnormal range without the guard,
|
||||
/// with the checkpoint by which each must hold a subnormal in the control
|
||||
/// run. The control proves the scenario still reaches every known source;
|
||||
/// without it, a scenario that stopped producing subnormals would pass.
|
||||
const SOURCES: &[(usize, &str)] = &[
|
||||
// Render side, reached in the reported case (onset about frame 110-140).
|
||||
(
|
||||
CHECKPOINT_A,
|
||||
"render_audio.splitting_filter.state.analysis_state1",
|
||||
),
|
||||
(
|
||||
CHECKPOINT_A,
|
||||
"render_audio.splitting_filter.state.synthesis_state1",
|
||||
),
|
||||
(
|
||||
CHECKPOINT_A,
|
||||
"render_decimator.anti_aliasing_filter.biquads.y",
|
||||
),
|
||||
(
|
||||
CHECKPOINT_A,
|
||||
"render_decimator.noise_reduction_filter.biquads.y",
|
||||
),
|
||||
// Slower render-driven smoothers (onset about frame 330 and 500).
|
||||
(CHECKPOINT_B, "aec_state.avg_render_reverb.reverb"),
|
||||
(CHECKPOINT_B, "residual_echo_estimator.echo_reverb.reverb"),
|
||||
(CHECKPOINT_B, "low_render_detector.average_power"),
|
||||
// Capture side, once capture is exact zero too (onset about 310-650).
|
||||
(
|
||||
CHECKPOINT_B,
|
||||
"capture_audio.splitting_filter.state.analysis_state1",
|
||||
),
|
||||
(
|
||||
CHECKPOINT_B,
|
||||
"capture_audio.splitting_filter.state.synthesis_state1",
|
||||
),
|
||||
(CHECKPOINT_B, "high_pass_filter.filters.biquads.y"),
|
||||
(
|
||||
CHECKPOINT_B,
|
||||
"capture_decimator.anti_aliasing_filter.biquads.y",
|
||||
),
|
||||
(CHECKPOINT_B, "echo_remover.cng.y2_smoothed"),
|
||||
];
|
||||
|
||||
/// Issue #34. After the render reference goes silent, the pipeline's
|
||||
/// recursive filters (QMF all-pass, decimator and high-pass biquads,
|
||||
/// reverb models, smoothers) settle a few ulps above zero under IEEE
|
||||
/// gradual underflow and never reach zero, so every later frame computes
|
||||
/// on subnormals: a microcode assist per operation on x86. With the guard
|
||||
/// in every `process_*` entry point, no subnormal may survive in any
|
||||
/// state. Deterministic, no timing, so it runs on real x86_64 in CI.
|
||||
#[test]
|
||||
fn silent_render_leaves_no_subnormal_state() {
|
||||
assert_ieee_default();
|
||||
BYPASS.set(true);
|
||||
let control = silent_render_scenario(false);
|
||||
BYPASS.set(false);
|
||||
for &(checkpoint, source) in SOURCES {
|
||||
let at = &control[usize::from(checkpoint == CHECKPOINT_B)];
|
||||
assert!(
|
||||
at.iter().any(|(k, &v)| k.ends_with(source) && v > 0),
|
||||
"control: scenario no longer drives {source} subnormal by frame {checkpoint}"
|
||||
);
|
||||
}
|
||||
for use_i16 in [false, true] {
|
||||
for (at, checkpoint) in silent_render_scenario(use_i16)
|
||||
.iter()
|
||||
.zip([CHECKPOINT_A, CHECKPOINT_B])
|
||||
{
|
||||
let total: usize = at.values().sum();
|
||||
assert_eq!(
|
||||
total == 0,
|
||||
DenormalDisabler::is_supported(),
|
||||
"{total} subnormal state values at frame {checkpoint} (i16 API: {use_i16}): {at:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
-8
@@ -560,11 +560,15 @@ impl EchoCanceller3 {
|
||||
&mut self.capture_sub_frame_view,
|
||||
);
|
||||
|
||||
// Convert sub-frame slices to the format FrameBlocker expects.
|
||||
let sub_frame_refs: Vec<Vec<&[f32]>> = self
|
||||
.capture_sub_frame_view
|
||||
.iter()
|
||||
.map(|band| band.iter().map(|ch| ch.as_slice()).collect())
|
||||
.collect();
|
||||
|
||||
self.capture_blocker
|
||||
.insert_owned_sub_frame_and_extract_block(
|
||||
&self.capture_sub_frame_view,
|
||||
&mut self.capture_block,
|
||||
);
|
||||
.insert_sub_frame_and_extract_block(&sub_frame_refs, &mut self.capture_block);
|
||||
|
||||
// Process through block processor.
|
||||
let echo_path_gain_change = level_change || aec_reference_is_downmixed_stereo;
|
||||
@@ -675,11 +679,14 @@ impl EchoCanceller3 {
|
||||
&mut self.render_sub_frame_view,
|
||||
);
|
||||
|
||||
let sub_frame_refs: Vec<Vec<&[f32]>> = self
|
||||
.render_sub_frame_view
|
||||
.iter()
|
||||
.map(|band| band.iter().map(|ch| ch.as_slice()).collect())
|
||||
.collect();
|
||||
|
||||
self.render_blocker
|
||||
.insert_owned_sub_frame_and_extract_block(
|
||||
&self.render_sub_frame_view,
|
||||
&mut self.render_block,
|
||||
);
|
||||
.insert_sub_frame_and_extract_block(&sub_frame_refs, &mut self.render_block);
|
||||
self.block_processor.buffer_render(&self.render_block);
|
||||
}
|
||||
|
||||
|
||||
+24
-29
@@ -104,14 +104,11 @@ fn compute_audio_levels(audio: &AudioBuffer) -> AudioLevels {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies the channels of `audio` into `channel_data`, reusing its buffers:
|
||||
/// once they have grown to the frame size, this does not allocate.
|
||||
fn copy_channels(audio: &AudioBuffer, channel_data: &mut Vec<Vec<f32>>) {
|
||||
channel_data.resize_with(audio.num_channels(), Vec::new);
|
||||
for (ch, data) in channel_data.iter_mut().enumerate() {
|
||||
data.clear();
|
||||
data.extend_from_slice(audio.channel(ch));
|
||||
}
|
||||
/// Copies channel data out of an AudioBuffer for use with `&mut [&mut [f32]]` APIs.
|
||||
fn extract_channels(audio: &AudioBuffer) -> Vec<Vec<f32>> {
|
||||
(0..audio.num_channels())
|
||||
.map(|ch| audio.channel(ch).to_vec())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Writes channel data back into an AudioBuffer.
|
||||
@@ -135,9 +132,6 @@ pub(crate) struct GainController2 {
|
||||
adaptive_digital_controller: Option<AdaptiveDigitalGainController>,
|
||||
limiter: Limiter,
|
||||
recommended_input_volume: Option<i32>,
|
||||
/// Reusable frame buffers for the upstream multichannel path. Mono borrows
|
||||
/// the existing audio channel without allocating or copying these buffers.
|
||||
channel_data: Vec<Vec<f32>>,
|
||||
}
|
||||
|
||||
impl GainController2 {
|
||||
@@ -207,13 +201,6 @@ impl GainController2 {
|
||||
adaptive_digital_controller,
|
||||
limiter: Limiter::new(samples_per_channel),
|
||||
recommended_input_volume: None,
|
||||
channel_data: if num_channels == 1 {
|
||||
Vec::new()
|
||||
} else {
|
||||
(0..num_channels)
|
||||
.map(|_| Vec::with_capacity(samples_per_channel))
|
||||
.collect()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,17 +258,14 @@ impl GainController2 {
|
||||
// Compute audio levels from the first channel.
|
||||
let audio_levels = compute_audio_levels(audio);
|
||||
|
||||
// Mono capture borrows its channel directly; multichannel reuses upstream buffers.
|
||||
if audio.num_channels() != 1 {
|
||||
copy_channels(audio, &mut self.channel_data);
|
||||
}
|
||||
|
||||
// Noise level estimation.
|
||||
let noise_rms_dbfs = if let Some(ref mut nle) = self.noise_level_estimator {
|
||||
if audio.num_channels() == 1 {
|
||||
Some(nle.analyze(&[audio.channel(0)]))
|
||||
} else {
|
||||
Some(nle.analyze_owned_frame(&self.channel_data))
|
||||
let num_ch = audio.num_channels();
|
||||
let channels: Vec<&[f32]> = (0..num_ch).map(|ch| audio.channel(ch)).collect();
|
||||
Some(nle.analyze(&channels))
|
||||
}
|
||||
} else {
|
||||
None
|
||||
@@ -327,10 +311,15 @@ impl GainController2 {
|
||||
limiter_envelope_dbfs,
|
||||
};
|
||||
|
||||
// Mono capture borrows the existing channel; no sample/descriptor Vec is needed.
|
||||
if audio.num_channels() == 1 {
|
||||
adc.process(&info, &mut [audio.channel_mut(0)]);
|
||||
} else {
|
||||
adc.process_owned_frame(&info, &mut self.channel_data);
|
||||
let mut channel_data = extract_channels(audio);
|
||||
let mut channel_slices: Vec<&mut [f32]> =
|
||||
channel_data.iter_mut().map(|v| v.as_mut_slice()).collect();
|
||||
adc.process(&info, &mut channel_slices);
|
||||
write_back_channels(audio, &channel_data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,16 +327,22 @@ impl GainController2 {
|
||||
if audio.num_channels() == 1 {
|
||||
self.fixed_gain_applier.apply_gain(&mut [audio.channel_mut(0)]);
|
||||
} else {
|
||||
self.fixed_gain_applier
|
||||
.apply_gain_to_owned_signal(&mut self.channel_data);
|
||||
let mut channel_data = extract_channels(audio);
|
||||
let mut channel_slices: Vec<&mut [f32]> =
|
||||
channel_data.iter_mut().map(|v| v.as_mut_slice()).collect();
|
||||
self.fixed_gain_applier.apply_gain(&mut channel_slices);
|
||||
write_back_channels(audio, &channel_data);
|
||||
}
|
||||
|
||||
// Limiter.
|
||||
if audio.num_channels() == 1 {
|
||||
self.limiter.process(&mut [audio.channel_mut(0)]);
|
||||
} else {
|
||||
self.limiter.process_owned_signal(&mut self.channel_data);
|
||||
write_back_channels(audio, &self.channel_data);
|
||||
let mut channel_data = extract_channels(audio);
|
||||
let mut channel_slices: Vec<&mut [f32]> =
|
||||
channel_data.iter_mut().map(|v| v.as_mut_slice()).collect();
|
||||
self.limiter.process(&mut channel_slices);
|
||||
write_back_channels(audio, &channel_data);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+25
-140
@@ -116,9 +116,6 @@ pub(crate) struct InputVolumeControllerConfig {
|
||||
pub speech_ratio_threshold: f32,
|
||||
}
|
||||
|
||||
/// Upstream's production `InputVolumeController::Config{}` (upstream commit
|
||||
/// d9b92fe1bc), which C++ `AudioProcessingImpl::InitializeGainController2()`
|
||||
/// passes to the controller.
|
||||
impl Default for InputVolumeControllerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -127,12 +124,12 @@ impl Default for InputVolumeControllerConfig {
|
||||
clipped_level_step: 15,
|
||||
clipped_ratio_threshold: 0.1,
|
||||
clipped_wait_frames: 300,
|
||||
enable_clipping_predictor: true,
|
||||
target_range_max_dbfs: -12,
|
||||
target_range_min_dbfs: -50,
|
||||
update_input_volume_wait_frames: 100,
|
||||
speech_probability_threshold: 0.7,
|
||||
speech_ratio_threshold: 0.6,
|
||||
enable_clipping_predictor: false,
|
||||
target_range_max_dbfs: -18,
|
||||
target_range_min_dbfs: -30,
|
||||
update_input_volume_wait_frames: 0,
|
||||
speech_probability_threshold: 0.5,
|
||||
speech_ratio_threshold: 0.8,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1416,124 +1413,12 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The APM pipeline builds the controller from
|
||||
/// `InputVolumeControllerConfig::default()`, just as C++ APM builds it from
|
||||
/// `InputVolumeController::Config{}`. Any difference between the two
|
||||
/// changes `recommended_stream_analog_level()` relative to C++. The Rust
|
||||
/// default once drifted to test-like values (target range [-30, -18]
|
||||
/// dBFS, no clipping predictor, no update wait), so this test pins every
|
||||
/// field to upstream's production values in
|
||||
/// `modules/audio_processing/agc2/input_volume_controller.h` at upstream
|
||||
/// commit d9b92fe1bc ("Make max target input level for input controller
|
||||
/// -12dB").
|
||||
#[test]
|
||||
fn default_config_matches_upstream_production_config() {
|
||||
let config = InputVolumeControllerConfig::default();
|
||||
assert_eq!(config.min_input_volume, 20);
|
||||
assert_eq!(config.clipped_level_min, 70);
|
||||
assert_eq!(config.clipped_level_step, 15);
|
||||
assert_eq!(config.clipped_ratio_threshold, 0.1);
|
||||
assert_eq!(config.clipped_wait_frames, 300);
|
||||
assert!(config.enable_clipping_predictor);
|
||||
// d9b92fe1bc raised this from -30 (M145) to the former experimental
|
||||
// value of -12 and removed `target_range_experimental_max_dbfs`.
|
||||
assert_eq!(config.target_range_max_dbfs, -12);
|
||||
assert_eq!(config.target_range_min_dbfs, -50);
|
||||
assert_eq!(config.update_input_volume_wait_frames, 100);
|
||||
assert_eq!(config.speech_probability_threshold, 0.7);
|
||||
assert_eq!(config.speech_ratio_threshold, 0.6);
|
||||
}
|
||||
|
||||
/// Port of upstream `InputVolumeControllerChannelSampleRateTest.CheckIsAlive`.
|
||||
/// Upstream's `Config{.enable_clipping_predictor = true}` equals the
|
||||
/// production default, so this checks that the default config lowers the
|
||||
/// volume on clipping, raises it below the target range, and lowers it
|
||||
/// above the target range.
|
||||
#[test]
|
||||
fn check_is_alive() {
|
||||
for num_channels in [1, 2, 3, 6] {
|
||||
for sample_rate_hz in [8000, 16000, 32000, 48000] {
|
||||
let case = format!("num_channels={num_channels}, sample_rate_hz={sample_rate_hz}");
|
||||
let config = InputVolumeControllerConfig {
|
||||
enable_clipping_predictor: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut controller = InputVolumeController::new(num_channels, &config);
|
||||
controller.initialize();
|
||||
let mut buffer = AudioBuffer::new(
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
num_channels,
|
||||
sample_rate_hz,
|
||||
);
|
||||
|
||||
const STARTUP_VOLUME: i32 = 100;
|
||||
let mut applied_input_volume = STARTUP_VOLUME;
|
||||
|
||||
// Trigger a downward adaptation with clipping.
|
||||
let level_within_target_dbfs =
|
||||
(config.target_range_min_dbfs + config.target_range_max_dbfs) / 2;
|
||||
write_alternating_audio_buffer_samples(MAX_SAMPLE, &mut buffer);
|
||||
let initial_volume_1 = applied_input_volume;
|
||||
for _ in 0..400 {
|
||||
controller.analyze_input_audio(applied_input_volume, &buffer);
|
||||
applied_input_volume = controller
|
||||
.recommend_input_volume(
|
||||
LOW_SPEECH_PROBABILITY,
|
||||
Some(level_within_target_dbfs as f32),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert!(
|
||||
controller.recommended_input_volume() < initial_volume_1,
|
||||
"{case}"
|
||||
);
|
||||
|
||||
// Fill in audio that does not clip.
|
||||
write_alternating_audio_buffer_samples(1234.5, &mut buffer);
|
||||
|
||||
// Trigger an upward adaptation.
|
||||
let initial_volume_2 = controller.recommended_input_volume();
|
||||
for _ in 0..config.clipped_wait_frames {
|
||||
controller.analyze_input_audio(applied_input_volume, &buffer);
|
||||
applied_input_volume = controller
|
||||
.recommend_input_volume(
|
||||
HIGH_SPEECH_PROBABILITY,
|
||||
Some((config.target_range_min_dbfs - 5) as f32),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert!(
|
||||
controller.recommended_input_volume() > initial_volume_2,
|
||||
"{case}"
|
||||
);
|
||||
|
||||
// Trigger a downward adaptation.
|
||||
let initial_volume = controller.recommended_input_volume();
|
||||
for _ in 0..config.update_input_volume_wait_frames {
|
||||
controller.analyze_input_audio(applied_input_volume, &buffer);
|
||||
applied_input_volume = controller
|
||||
.recommend_input_volume(
|
||||
HIGH_SPEECH_PROBABILITY,
|
||||
Some((config.target_range_max_dbfs + 5) as f32),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert!(
|
||||
controller.recommended_input_volume() < initial_volume,
|
||||
"{case}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_min_volume_configuration_respected_when_applied_input_volume_above_min() {
|
||||
for min_input_volume in [12, 20] {
|
||||
let mut helper = TestHelper::new(InputVolumeControllerConfig {
|
||||
min_input_volume,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
});
|
||||
|
||||
assert_eq!(helper.call_agc_sequence(128, 0.9, -80.0, 1).unwrap(), 128);
|
||||
@@ -1545,7 +1430,7 @@ mod tests {
|
||||
for min_input_volume in [12, 20] {
|
||||
let mut helper = TestHelper::new(InputVolumeControllerConfig {
|
||||
min_input_volume,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
});
|
||||
|
||||
assert!(helper.call_agc_sequence(10, 0.9, -80.0, 1).unwrap() >= 10);
|
||||
@@ -1561,7 +1446,7 @@ mod tests {
|
||||
update_input_volume_wait_frames: 1,
|
||||
speech_probability_threshold: 0.5,
|
||||
speech_ratio_threshold: 0.5,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
});
|
||||
|
||||
let volume = helper.call_agc_sequence(1, 0.9, -80.0, 1).unwrap();
|
||||
@@ -1578,7 +1463,7 @@ mod tests {
|
||||
update_input_volume_wait_frames: 1,
|
||||
speech_probability_threshold: 0.5,
|
||||
speech_ratio_threshold: 0.5,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
});
|
||||
|
||||
for _ in 0..100 {
|
||||
@@ -1597,7 +1482,7 @@ mod tests {
|
||||
update_input_volume_wait_frames: 1,
|
||||
speech_probability_threshold: 0.5,
|
||||
speech_ratio_threshold: 0.5,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
});
|
||||
|
||||
let volume = helper.call_agc_sequence(0, 0.9, -80.0, 1).unwrap();
|
||||
@@ -1710,7 +1595,7 @@ mod tests {
|
||||
for min_input_volume in [12, 20] {
|
||||
let config = InputVolumeControllerConfig {
|
||||
min_input_volume,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
};
|
||||
let mut helper_1 = TestHelper::new(config.clone());
|
||||
let mut helper_2 = TestHelper::new(config);
|
||||
@@ -1747,7 +1632,7 @@ mod tests {
|
||||
for min_input_volume in [12, 20] {
|
||||
let config = InputVolumeControllerConfig {
|
||||
min_input_volume,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
};
|
||||
let mut helper = TestHelper::new(config);
|
||||
helper.call_agc_sequence(
|
||||
@@ -1778,7 +1663,7 @@ mod tests {
|
||||
for min_input_volume in [12, 20] {
|
||||
let config = InputVolumeControllerConfig {
|
||||
min_input_volume,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
};
|
||||
let mut helper = TestHelper::new(config);
|
||||
helper.call_agc_sequence(
|
||||
@@ -1809,7 +1694,7 @@ mod tests {
|
||||
for min_input_volume in [12, 20] {
|
||||
let config = InputVolumeControllerConfig {
|
||||
min_input_volume,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
};
|
||||
let mut helper = TestHelper::new(config);
|
||||
helper.call_agc_sequence(
|
||||
@@ -1829,7 +1714,7 @@ mod tests {
|
||||
for min_input_volume in [12, 20] {
|
||||
let config = InputVolumeControllerConfig {
|
||||
min_input_volume,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
};
|
||||
let mut helper = TestHelper::new(config);
|
||||
helper.call_agc_sequence(
|
||||
@@ -1849,7 +1734,7 @@ mod tests {
|
||||
for min_input_volume in [12, 20] {
|
||||
let config = InputVolumeControllerConfig {
|
||||
min_input_volume,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
};
|
||||
let mut helper = TestHelper::new(config);
|
||||
helper.call_agc_sequence(255, HIGH_SPEECH_PROBABILITY, SPEECH_LEVEL, 1);
|
||||
@@ -1864,7 +1749,7 @@ mod tests {
|
||||
for min_input_volume in [12, 20] {
|
||||
let config = InputVolumeControllerConfig {
|
||||
min_input_volume,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
};
|
||||
let mut helper = TestHelper::new(config);
|
||||
helper.call_agc_sequence(255, HIGH_SPEECH_PROBABILITY, SPEECH_LEVEL, 1);
|
||||
@@ -1903,7 +1788,7 @@ mod tests {
|
||||
clipped_level_step: CLIPPED_LEVEL_STEP,
|
||||
clipped_ratio_threshold: CLIPPED_RATIO_THRESHOLD,
|
||||
clipped_wait_frames: CLIPPED_WAIT_FRAMES,
|
||||
..get_test_config()
|
||||
..Default::default()
|
||||
};
|
||||
let mut controller = InputVolumeController::new(1, &config);
|
||||
controller.initialize();
|
||||
@@ -1915,7 +1800,7 @@ mod tests {
|
||||
clipped_level_step: 10,
|
||||
clipped_ratio_threshold: 0.2,
|
||||
clipped_wait_frames: 50,
|
||||
..get_test_config()
|
||||
..Default::default()
|
||||
};
|
||||
let mut controller_custom = InputVolumeController::new(1, &config_custom);
|
||||
controller_custom.initialize();
|
||||
@@ -1933,7 +1818,7 @@ mod tests {
|
||||
clipped_ratio_threshold: CLIPPED_RATIO_THRESHOLD,
|
||||
clipped_wait_frames: CLIPPED_WAIT_FRAMES,
|
||||
enable_clipping_predictor: false,
|
||||
..get_test_config()
|
||||
..Default::default()
|
||||
};
|
||||
let mut controller = InputVolumeController::new(1, &config);
|
||||
controller.initialize();
|
||||
@@ -1951,7 +1836,7 @@ mod tests {
|
||||
clipped_ratio_threshold: CLIPPED_RATIO_THRESHOLD,
|
||||
clipped_wait_frames: CLIPPED_WAIT_FRAMES,
|
||||
enable_clipping_predictor: true,
|
||||
..get_test_config()
|
||||
..Default::default()
|
||||
};
|
||||
let mut controller = InputVolumeController::new(1, &config);
|
||||
controller.initialize();
|
||||
@@ -1966,7 +1851,7 @@ mod tests {
|
||||
for min_input_volume in [12, 20] {
|
||||
let config = InputVolumeControllerConfig {
|
||||
min_input_volume,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
};
|
||||
let mut helper = TestHelper::new(config);
|
||||
helper.call_agc_sequence(
|
||||
@@ -2002,7 +1887,7 @@ mod tests {
|
||||
let mut helper = TestHelper::new(InputVolumeControllerConfig {
|
||||
min_input_volume: 80,
|
||||
clipped_level_min: 70,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
});
|
||||
|
||||
write_audio_buffer_samples(4000.0, 0.8, &mut helper.audio_buffer);
|
||||
@@ -2017,7 +1902,7 @@ mod tests {
|
||||
let mut helper = TestHelper::new(InputVolumeControllerConfig {
|
||||
min_input_volume: 70,
|
||||
clipped_level_min: 80,
|
||||
..InputVolumeControllerConfig::default()
|
||||
..get_test_config()
|
||||
});
|
||||
|
||||
write_audio_buffer_samples(4000.0, 0.8, &mut helper.audio_buffer);
|
||||
|
||||
Vendored
-1
@@ -7,7 +7,6 @@ pub(crate) mod audio_processing_impl;
|
||||
pub(crate) mod audio_samples_scaler;
|
||||
pub(crate) mod capture_levels_adjuster;
|
||||
pub(crate) mod config_selector;
|
||||
pub(crate) mod denormal_disabler;
|
||||
pub(crate) mod echo_canceller3;
|
||||
pub(crate) mod echo_detector;
|
||||
pub(crate) mod gain_controller2;
|
||||
|
||||
+17
-175
@@ -5,8 +5,6 @@
|
||||
//!
|
||||
//! Ported from `modules/audio_processing/three_band_filter_bank.h/cc`.
|
||||
|
||||
use sonora_simd::NATIVE_FMA;
|
||||
|
||||
const SQRT_3: f32 = 1.732_050_8;
|
||||
|
||||
const SPARSITY: usize = 4;
|
||||
@@ -59,20 +57,8 @@ const DCT_MODULATION: [[f32; NUM_BANDS]; NUM_NON_ZERO_FILTERS] = [
|
||||
/// Polyphase filter core: filters `input` through `filter` with shift `in_shift`,
|
||||
/// using and updating `state`.
|
||||
///
|
||||
/// If `FMA`, the unrolled 4-tap sums of Parts 1 and 3 use [`f32::mul_add`];
|
||||
/// otherwise they use plain arithmetic, in the C++ operation order. C++ starts
|
||||
/// that sum from `0.0`; leaving it out changes only the sign of an all-zero
|
||||
/// sum, which `analysis` and `synthesis` lose when they add the result into
|
||||
/// zeroed buffers. The public methods pass [`NATIVE_FMA`]; the tests run both
|
||||
/// forms.
|
||||
///
|
||||
/// Direct port of C++ `FilterCore` in `three_band_filter_bank.cc`.
|
||||
// LLVM's inline cost for this body sits at its threshold, so without
|
||||
// `inline(always)` whether `analysis` and `synthesis` inline it depends on
|
||||
// the codegen-unit partition (with Cargo's default 16 units it did on
|
||||
// aarch64 and did not on x86_64).
|
||||
#[inline(always)]
|
||||
fn filter_core<const FMA: bool>(
|
||||
fn filter_core(
|
||||
filter: &[f32; FILTER_SIZE],
|
||||
input: &[f32; SPLIT_BAND_SIZE],
|
||||
in_shift: usize,
|
||||
@@ -93,20 +79,13 @@ fn filter_core<const FMA: bool>(
|
||||
#[allow(clippy::needless_range_loop, reason = "index used in arithmetic")]
|
||||
for k in 0..in_shift {
|
||||
let j = MEMORY_SIZE + k - in_shift;
|
||||
output[k] = if FMA {
|
||||
f0.mul_add(
|
||||
state[j],
|
||||
f1.mul_add(
|
||||
state[j - STRIDE],
|
||||
f2.mul_add(state[j - 2 * STRIDE], f3 * state[j - 3 * STRIDE]),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
f0 * state[j]
|
||||
+ f1 * state[j - STRIDE]
|
||||
+ f2 * state[j - 2 * STRIDE]
|
||||
+ f3 * state[j - 3 * STRIDE]
|
||||
};
|
||||
output[k] = f0.mul_add(
|
||||
state[j],
|
||||
f1.mul_add(
|
||||
state[j - STRIDE],
|
||||
f2.mul_add(state[j - 2 * STRIDE], f3 * state[j - 3 * STRIDE]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Part 2: transition samples (partially from input, partially from state).
|
||||
@@ -133,20 +112,13 @@ fn filter_core<const FMA: bool>(
|
||||
#[allow(clippy::needless_range_loop, reason = "index used in arithmetic")]
|
||||
for k in (FILTER_SIZE * STRIDE)..SPLIT_BAND_SIZE {
|
||||
let base = k - in_shift;
|
||||
output[k] = if FMA {
|
||||
f0.mul_add(
|
||||
input[base],
|
||||
f1.mul_add(
|
||||
input[base - STRIDE],
|
||||
f2.mul_add(input[base - 2 * STRIDE], f3 * input[base - 3 * STRIDE]),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
f0 * input[base]
|
||||
+ f1 * input[base - STRIDE]
|
||||
+ f2 * input[base - 2 * STRIDE]
|
||||
+ f3 * input[base - 3 * STRIDE]
|
||||
};
|
||||
output[k] = f0.mul_add(
|
||||
input[base],
|
||||
f1.mul_add(
|
||||
input[base - STRIDE],
|
||||
f2.mul_add(input[base - 2 * STRIDE], f3 * input[base - 3 * STRIDE]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Update state from end of input.
|
||||
@@ -179,18 +151,6 @@ impl ThreeBandFilterBank {
|
||||
&mut self,
|
||||
input: &[f32; FULL_BAND_SIZE],
|
||||
output: &mut [[f32; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
) {
|
||||
self.analysis_with::<NATIVE_FMA>(input, output);
|
||||
}
|
||||
|
||||
/// [`Self::analysis`], with [`filter_core`] in the form `FMA` selects.
|
||||
/// Always inlined, so that LLVM optimizes this body as part of
|
||||
/// `analysis`.
|
||||
#[inline(always)]
|
||||
fn analysis_with<const FMA: bool>(
|
||||
&mut self,
|
||||
input: &[f32; FULL_BAND_SIZE],
|
||||
output: &mut [[f32; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
) {
|
||||
// Initialize output to zero.
|
||||
for band in output.iter_mut() {
|
||||
@@ -224,7 +184,7 @@ impl ThreeBandFilterBank {
|
||||
|
||||
// Filter.
|
||||
let mut out_subsampled = [0.0f32; SPLIT_BAND_SIZE];
|
||||
filter_core::<FMA>(
|
||||
filter_core(
|
||||
filter,
|
||||
&in_subsampled,
|
||||
in_shift,
|
||||
@@ -248,18 +208,6 @@ impl ThreeBandFilterBank {
|
||||
&mut self,
|
||||
input: &[[f32; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
output: &mut [f32; FULL_BAND_SIZE],
|
||||
) {
|
||||
self.synthesis_with::<NATIVE_FMA>(input, output);
|
||||
}
|
||||
|
||||
/// [`Self::synthesis`], with [`filter_core`] in the form `FMA` selects.
|
||||
/// Always inlined, so that LLVM optimizes this body as part of
|
||||
/// `synthesis`.
|
||||
#[inline(always)]
|
||||
fn synthesis_with<const FMA: bool>(
|
||||
&mut self,
|
||||
input: &[[f32; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
output: &mut [f32; FULL_BAND_SIZE],
|
||||
) {
|
||||
output.fill(0.0);
|
||||
|
||||
@@ -292,7 +240,7 @@ impl ThreeBandFilterBank {
|
||||
|
||||
// Filter.
|
||||
let mut out_subsampled = [0.0f32; SPLIT_BAND_SIZE];
|
||||
filter_core::<FMA>(
|
||||
filter_core(
|
||||
filter,
|
||||
&in_subsampled,
|
||||
in_shift,
|
||||
@@ -386,112 +334,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Both forms of the unrolled Parts 1 and 3 of `filter_core`, on every
|
||||
/// target: the fused form must match the `mul_add` chain, and the plain
|
||||
/// form the C++ tap order, bit for bit.
|
||||
#[test]
|
||||
fn filter_core_matches_fused_and_plain_references() {
|
||||
use std::array::from_fn;
|
||||
|
||||
let filter = &FILTER_COEFFS[1];
|
||||
let state: [f32; MEMORY_SIZE] = from_fn(|i| (i as f32 * 0.618_034).fract() - 0.5);
|
||||
let input: [f32; SPLIT_BAND_SIZE] = from_fn(|i| (i as f32 * 0.414_214).fract() - 0.5);
|
||||
// Sample n of the stream is history[MEMORY_SIZE + n]; n < 0 is state.
|
||||
let history: Vec<f32> = state.iter().chain(&input).copied().collect();
|
||||
|
||||
let (mut part1_differs, mut part3_differs) = (false, false);
|
||||
// in_shift >= 1 so that Part 1 (state only) runs.
|
||||
for in_shift in 1..STRIDE {
|
||||
let mut fused_output = [0.0_f32; SPLIT_BAND_SIZE];
|
||||
filter_core::<true>(
|
||||
filter,
|
||||
&input,
|
||||
in_shift,
|
||||
&mut fused_output,
|
||||
&mut state.clone(),
|
||||
);
|
||||
let mut plain_output = [0.0_f32; SPLIT_BAND_SIZE];
|
||||
filter_core::<false>(
|
||||
filter,
|
||||
&input,
|
||||
in_shift,
|
||||
&mut plain_output,
|
||||
&mut state.clone(),
|
||||
);
|
||||
|
||||
// Part 2 (taps split between state and input) is unchanged.
|
||||
let parts_1_and_3 = (0..in_shift).chain(FILTER_SIZE * STRIDE..SPLIT_BAND_SIZE);
|
||||
for k in parts_1_and_3 {
|
||||
let t: [f32; FILTER_SIZE] =
|
||||
from_fn(|i| history[MEMORY_SIZE + k - in_shift - i * STRIDE]);
|
||||
let f = filter;
|
||||
let fused = f[0].mul_add(t[0], f[1].mul_add(t[1], f[2].mul_add(t[2], f[3] * t[3])));
|
||||
// C++ accumulates `out[k] += in[j] * filter[i]` for i = 0..3.
|
||||
let plain = f[0] * t[0] + f[1] * t[1] + f[2] * t[2] + f[3] * t[3];
|
||||
if fused.to_bits() != plain.to_bits() {
|
||||
if k < in_shift {
|
||||
part1_differs = true;
|
||||
} else {
|
||||
part3_differs = true;
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
fused_output[k].to_bits(),
|
||||
fused.to_bits(),
|
||||
"fused, in_shift {in_shift}, k {k}"
|
||||
);
|
||||
assert_eq!(
|
||||
plain_output[k].to_bits(),
|
||||
plain.to_bits(),
|
||||
"plain, in_shift {in_shift}, k {k}"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(part1_differs && part3_differs);
|
||||
}
|
||||
|
||||
fn bits(v: &[f32]) -> Vec<u32> {
|
||||
v.iter().map(|x| x.to_bits()).collect()
|
||||
}
|
||||
|
||||
/// Output bits of `analysis_with::<FMA>` on `input` and of
|
||||
/// `synthesis_with::<FMA>` on `bands`, each on a new filter bank.
|
||||
fn run_forms<const FMA: bool>(
|
||||
input: &[f32; FULL_BAND_SIZE],
|
||||
bands: &[[f32; SPLIT_BAND_SIZE]; NUM_BANDS],
|
||||
) -> [Vec<u32>; 2] {
|
||||
let mut analysis = [[0.0_f32; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
ThreeBandFilterBank::new().analysis_with::<FMA>(input, &mut analysis);
|
||||
let mut synthesis = [0.0_f32; FULL_BAND_SIZE];
|
||||
ThreeBandFilterBank::new().synthesis_with::<FMA>(bands, &mut synthesis);
|
||||
[bits(analysis.as_flattened()), bits(&synthesis)]
|
||||
}
|
||||
|
||||
/// `analysis` and `synthesis` run the [`NATIVE_FMA`] form.
|
||||
#[test]
|
||||
fn analysis_and_synthesis_use_native_fma() {
|
||||
use std::array::from_fn;
|
||||
|
||||
let input: [f32; FULL_BAND_SIZE] = from_fn(|i| (i as f32 * 0.618_034).fract() - 0.5);
|
||||
let bands: [[f32; SPLIT_BAND_SIZE]; NUM_BANDS] =
|
||||
from_fn(|b| from_fn(|i| ((b * SPLIT_BAND_SIZE + i) as f32 * 0.414_214).fract() - 0.5));
|
||||
// The forms differ on these inputs, so the comparison below can fail.
|
||||
let [fused, plain] = [
|
||||
run_forms::<true>(&input, &bands),
|
||||
run_forms::<false>(&input, &bands),
|
||||
];
|
||||
assert!(fused[0] != plain[0] && fused[1] != plain[1]);
|
||||
|
||||
let mut analysis = [[0.0_f32; SPLIT_BAND_SIZE]; NUM_BANDS];
|
||||
ThreeBandFilterBank::new().analysis(&input, &mut analysis);
|
||||
let mut synthesis = [0.0_f32; FULL_BAND_SIZE];
|
||||
ThreeBandFilterBank::new().synthesis(&bands, &mut synthesis);
|
||||
assert_eq!(
|
||||
[bits(analysis.as_flattened()), bits(&synthesis)],
|
||||
run_forms::<NATIVE_FMA>(&input, &bands)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_input_produces_zero_output() {
|
||||
let mut fb = ThreeBandFilterBank::new();
|
||||
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
//! `AudioProcessingBuilder::echo_canceller3_config`: a caller's AEC3 tuning
|
||||
//! reaches the echo canceller, also for stereo render, and the default path
|
||||
//! is unchanged.
|
||||
|
||||
use sonora::config::{EchoCanceller, EchoCanceller3Config};
|
||||
use sonora::{AudioProcessing, Config, StreamConfig};
|
||||
|
||||
const RATE: usize = 48_000;
|
||||
const FRAME: usize = RATE / 100;
|
||||
|
||||
/// Deterministic white noise in [-0.5, 0.5] (xorshift).
|
||||
fn noise(len: usize, seed: u64) -> Vec<f32> {
|
||||
let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
|
||||
(0..len)
|
||||
.map(|_| {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
((state >> 40) as f32 / (1u64 << 24) as f32) - 0.5
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs 4 s of far-end noise with a delayed echo plus near-end bursts
|
||||
/// (double talk) through an APM and returns the processed capture signal.
|
||||
fn run(apm: &mut AudioProcessing) -> Vec<f32> {
|
||||
let len = 4 * RATE;
|
||||
let far = noise(len, 1);
|
||||
let near = noise(len, 2);
|
||||
let mut output = Vec::with_capacity(len);
|
||||
let mut unused = [0.0f32; FRAME];
|
||||
let mut out = [0.0f32; FRAME];
|
||||
for f in 0..len / FRAME {
|
||||
let range = f * FRAME..(f + 1) * FRAME;
|
||||
let mic: Vec<f32> = range
|
||||
.clone()
|
||||
.map(|n| {
|
||||
let echo = if n >= 2400 { 0.3 * far[n - 2400] } else { 0.0 };
|
||||
// Near-end talk in every other half second.
|
||||
let talk = if (n / (RATE / 2)) % 2 == 1 {
|
||||
0.2 * near[n]
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
echo + talk
|
||||
})
|
||||
.collect();
|
||||
apm.process_render_f32(&[&far[range]], &mut [&mut unused])
|
||||
.unwrap();
|
||||
apm.process_capture_f32(&[&mic], &mut [&mut out]).unwrap();
|
||||
output.extend_from_slice(&out);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn apm(aec3: Option<EchoCanceller3Config>) -> AudioProcessing {
|
||||
apm_with_render_channels(aec3, 1)
|
||||
}
|
||||
|
||||
fn apm_with_render_channels(
|
||||
aec3: Option<EchoCanceller3Config>,
|
||||
render_channels: u16,
|
||||
) -> AudioProcessing {
|
||||
let mut builder = AudioProcessing::builder()
|
||||
.config(Config {
|
||||
echo_canceller: Some(EchoCanceller::default()),
|
||||
..Config::default()
|
||||
})
|
||||
.capture_config(StreamConfig::new(RATE as u32, 1))
|
||||
.render_config(StreamConfig::new(RATE as u32, render_channels));
|
||||
if let Some(aec3) = aec3 {
|
||||
builder = builder.echo_canceller3_config(aec3);
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_config_gives_the_same_output_as_no_config() {
|
||||
let without = run(&mut apm(None));
|
||||
let with_default = run(&mut apm(Some(EchoCanceller3Config::default())));
|
||||
assert_eq!(without, with_default);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_tuning_reaches_the_echo_canceller() {
|
||||
let default = run(&mut apm(None));
|
||||
let mut tuned_config = EchoCanceller3Config::default();
|
||||
// A much stronger assumed echo path: the suppressor removes more.
|
||||
tuned_config.ep_strength.default_gain = 10.0;
|
||||
let tuned = run(&mut apm(Some(tuned_config)));
|
||||
assert_ne!(default, tuned);
|
||||
}
|
||||
|
||||
/// Runs 8 s of independent far-end noise on two render channels with a
|
||||
/// delayed echo of both on one microphone, and returns the processed capture
|
||||
/// signal of the last 2 s: by then AEC3 has detected stereo render (after 2 s
|
||||
/// of differing channels) and processes with its multichannel config.
|
||||
fn run_stereo(apm: &mut AudioProcessing) -> Vec<f32> {
|
||||
let len = 8 * RATE;
|
||||
let far = [noise(len, 3), noise(len, 4)];
|
||||
let mut output = Vec::with_capacity(2 * RATE);
|
||||
let mut unused = [[0.0f32; FRAME]; 2];
|
||||
let mut out = [0.0f32; FRAME];
|
||||
for f in 0..len / FRAME {
|
||||
let range = f * FRAME..(f + 1) * FRAME;
|
||||
let mic: Vec<f32> = range
|
||||
.clone()
|
||||
.map(|n| {
|
||||
if n >= 2400 {
|
||||
0.3 * far[0][n - 2400] + 0.1 * far[1][n - 2400]
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let [u0, u1] = &mut unused;
|
||||
apm.process_render_f32(
|
||||
&[&far[0][range.clone()], &far[1][range.clone()]],
|
||||
&mut [u0, u1],
|
||||
)
|
||||
.unwrap();
|
||||
apm.process_capture_f32(&[&mic], &mut [&mut out]).unwrap();
|
||||
if range.start >= len - 2 * RATE {
|
||||
output.extend_from_slice(&out);
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_config_with_a_fixed_capture_delay_builds_and_processes() {
|
||||
// The default multichannel config has no fixed capture delay. Combining
|
||||
// the two used to trip ConfigSelector's compatibility check in debug
|
||||
// builds, even with mono render.
|
||||
let mut config = EchoCanceller3Config::default();
|
||||
config.delay.fixed_capture_delay_samples = 480;
|
||||
let output = run(&mut apm(Some(config)));
|
||||
assert!(output.iter().all(|s| s.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_tuning_reaches_the_echo_canceller_with_stereo_render() {
|
||||
let default = run_stereo(&mut apm_with_render_channels(None, 2));
|
||||
let mut tuned_config = EchoCanceller3Config::default();
|
||||
tuned_config.ep_strength.default_gain = 10.0;
|
||||
let tuned = run_stereo(&mut apm_with_render_channels(Some(tuned_config), 2));
|
||||
assert_ne!(default, tuned);
|
||||
}
|
||||
-505
@@ -1,505 +0,0 @@
|
||||
//! Echo cancellation runs in real-time audio callbacks, where allocating
|
||||
//! memory can block. These tests check that steady-state processing with the
|
||||
//! echo canceller enabled does not allocate, through the float and int16
|
||||
//! APIs, at the 16, 32 and 48 kHz processing rates (one, two and three
|
||||
//! bands), with rate conversion, downmixing, stereo, an unused capture output,
|
||||
//! a change of the echo delay, noise suppression and the adaptive digital
|
||||
//! gain (AGC2). They count allocations
|
||||
//! (`alloc` and `realloc`) of the current thread only, so tests running in
|
||||
//! parallel do not interfere.
|
||||
//!
|
||||
//! Frees are not counted. With multichannel render, the echo canceller
|
||||
//! rebuilds its block processor when it detects stereo render, and the new
|
||||
//! comfort noise generator frees its initial noise estimate (one buffer of 260
|
||||
//! bytes per capture channel) 1000 blocks (4 s) later, while allocations are
|
||||
//! counted. Upstream frees the same buffer at the same point.
|
||||
//!
|
||||
//! Each test also checks that the echo canceller found and removed the echo,
|
||||
//! and the noise suppression and gain tests check that their stage changed
|
||||
//! the output, so that a test cannot pass because the processing it covers was
|
||||
//! skipped.
|
||||
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::cell::Cell;
|
||||
|
||||
use sonora::config::{
|
||||
AdaptiveDigital, EchoCanceller, GainController2, MaxProcessingRate, NoiseSuppression, Pipeline,
|
||||
};
|
||||
use sonora::{AudioProcessing, Config, StreamConfig};
|
||||
|
||||
thread_local! {
|
||||
static COUNTING: Cell<bool> = const { Cell::new(false) };
|
||||
static ALLOCATIONS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
fn count() {
|
||||
if COUNTING.with(Cell::get) {
|
||||
ALLOCATIONS.with(|a| a.set(a.get() + 1));
|
||||
}
|
||||
}
|
||||
|
||||
struct CountingAllocator;
|
||||
|
||||
// SAFETY: forwards every call unchanged to the system allocator and only
|
||||
// counts calls.
|
||||
unsafe impl GlobalAlloc for CountingAllocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
count();
|
||||
// SAFETY: same contract as the caller's.
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
// SAFETY: same contract as the caller's.
|
||||
unsafe { System.dealloc(ptr, layout) }
|
||||
}
|
||||
|
||||
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
||||
count();
|
||||
// SAFETY: same contract as the caller's.
|
||||
unsafe { System.realloc(ptr, layout, new_size) }
|
||||
}
|
||||
}
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: CountingAllocator = CountingAllocator;
|
||||
|
||||
/// Deterministic noise in [-1, 1] (xorshift64).
|
||||
struct Noise(u64);
|
||||
|
||||
impl Noise {
|
||||
fn next(&mut self) -> f32 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
((self.0 >> 40) as f32 / (1u64 << 23) as f32) - 1.0
|
||||
}
|
||||
}
|
||||
|
||||
/// The sample format passed to the processing calls.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Format {
|
||||
/// Deinterleaved float (`process_*_f32`).
|
||||
F32,
|
||||
/// Interleaved int16 (`process_*_i16`), as the C API's
|
||||
/// `wap_process_stream_i16` uses.
|
||||
I16,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Scenario {
|
||||
rate: u32,
|
||||
/// The highest internal processing rate. At the default of 32 kHz, 44.1
|
||||
/// and 48 kHz streams are resampled to 32 kHz and split into two bands;
|
||||
/// processing in three bands needs 48 kHz.
|
||||
max_processing_rate: MaxProcessingRate,
|
||||
format: Format,
|
||||
capture_in_channels: u16,
|
||||
capture_out_channels: u16,
|
||||
render_channels: u16,
|
||||
capture_output_used: bool,
|
||||
/// Whether the echo delay changes from 60 ms to 100 ms after
|
||||
/// `DELAY_CHANGE_SECONDS`, so that the echo canceller has to find the new
|
||||
/// delay while allocations are counted.
|
||||
delay_change: bool,
|
||||
/// Whether noise suppression runs after the echo canceller.
|
||||
noise_suppression: bool,
|
||||
/// Whether AGC2's adaptive digital gain runs at the end of the capture
|
||||
/// path.
|
||||
gain_control: bool,
|
||||
}
|
||||
|
||||
impl Scenario {
|
||||
const fn mono(rate: u32, format: Format) -> Self {
|
||||
Self {
|
||||
rate,
|
||||
max_processing_rate: MaxProcessingRate::Rate32kHz,
|
||||
format,
|
||||
capture_in_channels: 1,
|
||||
capture_out_channels: 1,
|
||||
render_channels: 1,
|
||||
capture_output_used: true,
|
||||
delay_change: false,
|
||||
noise_suppression: false,
|
||||
gain_control: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_CHANNELS: usize = 2;
|
||||
const MAX_FRAME: usize = 480;
|
||||
const SECONDS: usize = 15;
|
||||
/// Lazy initialisation is allowed during the first 5 seconds.
|
||||
const WARM_UP_SECONDS: usize = 5;
|
||||
const DELAY_CHANGE_SECONDS: usize = 9;
|
||||
|
||||
/// Whether near-end talk is present in second `s` (every fourth second, so
|
||||
/// that double talk occurs while allocations are counted).
|
||||
fn near_end_active(s: usize) -> bool {
|
||||
s % 4 == 3
|
||||
}
|
||||
|
||||
struct Outcome {
|
||||
allocations: usize,
|
||||
erle_db: f64,
|
||||
/// Echo removed from the first capture channel over the last 3 seconds
|
||||
/// without near-end talk: microphone energy over output energy.
|
||||
attenuation_db: f64,
|
||||
delay_ms: i32,
|
||||
processing_rate: usize,
|
||||
}
|
||||
|
||||
fn run(scenario: Scenario) -> Outcome {
|
||||
let rate = scenario.rate as usize;
|
||||
let frame = rate / 100;
|
||||
let frames = SECONDS * 100;
|
||||
let samples = frames * frame;
|
||||
let cin = scenario.capture_in_channels as usize;
|
||||
let cout = scenario.capture_out_channels as usize;
|
||||
let rch = scenario.render_channels as usize;
|
||||
|
||||
let mut noise = Noise(0x1234_5678_9abc_def1);
|
||||
// Far end with pauses, independent noise per channel so that stereo
|
||||
// render is detected as stereo. The pauses keep a low noise floor rather
|
||||
// than exact zeros: AEC3 treats render as stereo only after the channels
|
||||
// have differed for 2 s without a break, and identical silent channels in
|
||||
// each pause would restart that count, so stereo render would be
|
||||
// processed as mono.
|
||||
let far: Vec<Vec<f32>> = (0..rch)
|
||||
.map(|_| {
|
||||
(0..samples)
|
||||
.map(|n| {
|
||||
let active = ((n as f32 / rate as f32) * 9.4).sin() > -0.3;
|
||||
if active {
|
||||
0.3 * noise.next()
|
||||
} else {
|
||||
0.001 * noise.next()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
// Each microphone picks up every far-end channel, with a different gain,
|
||||
// delayed by 60 ms (100 ms after the delay change), plus near-end talk
|
||||
// and a little noise.
|
||||
let mic: Vec<Vec<f32>> = (0..cin)
|
||||
.map(|c| {
|
||||
(0..samples)
|
||||
.map(|n| {
|
||||
let delay_ms = if scenario.delay_change && n >= DELAY_CHANGE_SECONDS * rate {
|
||||
100
|
||||
} else {
|
||||
60
|
||||
};
|
||||
let delay = delay_ms * rate / 1000;
|
||||
let mut echo = 0.0;
|
||||
if n >= delay {
|
||||
for (r, far_r) in far.iter().enumerate() {
|
||||
let gain = if r == c { 0.3 } else { 0.1 };
|
||||
echo += gain * far_r[n - delay];
|
||||
}
|
||||
}
|
||||
let near = if near_end_active(n / rate) {
|
||||
0.2 * noise.next()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
echo + near + 0.001 * noise.next()
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
let interleave = |channels: &[Vec<f32>]| -> Vec<i16> {
|
||||
(0..samples)
|
||||
.flat_map(|n| channels.iter().map(move |c| (c[n] * 32767.0) as i16))
|
||||
.collect()
|
||||
};
|
||||
let far_i16 = interleave(&far);
|
||||
let mic_i16 = interleave(&mic);
|
||||
|
||||
let capture_in = StreamConfig::new(scenario.rate, scenario.capture_in_channels);
|
||||
let capture_out = StreamConfig::new(scenario.rate, scenario.capture_out_channels);
|
||||
let render = StreamConfig::new(scenario.rate, scenario.render_channels);
|
||||
let mut apm = AudioProcessing::builder()
|
||||
.config(Config {
|
||||
echo_canceller: Some(EchoCanceller::default()),
|
||||
noise_suppression: scenario.noise_suppression.then(NoiseSuppression::default),
|
||||
gain_controller2: scenario.gain_control.then(|| GainController2 {
|
||||
adaptive_digital: Some(AdaptiveDigital::default()),
|
||||
..GainController2::default()
|
||||
}),
|
||||
pipeline: Pipeline {
|
||||
maximum_internal_processing_rate: scenario.max_processing_rate,
|
||||
..Pipeline::default()
|
||||
},
|
||||
..Config::default()
|
||||
})
|
||||
.capture_config(capture_in)
|
||||
.render_config(render)
|
||||
.build();
|
||||
if !scenario.capture_output_used {
|
||||
apm.set_capture_output_used(false);
|
||||
}
|
||||
|
||||
let mut render_out = [[0.0f32; MAX_FRAME]; MAX_CHANNELS];
|
||||
let mut capture_out_f32 = [[0.0f32; MAX_FRAME]; MAX_CHANNELS];
|
||||
let mut render_out_i16 = [0i16; MAX_FRAME * MAX_CHANNELS];
|
||||
let mut capture_out_i16 = [0i16; MAX_FRAME * MAX_CHANNELS];
|
||||
let [r0, r1] = &mut render_out;
|
||||
let mut render_dest = [&mut r0[..frame], &mut r1[..frame]];
|
||||
let [c0, c1] = &mut capture_out_f32;
|
||||
let mut capture_dest = [&mut c0[..frame], &mut c1[..frame]];
|
||||
|
||||
let mut mic_energy = 0.0f64;
|
||||
let mut out_energy = 0.0f64;
|
||||
for f in 0..frames {
|
||||
if f == WARM_UP_SECONDS * 100 {
|
||||
ALLOCATIONS.with(|a| a.set(0));
|
||||
COUNTING.with(|c| c.set(true));
|
||||
}
|
||||
let range = f * frame..(f + 1) * frame;
|
||||
let measure = f >= (SECONDS - 3) * 100 && !near_end_active(f / 100);
|
||||
match scenario.format {
|
||||
Format::F32 => {
|
||||
let far_src = [&far[0][range.clone()], &far[rch - 1][range.clone()]];
|
||||
let mic_src = [&mic[0][range.clone()], &mic[cin - 1][range.clone()]];
|
||||
apm.process_render_f32(&far_src[..rch], &mut render_dest[..rch])
|
||||
.unwrap();
|
||||
apm.process_capture_f32_with_config(
|
||||
&mic_src[..cin],
|
||||
&capture_in,
|
||||
&capture_out,
|
||||
&mut capture_dest[..cout],
|
||||
)
|
||||
.unwrap();
|
||||
if measure {
|
||||
for (m, o) in mic_src[0].iter().zip(capture_dest[0].iter()) {
|
||||
mic_energy += f64::from(*m) * f64::from(*m);
|
||||
out_energy += f64::from(*o) * f64::from(*o);
|
||||
}
|
||||
}
|
||||
}
|
||||
Format::I16 => {
|
||||
let far_src = &far_i16[f * frame * rch..(f + 1) * frame * rch];
|
||||
let mic_src = &mic_i16[f * frame * cin..(f + 1) * frame * cin];
|
||||
apm.process_render_i16(far_src, &mut render_out_i16[..frame * rch])
|
||||
.unwrap();
|
||||
apm.process_capture_i16_with_config(
|
||||
mic_src,
|
||||
&capture_in,
|
||||
&capture_out,
|
||||
&mut capture_out_i16[..frame * cout],
|
||||
)
|
||||
.unwrap();
|
||||
if measure {
|
||||
for k in 0..frame {
|
||||
let m = f64::from(mic_src[k * cin]);
|
||||
let o = f64::from(capture_out_i16[k * cout]);
|
||||
mic_energy += m * m;
|
||||
out_energy += o * o;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = apm.statistics();
|
||||
}
|
||||
COUNTING.with(|c| c.set(false));
|
||||
|
||||
let stats = apm.statistics();
|
||||
Outcome {
|
||||
allocations: ALLOCATIONS.with(Cell::get),
|
||||
erle_db: stats.echo_return_loss_enhancement.unwrap(),
|
||||
attenuation_db: 10.0 * (mic_energy / out_energy.max(f64::MIN_POSITIVE)).log10(),
|
||||
delay_ms: stats.delay_ms.unwrap(),
|
||||
processing_rate: apm.proc_sample_rate_hz(),
|
||||
}
|
||||
}
|
||||
|
||||
fn check(scenario: Scenario) -> Outcome {
|
||||
let outcome = run(scenario);
|
||||
// Streams above 32 kHz are processed at the maximum processing rate,
|
||||
// which decides whether the scenario covers two bands or three.
|
||||
let expected_rate = if scenario.rate <= 32_000 {
|
||||
scenario.rate
|
||||
} else {
|
||||
scenario.max_processing_rate.as_hz()
|
||||
};
|
||||
assert_eq!(
|
||||
outcome.processing_rate, expected_rate as usize,
|
||||
"processing rate: {scenario:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
outcome.allocations, 0,
|
||||
"steady-state processing allocated: {scenario:?}"
|
||||
);
|
||||
|
||||
// Without echo in the microphone signal the ERLE stays below 1 dB.
|
||||
// Without echo removal the attenuation still reaches about 6.4 dB: the
|
||||
// average of two microphones carries less echo than the first one, which
|
||||
// is the one measured (3.5 dB), and processing 48 kHz at 32 kHz drops the
|
||||
// noise above 16 kHz (2.9 dB). Noise suppression raises that to 7.3 dB.
|
||||
// Here both are above 15 dB, so 10 dB shows that the echo canceller ran
|
||||
// and converged.
|
||||
assert!(
|
||||
outcome.erle_db > 10.0,
|
||||
"ERLE is {:.1} dB: {scenario:?}",
|
||||
outcome.erle_db
|
||||
);
|
||||
if scenario.capture_output_used {
|
||||
assert!(
|
||||
outcome.attenuation_db > 10.0,
|
||||
"echo attenuated by only {:.1} dB: {scenario:?}",
|
||||
outcome.attenuation_db
|
||||
);
|
||||
}
|
||||
// The delay estimate must follow the echo, including after a change.
|
||||
let expected_delay_ms = if scenario.delay_change { 100 } else { 60 };
|
||||
assert!(
|
||||
(outcome.delay_ms - expected_delay_ms).abs() <= 10,
|
||||
"delay estimate {} ms, expected {expected_delay_ms} ms: {scenario:?}",
|
||||
outcome.delay_ms
|
||||
);
|
||||
outcome
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f32_16k_mono() {
|
||||
check(Scenario::mono(16_000, Format::F32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f32_32k_mono() {
|
||||
check(Scenario::mono(32_000, Format::F32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f32_48k_mono() {
|
||||
check(Scenario::mono(48_000, Format::F32));
|
||||
}
|
||||
|
||||
/// The only scenario that processes at 48 kHz, in three bands.
|
||||
#[test]
|
||||
fn f32_48k_mono_three_bands() {
|
||||
check(Scenario {
|
||||
max_processing_rate: MaxProcessingRate::Rate48kHz,
|
||||
..Scenario::mono(48_000, Format::F32)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn i16_16k_mono() {
|
||||
check(Scenario::mono(16_000, Format::I16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn i16_48k_mono() {
|
||||
check(Scenario::mono(48_000, Format::I16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f32_48k_stereo_in_mono_out() {
|
||||
check(Scenario {
|
||||
capture_in_channels: 2,
|
||||
..Scenario::mono(48_000, Format::F32)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f32_48k_stereo() {
|
||||
check(Scenario {
|
||||
capture_in_channels: 2,
|
||||
capture_out_channels: 2,
|
||||
render_channels: 2,
|
||||
..Scenario::mono(48_000, Format::F32)
|
||||
});
|
||||
}
|
||||
|
||||
/// 44.1 kHz is resampled to the 32 kHz processing rate and back, so this
|
||||
/// covers the int16 downmix with resampling.
|
||||
#[test]
|
||||
fn i16_44k_stereo_in_mono_out() {
|
||||
check(Scenario {
|
||||
capture_in_channels: 2,
|
||||
..Scenario::mono(44_100, Format::I16)
|
||||
});
|
||||
}
|
||||
|
||||
/// Covers the int16 multi-channel conversions with resampling.
|
||||
#[test]
|
||||
fn i16_44k_stereo() {
|
||||
check(Scenario {
|
||||
capture_in_channels: 2,
|
||||
capture_out_channels: 2,
|
||||
render_channels: 2,
|
||||
..Scenario::mono(44_100, Format::I16)
|
||||
});
|
||||
}
|
||||
|
||||
/// Noise suppression runs in the same capture callback: here two
|
||||
/// suppressors, one per capture channel, each over two bands.
|
||||
#[test]
|
||||
fn f32_48k_stereo_noise_suppression() {
|
||||
let scenario = Scenario {
|
||||
capture_in_channels: 2,
|
||||
capture_out_channels: 2,
|
||||
render_channels: 2,
|
||||
noise_suppression: true,
|
||||
..Scenario::mono(48_000, Format::F32)
|
||||
};
|
||||
let with_ns = check(scenario);
|
||||
// `check` covers the echo canceller only. If noise suppression were
|
||||
// skipped, the output would equal that of the same run without it, so
|
||||
// require a clear difference in the echo attenuation (about 2.1 dB here).
|
||||
let without_ns = run(Scenario {
|
||||
noise_suppression: false,
|
||||
..scenario
|
||||
});
|
||||
assert!(
|
||||
(with_ns.attenuation_db - without_ns.attenuation_db).abs() > 1.0,
|
||||
"noise suppression did not change the output: {:.2} dB with it, {:.2} dB without",
|
||||
with_ns.attenuation_db,
|
||||
without_ns.attenuation_db
|
||||
);
|
||||
}
|
||||
|
||||
/// AGC2's adaptive digital gain runs in the same capture callback, once per
|
||||
/// capture channel.
|
||||
#[test]
|
||||
fn f32_48k_stereo_gain_control() {
|
||||
let scenario = Scenario {
|
||||
capture_in_channels: 2,
|
||||
capture_out_channels: 2,
|
||||
render_channels: 2,
|
||||
gain_control: true,
|
||||
..Scenario::mono(48_000, Format::F32)
|
||||
};
|
||||
let with_gain = check(scenario);
|
||||
// As for noise suppression: if the gain were skipped, the output would
|
||||
// equal that of the same run without it.
|
||||
let without_gain = run(Scenario {
|
||||
gain_control: false,
|
||||
..scenario
|
||||
});
|
||||
assert!(
|
||||
(with_gain.attenuation_db - without_gain.attenuation_db).abs() > 1.0,
|
||||
"the gain did not change the output: {:.2} dB with it, {:.2} dB without",
|
||||
with_gain.attenuation_db,
|
||||
without_gain.attenuation_db
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f32_48k_capture_output_unused() {
|
||||
check(Scenario {
|
||||
capture_output_used: false,
|
||||
..Scenario::mono(48_000, Format::F32)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f32_48k_delay_change() {
|
||||
check(Scenario {
|
||||
delay_change: true,
|
||||
..Scenario::mono(48_000, Format::F32)
|
||||
});
|
||||
}
|
||||
+17
-17
@@ -25,23 +25,22 @@ serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
teamspeach-core = { path = "../core" }
|
||||
tokio.workspace = true
|
||||
i-slint-core = { version = "=1.19.1", default-features = false, features = ["std"] }
|
||||
i-slint-core = { version = "=1.18.1", default-features = false, features = ["std"] }
|
||||
libwebrtc = { workspace = true, optional = true }
|
||||
webrtc-sys = { workspace = true, optional = true }
|
||||
cxx = { version = "1", optional = true }
|
||||
tokio-stream = { version = "0.1", optional = true }
|
||||
cssparser.workspace = true
|
||||
cssparser = "=0.38.0"
|
||||
cssparser-color = "=0.6.0"
|
||||
semver = "1"
|
||||
same-file = "1"
|
||||
katex-native.workspace = true
|
||||
katex-rs.workspace = true
|
||||
mermaid-rs-renderer.workspace = true
|
||||
usvg = { version = "=0.50.0", default-features = false, features = ["text"] }
|
||||
usvg = { version = "=0.48.1", default-features = false, features = ["text"] }
|
||||
unicode-segmentation = "=1.13.3"
|
||||
base64 = "0.23"
|
||||
sha2 = "0.11"
|
||||
base16ct.workspace = true
|
||||
base64 = "0.22"
|
||||
sha2 = "0.10"
|
||||
serde_yaml_ng = "0.10"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
tempfile = "3"
|
||||
@@ -50,7 +49,7 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls", "j
|
||||
regex = "1"
|
||||
roxmltree = "0.21"
|
||||
futures = "0.3"
|
||||
zeroize = "=1.9.2"
|
||||
zeroize = "=1.9.1"
|
||||
getrandom = "=0.4.3"
|
||||
fs2 = "=0.4.3"
|
||||
indexmap = { version = "2", features = ["serde"] }
|
||||
@@ -58,10 +57,10 @@ image = { version = "=0.25.10", default-features = false, features = ["png", "jp
|
||||
teamspeach-denoise = { path = "../dsp" }
|
||||
cpal.workspace = true
|
||||
rubato.workspace = true
|
||||
ringbuf = "=0.6.0"
|
||||
ringbuf = "=0.4.8"
|
||||
hound = "=3.5.1"
|
||||
audioadapter-buffers = "=5.2.0"
|
||||
zip = { version = "=9.8.2", default-features = false, features = ["deflate"] }
|
||||
audioadapter-buffers = "=5.1.0"
|
||||
zip = { version = "=9.5.0", default-features = false, features = ["deflate"] }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
@@ -74,19 +73,19 @@ security-framework = { version = "=3.7.0", features = ["OSX_10_15"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
cpal = { workspace = true, features = ["pipewire", "pulseaudio"] }
|
||||
secret-service = { version = "=6.0.0", default-features = false, features = ["rt-default", "crypto-rust"] }
|
||||
secret-service = { version = "=5.1.0", default-features = false, features = ["rt-async-io-crypto-rust"] }
|
||||
libwebrtc = { workspace = true, optional = true, features = ["glib-main-loop"] }
|
||||
zbus = { version = "=6.5.0", features = ["tokio"] }
|
||||
zbus = { version = "=5.19.0", features = ["blocking-api"] }
|
||||
ksni = { version = "=0.3.7", features = ["blocking"] }
|
||||
directories = "=6.0.0"
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
slint = { workspace = true, features = ["backend-winit", "renderer-software", "system-tray", "raw-window-handle-06", "unstable-winit-030"] }
|
||||
cap-std = "=4.0.3"
|
||||
cap-fs-ext = "=4.0.3"
|
||||
rfd = "=0.18.0"
|
||||
cap-std = "=3.4.5"
|
||||
cap-fs-ext = "=3.4.5"
|
||||
rfd = "=0.15.4"
|
||||
arboard = { version = "=3.7.0", default-features = false }
|
||||
open = "=5.4.5"
|
||||
open = "=5.3.2"
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
slint = { workspace = true, features = ["backend-winit", "renderer-skia"] }
|
||||
@@ -94,8 +93,9 @@ slint = { workspace = true, features = ["backend-winit", "renderer-skia"] }
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
slint = { workspace = true, features = ["backend-android-activity-06"] }
|
||||
jni = "=0.21.1"
|
||||
i-slint-backend-android-activity = { version = "=1.19.1", default-features = false, features = ["aa-06", "native-activity"] }
|
||||
i-slint-backend-android-activity = { version = "=1.18.1", default-features = false, features = ["aa-06", "native-activity"] }
|
||||
|
||||
[build-dependencies]
|
||||
slint-build.workspace = true
|
||||
cc = "1"
|
||||
webrtc-sys-build = "=0.3.21"
|
||||
+6
-8
@@ -1,15 +1,13 @@
|
||||
fn main() {
|
||||
println!("cargo:rustc-env=TEAMSPEACH_BUILD_TARGET={}", std::env::var("TARGET").expect("target triple"));
|
||||
build_platform();
|
||||
if std::env::var_os("CARGO_FEATURE_TEST_HARNESS").is_some()
|
||||
&& matches!(std::env::var("CARGO_CFG_TARGET_OS").as_deref(), Ok(os) if !matches!(os, "android" | "ios"))
|
||||
{
|
||||
let config = slint_build::CompilerConfiguration::new().with_debug_info(true);
|
||||
slint_build::compile_with_config("ui/app.slint", config).expect("compile native interface");
|
||||
} else {
|
||||
slint_build::compile("ui/app.slint").expect("compile native interface");
|
||||
}
|
||||
slint_build::compile("ui/app.slint").expect("compile native interface");
|
||||
if std::env::var_os("CARGO_FEATURE_WEBRTC").is_some() {
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("android") {
|
||||
// Link arguments from the webrtc-sys rlib do not propagate into this cdylib.
|
||||
assert!(std::env::var_os("LK_CUSTOM_WEBRTC").is_some(), "Android requires verified source-built WebRTC");
|
||||
webrtc_sys_build::configure_jni_symbols().expect("export matching WebRTC JNI entrypoints");
|
||||
}
|
||||
build_camera();
|
||||
build_mobile_capture();
|
||||
}
|
||||
|
||||
@@ -27,30 +27,21 @@ async fn main()->Result<(),Box<dyn std::error::Error>> {
|
||||
let a=tokio::spawn(async move{while let Some(event)=outgoing.recv().await{if let SignalPeerEvent::LocalCandidate(candidate)=event{target.add_candidate(candidate).await?;}}Ok::<_,teamspeach_native::media::stream::signal::StreamError>(())});
|
||||
let target=publisher.clone();
|
||||
let b=tokio::spawn(async move{while let Some(event)=incoming.recv().await{if let SignalPeerEvent::LocalCandidate(candidate)=event{target.add_candidate(candidate).await?;}}Ok::<_,teamspeach_native::media::stream::signal::StreamError>(())});
|
||||
let mut frames=[(81,90,240),(145,54,34)].map(|(luma,cb,cr)|{
|
||||
let mut pixels=I420Buffer::new(64,48);
|
||||
let(y,u,v)=pixels.data_mut();y.fill(luma);u.fill(cb);v.fill(cr);
|
||||
let mut frame=VideoFrame::new(VideoRotation::VideoRotation0,pixels);
|
||||
frame.color_matrix=6;frame.color_range=1;frame
|
||||
});
|
||||
let output=std::path::Path::new("target/codec-fixtures");std::fs::create_dir_all(output)?;
|
||||
let started=Instant::now();let mut shown=[0usize;2];let mut sent=0;
|
||||
while started.elapsed()<Duration::from_secs(12)&&shown[1]<6 {
|
||||
let phase=usize::from(shown[0]>=6);
|
||||
let frame=&mut frames[phase];
|
||||
let mut pixels=I420Buffer::new(64,48);
|
||||
{let(y,u,v)=pixels.data_mut();y.fill(81);u.fill(90);v.fill(240);}
|
||||
let mut frame=VideoFrame::new(VideoRotation::VideoRotation0,pixels);
|
||||
frame.color_matrix=6;frame.color_range=1;
|
||||
let started=Instant::now();let mut shown=0;let mut sent=0;
|
||||
while started.elapsed()<Duration::from_secs(12)&&shown<12 {
|
||||
frame.timestamp_us=started.elapsed().as_micros().max(1) as i64;
|
||||
source.capture_video(frame)?;sent+=1;
|
||||
source.capture_video(&frame)?;sent+=1;
|
||||
let surface=surfaces.lock().unwrap().clone();
|
||||
if let Some(surface)=surface {
|
||||
if let Some(image)=surface.take_image(64,48)?{
|
||||
let bytes=image.pixels.as_bytes();let at=((24*64+32)*4) as usize;
|
||||
let colour=match bytes[at..at+3] {
|
||||
[220..=255,0..=30,0..=30] if shown[1]==0=>0,
|
||||
[0..=30,220..=255,0..=30] if phase==1=>1,
|
||||
_=>return Err(format!("Unexpected decoded pixel {:?} in phase {phase}",&bytes[at..at+4]).into()),
|
||||
};
|
||||
if shown[colour]==0{image::save_buffer(output.join(["peer-loopback-red.png","peer-loopback-green.png"][colour]),bytes,image.pixels.width(),image.pixels.height(),image::ColorType::Rgba8)?;}
|
||||
shown[colour]+=1;drop(image.image);surface.recycle(image.pixels);
|
||||
if bytes[at]<220||bytes[at+1]>30||bytes[at+2]>30{return Err(format!("Wrong decoded red pixel {:?}",&bytes[at..at+4]).into())}
|
||||
if shown==0{image::save_buffer("target/codec-fixtures/peer-loopback.png",bytes,image.pixels.width(),image.pixels.height(),image::ColorType::Rgba8)?;}
|
||||
shown+=1;drop(image.image);surface.recycle(image.pixels);
|
||||
}
|
||||
}
|
||||
for event in events.try_iter(){if matches!(event,AudioEvent::Started{..}){return Err("A physical audio device was unexpectedly started".into())}}
|
||||
@@ -58,13 +49,13 @@ async fn main()->Result<(),Box<dyn std::error::Error>> {
|
||||
tokio::time::sleep(Duration::from_millis(34)).await;
|
||||
}
|
||||
let statistics=viewer.decoder_status().await?;
|
||||
source.ended();assert!(source.capture_video(&frames[1]).is_err());
|
||||
source.ended();assert!(source.capture_video(&frame).is_err());
|
||||
publisher.close();viewer.close();a.abort();b.abort();let _=a.await;let _=b.await;
|
||||
if let Some(surface)=surfaces.lock().unwrap().take(){assert!(surface.take_image(64,48)?.is_none());}
|
||||
assert_eq!(stopped.load(Ordering::SeqCst),1);
|
||||
audio.shutdown().await?;manager.shutdown().await?;
|
||||
if shown[0]<6||shown[1]<6{return Err(format!("Only {shown:?} red/green frames from {sent} generated frames; stats={statistics:?}").into())}
|
||||
if shown<12{return Err(format!("Only {shown} decoded frames from {sent} generated frames; stats={statistics:?}").into())}
|
||||
if !statistics.iter().any(|stat|stat.frames_decoded>=12&&!stat.implementation.is_empty()){return Err(format!("Missing actual decoder statistics: {statistics:?}").into())}
|
||||
println!("native_peer_loopback sent={sent} red={} green={} stop_callbacks=1 no_physical_audio=true stats={statistics:?}",shown[0],shown[1]);
|
||||
println!("native_peer_loopback sent={sent} presented={shown} stop_callbacks=1 no_physical_audio=true stats={statistics:?}");
|
||||
Ok(())
|
||||
}
|
||||
+296571
-43526
File diff suppressed because it is too large.
Load diff
@@ -9,7 +9,7 @@ import sys
|
||||
|
||||
root, archive, output, target, compiler = sys.argv[1:]
|
||||
root, archive, output = map(pathlib.Path, (root, archive, output))
|
||||
wrapper = root / 'native/vendor/webrtc-sys-0.3.55'
|
||||
wrapper = root / 'native/vendor/webrtc-sys-0.3.53'
|
||||
include = archive / 'include'
|
||||
lines = (archive / 'webrtc.ninja').read_text().splitlines()
|
||||
definitions = next((line.removeprefix('defines = ') for line in lines if line.startswith('defines = ')), None)
|
||||
|
||||
@@ -23,12 +23,9 @@
|
||||
"bookmarks.empty": "No Bookmarks",
|
||||
"window.titlebar": "Window title bar",
|
||||
"ui.starting.core": "Starting core…",
|
||||
"native.identity.review_level": "Review identity: level {level} required",
|
||||
"native.core.stopping": "Stopping core…",
|
||||
"ui.restarting.core": "Restarting core…",
|
||||
"ui.core.unavailable": "Core unavailable",
|
||||
"ui.restart.core": "Restart core",
|
||||
"native.core.restarted": "Restarted the core for {tab}.",
|
||||
"ui.import.backup": "Import backup…",
|
||||
"ui.open.logs": "Open logs",
|
||||
"ui.what.should.we.call.you": "What should we call you?",
|
||||
@@ -289,7 +286,6 @@
|
||||
"ui.selected.device": "selected device",
|
||||
"ui.system.default.device": "Default Device",
|
||||
"ui.previously.selected.device.currently.unavailable": "Previously selected device (currently unavailable)",
|
||||
"audio.recovery.connect_or_select_new": "Reconnect the device or select another one.",
|
||||
"ui.output.device.selection.is.not.supported": "Output device selection is not supported",
|
||||
"ui.selected.microphone.unavailable.using.the.default.microphone": "Selected microphone unavailable; using the default microphone",
|
||||
"ui.microphone.disconnected": "Microphone disconnected",
|
||||
@@ -684,7 +680,6 @@
|
||||
"themes.user.enabled": "Use a third party theme",
|
||||
"themes.user.disabled": "Use stock theme",
|
||||
"themes.open.directory": "Open Extension Directory",
|
||||
"native.theme.open_package_directory": "Open folder for {name}",
|
||||
"themes.refresh": "Reload themes",
|
||||
"themes.empty": "We didn't find any themes",
|
||||
"themes.choose.above": "Choose a theme above",
|
||||
@@ -693,7 +688,6 @@
|
||||
"themes.details": "Version {version} · License {license} · Author {author}",
|
||||
"themes.community.server": "Community server: {address}",
|
||||
"themes.resources.homepage": "Open Homepage",
|
||||
"themes.resources.docs": "Open Documentation",
|
||||
"themes.resources.repository": "Open Repository",
|
||||
"themes.contact.send.email": "Send an E-Mail",
|
||||
"themes.link.confirm": "Open {url} outside TeamsPeach?",
|
||||
@@ -771,7 +765,6 @@
|
||||
"recording.status.idle": "Not Recording",
|
||||
"recording.status.recording": "Recording",
|
||||
"recording.status.paused": "Paused",
|
||||
"recording.status.finalizing": "Finalizing recording",
|
||||
"recording.card.title": "Record your TeamSpeak session.",
|
||||
"recording.card.setup.title": "Recording Options",
|
||||
"recording.card.subtitle.modes": "Choose between recording each client on a separate track, recording the mixed audio output, or creating both recordings simultaneously.",
|
||||
@@ -905,7 +898,7 @@
|
||||
"os.hide_in_taskbar.close": "On Close",
|
||||
"os.hide_in_taskbar.warning": "TeamsPeach keeps running in the background; use Quit in the tray icon menu to exit.",
|
||||
"os.locked.mute_microphone": "Mute microphone when locked",
|
||||
"os.locked.mute_microphone.desc": "Mute the microphone when the computer is locked. Unlocking does not unmute it.",
|
||||
"os.locked.mute_microphone.desc": "Mute the microphone when the computer is locked and unmute it again on unlock if TeamsPeach muted it.",
|
||||
"os.unsupported.platform": "Not available on this operating system.",
|
||||
"os.unsupported.not_packaged": "Only available in the installed app.",
|
||||
"os.unsupported.test_mode": "Disabled in test mode.",
|
||||
@@ -932,8 +925,6 @@
|
||||
"files.action.upload": "Upload",
|
||||
"files.action.new_folder": "New Folder",
|
||||
"files.action.download": "Download",
|
||||
"files.action.download_folder": "Download folder",
|
||||
"files.transfer.control_unavailable": "{operation}: unavailable for this transfer.",
|
||||
"files.action.copy_url": "Copy URL",
|
||||
"files.action.rename": "Rename",
|
||||
"files.action.delete": "Delete",
|
||||
@@ -946,9 +937,7 @@
|
||||
"files.password.placeholder": "Password",
|
||||
"files.password.open": "Open File Browser",
|
||||
"files.password.invalid": "The given password is invalid",
|
||||
"files.storage.operation_unavailable": "{operation}: unavailable with TeamSpeak 6 {kind} file transfer.",
|
||||
"files.storage.inline_images": "Inline server images",
|
||||
"files.storage.snapshot_icons": "Snapshot icons",
|
||||
"files.storage.unsupported": "This server stores channel files with TeamSpeak 6 {kind} file transfer, which TeamsPeach does not support yet. Files kept there cannot be shown or transferred here.",
|
||||
"files.malformed": "The server sent {count} unreadable entries; they are not shown.",
|
||||
"files.confirm.delete.file": "Are you sure you want to delete the file {name}?",
|
||||
"files.confirm.delete.folder": "Are you sure you want to delete the folder {name}?",
|
||||
@@ -1008,14 +997,6 @@
|
||||
"appearance.detailed": "Detailed",
|
||||
"recording.mute_client": "Mute or unmute {name}",
|
||||
"recording.client_gain": "Volume for {name}",
|
||||
"notify.event.group_changed": "Your channel group changed",
|
||||
"notify.event.error": "General error",
|
||||
"notify.event.moderator_moved_in": "Client moved to your channel by a moderator",
|
||||
"notify.event.kicked_in": "Client kicked into your channel",
|
||||
"notify.event.moderator_moved_out": "Client moved out of your channel by a moderator",
|
||||
"notify.event.server_group_assigned": "Server group assigned to you",
|
||||
"notify.event.server_group_revoked": "Server group removed from you",
|
||||
"notify.event.permission_denied": "Insufficient permissions",
|
||||
"notify.event.poked": "Poke received",
|
||||
"notify.event.text_client": "Private message received",
|
||||
"notify.event.text_channel": "Channel message received",
|
||||
@@ -1183,8 +1164,6 @@
|
||||
"admin.serverField.max_upload_total_bandwidth": "Maximum Upload Bandwidth",
|
||||
"admin.serverField.download_quota": "Download Quota",
|
||||
"admin.serverField.upload_quota": "Upload Quota",
|
||||
"admin.serverField.storage_quota": "Storage Quota",
|
||||
"admin.serverField.sfu_endpoint": "SFU Endpoint",
|
||||
"admin.serverField.antiflood_points_tick_reduce": "Flood Points Removed per Tick",
|
||||
"admin.serverField.antiflood_points_needed_command_block": "Command Block Flood Threshold",
|
||||
"admin.serverField.antiflood_points_needed_ip_block": "IP Block Flood Threshold",
|
||||
@@ -1214,7 +1193,6 @@
|
||||
"admin.showAdvanced": "Show Advanced",
|
||||
"admin.hideAdvanced": "Hide Advanced",
|
||||
"admin.encrypt": "Encrypt Voice Chat",
|
||||
"admin.serverDefault": "Server default",
|
||||
"admin.flagDefault": "Default",
|
||||
"admin.noTopic": "No topic",
|
||||
"admin.noDescription": "No description",
|
||||
@@ -1356,17 +1334,9 @@
|
||||
"snapshots.cancelledPartial": "Cancelled. Completed server changes remain; review the results below.",
|
||||
"snapshots.cancelled": "Cancelled.",
|
||||
"snapshots.partial": "Completed with omissions or failures. Review each result below; this is not a complete snapshot operation.",
|
||||
"snapshots.partialApply": "Completed with omissions or failures. Completed server changes remain; review the results below.",
|
||||
"snapshots.saved": "Saved {name}.",
|
||||
"snapshots.applied": "Snapshot applied successfully.",
|
||||
"snapshots.completedChanges": "Completed changes: {count}",
|
||||
"snapshots.changeCreated": "Created",
|
||||
"snapshots.changeIconUploaded": "Icon uploaded",
|
||||
"snapshots.changeRenamed": "Renamed",
|
||||
"snapshots.changeProperty": "Property changed",
|
||||
"snapshots.changeDefault": "Default group set",
|
||||
"snapshots.changePermission": "Permission set",
|
||||
"snapshots.changeMemberAdded": "Member added",
|
||||
"snapshots.cancelling": "Cancelling after the current server operation…",
|
||||
"snapshots.warning": "Import creates channels and groups and may change server settings, defaults and existing names. It is not atomic: cancellation or failure does not undo completed changes. The target server must support UID-based member assignment; refused assignments are reported individually.",
|
||||
"snapshots.catalog": "Catalog entry",
|
||||
@@ -1547,7 +1517,6 @@
|
||||
"audio.perDevice": "Processing settings apply to the selected input or output device. Unavailable devices keep their profiles.",
|
||||
"audio.ptt": "Push to talk",
|
||||
"audio.pttKey": "Push-to-talk key",
|
||||
"audio.pttKey.single": "Choose one key without modifiers.",
|
||||
"audio.releaseDelay": "Release delay",
|
||||
"audio.off": "Off",
|
||||
"audio.vad": "Voice activity detection",
|
||||
@@ -1880,10 +1849,6 @@
|
||||
"settings.privacy.chat.typing.info": "When enabled other people will see your typing status.",
|
||||
"settings.privacy.chat.unavailable": "Not available in TeamsPeach: these options control myTeamSpeak chat services, which TeamsPeach does not use. Your server connection and typing status are never published.",
|
||||
"settings.privacy.external_links": "External Links",
|
||||
"native.privacy.list": "Phishing domain list",
|
||||
"native.privacy.list.current": "Up to date",
|
||||
"native.privacy.list.cached": "Using the last available list",
|
||||
"native.privacy.list.unavailable": "No list loaded",
|
||||
"settings.privacy.external_links.allow_whitelist_malicious": "Allow trusting sites flagged as malicious",
|
||||
"settings.privacy.external_links.allow_whitelist_malicious.info": "When enabled, you can mark sites flagged as potentially malicious as trusted. Use with caution.",
|
||||
"settings.privacy.external_links.manage_trusted": "Manage trusted sites",
|
||||
@@ -2137,8 +2102,6 @@
|
||||
"settings.whisper.receive": "Receive whispers",
|
||||
"settings.whisper.receive.all": "Allow All",
|
||||
"settings.whisper.receive.deny": "Deny All",
|
||||
"settings.whisper.warning.read_only": "Whisper settings are read-only because they were saved by a newer version. The original file has not been changed.",
|
||||
"settings.whisper.warning.recovery": "Some saved Whisper settings could not be loaded. The original file has not been changed.",
|
||||
"settings.whisper.title.activity": "Manage Whisper Lists",
|
||||
"settings.whisper.type.clients_channel": "Clients & Channels",
|
||||
"universal.disconnected": "Disconnected",
|
||||
@@ -2195,21 +2158,6 @@
|
||||
"settings.identity.nickname.info": "Your nickname is displayed to other users on a TeamSpeak Server",
|
||||
"settings.identity.security_level.info": "Some servers may require a higher security level to connect as a spam protection mechanism. You can increase your own security level here, which takes exponentially longer per level.",
|
||||
"settings.identity.delete.warning": "Are sure you want to delete this identity? TeamSpeak servers will not be able to uniquely identify you.",
|
||||
"settings.identity.delete.title": "Delete identity",
|
||||
"settings.identity.delete.backup_warning": "Permanently delete this private identity? Export a backup first. Bookmarks referencing it must be reassigned.",
|
||||
"settings.identity.delete.referenced": "Reassign this identity's bookmarks before deleting it.",
|
||||
"settings.identity.import.warning": "Only import identities you own. The selected INI contains a private key.",
|
||||
"settings.identity.import.size": "Identity import exceeds one MiB.",
|
||||
"settings.identity.import.result": "Added: {added}. Already in profile: {existing}.",
|
||||
"settings.identity.import.encoding": "Identity INI must be UTF-8.",
|
||||
"settings.identity.export.overwrite.title": "Overwrite identity export",
|
||||
"settings.identity.export.overwrite.warning": "The selected file already contains data. Replace it with this private identity?",
|
||||
"settings.identity.export.worker_stopped": "The identity export worker stopped.",
|
||||
"settings.identity.name.invalid": "Use at most 64 characters and no control characters in the identity name.",
|
||||
"settings.identity.missing": "This identity no longer exists.",
|
||||
"settings.identity.improve.higher_target": "Choose a higher security target.",
|
||||
"settings.identity.improve.busy": "Security improvement is already running.",
|
||||
"settings.identity.improve.worker_stopped": "The security improvement worker stopped.",
|
||||
"settings.identity.new.placeholder": "New Identity Name",
|
||||
"settings.identity.improve": "Improve",
|
||||
"universal.stop": "Stop",
|
||||
@@ -2276,25 +2224,6 @@
|
||||
"settings.about.project.releases": "Releases",
|
||||
"settings.about.project.notice": "TeamSpeak is a trademark of TeamSpeak Systems GmbH. TeamsPeach is an independent client and is not affiliated with or endorsed by TeamSpeak Systems GmbH.",
|
||||
"settings.about.details.title": "Installation Details",
|
||||
"settings.about.details.runtime": "Native Runtime",
|
||||
"settings.about.details.target": "Build Target",
|
||||
"settings.about.details.os": "Operating System",
|
||||
"settings.about.details.arch": "Architecture",
|
||||
"settings.about.details.profile": "Profile Directory",
|
||||
"settings.about.details.logs": "Log Directory",
|
||||
"settings.about.details.logs_disabled": "Opening the log directory is disabled in this session.",
|
||||
"settings.about.details.logs_no_reveal": "This operating system cannot open the application’s log directory.",
|
||||
"settings.about.details.logs_missing": "The log directory does not exist.",
|
||||
"settings.about.details.connections": "Connection Tabs",
|
||||
"settings.about.details.network": "Network Access",
|
||||
"settings.about.details.os_actions": "Operating System Actions",
|
||||
"settings.about.details.enabled": "Enabled",
|
||||
"settings.about.details.disabled": "Disabled",
|
||||
"settings.about.details.audio": "Audio Status",
|
||||
"settings.about.details.video": "Video Backend",
|
||||
"settings.about.details.prefs": "Preferences",
|
||||
"settings.about.licenses.group.native": "Native Application",
|
||||
"settings.about.licenses.no_bundled_text": "No license text is bundled for this dependency. Its declared license is {license}.",
|
||||
"settings.privacy.analytics.limited.basic_system_information": "Basic System Information",
|
||||
"settings.privacy.analytics.limited.client_launch_time": "Client Launch Time",
|
||||
"settings.privacy.analytics.limited.client_usage_duration": "Client Usage Duration",
|
||||
@@ -2337,7 +2266,6 @@
|
||||
"native.stream.waiting": "Waiting for video",
|
||||
"native.stream.preview": "Preview selected source",
|
||||
"native.stream.start": "Start sharing",
|
||||
"native.stream.edit": "Edit broadcast",
|
||||
"native.stream.stop": "Stop sharing",
|
||||
"native.stream.fullscreen": "Full screen",
|
||||
"native.stream.popout": "Open in separate window",
|
||||
@@ -2347,9 +2275,7 @@
|
||||
"native.form.confirm": "Type the target name to confirm: {target}",
|
||||
"native.form.changed": "The target changed. Close this form and try again.",
|
||||
"native.form.length": "This value is too long",
|
||||
"native.form.pokeControls": "Use one line without tabs or other control characters",
|
||||
"native.shell.details": "Details",
|
||||
"native.shell.recentServerEvents": "Recent Server Events",
|
||||
"native.shell.chat": "Chat",
|
||||
"native.shell.streams": "Streams",
|
||||
"native.shell.resize": "Resize pane",
|
||||
@@ -2358,7 +2284,6 @@
|
||||
"native.snapshot.variable": "Variable",
|
||||
"native.snapshot.value": "Value",
|
||||
"native.bookmark.move": "Move bookmark",
|
||||
"native.bookmark.move.before": "Insert Before",
|
||||
"native.bookmark.reveal": "Reveal saved password",
|
||||
"native.bookmark.clear": "Clear saved password",
|
||||
"native.contact.add": "Add contact",
|
||||
@@ -2366,9 +2291,6 @@
|
||||
"native.stream.admission": "Stream access request",
|
||||
"native.stream.accept": "Allow viewer",
|
||||
"native.stream.reject": "Reject viewer",
|
||||
"native.stream.accept_viewer": "Allow {name}",
|
||||
"native.stream.reject_viewer": "Reject {name}",
|
||||
"native.stream.remove_viewer": "Kick {name} from Stream",
|
||||
"native.files.overwrite": "Replace existing file",
|
||||
"native.form.advanced": "Advanced options"
|
||||
,"native.theme.import": "Import Theme…"
|
||||
@@ -2380,5 +2302,4 @@
|
||||
,"native.audio.new_device": "New device"
|
||||
,"native.audio.copy_template": "Use as template"
|
||||
,"native.audio.apply_template": "Apply template"
|
||||
,"native.chat.matrix_rooms_unavailable": "This server offers Matrix rooms, which TeamsPeach does not support. This conversation uses standard server chat."
|
||||
}
|
||||
@@ -26,7 +26,6 @@
|
||||
"ui.restarting.core": "Перезапуск ядра…",
|
||||
"ui.core.unavailable": "Ядро недоступно",
|
||||
"ui.restart.core": "Перезапустить ядро",
|
||||
"native.core.restarted": "Ядро вкладки «{tab}» перезапущено.",
|
||||
"ui.import.backup": "Импортировать резервную копию…",
|
||||
"ui.open.logs": "Открыть журналы",
|
||||
"ui.what.should.we.call.you": "Как вас называть?",
|
||||
@@ -287,7 +286,6 @@
|
||||
"ui.selected.device": "выбранное устройство",
|
||||
"ui.system.default.device": "Устройство по умолчанию",
|
||||
"ui.previously.selected.device.currently.unavailable": "Выбранное ранее устройство (сейчас не найдено)",
|
||||
"audio.recovery.connect_or_select_new": "Подключите устройство снова или выберите другое.",
|
||||
"ui.output.device.selection.is.not.supported": "Выбор устройства вывода не поддерживается",
|
||||
"ui.selected.microphone.unavailable.using.the.default.microphone": "Выбранный микрофон недоступен, используется микрофон по умолчанию",
|
||||
"ui.microphone.disconnected": "Микрофон отключён",
|
||||
@@ -684,7 +682,6 @@
|
||||
"themes.user.enabled": "Использовать внешнюю тему",
|
||||
"themes.user.disabled": "Использовать стандартную тему",
|
||||
"themes.open.directory": "Открыть каталог расширений",
|
||||
"native.theme.open_package_directory": "Открыть папку темы «{name}»",
|
||||
"themes.refresh": "Перезагрузить темы",
|
||||
"themes.empty": "Мы не нашли ни одной темы",
|
||||
"themes.choose.above": "Выбери тему из вариантов выше",
|
||||
@@ -693,7 +690,6 @@
|
||||
"themes.details": "Версия {version} · Лицензия {license} · Автор {author}",
|
||||
"themes.community.server": "Сервер сообщества: {address}",
|
||||
"themes.resources.homepage": "Открыть домашнюю страницу",
|
||||
"themes.resources.docs": "Открыть документацию",
|
||||
"themes.resources.repository": "Открыть репозиторий",
|
||||
"themes.contact.send.email": "Отправить эл. письмо",
|
||||
"themes.link.confirm": "Открыть {url} вне TeamsPeach?",
|
||||
@@ -771,7 +767,6 @@
|
||||
"recording.status.idle": "Запись не ведётся",
|
||||
"recording.status.recording": "Идёт запись",
|
||||
"recording.status.paused": "Пауза",
|
||||
"recording.status.finalizing": "Завершение записи",
|
||||
"recording.card.title": "Запишите свою сессию TeamSpeak.",
|
||||
"recording.card.setup.title": "Параметры записи",
|
||||
"recording.card.subtitle.modes": "Выберите, как записывать: каждого участника на отдельную дорожку, общий микс или оба варианта одновременно.",
|
||||
@@ -905,7 +900,7 @@
|
||||
"os.hide_in_taskbar.close": "При закрытии",
|
||||
"os.hide_in_taskbar.warning": "TeamsPeach продолжит работать в фоне; для выхода используйте «Выйти» в меню значка в трее.",
|
||||
"os.locked.mute_microphone": "Выключать микрофон при блокировке",
|
||||
"os.locked.mute_microphone.desc": "Выключать микрофон при блокировке компьютера. После разблокировки он останется выключенным.",
|
||||
"os.locked.mute_microphone.desc": "Выключать микрофон, когда компьютер заблокирован, и включать снова после разблокировки, если его выключил TeamsPeach.",
|
||||
"os.unsupported.platform": "Недоступно в этой операционной системе.",
|
||||
"os.unsupported.not_packaged": "Доступно только в установленном приложении.",
|
||||
"os.unsupported.test_mode": "Отключено в тестовом режиме.",
|
||||
@@ -932,8 +927,6 @@
|
||||
"files.action.upload": "Загрузить",
|
||||
"files.action.new_folder": "Новая папка",
|
||||
"files.action.download": "Скачать",
|
||||
"files.action.download_folder": "Скачать папку",
|
||||
"files.transfer.control_unavailable": "{operation}: недоступно для этой передачи.",
|
||||
"files.action.copy_url": "Копировать URL",
|
||||
"files.action.rename": "Переименовать",
|
||||
"files.action.delete": "Удалить",
|
||||
@@ -946,9 +939,7 @@
|
||||
"files.password.placeholder": "Пароль",
|
||||
"files.password.open": "Открыть файловый браузер",
|
||||
"files.password.invalid": "Указанный пароль недействителен",
|
||||
"files.storage.operation_unavailable": "{operation}: недоступно при передаче файлов через TeamSpeak 6 {kind}.",
|
||||
"files.storage.inline_images": "Изображения из файлов сервера в чате",
|
||||
"files.storage.snapshot_icons": "Значки снимка сервера",
|
||||
"files.storage.unsupported": "Этот сервер хранит файлы каналов через передачу файлов TeamSpeak 6 {kind}, которую TeamsPeach пока не поддерживает. Файлы из этого хранилища здесь не показываются и не передаются.",
|
||||
"files.malformed": "Сервер прислал нечитаемые записи ({count}); они не показаны.",
|
||||
"files.confirm.delete.file": "Действительно удалить файл {name}?",
|
||||
"files.confirm.delete.folder": "Действительно удалить папку {name}?",
|
||||
@@ -1008,14 +999,6 @@
|
||||
"appearance.detailed": "Подробнее",
|
||||
"recording.mute_client": "Заглушить или включить {name}",
|
||||
"recording.client_gain": "Громкость {name}",
|
||||
"notify.event.group_changed": "Ваша канальная группа изменена",
|
||||
"notify.event.error": "Общая ошибка",
|
||||
"notify.event.moderator_moved_in": "Клиент перемещён в ваш канал модератором",
|
||||
"notify.event.kicked_in": "Клиент исключён из другого канала и перемещён в ваш",
|
||||
"notify.event.moderator_moved_out": "Клиент перемещён из вашего канала модератором",
|
||||
"notify.event.server_group_assigned": "Вам назначена серверная группа",
|
||||
"notify.event.server_group_revoked": "У вас отозвана серверная группа",
|
||||
"notify.event.permission_denied": "Недостаточно прав",
|
||||
"notify.event.poked": "Получен толчок",
|
||||
"notify.event.text_client": "Получено личное сообщение",
|
||||
"notify.event.text_channel": "Сообщение канала",
|
||||
@@ -1183,8 +1166,6 @@
|
||||
"admin.serverField.max_upload_total_bandwidth": "Максимальная скорость загрузки",
|
||||
"admin.serverField.download_quota": "Квота скачивания",
|
||||
"admin.serverField.upload_quota": "Квота загрузки",
|
||||
"admin.serverField.storage_quota": "Квота хранения",
|
||||
"admin.serverField.sfu_endpoint": "Адрес SFU",
|
||||
"admin.serverField.antiflood_points_tick_reduce": "Снижение баллов флуда за такт",
|
||||
"admin.serverField.antiflood_points_needed_command_block": "Порог блокировки команд за флуд",
|
||||
"admin.serverField.antiflood_points_needed_ip_block": "Порог блокировки IP за флуд",
|
||||
@@ -1214,7 +1195,6 @@
|
||||
"admin.showAdvanced": "Показать дополнительные",
|
||||
"admin.hideAdvanced": "Скрыть дополнительные",
|
||||
"admin.encrypt": "Шифрование голосового чата",
|
||||
"admin.serverDefault": "По умолчанию на сервере",
|
||||
"admin.flagDefault": "По умолчанию",
|
||||
"admin.noTopic": "Нет темы",
|
||||
"admin.noDescription": "Без описания",
|
||||
@@ -1356,17 +1336,9 @@
|
||||
"snapshots.cancelledPartial": "Отменено. Уже выполненные изменения сохранены; просмотрите результаты ниже.",
|
||||
"snapshots.cancelled": "Отменено.",
|
||||
"snapshots.partial": "Операция завершена с пропусками или ошибками. Просмотрите результаты ниже: снимок обработан не полностью.",
|
||||
"snapshots.partialApply": "Операция завершена с пропусками или ошибками. Уже выполненные изменения сохранены; просмотрите результаты ниже.",
|
||||
"snapshots.saved": "Сохранён файл {name}.",
|
||||
"snapshots.applied": "Снимок успешно применён.",
|
||||
"snapshots.completedChanges": "Выполнено изменений: {count}",
|
||||
"snapshots.changeCreated": "Создание",
|
||||
"snapshots.changeIconUploaded": "Значок загружен",
|
||||
"snapshots.changeRenamed": "Переименование",
|
||||
"snapshots.changeProperty": "Свойство изменено",
|
||||
"snapshots.changeDefault": "Группа по умолчанию назначена",
|
||||
"snapshots.changePermission": "Право назначено",
|
||||
"snapshots.changeMemberAdded": "Участник добавлен",
|
||||
"snapshots.cancelling": "Отмена после текущей операции сервера…",
|
||||
"snapshots.warning": "Импорт создаёт каналы и группы и может изменить настройки сервера, значения по умолчанию и существующие имена. Операция не атомарна: отмена или ошибка не откатывает выполненные изменения. Целевой сервер должен поддерживать назначение участников по UID; каждый отказ будет указан.",
|
||||
"snapshots.catalog": "Запись каталога",
|
||||
@@ -1547,7 +1519,6 @@
|
||||
"audio.perDevice": "Обработка применяется к выбранному устройству ввода или вывода. Профили недоступных устройств сохраняются.",
|
||||
"audio.ptt": "Нажми и говори",
|
||||
"audio.pttKey": "Клавиша разговора",
|
||||
"audio.pttKey.single": "Выберите одну клавишу без модификаторов.",
|
||||
"audio.releaseDelay": "Задержка отпускания",
|
||||
"audio.off": "Выкл.",
|
||||
"audio.vad": "Определение голосовой активности",
|
||||
@@ -1915,7 +1886,6 @@
|
||||
"bookmarks.edit.name.tooltip": "Поле имени сервера будет использоваться для идентификации добавленного в закладки сервера на панели подключения",
|
||||
"bookmarks.edit.title": "Изменить закладку",
|
||||
"bookmarks.folder.empty_name": "Безымянная папка",
|
||||
"native.bookmark.move.before": "Вставить перед",
|
||||
"bookmarks.save.error": "Возникла проблема с сохранением закладки: {error}",
|
||||
"bookmarks.warning.delete": "Действительно навсегда удалить закладку {name}?",
|
||||
"bookmarks.warning.folder_not_empty": "Папка {name} не пуста. Действительно удалить папку {name} и все ее содержимое без возможности восстановления?",
|
||||
@@ -2146,8 +2116,6 @@
|
||||
"settings.whisper.receive": "Получать шепоты",
|
||||
"settings.whisper.receive.all": "Разрешить все",
|
||||
"settings.whisper.receive.deny": "Запретить все",
|
||||
"settings.whisper.warning.read_only": "Настройки шепотов сохранены в более новой версии и доступны только для чтения. Исходный файл не изменён.",
|
||||
"settings.whisper.warning.recovery": "Не удалось загрузить часть сохранённых настроек шепотов. Исходный файл не изменён.",
|
||||
"settings.whisper.title.activity": "Управление списками шепотов",
|
||||
"settings.whisper.type.clients_channel": "Клиенты и каналы",
|
||||
"universal.disconnected": "Отключен(-а)",
|
||||
@@ -2204,21 +2172,6 @@
|
||||
"settings.identity.nickname.info": "Твой ник видят другие пользователи на сервере TeamSpeak",
|
||||
"settings.identity.security_level.info": "Для подключения к некоторым серверам может потребоваться более высокий уровень безопасности, например, с целью защиты от спама. Ты можешь повысить свой уровень безопасности здесь, при этом повышение на каждый уровень будет занимать экспоненциально больше времени.",
|
||||
"settings.identity.delete.warning": "Действительно удалить этот идентификатор? Без него серверы TeamSpeak не смогут уникально опознать тебя.",
|
||||
"settings.identity.delete.title": "Удаление идентификатора",
|
||||
"settings.identity.delete.backup_warning": "Удалить этот идентификатор без возможности восстановления? Сначала экспортируйте резервную копию. Закладкам, использующим его, нужно назначить другой идентификатор.",
|
||||
"settings.identity.delete.referenced": "Перед удалением назначьте другой идентификатор использующим его закладкам.",
|
||||
"settings.identity.import.warning": "Импортируйте только свои идентификаторы. Выбранный INI-файл содержит закрытый ключ.",
|
||||
"settings.identity.import.size": "Размер файла для импорта превышает 1 МиБ.",
|
||||
"settings.identity.import.result": "Добавлено: {added}. Уже в профиле: {existing}.",
|
||||
"settings.identity.import.encoding": "INI-файл идентификатора должен быть в кодировке UTF-8.",
|
||||
"settings.identity.export.overwrite.title": "Перезапись файла идентификатора",
|
||||
"settings.identity.export.overwrite.warning": "Выбранный файл уже содержит данные. Заменить их этим идентификатором?",
|
||||
"settings.identity.export.worker_stopped": "Не удалось завершить экспорт идентификатора.",
|
||||
"settings.identity.name.invalid": "В имени идентификатора допускается не более 64 символов и не должно быть управляющих символов.",
|
||||
"settings.identity.missing": "Этот идентификатор больше не существует.",
|
||||
"settings.identity.improve.higher_target": "Укажите более высокий целевой уровень безопасности.",
|
||||
"settings.identity.improve.busy": "Повышение уровня безопасности уже запущено.",
|
||||
"settings.identity.improve.worker_stopped": "Не удалось завершить повышение уровня безопасности.",
|
||||
"settings.identity.new.placeholder": "Имя нового идентификатора",
|
||||
"settings.identity.improve": "Улучшить",
|
||||
"universal.stop": "Остановить",
|
||||
@@ -2285,25 +2238,6 @@
|
||||
"settings.about.project.releases": "Выпуски",
|
||||
"settings.about.project.notice": "TeamSpeak — товарный знак TeamSpeak Systems GmbH. TeamsPeach — независимый клиент, не связанный с TeamSpeak Systems GmbH и не одобренный ею.",
|
||||
"settings.about.details.title": "Сведения об установке",
|
||||
"settings.about.details.runtime": "Нативная среда выполнения",
|
||||
"settings.about.details.target": "Целевая платформа сборки",
|
||||
"settings.about.details.os": "Операционная система",
|
||||
"settings.about.details.arch": "Архитектура",
|
||||
"settings.about.details.profile": "Каталог профиля",
|
||||
"settings.about.details.logs": "Каталог журналов",
|
||||
"settings.about.details.logs_disabled": "В этом сеансе открытие каталога журналов запрещено.",
|
||||
"settings.about.details.logs_no_reveal": "Операционная система не позволяет открыть каталог журналов приложения.",
|
||||
"settings.about.details.logs_missing": "Каталог журналов не существует.",
|
||||
"settings.about.details.connections": "Вкладки подключений",
|
||||
"settings.about.details.network": "Доступ к сети",
|
||||
"settings.about.details.os_actions": "Действия операционной системы",
|
||||
"settings.about.details.enabled": "Разрешено",
|
||||
"settings.about.details.disabled": "Запрещено",
|
||||
"settings.about.details.audio": "Состояние звука",
|
||||
"settings.about.details.video": "Видеоподсистема",
|
||||
"settings.about.details.prefs": "Настройки",
|
||||
"settings.about.licenses.group.native": "Нативное приложение",
|
||||
"settings.about.licenses.no_bundled_text": "Текст лицензии для этой зависимости не включён в сборку. Заявленная лицензия: {license}.",
|
||||
"settings.privacy.analytics.limited.basic_system_information": "Основная информация о системе",
|
||||
"settings.privacy.analytics.limited.client_launch_time": "Время запуска клиента",
|
||||
"settings.privacy.analytics.limited.client_usage_duration": "Продолжительность использования клиента",
|
||||
@@ -2346,7 +2280,6 @@
|
||||
"native.stream.waiting": "Ожидание видео",
|
||||
"native.stream.preview": "Предпросмотр источника",
|
||||
"native.stream.start": "Начать трансляцию",
|
||||
"native.stream.edit": "Редактировать трансляцию",
|
||||
"native.stream.stop": "Остановить трансляцию",
|
||||
"native.stream.fullscreen": "На весь экран",
|
||||
"native.stream.popout": "Открыть в отдельном окне",
|
||||
@@ -2356,9 +2289,7 @@
|
||||
"native.form.confirm": "Для подтверждения введите имя цели: {target}",
|
||||
"native.form.changed": "Цель изменилась. Закройте форму и попробуйте снова.",
|
||||
"native.form.length": "Слишком длинное значение",
|
||||
"native.form.pokeControls": "Введите одну строку без табуляции и других управляющих символов",
|
||||
"native.shell.details": "Сведения",
|
||||
"native.shell.recentServerEvents": "Последние события сервера",
|
||||
"native.shell.chat": "Чат",
|
||||
"native.shell.streams": "Трансляции",
|
||||
"native.shell.resize": "Изменить ширину панели",
|
||||
@@ -2374,9 +2305,6 @@
|
||||
"native.stream.admission": "Запрос доступа к трансляции",
|
||||
"native.stream.accept": "Разрешить просмотр",
|
||||
"native.stream.reject": "Отклонить просмотр",
|
||||
"native.stream.accept_viewer": "Разрешить просмотр для {name}",
|
||||
"native.stream.reject_viewer": "Отклонить запрос от {name}",
|
||||
"native.stream.remove_viewer": "Исключить {name} из трансляции",
|
||||
"native.files.overwrite": "Заменить существующий файл",
|
||||
"native.form.advanced": "Дополнительные параметры"
|
||||
,"native.theme.import": "Импортировать тему…"
|
||||
@@ -2388,11 +2316,4 @@
|
||||
,"native.audio.new_device": "Новое устройство"
|
||||
,"native.audio.copy_template": "Использовать как шаблон"
|
||||
,"native.audio.apply_template": "Применить шаблон"
|
||||
,"native.chat.matrix_rooms_unavailable": "Сервер предлагает комнаты Matrix, которые TeamsPeach не поддерживает. Здесь используется обычный серверный чат."
|
||||
,"native.privacy.list": "Список фишинговых доменов"
|
||||
,"native.privacy.list.current": "Список актуален"
|
||||
,"native.privacy.list.cached": "Используется последняя доступная копия"
|
||||
,"native.privacy.list.unavailable": "Список не загружен"
|
||||
,"native.core.stopping": "Остановка ядра…"
|
||||
,"native.identity.review_level": "Проверить идентичность: требуется уровень {level}"
|
||||
}
|
||||
+72
-163
@@ -13,7 +13,7 @@ use serde_json::Value;
|
||||
use teamspeach_core::{
|
||||
audio::CapturedFrame,
|
||||
output::PlaybackFrame,
|
||||
protocol::{Command, ErrorCode, ErrorObj, TextTarget, ValidatedCommand, validate_command},
|
||||
protocol::{Command, ErrorObj},
|
||||
runtime::{self, CoreConfig, CoreEvents, CoreHandle},
|
||||
vad::GateMode,
|
||||
whisper::WhisperCommand,
|
||||
@@ -62,7 +62,7 @@ impl From<ErrorObj> for ConnectionError {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ConnectionState { Disconnected, Connecting, Connected, Disconnecting }
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CoreStatus { Starting, Ready, Stopping, Stopped, Failed }
|
||||
pub enum CoreStatus { Ready, Stopping, Stopped, Failed }
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AudioState {
|
||||
pub input_muted: bool,
|
||||
@@ -107,18 +107,6 @@ pub struct ConnectionSnapshot {
|
||||
pub input_enabled: bool,
|
||||
}
|
||||
impl ConnectionSnapshot {
|
||||
pub(crate) fn joined_channel_codec(&self) -> Option<&str> {
|
||||
let server = self.server.as_deref()?;
|
||||
let joined = server["own_channel_id"].as_u64()?;
|
||||
server["channels"].as_array()?.iter().find(|c| c["id"].as_u64() == Some(joined))?["codec"].as_str()
|
||||
}
|
||||
pub(crate) fn identity_challenge(&self) -> Option<(&str,u8)> {
|
||||
if self.status!=CoreStatus::Ready || self.state!=ConnectionState::Disconnected { return None; }
|
||||
let reason=self.reason.as_deref()?;
|
||||
if reason["code"]!="connect_failed" { return None; }
|
||||
let level=u8::try_from(reason["detail"]["required_security_level"].as_u64()?).ok()?;
|
||||
(1..=teamspeach_core::profile::MAX_TARGET_LEVEL).contains(&level).then_some((self.identity_id.as_deref()?,level))
|
||||
}
|
||||
pub fn is_connected(&self) -> bool {
|
||||
self.state == ConnectionState::Connected && self.server.is_some()
|
||||
}
|
||||
@@ -143,13 +131,9 @@ impl ConnectionsSnapshot {
|
||||
pub enum ConnectionEvent {
|
||||
Control { key: SessionKey, value: Arc<Value> },
|
||||
Playback { key: SessionKey, frame: PlaybackFrame },
|
||||
/// Revoke local capture buffers synchronously without invalidating a pending manager request.
|
||||
/// The media owner must clear held PTT/whisper and its capture buffers here.
|
||||
InputReset,
|
||||
/// Accepted local close/restart, before stopping the old worker. Not a server state event.
|
||||
Retired { key: SessionKey },
|
||||
/// The retired core has joined; holders of its file descriptors may release their leases.
|
||||
CoreStopped { key: SessionKey, restarting: bool },
|
||||
Failure { key: Option<SessionKey>, error: ConnectionError, terminal: bool },
|
||||
Failure { key: Option<SessionKey>, error: ConnectionError },
|
||||
}
|
||||
pub trait ConnectionSink: Send + Sync + 'static {
|
||||
fn on_event(&self, event: ConnectionEvent);
|
||||
@@ -159,35 +143,14 @@ impl<F: Fn(ConnectionEvent) + Send + Sync + 'static> ConnectionSink for F {
|
||||
}
|
||||
|
||||
struct AudioRoute { permit: CapturePermit, core: Arc<CoreHandle> }
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CaptureIngress { Accepted, FrameRejected, PermitRevoked }
|
||||
|
||||
impl AudioRoute {
|
||||
fn is_current(&self) -> bool {
|
||||
self.core.connection_generation() == self.permit.key.generation
|
||||
&& self.core.audio_epoch() == self.permit.capture_epoch
|
||||
}
|
||||
fn push(&self, key: &SessionKey, frame: CapturedFrame) -> CaptureIngress {
|
||||
if self.permit.key != *key || frame.capture_epoch != self.permit.capture_epoch
|
||||
|| frame.connection_generation != key.generation || !self.is_current() {
|
||||
return CaptureIngress::PermitRevoked;
|
||||
}
|
||||
if self.core.push_audio(frame) { CaptureIngress::Accepted }
|
||||
else if self.is_current() { CaptureIngress::FrameRejected }
|
||||
else { CaptureIngress::PermitRevoked }
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct CaptureState { revision: u64, route: Option<AudioRoute> }
|
||||
impl CaptureState {
|
||||
fn revoke(&mut self, selected: Option<&Arc<CoreHandle>>) -> u64 {
|
||||
fn revoke(&mut self) -> u64 {
|
||||
self.revision = self.revision.checked_add(1).expect("capture revision exhausted");
|
||||
let route = self.route.take();
|
||||
if let Some(route) = &route { route.core.invalidate_audio(); }
|
||||
// Before the input acknowledgement, the selected worker may not have a route yet.
|
||||
if let Some(core) = selected.filter(|core| route.as_ref().is_none_or(|r| !Arc::ptr_eq(&r.core, core))) {
|
||||
core.invalidate_audio();
|
||||
if let Some(route) = self.route.take() {
|
||||
route.core.invalidate_audio();
|
||||
route.core.end_audio();
|
||||
}
|
||||
self.revision
|
||||
}
|
||||
@@ -248,28 +211,26 @@ impl ConnectionManager {
|
||||
pub async fn set_input(&self, key: Option<&SessionKey>, config: InputConfiguration) -> Result<Option<CapturePermit>, ConnectionError> {
|
||||
self.call(|reply| Operation::SetInput(key.cloned(), config, reply)).await
|
||||
}
|
||||
/// Device startup needs the live route, not the asynchronously published snapshot.
|
||||
pub(crate) fn has_capture_permit(&self, permit: &CapturePermit) -> bool {
|
||||
let capture = self.capture.lock().expect("capture route poisoned");
|
||||
capture.route.as_ref().is_some_and(|route| &route.permit == permit && route.is_current())
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn fixture_control(&self, key: &SessionKey, value: Value) -> Result<(), ConnectionError> {
|
||||
self.call(|reply| Operation::FixtureControl(key.clone(), value, reply)).await
|
||||
}
|
||||
/// Invoke from the DSP/service worker, not a device callback. No per-frame allocation.
|
||||
pub fn push_audio(&self, key: &SessionKey, frame: CapturedFrame) -> CaptureIngress {
|
||||
pub fn push_audio(&self, key: &SessionKey, frame: CapturedFrame) -> bool {
|
||||
let capture = self.capture.lock().expect("capture route poisoned");
|
||||
capture.route.as_ref().map_or(CaptureIngress::PermitRevoked, |route| route.push(key, frame))
|
||||
capture.route.as_ref().is_some_and(|route| {
|
||||
route.permit.key == *key && frame.capture_epoch == route.permit.capture_epoch
|
||||
&& frame.connection_generation == key.generation && route.core.push_audio(frame)
|
||||
})
|
||||
}
|
||||
/// Synchronous privacy boundary for device loss, held-key release and capture changes.
|
||||
/// The caller must obtain a new acknowledged permit before forwarding more PCM.
|
||||
pub fn invalidate_audio(&self) {
|
||||
self.capture.lock().expect("capture route poisoned").revoke(None);
|
||||
self.capture.lock().expect("capture route poisoned").revoke();
|
||||
}
|
||||
pub async fn request(&self, key: &SessionKey, command: Command) -> Result<Value, ConnectionError> {
|
||||
let command = validate_command(command)?;
|
||||
self.call(|reply| Operation::Request(key.clone(), command, reply)).await
|
||||
self.call(|reply| Operation::Request(key.clone(), command, None, reply)).await
|
||||
}
|
||||
/// Capture the conversation channel before awaiting. A local channel move
|
||||
/// cannot overtake this message while its server acknowledgement is pending.
|
||||
pub async fn request_in_channel(&self,key:&SessionKey,channel:u64,command:Command)->Result<Value,ConnectionError>{
|
||||
self.call(|reply|Operation::Request(key.clone(),command,Some(channel),reply)).await
|
||||
}
|
||||
pub async fn close(&self, key: &SessionKey) -> Result<(), ConnectionError> {
|
||||
self.call(|reply| Operation::Close(key.clone(), reply)).await
|
||||
@@ -310,11 +271,9 @@ enum Operation {
|
||||
SelectChannel(SessionKey, u64, Reply<()>),
|
||||
Workflow(WorkflowSettings, Reply<()>),
|
||||
SetInput(Option<SessionKey>, InputConfiguration, Reply<Option<CapturePermit>>),
|
||||
Request(SessionKey, ValidatedCommand, Reply<Value>),
|
||||
Request(SessionKey, Command, Option<u64>, Reply<Value>),
|
||||
Close(SessionKey, Reply<()>),
|
||||
Restart(SessionKey, Reply<SessionKey>),
|
||||
#[cfg(test)]
|
||||
FixtureControl(SessionKey, Value, Reply<()>),
|
||||
}
|
||||
struct Worker {
|
||||
core: Arc<CoreHandle>,
|
||||
@@ -346,7 +305,6 @@ impl Entry {
|
||||
self.session_clock.store(self.snapshot.key.session, Ordering::Release);
|
||||
if let Some(worker) = &self.worker { *worker.playback_key.lock().expect("playback key poisoned") = None; }
|
||||
self.snapshot.server = None;
|
||||
self.snapshot.reason = None;
|
||||
self.snapshot.talking.clear();
|
||||
self.snapshot.selected_channel_id = None;
|
||||
self.snapshot.audio.transmitting = false;
|
||||
@@ -377,10 +335,10 @@ enum Internal {
|
||||
Ended { id: String, incarnation: u64 },
|
||||
}
|
||||
enum StopPurpose {
|
||||
Close(SessionKey, Reply<()>),
|
||||
Restart(SessionKey, Reply<SessionKey>),
|
||||
Close(Reply<()>),
|
||||
Restart(Reply<SessionKey>),
|
||||
Shutdown,
|
||||
Failed(SessionKey),
|
||||
Failed,
|
||||
}
|
||||
struct Stopped {
|
||||
id: String,
|
||||
@@ -441,18 +399,20 @@ impl Actor {
|
||||
self.snapshots.send_replace(Arc::new(snapshot));
|
||||
}
|
||||
fn failure(&self, key: Option<SessionKey>, error: ConnectionError) {
|
||||
self.sink.on_event(ConnectionEvent::Failure { key, error, terminal: false });
|
||||
self.sink.on_event(ConnectionEvent::Failure { key, error });
|
||||
}
|
||||
fn revoke(&mut self) -> u64 {
|
||||
let index = self.input.as_deref().and_then(|id| self.index(id).ok());
|
||||
let selected = index.and_then(|i| self.entries[i].worker.as_ref()).map(|w| &w.core);
|
||||
let revision = self.capture.lock().expect("capture route poisoned").revoke(selected);
|
||||
let revision = self.capture.lock().expect("capture route poisoned").revoke();
|
||||
self.sink.on_event(ConnectionEvent::InputReset);
|
||||
if let Some(index) = index {
|
||||
if let Some(epoch) = self.entries[index].whisper.take() {
|
||||
let command = validate_command(Command::Whisper(WhisperCommand::Stop { epoch }))
|
||||
.expect("tracked whisper epoch came from a validated start");
|
||||
self.dispatch(index, self.entries[index].key(), command, CompletionKind::ReleaseWhisper);
|
||||
if let Some(id) = self.input.clone() {
|
||||
if let Ok(index) = self.index(&id) {
|
||||
if let Some(worker) = &self.entries[index].worker {
|
||||
worker.core.invalidate_audio();
|
||||
worker.core.end_audio();
|
||||
}
|
||||
if let Some(epoch) = self.entries[index].whisper.take() {
|
||||
self.dispatch(index, self.entries[index].key(), Command::Whisper(WhisperCommand::Stop { epoch }), CompletionKind::ReleaseWhisper);
|
||||
}
|
||||
}
|
||||
}
|
||||
revision
|
||||
@@ -502,7 +462,7 @@ impl Actor {
|
||||
if let Ok(index) = self.index(&next) { self.configure_input(index, self.entries[index].key(), None); }
|
||||
}
|
||||
}
|
||||
fn dispatch(&mut self, index: usize, key: SessionKey, mut command: ValidatedCommand, mut kind: CompletionKind) {
|
||||
fn dispatch(&mut self, index: usize, key: SessionKey, mut command: Command, mut kind: CompletionKind) {
|
||||
let session_clock = self.entries[index].session_clock.clone();
|
||||
let capture = self.capture.clone();
|
||||
let request = self.next_request;
|
||||
@@ -516,22 +476,24 @@ impl Actor {
|
||||
// Resolve only the public UID, never identity private material. This also binds a
|
||||
// default-identity connect if another session changes the default while awaiting it.
|
||||
if let CompletionKind::Request { guard: Guard::Connect { identity, .. }, .. } = &mut kind {
|
||||
if identity.is_none() {
|
||||
let mut profile = core.request(Command::ProfileGet).await?;
|
||||
let Some(Value::String(uid)) = profile.as_object_mut().and_then(|profile| profile.remove("uid")) else {
|
||||
return Err(ErrorObj::new(ErrorCode::ProfileMissing, "profile has no identity").into());
|
||||
};
|
||||
if identity.as_ref().is_none_or(|identity| identity.is_empty()) {
|
||||
let profile = core.request(Command::ProfileGet).await.map_err(ConnectionError::from)?;
|
||||
*identity = profile.get("uid").and_then(Value::as_str).map(str::to_owned);
|
||||
if identity.is_none() {
|
||||
return Err(ConnectionError::Core(ErrorObj::new(teamspeach_core::protocol::ErrorCode::ProfileMissing, "profile has no identity")));
|
||||
}
|
||||
if core.connection_generation() != key.generation || session_clock.load(Ordering::Acquire) != key.session { return Err(ConnectionError::TargetChanged); }
|
||||
command.bind_default_identity(&uid)?;
|
||||
*identity = Some(uid);
|
||||
}
|
||||
}
|
||||
if let (Command::Connect(args), CompletionKind::Request { guard: Guard::Connect { identity, .. }, .. }) = (&mut command, &kind) {
|
||||
args.identity_id = identity.clone();
|
||||
}
|
||||
if let CompletionKind::Request { capture_revision: Some(revision), .. } = &kind {
|
||||
if capture.lock().expect("capture route poisoned").revision != *revision {
|
||||
return Err(ConnectionError::TargetChanged);
|
||||
}
|
||||
}
|
||||
core.request_validated(command).await.map_err(ConnectionError::from)
|
||||
core.request(command).await.map_err(ConnectionError::from)
|
||||
}.await;
|
||||
drop(core);
|
||||
let _ = completions.send(Completion { request, key, result, kind }).await;
|
||||
@@ -578,24 +540,16 @@ impl Actor {
|
||||
}
|
||||
fn operation(&mut self, operation: Operation) {
|
||||
match operation {
|
||||
#[cfg(test)]
|
||||
Operation::FixtureControl(key, value, reply) => {
|
||||
let result = self.checked(&key).map(|index| self.control(index, value));
|
||||
self.publish(); let _ = reply.send(result);
|
||||
}
|
||||
Operation::Create(reply) => { let result = self.create(); self.publish(); let _ = reply.send(result); }
|
||||
Operation::Key(id, reply) => { let _ = reply.send(self.index(&id).map(|index| self.entries[index].key())); }
|
||||
Operation::Workflow(settings, reply) => { self.workflow = settings; let _ = reply.send(Ok(())); }
|
||||
Operation::View(key, reply) => {
|
||||
let result = self.index(&key.connection_id).and_then(|index| {
|
||||
if self.entries[index].key()!=key { return Err(ConnectionError::TargetChanged); }
|
||||
let result = self.checked(&key).map(|index| {
|
||||
let changed = self.viewed.as_ref() != Some(&key.connection_id);
|
||||
self.viewed = Some(key.connection_id.clone());
|
||||
if changed && self.workflow.auto_enable_microphone && self.entries[index].snapshot.is_connected()
|
||||
&& !self.capture.lock().expect("capture route poisoned").route.as_ref().is_some_and(|route| route.permit.key == key && route.is_current()) {
|
||||
if changed && self.workflow.auto_enable_microphone && self.entries[index].snapshot.is_connected() {
|
||||
self.revoke(); self.choose_input(Some(key.connection_id.clone())); self.configure_input(index, key, None);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
self.publish(); let _ = reply.send(result);
|
||||
}
|
||||
@@ -614,62 +568,46 @@ impl Actor {
|
||||
Ok(index) => index,
|
||||
Err(error) => { let _ = reply.send(Err(error)); return; }
|
||||
};
|
||||
if index.is_some() {
|
||||
if let Err(error) = validate_command(Command::SetTransmit { vad: config.vad }) {
|
||||
let _ = reply.send(Err(error.into())); return;
|
||||
}
|
||||
}
|
||||
self.revoke();
|
||||
self.choose_input(key.as_ref().map(|key| key.connection_id.clone()));
|
||||
if let (Some(index), Some(key)) = (index, key) {
|
||||
if self.entries[index].worker.as_ref().expect("checked live worker").requests.len() >= COMMAND_CAPACITY {
|
||||
self.publish(); let _ = reply.send(Err(ConnectionError::Busy)); return;
|
||||
let _ = reply.send(Err(ConnectionError::Busy)); self.publish(); return;
|
||||
}
|
||||
self.entries[index].config = Some(config);
|
||||
self.configure_input(index, key, Some(reply));
|
||||
} else { self.publish(); let _ = reply.send(Ok(None)); return; }
|
||||
} else { let _ = reply.send(Ok(None)); }
|
||||
self.publish();
|
||||
}
|
||||
Operation::Request(key, command, reply) => {
|
||||
Operation::Request(key, command, expected_channel, reply) => {
|
||||
let index = match self.checked(&key) { Ok(index) => index, Err(error) => { let _ = reply.send(Err(error)); return; } };
|
||||
if self.entries[index].worker.as_ref().expect("checked live worker").requests.len() >= COMMAND_CAPACITY {
|
||||
let _ = reply.send(Err(ConnectionError::Busy)); return;
|
||||
}
|
||||
let request = command.as_command();
|
||||
if matches!(request, Command::Shutdown) {
|
||||
if matches!(command, Command::Shutdown) {
|
||||
let _ = reply.send(Err(ConnectionError::Worker("use close, restart or shutdown to join the core".into()))); return;
|
||||
}
|
||||
let channel_lease=if matches!(request,Command::JoinChannel{..}|Command::SendText{target:TextTarget::Channel,..}){
|
||||
let channel_lease=if matches!(command,Command::JoinChannel{..}|Command::SendText{target:teamspeach_core::protocol::TextTarget::Channel,..}){
|
||||
match self.entries[index].worker.as_ref().expect("checked live worker").channel_request.clone().try_lock_owned(){Ok(lease)=>Some(lease),Err(_)=>{let _=reply.send(Err(ConnectionError::Busy));return}}
|
||||
}else{None};
|
||||
if let Command::SendText { target:TextTarget::Channel, expected_channel_id:Some(channel), .. }=request {
|
||||
if !self.entries[index].snapshot.is_connected() || self.entries[index].snapshot.server.as_deref().and_then(|s|s["own_channel_id"].as_u64())!=Some(*channel){let _=reply.send(Err(ConnectionError::TargetChanged));return}
|
||||
if let Some(channel)=expected_channel{
|
||||
if !matches!(command,Command::SendText{target:teamspeach_core::protocol::TextTarget::Channel,..})||!self.entries[index].snapshot.is_connected()||self.entries[index].snapshot.server.as_deref().and_then(|s|s["own_channel_id"].as_u64())!=Some(channel){let _=reply.send(Err(ConnectionError::TargetChanged));return}
|
||||
}
|
||||
let guard = match request {
|
||||
let guard = match &command {
|
||||
Command::Connect(args) => Guard::Connect { address: args.address.clone(), identity: args.identity_id.clone() },
|
||||
Command::Disconnect { .. } => Guard::Disconnect,
|
||||
_ => Guard::Strict,
|
||||
};
|
||||
let changes_config = matches!(request, Command::SetTransmit { .. } | Command::SetAudio { input_muted:Some(_), .. } | Command::SetAudio { output_muted:Some(_), .. });
|
||||
let boundary = match request {
|
||||
Command::Whisper(WhisperCommand::Stop { epoch }) => {
|
||||
// The explicit stop closes its own epoch. Do not schedule a second stop
|
||||
// in revoke(), or invalidate the current permit for a stale key release.
|
||||
let current = self.entries[index].whisper == Some(*epoch);
|
||||
if current { self.entries[index].whisper = None; }
|
||||
current
|
||||
},
|
||||
Command::Connect(_) | Command::Disconnect { .. } | Command::JoinChannel { .. }
|
||||
| Command::Whisper(WhisperCommand::Start { .. }) => true,
|
||||
_ => changes_config,
|
||||
};
|
||||
let boundary = matches!(command, Command::Connect(_) | Command::Disconnect { .. } | Command::JoinChannel { .. }
|
||||
| Command::SetAudio { .. } | Command::SetTransmit { .. } | Command::Whisper(WhisperCommand::Start { .. } | WhisperCommand::Stop { .. }));
|
||||
let capture_revision = if boundary {
|
||||
let revision = if self.input.as_ref() == Some(&key.connection_id) { Some(self.revoke()) } else { None };
|
||||
self.entries[index].worker.as_ref().expect("checked live worker").core.invalidate_audio();
|
||||
revision
|
||||
} else { None };
|
||||
let changes_config = matches!(command, Command::SetAudio { .. } | Command::SetTransmit { .. });
|
||||
if let Some(config) = &mut self.entries[index].config {
|
||||
match request {
|
||||
match &command {
|
||||
Command::SetTransmit { vad } => config.vad = *vad,
|
||||
Command::SetAudio { input_muted, output_muted } => {
|
||||
if let Some(muted) = input_muted { config.input_muted = *muted; }
|
||||
@@ -678,7 +616,7 @@ impl Actor {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Command::Whisper(WhisperCommand::Start { epoch, .. }) = request { self.entries[index].whisper = Some(*epoch); }
|
||||
if let Command::Whisper(WhisperCommand::Start { epoch, .. }) = &command { self.entries[index].whisper = Some(*epoch); }
|
||||
self.dispatch(index, key, command, CompletionKind::Request { guard, capture_revision, changes_config, channel_lease, reply });
|
||||
self.publish();
|
||||
}
|
||||
@@ -693,22 +631,19 @@ impl Actor {
|
||||
self.viewed = Some(self.entries[index.min(self.entries.len() - 1)].snapshot.key.connection_id.clone());
|
||||
}
|
||||
if was_input { self.input = None; self.restore_input(); }
|
||||
self.stop(&mut entry, StopPurpose::Close(key, reply)); self.publish();
|
||||
self.stop(&mut entry, StopPurpose::Close(reply)); self.publish();
|
||||
}
|
||||
Operation::Restart(key, reply) => {
|
||||
let index = match self.lifecycle(&key) { Ok(index) => index, Err(error) => { let _ = reply.send(Err(error)); return; } };
|
||||
if self.input.as_ref() == Some(&key.connection_id) { self.revoke(); self.restore_input(); }
|
||||
let mut entry = self.entries.remove(index);
|
||||
self.stop(&mut entry, StopPurpose::Restart(key, reply));
|
||||
self.stop(&mut entry, StopPurpose::Restart(reply));
|
||||
self.entries.insert(index, entry); self.publish();
|
||||
}
|
||||
}
|
||||
}
|
||||
fn stop(&mut self, entry: &mut Entry, purpose: StopPurpose) {
|
||||
entry.reset_session();
|
||||
if let StopPurpose::Close(key, _) | StopPurpose::Restart(key, _) = &purpose {
|
||||
self.sink.on_event(ConnectionEvent::Retired { key: key.clone() });
|
||||
}
|
||||
entry.snapshot.state = ConnectionState::Disconnected;
|
||||
entry.snapshot.status = CoreStatus::Stopping;
|
||||
let id = entry.snapshot.key.connection_id.clone();
|
||||
@@ -762,9 +697,7 @@ impl Actor {
|
||||
else { entry.snapshot.talking.remove(&id); }
|
||||
}
|
||||
}
|
||||
Some("whisper_cleared") => {
|
||||
if entry.whisper.is_some_and(|epoch| value["epoch"] == epoch) { entry.whisper = None; }
|
||||
}
|
||||
Some("whisper_cleared") => { entry.whisper = None; }
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -815,8 +748,6 @@ impl Actor {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Callers may read the capture snapshot as soon as the reply wakes them.
|
||||
self.publish();
|
||||
let _ = reply.send(if valid { completion.result } else { Err(ConnectionError::TargetChanged) });
|
||||
}
|
||||
CompletionKind::Input { revision, config, reply } => {
|
||||
@@ -835,7 +766,6 @@ impl Actor {
|
||||
capture.route = Some(AudioRoute { permit: permit.clone(), core });
|
||||
Ok(Some(permit))
|
||||
});
|
||||
self.publish();
|
||||
if let Some(reply) = reply { let _ = reply.send(result); }
|
||||
else if let Err(error) = result {
|
||||
if !matches!(error, ConnectionError::TargetChanged) { self.failure(Some(completion.key), error); }
|
||||
@@ -843,7 +773,6 @@ impl Actor {
|
||||
}
|
||||
CompletionKind::ReleaseWhisper => {
|
||||
if valid { if let Err(error) = completion.result { self.failure(Some(completion.key), error); } }
|
||||
self.publish();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -856,13 +785,13 @@ impl Actor {
|
||||
if self.entries[index].incarnation != incarnation || self.entries[index].worker.is_none() { return; }
|
||||
match message {
|
||||
Internal::Control { value, .. } => self.control(index, value),
|
||||
Internal::Complete { completion, .. } => { self.complete(index, completion); return; }
|
||||
Internal::Complete { completion, .. } => self.complete(index, completion),
|
||||
Internal::Ended { .. } => {
|
||||
let key = self.entries[index].key();
|
||||
if self.input.as_ref() == Some(&key.connection_id) { self.revoke(); self.restore_input(); }
|
||||
self.sink.on_event(ConnectionEvent::Failure { key: Some(key.clone()), error: ConnectionError::Worker("core event stream ended".into()), terminal: true });
|
||||
self.failure(Some(key), ConnectionError::Worker("core event stream ended".into()));
|
||||
let mut entry = self.entries.remove(index);
|
||||
self.stop(&mut entry, StopPurpose::Failed(key));
|
||||
self.stop(&mut entry, StopPurpose::Failed);
|
||||
self.entries.insert(index, entry);
|
||||
}
|
||||
}
|
||||
@@ -871,23 +800,15 @@ impl Actor {
|
||||
fn stopped(&mut self, stopped: Stopped, shutting_down: bool) -> Result<(), ConnectionError> {
|
||||
self.stopping_slots.remove(&stopped.slot);
|
||||
if let Ok(index) = self.index(&stopped.id) {
|
||||
self.entries[index].snapshot.status = if stopped.result.is_err() || matches!(&stopped.purpose, StopPurpose::Failed(_)) {
|
||||
CoreStatus::Failed
|
||||
} else { CoreStatus::Stopped };
|
||||
self.entries[index].snapshot.status = if stopped.result.is_ok() { CoreStatus::Stopped } else { CoreStatus::Failed };
|
||||
}
|
||||
match stopped.purpose {
|
||||
StopPurpose::Close(key, reply) => {
|
||||
if stopped.result.is_ok() { self.sink.on_event(ConnectionEvent::CoreStopped { key, restarting: false }); }
|
||||
let _ = reply.send(stopped.result.clone());
|
||||
}
|
||||
StopPurpose::Restart(key, reply) => {
|
||||
if stopped.result.is_ok() { self.sink.on_event(ConnectionEvent::CoreStopped { key, restarting: true }); }
|
||||
StopPurpose::Close(reply) => { let _ = reply.send(stopped.result.clone()); }
|
||||
StopPurpose::Restart(reply) => {
|
||||
let result = if shutting_down { Err(ConnectionError::Stopped) } else {
|
||||
stopped.result.clone().and_then(|()| {
|
||||
let index = self.index(&stopped.id)?;
|
||||
let incarnation = self.entries[index].incarnation.checked_add(1).ok_or(ConnectionError::IdExhausted)?;
|
||||
self.entries[index].snapshot.status = CoreStatus::Starting;
|
||||
self.publish();
|
||||
let worker = self.spawn_worker(&stopped.id, stopped.slot, incarnation)?;
|
||||
self.entries[index].worker = Some(worker);
|
||||
self.entries[index].incarnation = incarnation;
|
||||
@@ -896,22 +817,10 @@ impl Actor {
|
||||
Ok(self.entries[index].key())
|
||||
})
|
||||
};
|
||||
if let Err(error) = &result {
|
||||
let target = self.index(&stopped.id).ok().map(|index| {
|
||||
if !shutting_down { self.entries[index].snapshot.status = CoreStatus::Failed; }
|
||||
self.entries[index].key()
|
||||
});
|
||||
self.failure(target, error.clone());
|
||||
}
|
||||
// An acknowledged restart must already be visible to snapshot readers.
|
||||
self.publish();
|
||||
if let Err(error) = &result { self.failure(None, error.clone()); }
|
||||
let _ = reply.send(result);
|
||||
return stopped.result;
|
||||
}
|
||||
StopPurpose::Failed(key) => {
|
||||
if stopped.result.is_ok() { self.sink.on_event(ConnectionEvent::CoreStopped { key, restarting:false }); }
|
||||
}
|
||||
StopPurpose::Shutdown => {}
|
||||
StopPurpose::Shutdown | StopPurpose::Failed => {}
|
||||
}
|
||||
self.publish();
|
||||
stopped.result
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! Reducer fixtures deliberately exercise presentation/session bookkeeping, not network success.
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use teamspeach_core::protocol::{ConnectArgs, ErrorCode};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
struct Profile(PathBuf);
|
||||
@@ -61,20 +60,6 @@ async fn channel_selection_stays_independent_until_own_channel_changes() {
|
||||
stop(actor).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn moved_channel_draft_is_not_sent_to_the_new_channel() {
|
||||
use teamspeach_core::protocol::TextTarget;
|
||||
let profile = Profile::new();
|
||||
let manager = ConnectionManager::start(profile.0.clone(), Arc::new(|_: ConnectionEvent| {})).unwrap();
|
||||
let key = manager.create().await.unwrap();
|
||||
manager.fixture_control(&key, snapshot(10, &[10, 20])).await.unwrap();
|
||||
let draft = Command::SendText { target: TextTarget::Channel, expected_channel_id: Some(10),
|
||||
client_id: None, expected_client_uid: None, message: "for the first channel".into() };
|
||||
manager.fixture_control(&key, snapshot(20, &[10, 20])).await.unwrap();
|
||||
assert!(matches!(manager.request(&key, draft).await, Err(ConnectionError::TargetChanged)));
|
||||
manager.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn state_transitions_revoke_sessions_and_ignore_foreign_generation_and_worker() {
|
||||
let profile = Profile::new();
|
||||
@@ -107,7 +92,7 @@ async fn real_reply_arriving_after_session_boundary_is_rejected() {
|
||||
let key = actor.create().unwrap();
|
||||
actor.entries[0].worker.as_ref().unwrap().core.request(Command::ProfileCreate { nickname: "Real reply".into() }).await.unwrap();
|
||||
let (reply, response) = oneshot::channel();
|
||||
actor.dispatch(0, key, validate_command(Command::ProfileGet).unwrap(), CompletionKind::Request {
|
||||
actor.dispatch(0, key, Command::ProfileGet, CompletionKind::Request {
|
||||
guard: Guard::Strict, capture_revision: None, changes_config: false, reply, channel_lease:None,
|
||||
});
|
||||
let completion = tokio::time::timeout(Duration::from_secs(10), async {
|
||||
@@ -144,267 +129,6 @@ async fn previous_microphone_owner_is_restored_only_when_enabled() {
|
||||
stop(actor).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn capture_ingress_distinguishes_frame_expiry_from_revocation() {
|
||||
let profile = Profile::new();
|
||||
let manager = ConnectionManager::start(profile.0.clone(), Arc::new(|_: ConnectionEvent| {})).unwrap();
|
||||
let key = manager.create().await.unwrap();
|
||||
// Only the reducer's connected snapshot is synthetic; input configuration and PCM ingress use the real offline core.
|
||||
manager.fixture_control(&key, snapshot(1, &[1])).await.unwrap();
|
||||
let first = manager.set_input(Some(&key), InputConfiguration::default()).await.unwrap().unwrap();
|
||||
assert_eq!(manager.snapshot().capture.as_ref(), Some(&first));
|
||||
|
||||
let frame = |permit: &CapturePermit, captured_at| CapturedFrame {
|
||||
pcm: [1; 960], captured_at, capture_epoch: permit.capture_epoch,
|
||||
connection_generation: permit.key.generation, whisper: None,
|
||||
};
|
||||
assert_eq!(manager.push_audio(&key, frame(&first, Instant::now() - Duration::from_secs(1))), CaptureIngress::FrameRejected);
|
||||
assert_eq!(manager.snapshot().capture.as_ref(), Some(&first));
|
||||
assert_eq!(manager.push_audio(&key, frame(&first, Instant::now())), CaptureIngress::Accepted);
|
||||
|
||||
assert_eq!(manager.set_input(None, InputConfiguration::default()).await.unwrap(), None);
|
||||
assert!(manager.snapshot().capture.is_none());
|
||||
assert_eq!(manager.push_audio(&key, frame(&first, Instant::now())), CaptureIngress::PermitRevoked);
|
||||
|
||||
let replacement = manager.set_input(Some(&key), InputConfiguration::default()).await.unwrap().unwrap();
|
||||
assert_ne!(first.capture_epoch, replacement.capture_epoch);
|
||||
assert_eq!(manager.push_audio(&key, frame(&first, Instant::now())), CaptureIngress::PermitRevoked);
|
||||
assert_eq!(manager.snapshot().capture.as_ref(), Some(&replacement));
|
||||
assert_eq!(manager.push_audio(&key, frame(&replacement, Instant::now())), CaptureIngress::Accepted);
|
||||
manager.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn malformed_connection_requests_preserve_acknowledged_capture() {
|
||||
let profile = Profile::new();
|
||||
let manager = ConnectionManager::start(profile.0.clone(), Arc::new(|_: ConnectionEvent| {})).unwrap();
|
||||
let key = manager.create().await.unwrap();
|
||||
let viewed = manager.create().await.unwrap();
|
||||
// A nonnumeric channel ID fails after identity selection, but before the core can dial.
|
||||
let connect = ConnectArgs {
|
||||
address: "127.0.0.1".into(), channel: Some("cid:not-a-number".into()),
|
||||
identity_id: None, nickname: None, server_password: None, channel_password: None,
|
||||
};
|
||||
assert!(matches!(manager.request(&key, Command::Connect(connect.clone())).await,
|
||||
Err(ConnectionError::Core(ErrorObj { code: ErrorCode::ProfileMissing, .. }))));
|
||||
manager.request(&key, Command::ProfileCreate { nickname: "Default identity".into() }).await.unwrap();
|
||||
|
||||
// Only the connected snapshot is synthetic; input configuration and ingress use the real offline core.
|
||||
manager.fixture_control(&key, snapshot(1, &[1])).await.unwrap();
|
||||
manager.view(&viewed).await.unwrap();
|
||||
let permit = manager.set_input(Some(&key), InputConfiguration::default()).await.unwrap().unwrap();
|
||||
assert_eq!(manager.snapshot().capture.as_ref(), Some(&permit));
|
||||
|
||||
for (expected, command) in [
|
||||
("invalid address", Command::Connect(ConnectArgs { address: String::new(), ..connect.clone() })),
|
||||
("invalid identity_id", Command::Connect(ConnectArgs { identity_id: Some(String::new()), ..connect.clone() })),
|
||||
("invalid disconnect message", Command::Disconnect { message: Some("x".repeat(81)) }),
|
||||
] {
|
||||
let error = manager.request(&key, command).await.unwrap_err();
|
||||
let ConnectionError::Core(error) = error else { panic!("expected {expected}, got {error:?}") };
|
||||
assert_eq!(error.code, ErrorCode::BadRequest, "{error:?}");
|
||||
assert_eq!(error.message, expected);
|
||||
let current = manager.snapshot();
|
||||
let entry = current.get(&key.connection_id).unwrap();
|
||||
assert_eq!(entry.key, key);
|
||||
assert!(entry.is_connected());
|
||||
assert_eq!(current.viewed_id.as_ref(), Some(&viewed.connection_id));
|
||||
assert_eq!(current.input_id.as_ref(), Some(&key.connection_id));
|
||||
assert_eq!(current.capture.as_ref(), Some(&permit));
|
||||
assert_eq!(manager.push_audio(&key, CapturedFrame {
|
||||
pcm: [1; 960], captured_at: Instant::now(), capture_epoch: permit.capture_epoch,
|
||||
connection_generation: permit.key.generation, whisper: None,
|
||||
}), CaptureIngress::Accepted, "{expected}");
|
||||
}
|
||||
|
||||
let error = manager.request(&key, Command::Connect(connect)).await.unwrap_err();
|
||||
let ConnectionError::Core(error) = error else { panic!("expected an offline channel error, got {error:?}") };
|
||||
assert_eq!(error.code, ErrorCode::BadRequest, "{error:?}");
|
||||
assert_eq!(error.message, "channel \"cid:<n>\" needs a number");
|
||||
manager.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn microphone_handoff_waits_for_ack_while_another_tab_is_viewed() {
|
||||
async fn input_ack(actor: &mut Actor, owner: &SessionKey) -> Internal {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
let event = actor.events.recv().await.unwrap();
|
||||
if matches!(&event, Internal::Complete { completion, .. } if completion.key == *owner && matches!(&completion.kind, CompletionKind::Input { reply: Some(_), .. })) {
|
||||
return event;
|
||||
}
|
||||
actor.internal(event);
|
||||
}
|
||||
}).await.expect("embedded core did not acknowledge input configuration")
|
||||
}
|
||||
let profile = Profile::new();
|
||||
let (mut actor, snapshots, _) = actor(&profile);
|
||||
let a = actor.create().unwrap();
|
||||
let b = actor.create().unwrap();
|
||||
let c = actor.create().unwrap();
|
||||
// Only connected presentation is synthetic; configuration, queues and replies use real cores.
|
||||
for i in 0..3 { actor.control(i, snapshot(1, &[1])); }
|
||||
let (reply, first) = oneshot::channel();
|
||||
actor.operation(Operation::SetInput(Some(a.clone()), InputConfiguration::default(), reply));
|
||||
let ack = input_ack(&mut actor, &a).await;
|
||||
actor.internal(ack);
|
||||
let first = first.await.unwrap().unwrap().unwrap();
|
||||
let frame = |p: &CapturePermit| CapturedFrame { pcm: [1; 960], captured_at: Instant::now(),
|
||||
connection_generation: p.key.generation, capture_epoch: p.capture_epoch, whisper: None };
|
||||
let old_core = actor.entries[0].worker.as_ref().unwrap().core.clone();
|
||||
assert_eq!(actor.capture.lock().unwrap().route.as_ref().unwrap().push(&a, frame(&first)), CaptureIngress::Accepted);
|
||||
|
||||
let (reply, mut second) = oneshot::channel();
|
||||
actor.operation(Operation::SetInput(Some(b.clone()), InputConfiguration::default(), reply));
|
||||
let ack = input_ack(&mut actor, &b).await;
|
||||
let (reply, viewed) = oneshot::channel();
|
||||
actor.operation(Operation::View(c.clone(), reply));
|
||||
viewed.await.unwrap().unwrap();
|
||||
assert!(matches!(second.try_recv(), Err(oneshot::error::TryRecvError::Empty)));
|
||||
assert!(!old_core.push_audio(frame(&first)), "old queued frames must no longer be admissible");
|
||||
assert!(actor.capture.lock().unwrap().route.is_none());
|
||||
assert!(snapshots.borrow().capture.is_none());
|
||||
assert_eq!(snapshots.borrow().input_id.as_ref(), Some(&b.connection_id));
|
||||
assert_eq!(snapshots.borrow().viewed_id.as_ref(), Some(&c.connection_id));
|
||||
|
||||
actor.internal(ack);
|
||||
let second = second.await.unwrap().unwrap().unwrap();
|
||||
assert_eq!(second.key, b);
|
||||
{
|
||||
let capture = actor.capture.lock().unwrap();
|
||||
let route = capture.route.as_ref().unwrap();
|
||||
assert_eq!(route.push(&a, frame(&first)), CaptureIngress::PermitRevoked);
|
||||
assert_eq!(route.push(&c, frame(&second)), CaptureIngress::PermitRevoked);
|
||||
assert_eq!(route.push(&b, frame(&second)), CaptureIngress::Accepted);
|
||||
}
|
||||
actor.workflow.auto_enable_microphone = true;
|
||||
let (reply, viewed) = oneshot::channel();
|
||||
actor.operation(Operation::View(b.clone(), reply));
|
||||
viewed.await.unwrap().unwrap();
|
||||
assert_eq!(snapshots.borrow().viewed_id.as_ref(), Some(&b.connection_id));
|
||||
assert_eq!(snapshots.borrow().capture.as_ref(), Some(&second));
|
||||
assert_eq!(actor.capture.lock().unwrap().route.as_ref().unwrap().push(&b, frame(&second)), CaptureIngress::Accepted);
|
||||
|
||||
let (reply, pending) = oneshot::channel();
|
||||
actor.operation(Operation::SetInput(Some(c.clone()), InputConfiguration::default(), reply));
|
||||
let delayed = input_ack(&mut actor, &c).await;
|
||||
let pending_core = actor.entries[2].worker.as_ref().unwrap().core.clone();
|
||||
let pending_frame = CapturedFrame { capture_epoch: pending_core.audio_epoch(), connection_generation: c.generation, ..frame(&second) };
|
||||
let (reply, released) = oneshot::channel();
|
||||
actor.operation(Operation::SetInput(None, InputConfiguration::default(), reply));
|
||||
assert_eq!(released.await.unwrap().unwrap(), None);
|
||||
assert!(!pending_core.push_audio(pending_frame));
|
||||
actor.internal(delayed);
|
||||
assert!(matches!(pending.await.unwrap(), Err(ConnectionError::TargetChanged)));
|
||||
assert!(snapshots.borrow().capture.is_none());
|
||||
let (reply, resumed) = oneshot::channel();
|
||||
actor.operation(Operation::SetInput(Some(c.clone()), InputConfiguration::default(), reply));
|
||||
let ack = input_ack(&mut actor, &c).await;
|
||||
actor.internal(ack);
|
||||
let resumed = resumed.await.unwrap().unwrap().unwrap();
|
||||
assert_eq!(actor.capture.lock().unwrap().route.as_ref().unwrap().push(&c, frame(&resumed)), CaptureIngress::Accepted);
|
||||
drop(pending_core);
|
||||
drop(old_core);
|
||||
stop(actor).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn closed_worker_cannot_republish_or_stop_a_reused_slot() {
|
||||
let profile = Profile::new();
|
||||
let (mut actor, mut snapshots, observed) = actor(&profile);
|
||||
let original = actor.create().unwrap();
|
||||
let closing = actor.create().unwrap();
|
||||
let slot = actor.entries[1].snapshot.slot;
|
||||
let (reply, done) = oneshot::channel();
|
||||
actor.operation(Operation::Close(closing.clone(), reply));
|
||||
let joined = tokio::time::timeout(Duration::from_secs(5), actor.stopping.join_next()).await.unwrap().unwrap().unwrap();
|
||||
actor.stopped(joined, false).unwrap();
|
||||
done.await.unwrap().unwrap();
|
||||
let (reply, created) = oneshot::channel();
|
||||
actor.operation(Operation::Create(reply));
|
||||
let replacement = created.await.unwrap().unwrap();
|
||||
let (reply, viewed) = oneshot::channel();
|
||||
actor.operation(Operation::View(replacement.clone(), reply));
|
||||
viewed.await.unwrap().unwrap();
|
||||
let before = snapshots.borrow_and_update().clone();
|
||||
assert_ne!(closing.connection_id, replacement.connection_id);
|
||||
assert_eq!(before.get(&replacement.connection_id).unwrap().slot, slot);
|
||||
assert_eq!(before.viewed_id.as_ref(), Some(&replacement.connection_id));
|
||||
assert_eq!(before.input_id.as_ref(), Some(&original.connection_id));
|
||||
let delivered = observed.load(Ordering::Relaxed);
|
||||
actor.internal(Internal::Control { id: closing.connection_id.clone(), incarnation: 0, value: snapshot(99, &[99]) });
|
||||
actor.internal(Internal::Ended { id: closing.connection_id.clone(), incarnation: 0 });
|
||||
assert!(!snapshots.has_changed().unwrap(), "closed worker published a tab update");
|
||||
assert_eq!(observed.load(Ordering::Relaxed), delivered);
|
||||
assert!(actor.index(&closing.connection_id).is_err());
|
||||
let live = &actor.entries[actor.checked(&replacement).unwrap()];
|
||||
assert_eq!(live.snapshot.state, ConnectionState::Disconnected);
|
||||
assert!(live.worker.as_ref().unwrap().core.request(Command::ProfileGet).await.is_ok());
|
||||
stop(actor).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn failed_worker_restart_reports_failure_and_recovers_after_slot_unlock() {
|
||||
let profile = Profile::new();
|
||||
let (mut actor, snapshots, _) = actor(&profile);
|
||||
let first = actor.create().unwrap();
|
||||
let other = actor.create().unwrap();
|
||||
let slot = actor.entries[0].snapshot.slot;
|
||||
let (reply, restarted) = oneshot::channel();
|
||||
actor.operation(Operation::Restart(first.clone(), reply));
|
||||
assert_eq!(snapshots.borrow().get(&first.connection_id).unwrap().status, CoreStatus::Stopping);
|
||||
let joined = tokio::time::timeout(Duration::from_secs(5), actor.stopping.join_next()).await.unwrap().unwrap().unwrap();
|
||||
let (blocker, _events) = runtime::spawn(CoreConfig { data_dir: profile.0.clone(),
|
||||
connection_dir: profile.0.join("connections").join(slot.to_string()) }).unwrap();
|
||||
actor.stopped(joined, false).unwrap();
|
||||
assert!(matches!(restarted.await.unwrap(), Err(ConnectionError::Worker(_))));
|
||||
let failed = snapshots.borrow().get(&first.connection_id).unwrap().clone();
|
||||
assert_eq!(failed.status, CoreStatus::Failed);
|
||||
assert_eq!(failed.state, ConnectionState::Disconnected);
|
||||
let (reply, viewed) = oneshot::channel();
|
||||
actor.operation(Operation::View(failed.key.clone(), reply));
|
||||
viewed.await.unwrap().unwrap();
|
||||
assert!(actor.entries[actor.checked(&other).unwrap()].worker.as_ref().unwrap().core.request(Command::ProfileGet).await.is_ok());
|
||||
|
||||
blocker.shutdown().await.unwrap();
|
||||
let (reply, restarted) = oneshot::channel();
|
||||
actor.operation(Operation::Restart(failed.key.clone(), reply));
|
||||
let joined = tokio::time::timeout(Duration::from_secs(5), actor.stopping.join_next()).await.unwrap().unwrap().unwrap();
|
||||
actor.stopped(joined, false).unwrap();
|
||||
let ready = restarted.await.unwrap().unwrap();
|
||||
assert_eq!(snapshots.borrow().get(&ready.connection_id).unwrap().status, CoreStatus::Ready);
|
||||
assert_ne!(ready, failed.key);
|
||||
assert!(actor.entries[actor.checked(&ready).unwrap()].worker.as_ref().unwrap().core.request(Command::ProfileGet).await.is_ok());
|
||||
stop(actor).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn restart_discards_an_outstanding_response_from_the_previous_worker() {
|
||||
let profile = Profile::new();
|
||||
let (mut actor, snapshots, _) = actor(&profile);
|
||||
let key = actor.create().unwrap();
|
||||
let other = actor.create().unwrap();
|
||||
let (reply, pending) = oneshot::channel();
|
||||
actor.operation(Operation::Request(key.clone(), validate_command(Command::ProfileGet).unwrap(), reply));
|
||||
let response = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
let message = actor.events.recv().await.unwrap();
|
||||
if matches!(&message, Internal::Complete { id, .. } if id == &key.connection_id) { break message; }
|
||||
actor.internal(message);
|
||||
}
|
||||
}).await.unwrap();
|
||||
let (reply, restarted) = oneshot::channel();
|
||||
actor.operation(Operation::Restart(key.clone(), reply));
|
||||
let joined = tokio::time::timeout(Duration::from_secs(5), actor.stopping.join_next()).await.unwrap().unwrap().unwrap();
|
||||
actor.stopped(joined, false).unwrap();
|
||||
let new_key = restarted.await.unwrap().unwrap();
|
||||
actor.internal(response);
|
||||
assert!(pending.await.is_err(), "outgoing worker reply crossed the restart");
|
||||
assert_eq!(snapshots.borrow().get(&key.connection_id).unwrap().key, new_key);
|
||||
assert_eq!(actor.entries[actor.checked(&other).unwrap()].worker.as_ref().unwrap().core.request(Command::ProfileGet).await.unwrap()["exists"], false);
|
||||
stop(actor).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn directory_slot_is_reserved_until_the_old_core_is_joined() {
|
||||
let profile = Profile::new();
|
||||
@@ -428,46 +152,3 @@ async fn directory_slot_is_reserved_until_the_old_core_is_joined() {
|
||||
assert!(actor.entries[actor.index(&replacement.connection_id).unwrap()].snapshot.server.is_none());
|
||||
stop(actor).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn manager_retirement_precedes_join_and_is_not_a_server_event() {
|
||||
let profile = Profile::new();
|
||||
let observed = Arc::new(Mutex::new(Vec::new()));
|
||||
let log = observed.clone();
|
||||
let (publish, _) = watch::channel(Arc::new(ConnectionsSnapshot::default()));
|
||||
let mut actor = Actor::new(profile.0.clone(), Arc::new(move |event| log.lock().unwrap().push(event)),
|
||||
Arc::new(Mutex::new(CaptureState::default())), publish);
|
||||
let first = actor.create().unwrap();
|
||||
let (reply, closed) = oneshot::channel();
|
||||
actor.operation(Operation::Close(first.clone(), reply));
|
||||
assert!(matches!(closed.await.unwrap(), Err(ConnectionError::LastConnection)));
|
||||
assert!(observed.lock().unwrap().is_empty());
|
||||
|
||||
let second = actor.create().unwrap();
|
||||
let (reply, closed) = oneshot::channel();
|
||||
actor.operation(Operation::Close(second.clone(), reply));
|
||||
assert!(matches!(observed.lock().unwrap().as_slice(), [ConnectionEvent::Retired { key }] if key == &second));
|
||||
let stopped = tokio::time::timeout(Duration::from_secs(3), actor.stopping.join_next()).await.unwrap().unwrap().unwrap();
|
||||
actor.stopped(stopped, false).unwrap();
|
||||
closed.await.unwrap().unwrap();
|
||||
assert!(matches!(std::mem::take(&mut *observed.lock().unwrap()).as_slice(),
|
||||
[ConnectionEvent::Retired { key: retired }, ConnectionEvent::CoreStopped { key: joined, restarting: false }]
|
||||
if retired == &second && joined == &second));
|
||||
|
||||
let playback_key = actor.entries[0].worker.as_ref().unwrap().playback_key.clone();
|
||||
*playback_key.lock().unwrap() = Some(first.clone());
|
||||
let (reply, restarted) = oneshot::channel();
|
||||
actor.operation(Operation::Restart(first.clone(), reply));
|
||||
assert!(playback_key.lock().unwrap().is_none());
|
||||
actor.internal(Internal::Control { id: first.connection_id.clone(), incarnation: 0,
|
||||
value: json!({"event":"state", "state":"disconnected", "generation":first.generation}) });
|
||||
assert!(matches!(observed.lock().unwrap().as_slice(),
|
||||
[ConnectionEvent::InputReset, ConnectionEvent::Retired { key }] if key == &first));
|
||||
let stopped = tokio::time::timeout(Duration::from_secs(3), actor.stopping.join_next()).await.unwrap().unwrap().unwrap();
|
||||
actor.stopped(stopped, false).unwrap();
|
||||
assert_ne!(restarted.await.unwrap().unwrap(), first);
|
||||
assert!(matches!(observed.lock().unwrap().as_slice(),
|
||||
[ConnectionEvent::InputReset, ConnectionEvent::Retired { key: retired }, ConnectionEvent::CoreStopped { key: joined, restarting: true }]
|
||||
if retired == &first && joined == &first));
|
||||
stop(actor).await;
|
||||
}
|
||||
Loaded 100 of 662 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user