Compare commits
255
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ee33dc33e | ||
|
|
815c7c446f | ||
|
|
dd433fac97 | ||
|
|
fa0546e215 | ||
|
|
20e99f000c | ||
|
|
d2617e44ba | ||
|
|
17089bca60 | ||
|
|
bf6adcd301 | ||
|
|
f453f48fc7 | ||
|
|
6dfaf45628 | ||
|
|
a47bebf922 | ||
|
|
00643532a3 | ||
|
|
a1bf10f801 | ||
|
|
aab5a34b7c | ||
|
|
4aaab8f649 | ||
|
|
0f5551ab86 | ||
|
|
9cbf0bd02d | ||
|
|
ef5c9a89e5 | ||
|
|
59d5a92583 | ||
|
|
639b8b7094 | ||
|
|
0e6b285a9e | ||
|
|
d8e40b497c | ||
|
|
bbd2c350fc | ||
|
|
ea957ec030 | ||
|
|
748e760caa | ||
|
|
bf8f819a9d | ||
|
|
d77d0c3e7f | ||
|
|
8be4404f54 | ||
|
|
82a72e2fb6 | ||
|
|
6d5e01693e | ||
|
|
0e7d0b9bf4 | ||
|
|
0d7edae8cf | ||
|
|
49cfd53f97 | ||
|
|
1d5e4ba860 | ||
|
|
e15858b79d | ||
|
|
c8cbf4613d | ||
|
|
d72c273acd | ||
|
|
f76a7fb237 | ||
|
|
aff60b9ff3 | ||
|
|
8e9f28c856 | ||
|
|
5e73b78b55 | ||
|
|
cebac974d9 | ||
|
|
534f9b56d1 | ||
|
|
baea1f7142 | ||
|
|
d687e35096 | ||
|
|
6f1ffc34c1 | ||
|
|
c3f3c43224 | ||
|
|
8072e6f1d1 | ||
|
|
d1b611a911 | ||
|
|
1213468924 | ||
|
|
bff5c3377d | ||
|
|
90bcf5d929 | ||
|
|
a0c33187bf | ||
|
|
49c747e3f5 | ||
|
|
5f71304898 | ||
|
|
37552c282b | ||
|
|
b41b2d75f8 | ||
|
|
e1a07a2e2f | ||
|
|
a6684d352a | ||
|
|
3396dcbd90 | ||
|
|
b684eca1d8 | ||
|
|
be3654f149 | ||
|
|
a8fc57c2e1 | ||
|
|
149bad248e | ||
|
|
9c0ddd48ca | ||
|
|
20240c1027 | ||
|
|
d1450439d5 | ||
|
|
d9570f3cc8 | ||
|
|
b266f4f1b7 | ||
|
|
62bb67b5a3 | ||
|
|
256e10a9c1 | ||
|
|
89a2b21746 | ||
|
|
0b4a707637 | ||
|
|
c80219b1a3 | ||
|
|
380e9d4b63 | ||
|
|
389e26dc89 | ||
|
|
f41e064ea6 | ||
|
|
c12cf2123f | ||
|
|
6bf4de71c6 | ||
|
|
75514f1a84 | ||
|
|
5f3cf5f797 | ||
|
|
179683867c | ||
|
|
e47a81d82c | ||
|
|
160ba55c92 | ||
|
|
c912eb3a9c | ||
|
|
89cf17066f | ||
|
|
4fee4c0ce6 | ||
|
|
061bb2d33c | ||
|
|
96d9c45203 | ||
|
|
2e45637f1d | ||
|
|
b7635deb8b | ||
|
|
de99c5fdea | ||
|
|
b4e084dd25 | ||
|
|
c6cb35366e | ||
|
|
67b2fc60b2 | ||
|
|
a3ee6cc0c0 | ||
|
|
8d4daf4ef8 | ||
|
|
e25263e807 | ||
|
|
ba6cae3948 | ||
|
|
e7951f1bc6 | ||
|
|
6712e6dab6 | ||
|
|
9a518bda66 | ||
|
|
59166106f2 | ||
|
|
dc3e596625 | ||
|
|
1fe05c06fe | ||
|
|
b685597092 | ||
|
|
59a2878447 | ||
|
|
8630542261 | ||
|
|
039af3f3b7 | ||
|
|
8004c01526 | ||
|
|
f7601e7a4f | ||
|
|
402d8ff675 | ||
|
|
1e2856e261 | ||
|
|
f563d2ba9a | ||
|
|
e52db5b112 | ||
|
|
c27a425680 | ||
|
|
f0ed160cd0 | ||
|
|
6053e8b315 | ||
|
|
5933297cae | ||
|
|
5e646fc527 | ||
|
|
aa88f78c44 | ||
|
|
85e559dad5 | ||
|
|
6fea1a8d31 | ||
|
|
54179705e2 | ||
|
|
dfb60d7b7c | ||
|
|
335466b4a1 | ||
|
|
6ac09676b0 | ||
|
|
4244adfed6 | ||
|
|
390261e166 | ||
|
|
2af19bcfcf | ||
|
|
0ef6447971 | ||
|
|
c0835c613c | ||
|
|
20e6008fd4 | ||
|
|
8a98e3dcc6 | ||
|
|
90c28eedbb | ||
|
|
533b2b2d81 | ||
|
|
509bbb872d | ||
|
|
c84910524f | ||
|
|
60d1953ff6 | ||
|
|
25575d1111 | ||
|
|
d84153004d | ||
|
|
643d0e45e6 | ||
|
|
3a8e15e4c5 | ||
|
|
d5ba657f6e | ||
|
|
e9f375c4f7 | ||
|
|
f804bef346 | ||
|
|
3db0766339 | ||
|
|
faf9f957e7 | ||
|
|
2c8a47d51f | ||
|
|
2e3b2719e7 | ||
|
|
7729f263c0 | ||
|
|
d59bebd7eb | ||
|
|
d5b9541d1d | ||
|
|
8a8f52d7f1 | ||
|
|
89a930d2f5 | ||
|
|
0354a6fb8b | ||
|
|
010e6b45fd | ||
|
|
a25bd6b19d | ||
|
|
e6a8d2f7bc | ||
|
|
95ebf37f0b | ||
|
|
b3f73c389d | ||
|
|
3c828e35f3 | ||
|
|
8930007945 | ||
|
|
9b19e96271 | ||
|
|
cc3cb2702c | ||
|
|
be1d308f9e | ||
|
|
981c486b0c | ||
|
|
827f2c3053 | ||
|
|
ced85a30cc | ||
|
|
2a0a95f668 | ||
|
|
0e6bfb77bc | ||
|
|
f1e7d8d5c4 | ||
|
|
afac6cffee | ||
|
|
20a36d0dcf | ||
|
|
2780adc2ce | ||
|
|
3daa2fd990 | ||
|
|
220119e64f | ||
|
|
4dd514ea05 | ||
|
|
764e3dc060 | ||
|
|
49b9ce5dcd | ||
|
|
abdcbf1135 | ||
|
|
373bd3d314 | ||
|
|
a215cebfee | ||
|
|
ab3508c9cb | ||
|
|
4fb47fbde1 | ||
|
|
bab7c93d00 | ||
|
|
2b176ccdff | ||
|
|
582fe2d6c2 | ||
|
|
4ca8678e6b | ||
|
|
b5302b813a | ||
|
|
6f8e4bd3df | ||
|
|
9496f99fd4 | ||
|
|
fe9fe247c4 | ||
|
|
d57e90e67c | ||
|
|
530d15aef7 | ||
|
|
351366fb3d | ||
|
|
8312cb029a | ||
|
|
5162a890c4 | ||
|
|
f3f0950313 | ||
|
|
5b27eb6d49 | ||
|
|
d55f71577c | ||
|
|
53daeca615 | ||
|
|
57cf5ba51b | ||
|
|
9d8a8ea2ae | ||
|
|
b6db8a2b29 | ||
|
|
5b508e70e6 | ||
|
|
73c73d5cbc | ||
|
|
923dced8b0 | ||
|
|
2b2160869e | ||
|
|
8cf21cf4de | ||
|
|
da12f9ae86 | ||
|
|
f6bc5f8922 | ||
|
|
bef919fa16 | ||
|
|
00ee68c348 | ||
|
|
206a5a61ed | ||
|
|
fa46fb1ade | ||
|
|
76795c6ac9 | ||
|
|
20fcc27182 | ||
|
|
a6e3c6b1d6 | ||
|
|
5b40669953 | ||
|
|
4d578bc028 | ||
|
|
82b7f000bd | ||
|
|
20e3ec5592 | ||
|
|
1f008bcb27 | ||
|
|
f0827a221c | ||
|
|
b93a87ba93 | ||
|
|
d738f2feca | ||
|
|
e45f80e363 | ||
|
|
84b6692230 | ||
|
|
5d3eb925fe | ||
|
|
6ce8153371 | ||
|
|
2c52126955 | ||
|
|
08647b6830 | ||
|
|
2ba2e8dda4 | ||
|
|
06ee7e1fb0 | ||
|
|
dff1fb2d7b | ||
|
|
476319613a | ||
|
|
fe3f8b1b62 | ||
|
|
09b55b8040 | ||
|
|
230023a13b | ||
|
|
d2c1f2294b | ||
|
|
72233d108b | ||
|
|
3ce99945b8 | ||
|
|
034f7c0198 | ||
|
|
d314dbc312 | ||
|
|
00f585c3b9 | ||
|
|
a153511710 | ||
|
|
3b5c49e329 | ||
|
|
b19b432281 | ||
|
|
58547c8221 | ||
|
|
845244ec2c | ||
|
|
de84b526d4 | ||
|
|
c3baa1952c | ||
|
|
c2d62e0fdc | ||
|
|
57807c184e |
No files matched your search
@@ -1,5 +1,3 @@
|
||||
# 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
|
||||
@@ -1,222 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CI-only Cargo cache bookkeeping; never manufactures build/provenance receipts.
|
||||
|
||||
Cargo compares checkout source mtimes with cached dep-info/build-script timestamps.
|
||||
A fresh checkout otherwise invalidates unchanged workspace and vendored crates.
|
||||
Restore a recorded timestamp only for the same path, SHA-256, kind and mode; a
|
||||
changed input keeps its real mtime. WebRTC is handled only AFTER xtask deps has
|
||||
rebuilt/verified it, so identical republished headers/archives can retain their
|
||||
original timestamps without trusting cached dependency provenance.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import stat
|
||||
import subprocess
|
||||
import time
|
||||
import tomllib
|
||||
|
||||
ROOT = pathlib.Path.cwd().resolve()
|
||||
STATE = ROOT / '.android-ci'
|
||||
RECEIPT = STATE / 'application-cache-inputs.json'
|
||||
PENDING = STATE / 'application-cache-pending.json'
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open('rb') as source:
|
||||
return hashlib.file_digest(source, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def tracked_paths():
|
||||
return [os.fsdecode(name) for name in subprocess.check_output(
|
||||
['git', 'ls-files', '-z']).split(b'\0') if name]
|
||||
|
||||
|
||||
def compatibility():
|
||||
# Content changes belong to Cargo's fingerprints and the input snapshot, not
|
||||
# the restore prefix. Only configuration that changes the build contract is
|
||||
# a compatibility boundary. In particular, dependency versions/features and
|
||||
# source/dependency drivers are deliberately absent here.
|
||||
target_dir = pathlib.Path(os.environ['CARGO_TARGET_DIR']).resolve()
|
||||
if target_dir != STATE / 'cargo-target':
|
||||
raise ValueError('Application cache requires the isolated .android-ci/cargo-target')
|
||||
names = {'.gitea/android-ci-tools.json', 'rust-toolchain.toml',
|
||||
'.gitea/setup-android-ci.sh', '.gitea/build-android-variant.sh',
|
||||
'.gitea/android-rustc-low-memory.sh',
|
||||
'platform/android/gradle/wrapper/gradle-wrapper.properties'}
|
||||
profiles = {}
|
||||
for name in tracked_paths():
|
||||
path = pathlib.PurePosixPath(name)
|
||||
if path.name in ('config', 'config.toml') and path.parent.name == '.cargo':
|
||||
names.add(name)
|
||||
if path.name == 'Cargo.toml':
|
||||
profile = tomllib.loads((ROOT / name).read_text()).get('profile')
|
||||
if profile:
|
||||
profiles[name] = profile
|
||||
environment = {
|
||||
name: os.environ.get(name, '') for name in (
|
||||
'TARGET', 'TEAMSPEACH_ANDROID_LOW_MEMORY', 'CARGO_TARGET_DIR',
|
||||
'RUSTFLAGS', 'CARGO_ENCODED_RUSTFLAGS', 'RUSTC_WRAPPER',
|
||||
'RUSTC_WORKSPACE_WRAPPER', 'RUSTUP_TOOLCHAIN', 'CARGO_HOME',
|
||||
'RUSTUP_HOME', 'HOME', 'LLVM_HOME', 'LIBCLANG_PATH',
|
||||
'ANDROID_SDK_ROOT', 'ANDROID_NDK_ROOT', 'ANDROID_API_LEVEL',
|
||||
'SKIA_SOURCE_DIR', 'SKIA_GN_COMMAND', 'SKIA_NINJA_COMMAND',
|
||||
'SKIA_FORCE_BUILD')}
|
||||
environment.update({name: value for name, value in os.environ.items()
|
||||
if name.startswith(('CARGO_PROFILE_', 'CARGO_TARGET_'))})
|
||||
return {
|
||||
'files': {name: digest(ROOT / name) for name in sorted(names)},
|
||||
'profiles': profiles, 'environment': environment,
|
||||
'rustc': subprocess.check_output(['rustc', '-vV'], text=True),
|
||||
'cargo': subprocess.check_output(['cargo', '-V'], text=True),
|
||||
'profile': 'release', 'variant': 'harness',
|
||||
}
|
||||
|
||||
|
||||
def identity(inputs):
|
||||
fingerprint = hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest()
|
||||
environment = inputs['environment']
|
||||
mode = 'low-memory' if environment['TEAMSPEACH_ANDROID_LOW_MEMORY'] == 'true' else 'normal'
|
||||
return f"android-application-linux-x64-{environment['TARGET']}-release-{mode}-harness-v2-{fingerprint}"
|
||||
|
||||
|
||||
def record(path):
|
||||
info = path.lstat()
|
||||
mode = stat.S_IMODE(info.st_mode)
|
||||
if stat.S_ISREG(info.st_mode):
|
||||
kind, value = 'file', digest(path)
|
||||
elif stat.S_ISDIR(info.st_mode):
|
||||
kind = 'directory'
|
||||
value = hashlib.sha256(json.dumps(sorted(os.listdir(path))).encode()).hexdigest()
|
||||
else:
|
||||
# Never follow checkout/cache symlinks, including symlinked ancestors.
|
||||
raise ValueError(f'Unsupported cache input: {path}')
|
||||
return {'kind': kind, 'sha256': value, 'mode': mode, 'mtime_ns': info.st_mtime_ns}
|
||||
|
||||
|
||||
def collect(names):
|
||||
result = {}
|
||||
for name in sorted(set(names)):
|
||||
path = ROOT / name
|
||||
if not path.exists():
|
||||
continue
|
||||
if not path.resolve().is_relative_to(ROOT) or any(parent.is_symlink() for parent in (path, *path.parents)):
|
||||
raise ValueError(f'Unconfined cache input: {name}')
|
||||
result[name] = record(path)
|
||||
return result
|
||||
|
||||
|
||||
def load(contract, path=RECEIPT):
|
||||
if path == RECEIPT and not path.exists():
|
||||
return {'inputs': {}, 'completed_ns': 0}
|
||||
data = json.loads(path.read_text())
|
||||
recorded = data.get('compatibility', {})
|
||||
comparable = {**recorded, 'environment': dict(recorded.get('environment', {}))}
|
||||
# Scheduling is not an artifact compatibility boundary. Accept the earlier
|
||||
# explicit four-job receipt only after all actual tool/profile inputs match.
|
||||
comparable['environment'].pop('CMAKE_BUILD_PARALLEL_LEVEL', None)
|
||||
if (data['schema'] != 2 or comparable != contract
|
||||
or data['identity'] != identity(recorded) or data['workspace'] != str(ROOT)):
|
||||
# v1's opaque content identity cannot prove configuration compatibility
|
||||
# after a manifest change. Start a new cache generation, never guess.
|
||||
raise ValueError('Application cache compatibility/workspace mismatch (requires v2 receipt)')
|
||||
return data
|
||||
|
||||
|
||||
def cargo_timestamps():
|
||||
# These are Cargo's real host/target build-start stamps, not target/ at the
|
||||
# repository root (which contains the separately verified WebRTC tree).
|
||||
target = STATE / 'cargo-target'
|
||||
paths = [*target.glob('*/.fingerprint/*/invoked.timestamp'),
|
||||
*target.glob('*/*/.fingerprint/*/invoked.timestamp')]
|
||||
return {str(path.relative_to(ROOT)): path.stat().st_mtime_ns for path in paths}
|
||||
|
||||
|
||||
def report_cargo_timestamps(previous):
|
||||
current = cargo_timestamps()
|
||||
recorded = previous.get('cargo_timestamps', {})
|
||||
changed = sum(current.get(name) != stamp for name, stamp in recorded.items())
|
||||
print(f'Cargo target: {STATE / "cargo-target"}; restored build-start stamps: '
|
||||
f'{len(current)}; missing/retimed since snapshot: {changed}; '
|
||||
f'cached completion ns: {previous["completed_ns"]}', flush=True)
|
||||
if changed:
|
||||
print('Cargo output timestamps changed during cache transport; Cargo may rebuild. '
|
||||
'Build output timestamps are never rewritten.', flush=True)
|
||||
|
||||
|
||||
def save(path, inputs, contract):
|
||||
STATE.mkdir(exist_ok=True)
|
||||
temporary = path.with_suffix('.tmp')
|
||||
stamps = cargo_timestamps() if path == RECEIPT else {}
|
||||
temporary.write_text(json.dumps({'schema': 2, 'identity': identity(contract),
|
||||
'compatibility': contract,
|
||||
'workspace': str(ROOT), 'inputs': inputs,
|
||||
'completed_ns': time.time_ns(),
|
||||
'cargo_timestamps': stamps}, sort_keys=True))
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def restore(current, previous):
|
||||
restored = 0
|
||||
for name, item in current.items():
|
||||
old = previous['inputs'].get(name)
|
||||
if old is None or any(item[key] != old[key] for key in ('kind', 'sha256', 'mode')):
|
||||
# Changed/new inputs must postdate the previous compilation. Reject
|
||||
# clock regressions rather than making stale outputs appear fresh.
|
||||
if previous['completed_ns'] and item['mtime_ns'] <= previous['completed_ns']:
|
||||
raise ValueError(f'Changed input predates cached compilation: {name}; refuse stale Cargo reuse')
|
||||
continue
|
||||
if old['mtime_ns'] > item['mtime_ns']:
|
||||
raise ValueError(f'Cached input timestamp is in the future: {name}')
|
||||
path = ROOT / name
|
||||
os.utime(path, ns=(path.stat().st_atime_ns, old['mtime_ns']), follow_symlinks=False)
|
||||
item['mtime_ns'] = old['mtime_ns']
|
||||
restored += 1
|
||||
print(f'Restored {restored}/{len(current)} content-matched input timestamps', flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('key', 'sources', 'dependencies', 'snapshot'))
|
||||
action = parser.parse_args().action
|
||||
contract = compatibility()
|
||||
if action == 'key':
|
||||
with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
|
||||
out.write(f'key={identity(contract)}\n')
|
||||
previous = {**contract, 'environment': {**contract['environment'], 'CMAKE_BUILD_PARALLEL_LEVEL': '4'}}
|
||||
out.write(f'previous-parallelism-key={identity(previous)}\n')
|
||||
return
|
||||
previous = load(contract)
|
||||
if action == 'sources':
|
||||
report_cargo_timestamps(previous)
|
||||
names = set(tracked_paths())
|
||||
# Cargo's directory rerun rules also inspect directory mtimes. Preserve
|
||||
# those only if their exact child-name inventory and mode still match.
|
||||
for name in tuple(names):
|
||||
names.update(str(parent) for parent in pathlib.Path(name).parents if parent != pathlib.Path('.'))
|
||||
current = collect(names)
|
||||
restore(current, previous)
|
||||
save(PENDING, current, contract)
|
||||
elif action == 'dependencies':
|
||||
base = pathlib.Path('target/native-deps') / os.environ['TARGET'] / 'webrtc'
|
||||
if not base.is_dir():
|
||||
raise ValueError('Verified WebRTC artifact tree is missing')
|
||||
current = collect([str(base), *(str(path) for path in base.rglob('*'))])
|
||||
restore(current, previous)
|
||||
pending = load(contract, PENDING)['inputs']
|
||||
pending.update(current)
|
||||
save(PENDING, pending, contract)
|
||||
else:
|
||||
pending = load(contract, PENDING)['inputs']
|
||||
current = collect(pending)
|
||||
# Only retain inputs whose bytes/mode/mtime stayed stable throughout the
|
||||
# build. A generated or concurrently edited file is never backdated.
|
||||
stable = {name: item for name, item in current.items() if item == pending[name]}
|
||||
save(RECEIPT, stable, contract)
|
||||
print(f'Recorded {len(stable)} stable application/dependency inputs', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,39 +0,0 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"rust": {
|
||||
"version": "1.96.0",
|
||||
"target": "aarch64-linux-android",
|
||||
"rustupVersion": "1.29.3",
|
||||
"rustupUrl": "https://static.rust-lang.org/rustup/archive/1.29.3/x86_64-unknown-linux-gnu/rustup-init",
|
||||
"rustupSha256": "b1c8cb14e30889e7e2999e6b69e62d9e9b9ffc0f4df8180564d306d9680e6c55",
|
||||
"checksumSource": "https://static.rust-lang.org/rustup/archive/1.29.3/x86_64-unknown-linux-gnu/rustup-init.sha256"
|
||||
},
|
||||
"android": {
|
||||
"commandLineToolsVersion": "15859902",
|
||||
"commandLineToolsUrl": "https://dl.google.com/android/repository/commandlinetools-linux-15859902_latest.zip",
|
||||
"commandLineToolsSha256": "4e4c464f145a7512b57d088ac6c278c03c9eea610886b35a5e0804e74eedf583",
|
||||
"checksumSource": "https://developer.android.com/studio#command-line-tools-only",
|
||||
"platform": "android-36",
|
||||
"buildTools": "36.0.0",
|
||||
"ndk": "28.2.13676358"
|
||||
},
|
||||
"gradle": {
|
||||
"version": "8.14.3",
|
||||
"pinSource": "platform/android/gradle/wrapper/gradle-wrapper.properties"
|
||||
},
|
||||
"skia": {
|
||||
"revision": "m153-0.101.2",
|
||||
"url": "https://codeload.github.com/rust-skia/skia/tar.gz/m153-0.101.2",
|
||||
"sha256": "30c8b51a0a32fae63562c303bdc91605519a9598951422610e3fb8685b3c4f6f",
|
||||
"metadataSource": "https://raw.githubusercontent.com/rust-skia/rust-skia/0.153.3/skia-bindings/Cargo.toml",
|
||||
"urlSource": "https://raw.githubusercontent.com/rust-skia/rust-skia/0.153.3/skia-bindings/build_support/binary_cache/download.rs",
|
||||
"gnRevision": "b2afae122eeb6ce09c52d63f67dc53fc517dbdc8",
|
||||
"gnPinSource": "https://raw.githubusercontent.com/rust-skia/skia/m153-0.101.2/bin/fetch-gn"
|
||||
},
|
||||
"bundletool": {
|
||||
"version": "1.18.3",
|
||||
"url": "https://github.com/google/bundletool/releases/download/1.18.3/bundletool-all-1.18.3.jar",
|
||||
"sha256": "a099cfa1543f55593bc2ed16a70a7c67fe54b1747bb7301f37fdfd6d91028e29",
|
||||
"checksumSource": "https://api.github.com/repos/google/bundletool/releases/tags/1.18.3"
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Read only resource counters; no environment, credentials, process arguments or kernel logs.
|
||||
set -euo pipefail
|
||||
printf 'RESOURCE_SNAPSHOT %s\n' "$(date -u +%FT%TZ)"
|
||||
while read -r key value unit; do
|
||||
case "$key" in MemTotal:|MemAvailable:|SwapTotal:|SwapFree:|CommitLimit:|Committed_AS:) printf '%s %s %s\n' "$key" "$value" "${unit:-}" ;; esac
|
||||
done < /proc/meminfo
|
||||
while IFS=: read -r hierarchy controllers relative; do
|
||||
if [[ -z "$controllers" ]]; then
|
||||
base=/sys/fs/cgroup
|
||||
names=(memory.max memory.high memory.current memory.peak memory.events memory.events.local memory.swap.max memory.swap.current)
|
||||
elif [[ ",$controllers," == *,memory,* ]]; then
|
||||
base=/sys/fs/cgroup/memory
|
||||
names=(memory.limit_in_bytes memory.usage_in_bytes memory.max_usage_in_bytes memory.failcnt memory.oom_control)
|
||||
else
|
||||
continue
|
||||
fi
|
||||
current="$(realpath -m "$base/${relative#/}")"
|
||||
case "$current" in "$base"|"$base/"*) ;; *) current="$base" ;; esac
|
||||
[[ -d "$current" ]] || current="$base"
|
||||
while :; do
|
||||
for name in "${names[@]}"; do
|
||||
if [[ -r "$current/$name" ]]; then printf '%s\n' "$current/$name"; cat "$current/$name"; fi
|
||||
done
|
||||
[[ "$current" != "$base" ]] || break
|
||||
current="${current%/*}"
|
||||
done
|
||||
done < /proc/self/cgroup
|
||||
ulimit -a
|
||||
df -Pk . /
|
||||
@@ -1,14 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Explicitly authorized Android CI optimization override, not a workspace release default.
|
||||
set -euo pipefail
|
||||
compiler="$1"
|
||||
shift
|
||||
crate= target= previous=
|
||||
for argument in "$@"; do
|
||||
case "$previous" in --crate-name) crate="$argument" ;; --target) target="$argument" ;; esac
|
||||
previous="$argument"
|
||||
done
|
||||
if [[ "$crate" == teamspeach_native && "$target" == aarch64-linux-android ]]; then
|
||||
exec "$compiler" "$@" -C codegen-units=256 -C lto=off
|
||||
fi
|
||||
exec "$compiler" "$@"
|
||||
@@ -1,49 +0,0 @@
|
||||
#!/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"
|
||||
if [[ "${TEAMSPEACH_ANDROID_LOW_MEMORY:-false}" == true ]]; then
|
||||
[[ "$TARGET" == aarch64-linux-android ]] || { echo 'Low-memory CI mode is Android ARM64 only' >&2; exit 1; }
|
||||
export RUSTC_WORKSPACE_WRAPPER="$PWD/.gitea/android-rustc-low-memory.sh"
|
||||
fi
|
||||
cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --test-harness "$harness" --jobs "${CARGO_BUILD_JOBS:-1}"
|
||||
# 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
|
||||
# xtask package already verifies the completed APK/AAB before returning success.
|
||||
# The receipt and artifact hashes below bind that verification to the uploaded bytes.
|
||||
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()
|
||||
low_memory = os.environ.get('TEAMSPEACH_ANDROID_LOW_MEMORY') == 'true'
|
||||
optimization = {'scope': 'teamspeach_native/aarch64-linux-android', 'codegenUnits': 256, 'lto': 'off'} if low_memory else {'scope': 'workspace release defaults'}
|
||||
(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, 'optimization': optimization, 'deviceAcceptance': 'not exercised', 'publicationAuthorized': False, 'sha256': hashes}, indent=2) + '\n')
|
||||
PY
|
||||
@@ -1,48 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Undo only receipt-matched source patches before gclient reuses a CI checkpoint."""
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
|
||||
def unpatch(checkout, diffs):
|
||||
checkout = checkout.resolve(strict=True)
|
||||
pending = []
|
||||
for relative, expected in diffs.items():
|
||||
parts = pathlib.PurePosixPath(relative)
|
||||
if parts.is_absolute() or '..' in parts.parts or not parts.parts or parts.parts[0] != 'src':
|
||||
raise ValueError('Unconfined dependency receipt path')
|
||||
directory = checkout.joinpath(*parts.parts).resolve(strict=True)
|
||||
if not directory.is_relative_to(checkout):
|
||||
raise ValueError('Dependency checkout escapes cache')
|
||||
actual = subprocess.check_output(['git', '-C', str(directory), 'diff', '--binary', 'HEAD', '--'])
|
||||
encoded = expected.encode('utf-8')
|
||||
if actual != encoded:
|
||||
raise ValueError(f'Cached changes differ from verified receipt: {relative}; refusing to reset')
|
||||
if actual:
|
||||
subprocess.run(['git', '-C', str(directory), 'apply', '--reverse', '--check', '-'], input=actual, check=True)
|
||||
pending.append((directory, actual))
|
||||
# Validate every repository before making any mutation. Untracked outputs are not touched.
|
||||
for directory, patch in pending:
|
||||
subprocess.run(['git', '-C', str(directory), 'apply', '--reverse', '-'], input=patch, check=True)
|
||||
print(f'Removed {len(pending)} receipt-matched source patches; build objects retained', flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
base = pathlib.Path('target/native-deps/aarch64-linux-android')
|
||||
receipt_path = base / 'provenance.json'
|
||||
if not receipt_path.exists():
|
||||
print('No restored dependency receipt; fresh provisioning')
|
||||
return
|
||||
receipt = json.loads(receipt_path.read_text(encoding='utf-8'))
|
||||
lock = json.loads(pathlib.Path('native/native-deps.lock.json').read_text(encoding='utf-8'))
|
||||
if receipt['target'] != 'aarch64-linux-android':
|
||||
raise ValueError('Wrong cached target')
|
||||
for receipt_key, lock_key in [('webrtc_revision', 'webrtc'), ('sdk_revision', 'sdk'), ('depot_tools_revision', 'depot_tools')]:
|
||||
if receipt[receipt_key] != lock[lock_key]['revision']:
|
||||
raise ValueError('Cached source revision no longer matches policy')
|
||||
unpatch(base / 'checkout', receipt['applied_source_diffs'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,235 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Only the explicitly authorized, disposable Android CI job container may install tools.
|
||||
set -euo pipefail
|
||||
umask 022
|
||||
fail() { printf 'Android CI provisioning refused: %s\n' "$*" >&2; exit 1; }
|
||||
[[ "$(uname -s)" == Linux && "$(uname -m)" == x86_64 ]] || fail 'Linux x86_64 is required'
|
||||
[[ "${ANDROID_CI_PROVISION:-}" == container ]] || fail 'ANDROID_CI_PROVISION=container is required'
|
||||
[[ "${GITHUB_ACTIONS:-}" == true || "${GITEA_ACTIONS:-}" == true ]] || fail 'an Actions job is required'
|
||||
[[ -f /.dockerenv || -f /run/.containerenv ]] || fail 'no Docker/Podman container marker; host provisioning is forbidden'
|
||||
: "${GITHUB_WORKSPACE:?Actions workspace is required}"
|
||||
: "${GITHUB_ENV:?Actions environment output is required}"
|
||||
: "${GITHUB_PATH:?Actions PATH output is required}"
|
||||
if (( EUID == 0 )); then
|
||||
elevate=()
|
||||
else
|
||||
command -v sudo >/dev/null || fail 'root or passwordless sudo is required inside the container'
|
||||
sudo -n true || fail 'passwordless sudo is required inside the container'
|
||||
elevate=(sudo -n)
|
||||
fi
|
||||
|
||||
# No apt update, download, installation, or cache creation precedes this gate.
|
||||
# MemAvailable alone can describe the host, so also respect every visible cgroup ancestor.
|
||||
for filesystem in "$GITHUB_WORKSPACE" /; do
|
||||
free="$(df --output=avail -B1 "$filesystem")"
|
||||
free="${free##*$'\n'}"
|
||||
[[ "$free" =~ ^[[:space:]]*[0-9]+[[:space:]]*$ ]] || fail 'cannot determine free disk'
|
||||
printf 'RESOURCE disk=%s availableBytes=%s requiredBytes=%s\n' "$filesystem" "$free" "$((100 * 1024**3))"
|
||||
(( free >= 100 * 1024**3 )) || fail 'resource gate needs at least 100 GiB free disk, including cache hits; no provisioning performed'
|
||||
done
|
||||
available=0
|
||||
while read -r key value _; do
|
||||
if [[ "$key" == MemAvailable: ]]; then available=$((value * 1024)); break; fi
|
||||
done < /proc/meminfo
|
||||
(( available > 0 )) || fail 'cannot determine available memory'
|
||||
limit_count=0
|
||||
while IFS=: read -r _ controllers relative; do
|
||||
if [[ -z "$controllers" ]]; then
|
||||
cgroup_root=/sys/fs/cgroup
|
||||
limit_names=(memory.max memory.high)
|
||||
usage_name=memory.current
|
||||
elif [[ ",$controllers," == *,memory,* ]]; then
|
||||
cgroup_root=/sys/fs/cgroup/memory
|
||||
limit_names=(memory.limit_in_bytes)
|
||||
usage_name=memory.usage_in_bytes
|
||||
else
|
||||
continue
|
||||
fi
|
||||
current="$(realpath -m "$cgroup_root/${relative#/}")"
|
||||
case "$current" in "$cgroup_root"|"$cgroup_root/"*) ;; *) current="$cgroup_root" ;; esac
|
||||
[[ -d "$current" ]] || current="$cgroup_root"
|
||||
while :; do
|
||||
for limit_name in "${limit_names[@]}"; do
|
||||
if [[ -f "$current/$limit_name" && -f "$current/$usage_name" ]]; then
|
||||
limit="$(<"$current/$limit_name")"
|
||||
if [[ "$limit" != max ]]; then
|
||||
[[ "$limit" =~ ^[0-9]+$ ]] || fail 'invalid cgroup memory limit'
|
||||
usage="$(<"$current/$usage_name")"
|
||||
[[ "$usage" =~ ^[0-9]+$ ]] || fail 'invalid cgroup memory usage'
|
||||
remaining=$((limit > usage ? limit - usage : 0))
|
||||
(( remaining >= available )) || available="$remaining"
|
||||
limit_count=$((limit_count + 1))
|
||||
fi
|
||||
fi
|
||||
done
|
||||
[[ "$current" != "$cgroup_root" ]] || break
|
||||
current="${current%/*}"
|
||||
done
|
||||
done < /proc/self/cgroup
|
||||
printf 'RESOURCE effectiveAvailableMemoryBytes=%s requiredBytes=%s cgroupLimits=%s\n' "$available" "$((8 * 1024**3))" "$limit_count"
|
||||
(( available >= 8 * 1024**3 )) || fail 'resource gate needs at least 8 GiB available memory; no provisioning performed'
|
||||
|
||||
# Stock noble packages provide matching LLVM/libclang18 and JDK21 without third-party apt setup.
|
||||
# shellcheck disable=SC1091
|
||||
source /etc/os-release
|
||||
[[ "$ID" == ubuntu && "$VERSION_ID" == 24.04 ]] || fail 'the container image must use Ubuntu 24.04 (noble)'
|
||||
workspace="$(realpath "$GITHUB_WORKSPACE")"
|
||||
cd "$workspace"
|
||||
[[ ! -L .android-ci && ! -L .android-ci/tools ]] || fail 'tool cache roots must not be symlinks'
|
||||
tools="$workspace/.android-ci/tools"
|
||||
mkdir -p "$tools"/{downloads,home,tmp,cache,config,data,apt/archives/partial,apt/lists/partial}
|
||||
export HOME="$tools/home" TMPDIR="$tools/tmp"
|
||||
export XDG_CACHE_HOME="$tools/cache" XDG_CONFIG_HOME="$tools/config" XDG_DATA_HOME="$tools/data"
|
||||
export CARGO_HOME="$tools/cargo" RUSTUP_HOME="$tools/rustup" GRADLE_USER_HOME="$tools/gradle"
|
||||
# New and legacy Android tools must resolve the same preferences directory.
|
||||
export ANDROID_USER_HOME="$HOME/.android" ANDROID_EMULATOR_HOME="$HOME/.android/emulator"
|
||||
export ANDROID_SDK_HOME="$HOME" JAVA_TOOL_OPTIONS="-Duser.home=$HOME"
|
||||
export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_TERMINAL_PROMPT=0
|
||||
export PIP_CACHE_DIR="$tools/pip-cache" CIPD_CACHE_DIR="$tools/cipd-cache" VPYTHON_VIRTUALENV_ROOT="$tools/vpython-cache"
|
||||
export DEPOT_TOOLS_METRICS=0 DEPOT_TOOLS_UPDATE=0
|
||||
mkdir -p "$CARGO_HOME" "$RUSTUP_HOME" "$GRADLE_USER_HOME" "$ANDROID_USER_HOME"
|
||||
|
||||
# Apt archives/lists are workspace-local; installed packages exist only in this job container.
|
||||
apt_options=(-o "Dir::Cache::archives=$tools/apt/archives" -o "Dir::State::lists=$tools/apt/lists" -o APT::Sandbox::User=root)
|
||||
"${elevate[@]}" env DEBIAN_FRONTEND=noninteractive apt-get "${apt_options[@]}" update
|
||||
"${elevate[@]}" env DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get "${apt_options[@]}" install -y --no-install-recommends \
|
||||
ca-certificates openjdk-21-jdk-headless clang-18 llvm-18 lld-18 libclang-18-dev \
|
||||
cmake ninja-build git python3 curl unzip zip pkg-config build-essential \
|
||||
autoconf automake libtool bison flex gperf nasm binutils file patch rsync \
|
||||
xz-utils bzip2 zstd gettext libxml2-utils locales time \
|
||||
libc6-i386 lib32gcc-s1 lib32stdc++6 zlib1g-dev libbz2-dev liblzma-dev \
|
||||
libssl-dev libffi-dev libelf-dev libcap-dev libudev-dev libglib2.0-dev \
|
||||
libnss3-dev libnspr4-dev libdbus-1-dev libdrm-dev libgbm-dev \
|
||||
libasound2-dev libpulse-dev libcups2-dev libatk1.0-dev libatspi2.0-dev \
|
||||
libcairo2-dev libpango1.0-dev libgtk-3-dev libfontconfig1-dev libfreetype6-dev \
|
||||
libx11-dev libx11-xcb-dev libxcb1-dev libxcomposite-dev libxcursor-dev libxdamage-dev \
|
||||
libxext-dev libxfixes-dev libxi-dev libxrandr-dev libxrender-dev libxss-dev libxtst-dev \
|
||||
libxkbcommon-dev libxshmfence-dev libwayland-dev libegl1-mesa-dev libgl1-mesa-dev
|
||||
|
||||
# Read checked-in pins; Gradle's URL and checksum have exactly one authority: its wrapper.
|
||||
pins="$(python3 - <<'PY'
|
||||
import json, pathlib, re, shlex, tomllib
|
||||
p = json.loads(pathlib.Path('.gitea/android-ci-tools.json').read_text())
|
||||
assert p['schema'] == 1
|
||||
rust = tomllib.loads(pathlib.Path('rust-toolchain.toml').read_text())['toolchain']['channel']
|
||||
assert rust == p['rust']['version'] == '1.96.0', 'toolchain pin mismatch'
|
||||
props = dict(line.split('=', 1) for line in pathlib.Path(p['gradle']['pinSource']).read_text().splitlines() if '=' in line)
|
||||
gradle_url = props['distributionUrl'].replace('\\:', ':')
|
||||
assert gradle_url == 'https://services.gradle.org/distributions/gradle-8.14.3-bin.zip'
|
||||
assert re.fullmatch(r'[0-9a-f]{64}', props['distributionSha256Sum'])
|
||||
values = {
|
||||
'rust_version': rust, 'rust_target': p['rust']['target'],
|
||||
'rustup_url': p['rust']['rustupUrl'], 'rustup_sha': p['rust']['rustupSha256'],
|
||||
'sdk_tools_version': p['android']['commandLineToolsVersion'],
|
||||
'sdk_tools_url': p['android']['commandLineToolsUrl'], 'sdk_tools_sha': p['android']['commandLineToolsSha256'],
|
||||
'sdk_platform': p['android']['platform'], 'build_tools': p['android']['buildTools'], 'ndk_version': p['android']['ndk'],
|
||||
'gradle_url': gradle_url, 'gradle_sha': props['distributionSha256Sum'],
|
||||
'skia_revision': p['skia']['revision'], 'skia_url': p['skia']['url'], 'skia_sha': p['skia']['sha256'],
|
||||
'skia_gn_revision': p['skia']['gnRevision'],
|
||||
'bundletool_version': p['bundletool']['version'], 'bundletool_url': p['bundletool']['url'], 'bundletool_sha': p['bundletool']['sha256'],
|
||||
}
|
||||
for key, value in values.items():
|
||||
assert '\n' not in value and '\r' not in value
|
||||
print(f'{key}={shlex.quote(value)}')
|
||||
PY
|
||||
)"
|
||||
eval "$pins"
|
||||
|
||||
fetch() {
|
||||
local url="$1" digest="$2" destination="$3"
|
||||
if [[ -f "$destination" ]]; then
|
||||
printf '%s %s\n' "$digest" "$destination" | sha256sum --check --status || fail "cached download checksum mismatch: $destination"
|
||||
return
|
||||
fi
|
||||
curl --fail --location --show-error --silent --retry 3 --proto '=https' --tlsv1.2 "$url" -o "$destination.part"
|
||||
printf '%s %s\n' "$digest" "$destination.part" | sha256sum --check --status || fail "download checksum mismatch: $url"
|
||||
mv "$destination.part" "$destination"
|
||||
}
|
||||
|
||||
export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 LLVM_HOME=/usr/lib/llvm-18 LIBCLANG_PATH=/usr/lib/llvm-18/lib
|
||||
export PATH="$CARGO_HOME/bin:$JAVA_HOME/bin:$LLVM_HOME/bin:$PATH"
|
||||
fetch "$rustup_url" "$rustup_sha" "$tools/downloads/rustup-init"
|
||||
chmod +x "$tools/downloads/rustup-init"
|
||||
if [[ ! -x "$CARGO_HOME/bin/rustup" ]]; then
|
||||
"$tools/downloads/rustup-init" -y --no-modify-path --profile minimal --default-toolchain none
|
||||
fi
|
||||
rustup toolchain install "$rust_version" --profile minimal --no-self-update
|
||||
rustup target add --toolchain "$rust_version" "$rust_target"
|
||||
export RUSTUP_TOOLCHAIN="$rust_version"
|
||||
|
||||
export ANDROID_HOME="$tools/android-sdk" ANDROID_SDK_ROOT="$tools/android-sdk"
|
||||
fetch "$sdk_tools_url" "$sdk_tools_sha" "$tools/downloads/commandlinetools-linux-$sdk_tools_version.zip"
|
||||
if [[ ! -x "$ANDROID_SDK_ROOT/cmdline-tools/$sdk_tools_version/bin/sdkmanager" ]]; then
|
||||
stage="$(mktemp -d "$tools/tmp/sdk-tools.XXXXXXXX")"
|
||||
unzip -q "$tools/downloads/commandlinetools-linux-$sdk_tools_version.zip" -d "$stage"
|
||||
mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools"
|
||||
mv "$stage/cmdline-tools" "$ANDROID_SDK_ROOT/cmdline-tools/$sdk_tools_version"
|
||||
rmdir "$stage"
|
||||
fi
|
||||
sdkmanager="$ANDROID_SDK_ROOT/cmdline-tools/$sdk_tools_version/bin/sdkmanager"
|
||||
# The owner explicitly authorized SDK license acceptance in this isolated CI container.
|
||||
# Ignore only yes(1)'s expected SIGPIPE; sdkmanager's own failure remains fatal.
|
||||
set +e
|
||||
yes | "$sdkmanager" --sdk_root="$ANDROID_SDK_ROOT" --licenses
|
||||
license_status=("${PIPESTATUS[@]}")
|
||||
set -e
|
||||
[[ "${license_status[1]}" == 0 ]] || fail 'sdkmanager license acceptance failed'
|
||||
"$sdkmanager" --sdk_root="$ANDROID_SDK_ROOT" --install "platforms;$sdk_platform" "build-tools;$build_tools" "ndk;$ndk_version" platform-tools
|
||||
export ANDROID_NDK_ROOT="$ANDROID_SDK_ROOT/ndk/$ndk_version"
|
||||
export ANDROID_NDK_HOME="$ANDROID_NDK_ROOT" ANDROID_NDK="$ANDROID_NDK_ROOT"
|
||||
export ANDROID_JAR="$ANDROID_SDK_ROOT/platforms/$sdk_platform/android.jar"
|
||||
export ANDROID_PLATFORM=android-26 ANDROID_API_LEVEL=26
|
||||
export PATH="$ANDROID_SDK_ROOT/cmdline-tools/$sdk_tools_version/bin:$ANDROID_SDK_ROOT/build-tools/$build_tools:$ANDROID_SDK_ROOT/platform-tools:$PATH"
|
||||
|
||||
export TEAMSPEACH_GRADLE_DISTRIBUTION="$tools/downloads/gradle-8.14.3-bin.zip"
|
||||
fetch "$gradle_url" "$gradle_sha" "$TEAMSPEACH_GRADLE_DISTRIBUTION"
|
||||
export TEAMSPEACH_BUNDLETOOL="$tools/downloads/bundletool-all-$bundletool_version.jar"
|
||||
fetch "$bundletool_url" "$bundletool_sha" "$TEAMSPEACH_BUNDLETOOL"
|
||||
|
||||
export SKIA_SOURCE_DIR="$tools/skia-$skia_revision"
|
||||
fetch "$skia_url" "$skia_sha" "$tools/downloads/skia-$skia_revision.tar.gz"
|
||||
if [[ ! -f "$SKIA_SOURCE_DIR/.android-ci-archive-sha256" ]]; then
|
||||
[[ ! -e "$SKIA_SOURCE_DIR" ]] || fail 'incomplete Skia cache; remove only that CI cache entry before retrying'
|
||||
stage="$(mktemp -d "$tools/tmp/skia.XXXXXXXX")"
|
||||
tar -xzf "$tools/downloads/skia-$skia_revision.tar.gz" --strip-components=1 -C "$stage"
|
||||
printf '%s\n' "$skia_sha" > "$stage/.android-ci-archive-sha256"
|
||||
mv "$stage" "$SKIA_SOURCE_DIR"
|
||||
fi
|
||||
[[ "$(cat "$SKIA_SOURCE_DIR/.android-ci-archive-sha256")" == "$skia_sha" ]] || fail 'Skia cache pin mismatch'
|
||||
# Android does not use emscripten. This skips only that unrelated toolchain, not native deps or GN.
|
||||
# Some mirrors fail a connection while other pinned checkouts succeed. Retry the same
|
||||
# immutable inputs only; revision verification below is still mandatory.
|
||||
for attempt in 1 2 3; do
|
||||
if GIT_SYNC_DEPS_SKIP_EMSDK=1 python3 "$SKIA_SOURCE_DIR/tools/git-sync-deps"; then break; fi
|
||||
(( attempt < 3 )) || fail 'Skia source hosts remain unreachable after three attempts; check runner HTTPS egress to skia.googlesource.com/chromium.googlesource.com'
|
||||
sleep "$((attempt * 10))"
|
||||
done
|
||||
python3 - "$SKIA_SOURCE_DIR" "$skia_gn_revision" <<'PY'
|
||||
import pathlib, runpy, subprocess, sys
|
||||
root = pathlib.Path(sys.argv[1])
|
||||
assert (root / 'BUILD.gn').is_file()
|
||||
assert sys.argv[2] in (root / 'bin/fetch-gn').read_text(), 'GN revision changed'
|
||||
deps = runpy.run_path(str(root / 'tools/git-sync-deps'))['parse_file_to_dict'](str(root / 'DEPS'))['deps']
|
||||
for relative, spec in deps.items():
|
||||
if not isinstance(spec, str):
|
||||
continue
|
||||
expected = spec.rsplit('@', 1)[1]
|
||||
actual = subprocess.check_output(['git', '-C', str(root / relative), 'rev-parse', 'HEAD'], text=True).strip()
|
||||
assert actual == expected, f'Skia dependency mismatch: {relative}'
|
||||
PY
|
||||
export SKIA_GN_COMMAND="$SKIA_SOURCE_DIR/bin/gn" SKIA_NINJA_COMMAND="$(command -v ninja)" SKIA_FORCE_BUILD=1
|
||||
[[ -x "$SKIA_GN_COMMAND" && -f "$ANDROID_JAR" && -x "$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/clang" ]] || fail 'provisioned Android/Skia files are missing'
|
||||
|
||||
# Workflow steps are new shells. Publish the complete isolated tools/cache contract.
|
||||
for name in HOME TMPDIR XDG_CACHE_HOME XDG_CONFIG_HOME XDG_DATA_HOME CARGO_HOME RUSTUP_HOME RUSTUP_TOOLCHAIN \
|
||||
GRADLE_USER_HOME ANDROID_USER_HOME ANDROID_EMULATOR_HOME ANDROID_SDK_HOME JAVA_TOOL_OPTIONS \
|
||||
GIT_CONFIG_NOSYSTEM GIT_CONFIG_GLOBAL GIT_TERMINAL_PROMPT PIP_CACHE_DIR CIPD_CACHE_DIR VPYTHON_VIRTUALENV_ROOT \
|
||||
DEPOT_TOOLS_METRICS DEPOT_TOOLS_UPDATE JAVA_HOME LLVM_HOME LIBCLANG_PATH \
|
||||
ANDROID_HOME ANDROID_SDK_ROOT ANDROID_NDK_ROOT ANDROID_NDK_HOME ANDROID_NDK ANDROID_JAR ANDROID_PLATFORM ANDROID_API_LEVEL \
|
||||
TEAMSPEACH_GRADLE_DISTRIBUTION TEAMSPEACH_BUNDLETOOL SKIA_SOURCE_DIR SKIA_GN_COMMAND SKIA_NINJA_COMMAND SKIA_FORCE_BUILD; do
|
||||
[[ "${!name}" != *$'\n'* && "${!name}" != *$'\r'* ]] || fail "invalid multiline environment value: $name"
|
||||
printf '%s=%s\n' "$name" "${!name}" >> "$GITHUB_ENV"
|
||||
done
|
||||
printf '%s\n' "$CARGO_HOME/bin" "$JAVA_HOME/bin" "$LLVM_HOME/bin" \
|
||||
"$ANDROID_SDK_ROOT/cmdline-tools/$sdk_tools_version/bin" "$ANDROID_SDK_ROOT/build-tools/$build_tools" "$ANDROID_SDK_ROOT/platform-tools" >> "$GITHUB_PATH"
|
||||
printf 'Android CI tools provisioned in %s (no build, signing or publication performed by setup).\n' "$tools"
|
||||
+167
-345
@@ -1,345 +1,167 @@
|
||||
# Trusted mobile-branch pushes only; never execute fork pull requests on the shared runner.
|
||||
# Installs occur only inside the disposable Ubuntu container. No releases or phone actions.
|
||||
name: android-ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [feature/mobile-port]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: Build the test APK, or inspect resources only
|
||||
required: true
|
||||
default: build
|
||||
type: choice
|
||||
options: [build, inventory]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
jobs:
|
||||
android-arm64:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ubuntu:24.04
|
||||
timeout-minutes: 360
|
||||
env:
|
||||
TARGET: aarch64-linux-android
|
||||
EXPECTED_REVISION: ${{ github.sha }}
|
||||
CI_RUN_ID: ${{ github.run_id }}
|
||||
ANDROID_CI_PROVISION: container
|
||||
CARGO_TERM_COLOR: never
|
||||
TEAMSPEACH_ANDROID_LOW_MEMORY: "false"
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/.android-ci/cargo-target
|
||||
steps:
|
||||
- name: Resource gate before checkout, cache restore or tool installation
|
||||
id: resources
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(uname -s)" = Linux
|
||||
test "$(uname -m)" = x86_64
|
||||
test -f /.dockerenv
|
||||
printf 'Architecture: '; uname -m
|
||||
printf 'CPU count: '; getconf _NPROCESSORS_ONLN
|
||||
df -Pk . /
|
||||
while IFS=: read -r key value; do
|
||||
case "$key" in MemTotal|MemAvailable) printf '%s:%s\n' "$key" "$value" ;; esac
|
||||
done < /proc/meminfo
|
||||
if [ '${{ github.event.inputs.mode }}' = inventory ]; then exit 0; fi
|
||||
for path in . /; do
|
||||
free=$(df --output=avail -B1 "$path")
|
||||
free=${free##*$'\n'}
|
||||
if ! [[ "$free" =~ ^[[:space:]]*[0-9]+[[:space:]]*$ ]] || (( free < 107374182400 )); then
|
||||
echo "BLOCKED: Android cold source build requires 100 GiB free on workspace and container root; no tools installed. Ask runner administrator for build storage."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
available=0
|
||||
while read -r key value unit; do if [ "$key" = MemAvailable: ]; then available=$value; fi; done < /proc/meminfo
|
||||
if (( available < 8388608 )); then echo 'BLOCKED: at least 8 GiB available RAM required'; exit 1; fi
|
||||
jobs=$(nproc)
|
||||
[[ "$jobs" =~ ^[1-9][0-9]*$ ]] || { echo 'Cannot determine available runner CPUs'; exit 1; }
|
||||
printf 'Using all available runner CPUs: %s Cargo/Ninja/CMake jobs\n' "$jobs"
|
||||
printf 'CARGO_BUILD_JOBS=%s\nCMAKE_BUILD_PARALLEL_LEVEL=%s\n' "$jobs" "$jobs" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Bootstrap utilities inside the disposable job container
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f /.dockerenv
|
||||
test "$(id -u)" = 0
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends ca-certificates git nodejs python3 zstd
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
with:
|
||||
clean: true
|
||||
persist-credentials: false
|
||||
|
||||
# Keep provisioned tools/registry sources separate from completed Cargo outputs.
|
||||
- name: Restore isolated tool and Cargo source cache
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: cache
|
||||
uses: actions/cache/restore@v3
|
||||
with:
|
||||
path: |
|
||||
.android-ci/tools/downloads
|
||||
.android-ci/tools/rustup
|
||||
.android-ci/tools/cargo
|
||||
.android-ci/tools/android-sdk
|
||||
.android-ci/tools/skia-m153-0.101.2
|
||||
.android-ci/tools/gradle
|
||||
# Lock changes may need new registry sources, not a new SDK/toolchain.
|
||||
# v3 starts one cold generation: v2 has no independently verifiable tool contract.
|
||||
key: android-tools-linux-x64-arm64-v3-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-${{ hashFiles('Cargo.lock') }}-${{ github.sha }}-${{ github.run_id }}
|
||||
restore-keys: |
|
||||
android-tools-linux-x64-arm64-v3-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-${{ hashFiles('Cargo.lock') }}-
|
||||
android-tools-linux-x64-arm64-v3-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-
|
||||
- name: Provision pinned Android tools in the job container
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: tools
|
||||
run: bash .gitea/setup-android-ci.sh
|
||||
|
||||
|
||||
# Setup publishes the pinned environment before compatibility is computed.
|
||||
# Never cross the opaque v1 application identity: one cold v2 generation.
|
||||
- name: Compute isolated application cache identity
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: application-key
|
||||
run: python3 .gitea/android-application-cache.py key
|
||||
|
||||
- name: Restore completed application compilation
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: application-cache
|
||||
uses: actions/cache/restore@v3
|
||||
with:
|
||||
path: |
|
||||
.android-ci/cargo-target
|
||||
.android-ci/application-cache-inputs.json
|
||||
key: ${{ steps.application-key.outputs.key }}-${{ github.sha }}-${{ github.run_id }}
|
||||
restore-keys: |
|
||||
${{ steps.application-key.outputs.key }}-${{ github.sha }}-
|
||||
${{ steps.application-key.outputs.key }}-
|
||||
${{ steps.application-key.outputs.previous-parallelism-key }}-
|
||||
|
||||
- name: Restore timestamps only for content-matched Cargo source inputs
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
run: python3 .gitea/android-application-cache.py sources
|
||||
|
||||
- name: Require exact revision and no production signing
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(git rev-parse HEAD)" = "$EXPECTED_REVISION"
|
||||
test ! -e dist/android
|
||||
for name in TEAMSPEACH_ANDROID_KEYSTORE TEAMSPEACH_ANDROID_STORE_PASSWORD TEAMSPEACH_ANDROID_KEY_ALIAS TEAMSPEACH_ANDROID_KEY_PASSWORD; do
|
||||
if [[ -v "$name" ]]; then echo 'Production signing environment forbidden in test CI'; exit 1; fi
|
||||
done
|
||||
cargo run --locked -p xtask -- check-version
|
||||
cargo test --locked -p xtask
|
||||
|
||||
- name: Compute source dependency cache identity
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: dependency-key
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import hashlib, json, os, pathlib
|
||||
policy = json.loads(pathlib.Path('native/native-deps.lock.json').read_text())
|
||||
policy.pop('builds', None)
|
||||
digest = hashlib.sha256(json.dumps(policy, sort_keys=True, separators=(',', ':')).encode())
|
||||
for name in ('.gitea/android-ci-tools.json', 'xtask/src/deps.rs', 'xtask/src/build_native.rs'):
|
||||
digest.update(name.encode() + b'\0' + pathlib.Path(name).read_bytes())
|
||||
with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
|
||||
out.write('key=android-webrtc-linux-arm64-v1-' + digest.hexdigest() + '\n')
|
||||
PY
|
||||
|
||||
- name: Restore pinned WebRTC source and object checkpoint
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: webrtc-cache
|
||||
uses: actions/cache/restore@v3
|
||||
with:
|
||||
path: target/native-deps/aarch64-linux-android
|
||||
key: ${{ steps.dependency-key.outputs.key }}
|
||||
|
||||
# Source provenance is regenerated and verified, never trusted from an Actions cache.
|
||||
- name: Build pinned WebRTC dependencies with bounded CI parallelism
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: dependencies
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 .gitea/prepare-android-dependency-cache.py
|
||||
cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME" --jobs "$CARGO_BUILD_JOBS"
|
||||
python3 .gitea/android-application-cache.py dependencies
|
||||
|
||||
- name: Checkpoint verified WebRTC before application build
|
||||
if: ${{ success() && github.event.inputs.mode != 'inventory' && steps.webrtc-cache.outputs.cache-hit != 'true' }}
|
||||
uses: actions/cache/save@v3
|
||||
with:
|
||||
path: target/native-deps/aarch64-linux-android
|
||||
key: ${{ steps.dependency-key.outputs.key }}
|
||||
|
||||
- name: Checkpoint provisioned tools before application build
|
||||
if: ${{ success() && github.event.inputs.mode != 'inventory' && steps.cache.outputs.cache-hit != 'true' }}
|
||||
uses: actions/cache/save@v3
|
||||
with:
|
||||
path: |
|
||||
.android-ci/tools/downloads
|
||||
.android-ci/tools/rustup
|
||||
.android-ci/tools/cargo
|
||||
.android-ci/tools/android-sdk
|
||||
.android-ci/tools/skia-m153-0.101.2
|
||||
.android-ci/tools/gradle
|
||||
key: ${{ steps.cache.outputs.cache-primary-key }}-checkpoint
|
||||
|
||||
# Host tests use neither Android artifacts nor Skia/WebRTC. The APK below keeps all features.
|
||||
- name: Install Linux host audio test prerequisites in container
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f /.dockerenv
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends libpipewire-0.3-dev libspa-0.2-dev libxkbcommon-x11-dev libxcb-shape0-dev libxcb-xfixes0-dev
|
||||
|
||||
- name: Restore isolated Linux audio test compilation
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: audio-test-cache
|
||||
uses: actions/cache/restore@v3
|
||||
with:
|
||||
path: .android-ci/host-audio-target
|
||||
key: host-audio-linux-x64-v1-${{ hashFiles('rust-toolchain.toml', 'Cargo.lock', '.cargo/config.toml', '.gitea/workflows/android.yml') }}-${{ github.sha }}-${{ github.run_id }}
|
||||
restore-keys: |
|
||||
host-audio-linux-x64-v1-${{ hashFiles('rust-toolchain.toml', 'Cargo.lock', '.cargo/config.toml', '.gitea/workflows/android.yml') }}-
|
||||
|
||||
- name: Run actual native audio worker and capture authorization regressions
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: audio-tests
|
||||
env:
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/.android-ci/host-audio-target
|
||||
CARGO_PROFILE_TEST_OPT_LEVEL: "1"
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
unset RUSTC_WORKSPACE_WRAPPER
|
||||
mkdir -p .android-ci/audio-test-results
|
||||
{
|
||||
printf 'Revision: %s\nHost: x86_64-unknown-linux-gnu\nFeatures: no-default-features (test binary only)\n' "$EXPECTED_REVISION"
|
||||
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/device_catalog.rs -o .android-ci/audio-test-results/device-catalog-tests
|
||||
.android-ci/audio-test-results/device-catalog-tests --test-threads=1
|
||||
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/capture_timing.rs -o .android-ci/audio-test-results/capture-timing-tests
|
||||
.android-ci/audio-test-results/capture-timing-tests --test-threads=1
|
||||
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/output_usage.rs -o .android-ci/audio-test-results/output-usage-tests
|
||||
.android-ci/audio-test-results/output-usage-tests --test-threads=1
|
||||
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/stream_start.rs -o .android-ci/audio-test-results/stream-start-tests
|
||||
.android-ci/audio-test-results/stream-start-tests --test-threads=1
|
||||
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/output_clock.rs -o .android-ci/audio-test-results/output-clock-tests
|
||||
.android-ci/audio-test-results/output-clock-tests --test-threads=1
|
||||
mkdir -p .android-ci/audio-test-results/java
|
||||
javac -d .android-ci/audio-test-results/java platform/android/src/main/java/dev/teamspeach/mobile/CommunicationRoutePolicy.java platform/android/src/test/java/dev/teamspeach/mobile/CommunicationRoutePolicyTest.java
|
||||
java -cp .android-ci/audio-test-results/java dev.teamspeach.mobile.CommunicationRoutePolicyTest
|
||||
cargo test --locked -p teamspeach-denoise --target x86_64-unknown-linux-gnu --lib capture::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib media::audio:: --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib capture_transition_tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib audit_lifecycle --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib android_call_authorization --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib only_explicit_output_device_actions_request_platform_routing --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib android_attachment_ --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib app::connections::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib ui::theme::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib services::prefs::tests::android_palette --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib ui::shell::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib ui::i18n::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib ui::settings::tests::communication_routes --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-core --target x86_64-unknown-linux-gnu --lib audio::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
cargo test --locked -p teamspeach-core --target x86_64-unknown-linux-gnu --lib output::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||
} 2>&1 | tee .android-ci/audio-test-results/tests.log
|
||||
|
||||
- name: Save successful Linux audio test compilation
|
||||
if: ${{ success() && steps.audio-tests.outcome == 'success' && steps.audio-test-cache.outputs.cache-hit != 'true' }}
|
||||
uses: actions/cache/save@v3
|
||||
with:
|
||||
path: .android-ci/host-audio-target
|
||||
key: ${{ steps.audio-test-cache.outputs.cache-primary-key }}
|
||||
|
||||
- name: Retain actual host audio test results
|
||||
if: ${{ always() && steps.audio-tests.outcome != 'skipped' && github.event.inputs.mode != 'inventory' }}
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: native-audio-tests-linux-x64-${{ github.sha }}
|
||||
path: .android-ci/audio-test-results/tests.log
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
- name: Build and verify full-feature test APK
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: application-build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
unset RUSTC_WORKSPACE_WRAPPER
|
||||
mkdir -p .android-ci/diagnostics
|
||||
bash .gitea/android-memory-report.sh | tee .android-ci/diagnostics/before.txt
|
||||
trap 'status=$?; trap - EXIT; bash .gitea/android-memory-report.sh | tee .android-ci/diagnostics/after.txt; exit "$status"' EXIT
|
||||
/usr/bin/time -v -o .android-ci/diagnostics/build-time.txt bash .gitea/build-android-variant.sh harness
|
||||
|
||||
# Save immediately after compilation/package verification, not after uploads.
|
||||
# always()+outcome also checkpoints a successful APK if later diagnostics fail.
|
||||
- name: Record stable inputs of the completed application build
|
||||
if: ${{ always() && steps.application-build.outcome == 'success' && github.event.inputs.mode != 'inventory' }}
|
||||
id: application-snapshot
|
||||
run: python3 .gitea/android-application-cache.py snapshot
|
||||
|
||||
- name: Save completed application compilation
|
||||
if: ${{ always() && steps.application-snapshot.outcome == 'success' && steps.application-cache.outputs.cache-hit != 'true' && github.event.inputs.mode != 'inventory' }}
|
||||
uses: actions/cache/save@v3
|
||||
with:
|
||||
path: |
|
||||
.android-ci/cargo-target
|
||||
.android-ci/application-cache-inputs.json
|
||||
key: ${{ steps.application-cache.outputs.cache-primary-key }}
|
||||
|
||||
- name: Report container memory evidence on build failure
|
||||
if: ${{ always() && steps.tools.outcome == 'success' && github.event.inputs.mode != 'inventory' }}
|
||||
run: |
|
||||
set -eu
|
||||
if [ -f .android-ci/diagnostics/build-time.txt ]; then cat .android-ci/diagnostics/build-time.txt; fi
|
||||
bash .gitea/android-memory-report.sh
|
||||
|
||||
- name: Retain native compiler resource diagnostics
|
||||
if: ${{ always() && steps.tools.outcome == 'success' && github.event.inputs.mode != 'inventory' }}
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: android-build-resources-${{ github.sha }}
|
||||
path: .android-ci/diagnostics/*.txt
|
||||
if-no-files-found: warn
|
||||
retention-days: 7
|
||||
|
||||
- name: Upload installable Android test APK and provenance
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: android-harness-arm64-${{ github.sha }}
|
||||
path: |
|
||||
dist/android/harness/*-harness-test.apk
|
||||
dist/android/harness/build-info.json
|
||||
dist/android/harness/aarch64-linux-android/*.json
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
- name: Save populated tool and Cargo source cache
|
||||
if: ${{ always() && steps.application-build.outcome == 'success' && github.event.inputs.mode != 'inventory' && steps.cache.outputs.cache-hit != 'true' }}
|
||||
uses: actions/cache/save@v3
|
||||
with:
|
||||
path: |
|
||||
.android-ci/tools/downloads
|
||||
.android-ci/tools/rustup
|
||||
.android-ci/tools/cargo
|
||||
.android-ci/tools/android-sdk
|
||||
.android-ci/tools/skia-m153-0.101.2
|
||||
.android-ci/tools/gradle
|
||||
key: ${{ steps.cache.outputs.cache-primary-key }}
|
||||
# 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.
|
||||
name: android-ci
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
working-directory: ${{ github.workspace }}/android-${{ github.run_id }}
|
||||
|
||||
jobs:
|
||||
android-arm64:
|
||||
runs-on: teamspeach-android-linux-x64
|
||||
env:
|
||||
CARGO_TERM_COLOR: never
|
||||
TARGET: aarch64-linux-android
|
||||
EXPECTED_REVISION: ${{ github.sha }}
|
||||
CI_RUN_ID: ${{ github.run_id }}
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/android-${{ github.run_id }}/target
|
||||
GRADLE_USER_HOME: ${{ github.workspace }}/android-${{ github.run_id }}/.gradle-ci
|
||||
ANDROID_HOME: ${{ vars.ANDROID_SDK_ROOT }}
|
||||
ANDROID_SDK_ROOT: ${{ vars.ANDROID_SDK_ROOT }}
|
||||
JAVA_HOME: ${{ vars.ANDROID_JAVA_HOME }}
|
||||
LLVM_HOME: ${{ vars.NATIVE_LLVM_HOME }}
|
||||
LIBCLANG_PATH: ${{ vars.NATIVE_LIBCLANG_PATH }}
|
||||
SKIA_SOURCE_DIR: ${{ vars.NATIVE_SKIA_SOURCE_DIR }}
|
||||
TEAMSPEACH_GRADLE_DISTRIBUTION: ${{ vars.ANDROID_GRADLE_DISTRIBUTION }}
|
||||
TEAMSPEACH_BUNDLETOOL: ${{ vars.ANDROID_BUNDLETOOL }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
path: android-${{ github.run_id }}
|
||||
clean: true
|
||||
persist-credentials: false
|
||||
|
||||
- name: Require provisioned Linux Android tools (no host installation)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(uname -s)" = Linux
|
||||
test "$(uname -m)" = x86_64
|
||||
test "$(git rev-parse HEAD)" = "$EXPECTED_REVISION"
|
||||
: "${ANDROID_SDK_ROOT:?set ANDROID_SDK_ROOT to installed SDK36 with build-tools/36.0.0 and NDK28.2.13676358}"
|
||||
: "${JAVA_HOME:?set ANDROID_JAVA_HOME to installed JDK17+ (JDK21 is supported)}"
|
||||
: "${LLVM_HOME:?set NATIVE_LLVM_HOME to installed LLVM}"
|
||||
: "${LIBCLANG_PATH:?set NATIVE_LIBCLANG_PATH to the matching libclang directory}"
|
||||
: "${SKIA_SOURCE_DIR:?set NATIVE_SKIA_SOURCE_DIR to a dependency-synchronized Skia checkout}"
|
||||
: "${TEAMSPEACH_GRADLE_DISTRIBUTION:?set ANDROID_GRADLE_DISTRIBUTION to local gradle-8.14.3-bin.zip}"
|
||||
: "${TEAMSPEACH_BUNDLETOOL:?set ANDROID_BUNDLETOOL to local bundletool.jar}"
|
||||
export ANDROID_NDK_ROOT="$ANDROID_SDK_ROOT/ndk/28.2.13676358"
|
||||
export ANDROID_NDK_HOME="$ANDROID_NDK_ROOT"
|
||||
export PATH="$JAVA_HOME/bin:$LLVM_HOME/bin:$ANDROID_SDK_ROOT/build-tools/36.0.0:$PATH"
|
||||
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; do
|
||||
command -v "$tool"
|
||||
done
|
||||
test -f "$ANDROID_SDK_ROOT/platforms/android-36/android.jar"
|
||||
test -f "$ANDROID_NDK_ROOT/source.properties"
|
||||
test -x "$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android26-clang"
|
||||
test -f "$SKIA_SOURCE_DIR/BUILD.gn"
|
||||
test -x "$SKIA_SOURCE_DIR/bin/gn"
|
||||
test -d "$SKIA_SOURCE_DIR/third_party/externals"
|
||||
test -f "$TEAMSPEACH_BUNDLETOOL"
|
||||
test -d "$(rustc --print target-libdir --target "$TARGET")"
|
||||
# A clean checkout and run-specific Cargo/Gradle/output trees prevent stale
|
||||
# packages or dependency receipts from another job/revision being selected.
|
||||
test ! -e target
|
||||
test ! -e dist/android
|
||||
test ! -e .gradle-ci
|
||||
python3 - <<'PY'
|
||||
import hashlib, os, pathlib, re, subprocess
|
||||
ndk = pathlib.Path(os.environ['ANDROID_NDK_ROOT'], 'source.properties').read_text()
|
||||
assert re.search(r'^Pkg\.Revision\s*=\s*28\.2\.13676358\s*$', ndk, re.M), 'NDK must match Gradle ndkVersion'
|
||||
java = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT, text=True)
|
||||
assert int(re.search(r'version "(\d+)', java)[1]) >= 17, 'JDK17+ is required'
|
||||
assert list(pathlib.Path(os.environ['LIBCLANG_PATH']).glob('libclang.so*')), 'matching LLVM libclang.so is required'
|
||||
properties = pathlib.Path('platform/android/gradle/wrapper/gradle-wrapper.properties').read_text()
|
||||
expected = re.search(r'^distributionSha256Sum=(\w+)$', properties, re.M)[1]
|
||||
with open(os.environ['TEAMSPEACH_GRADLE_DISTRIBUTION'], 'rb') as source:
|
||||
digest = hashlib.sha256()
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b''):
|
||||
digest.update(chunk)
|
||||
assert digest.hexdigest() == expected, 'local Gradle zip checksum mismatch'
|
||||
# No signing configuration is consumed from a dedicated runner's environment.
|
||||
for name in ('TEAMSPEACH_ANDROID_KEYSTORE', 'TEAMSPEACH_ANDROID_STORE_PASSWORD', 'TEAMSPEACH_ANDROID_KEY_ALIAS', 'TEAMSPEACH_ANDROID_KEY_PASSWORD'):
|
||||
assert name not in os.environ, 'remove production signing environment from this unsigned runner'
|
||||
PY
|
||||
echo "ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_NDK_HOME=$ANDROID_NDK_HOME" >> "$GITHUB_ENV"
|
||||
echo "$JAVA_HOME/bin" >> "$GITHUB_PATH"
|
||||
echo "$LLVM_HOME/bin" >> "$GITHUB_PATH"
|
||||
echo "$ANDROID_SDK_ROOT/build-tools/36.0.0" >> "$GITHUB_PATH"
|
||||
echo "SKIA_GN_COMMAND=$SKIA_SOURCE_DIR/bin/gn" >> "$GITHUB_ENV"
|
||||
echo "SKIA_NINJA_COMMAND=$(command -v ninja)" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Check workspace version and packaging behavior
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cargo run --locked -p xtask -- check-version
|
||||
cargo test --locked -p xtask
|
||||
|
||||
- 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: Retain installable test-only ARM64 harness and exact receipts
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: android-harness-arm64
|
||||
path: |
|
||||
android-${{ github.run_id }}/dist/android/harness/*-harness-test.apk
|
||||
android-${{ github.run_id }}/dist/android/harness/build-info.json
|
||||
android-${{ github.run_id }}/dist/android/harness/aarch64-linux-android/*.json
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Retain unsigned production ARM64 APK and store AAB (not installable)
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: android-production-unsigned-arm64
|
||||
path: |
|
||||
android-${{ github.run_id }}/dist/android/production/*-unsigned.apk
|
||||
android-${{ github.run_id }}/dist/android/production/*-unsigned.aab
|
||||
android-${{ github.run_id }}/dist/android/production/build-info.json
|
||||
android-${{ github.run_id }}/dist/android/production/aarch64-linux-android/*.json
|
||||
if-no-files-found: error
|
||||
@@ -8,7 +8,6 @@ dist/
|
||||
# Native Cargo artifacts
|
||||
target/
|
||||
core/target/
|
||||
.android-ci/
|
||||
|
||||
# local runtime data, logs and identities
|
||||
*.log
|
||||
|
||||
@@ -16,13 +16,5 @@
|
||||
"xtask/src/package.rs"
|
||||
],
|
||||
"fingerprintBaselineCommit": "a761afaa43dddbdf78c70afb2546c79c3b1289e5",
|
||||
"partialArchitectureUpdates": [{
|
||||
"baseRevision": "6e5c831940dff96ca94b7ff76893558f162b20e3",
|
||||
"workingTreeSnapshot": true,
|
||||
"scope": "native audio lifecycle and authorization",
|
||||
"files": ["native/src/media/audio/lifecycle.rs", "native/src/media/audio/engine.rs", "native/src/media/audio/devices.rs", "native/src/app/connections.rs", "native/src/app/runtime/context_helpers.rs"],
|
||||
"navigation": "engine.rs::Worker::lifecycle services live PCM while lifecycle.rs owns CPAL construct/start/drop, DSP construction and notification preparation. devices.rs StreamOwner never leaves lifecycle thread. ConnectionManager publishes acknowledged capture_revision/configuration and current_capture_permit validates live core epoch. Runtime reconciles same-owner permit changes without blind retries.",
|
||||
"graphWarning": "knowledge-graph.json remains the old full scan: engine single-worker ownership summaries and function line ranges are stale. This targeted navigation override does not mark the whole graph current; auto-update remains disabled."
|
||||
}],
|
||||
"note": "Граф актуализирован по незакоммиченному рабочему дереву. Штатный incremental save отказал из-за dirty tree; fingerprints/scan baseline оставлены прежними для следующего воспроизводимого обновления после коммита."
|
||||
}
|
||||
+722
-520
File diff suppressed because it is too large.
Load diff
Generated
+1019
-665
File diff suppressed because it is too large.
Load diff
+13
-12
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["core", "dsp", "native", "xtask"]
|
||||
exclude = ["core/vendor/tsclientlib", "core/vendor/tsproto", "dsp/vendor/sonora", "dsp/vendor/sonora-agc2", "native/vendor/libwebrtc-0.4.0", "native/vendor/webrtc-sys-0.3.53", "native/vendor/katex-rs-0.3.0", "native/vendor/mermaid-rs-renderer-0.3.1", "native/vendor/cpal-0.18.2", "native/vendor/i-slint-backend-android-activity-1.18.1", "native/vendor/ndk-0.9.0"]
|
||||
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"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.7"
|
||||
@@ -10,18 +10,19 @@ 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.18.1", default-features = false, features = ["std", "compat-1-18", "accessibility", "image-default-formats", "unstable-fontique-011"] }
|
||||
slint-build = "=1.18.1"
|
||||
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"
|
||||
cpal = "=0.18.2"
|
||||
rubato = { version = "=5.0.1", default-features = false }
|
||||
sonora = "=0.2.0"
|
||||
sonora-ns = "=0.2.0"
|
||||
libwebrtc = "=0.4.0"
|
||||
webrtc-sys = "=0.3.53"
|
||||
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"
|
||||
katex-native = "=0.1.1"
|
||||
katex-rs = "=0.3.0"
|
||||
mermaid-rs-renderer = { version = "=0.3.1", default-features = false }
|
||||
@@ -29,17 +30,17 @@ 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.0" }
|
||||
webrtc-sys = { path = "native/vendor/webrtc-sys-0.3.53" }
|
||||
libwebrtc = { path = "native/vendor/libwebrtc-0.4.2" }
|
||||
webrtc-sys = { path = "native/vendor/webrtc-sys-0.3.55" }
|
||||
katex-rs = { path = "native/vendor/katex-rs-0.3.0" }
|
||||
mermaid-rs-renderer = { path = "native/vendor/mermaid-rs-renderer-0.3.1" }
|
||||
cpal = { path = "native/vendor/cpal-0.18.2" }
|
||||
i-slint-backend-android-activity = { path = "native/vendor/i-slint-backend-android-activity-1.18.1" }
|
||||
ndk = { path = "native/vendor/ndk-0.9.0" }
|
||||
i-slint-backend-android-activity = { path = "native/vendor/i-slint-backend-android-activity-1.19.1" }
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: TeamsPeach
|
||||
description: The installed TeamSpeak 6 client's own visual system, reproduced from its source values.
|
||||
description: Native TeamsPeach's account-free visual contract, derived from TeamSpeak 6 reference evidence.
|
||||
colors:
|
||||
tsv-bg-dark: "#2b3346"
|
||||
tsv-bg-light: "#f5f5f5"
|
||||
@@ -97,13 +97,16 @@ components:
|
||||
|
||||
## Overview
|
||||
|
||||
**Desktop North Star: "The official TeamSpeak 6 client, value for value."**
|
||||
**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 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
|
||||
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
|
||||
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.
|
||||
@@ -115,25 +118,6 @@ and historical non-brand pictograms, have provenance/redistribution limitations
|
||||
The official JavaScript application and removed browser implementation are historical references only,
|
||||
not product runtime dependencies. Native cutover does not establish visual or functional acceptance.
|
||||
|
||||
### Android: Room (approved 2026-11-15)
|
||||
|
||||
The owner selected the entire **Room** direction from the interactive Android comparison, not a blend
|
||||
of the alternatives. This is an Android-only exception to desktop source parity. The reference is the
|
||||
Room variant in `target/tmp/android-ui-concepts/` and its captures in `target/tmp/android-ui-review/`;
|
||||
these local design artifacts are not native-runtime acceptance evidence.
|
||||
|
||||
The current voice channel is the primary surface: centered channel/server context, a responsive grid
|
||||
of participants, speaking emphasis from actual state, and a persistent rounded voice-control strip.
|
||||
Channels, channel chat, and profile/settings have separate labelled navigation destinations. Secondary
|
||||
server, contact, file and moderation operations remain reachable rather than being removed for visual
|
||||
simplicity. Phone navigation changes to a rail/split arrangement at wider windows.
|
||||
|
||||
Start with the TS6 palette and bundled Noto Sans, but allow Android users to edit accent, background,
|
||||
surface and text colors through a preview/save/cancel/reset workflow. Accent fill and readable accent
|
||||
text are separate roles; user palettes must not make controls or status labels illegible. Insets,
|
||||
IME, font scale, Back, focus and hold-release behavior constrain the layout. The installed Windows
|
||||
baseline, its three-pane composition, and its preference behavior are unchanged.
|
||||
|
||||
## Colors
|
||||
|
||||
Dark is the default for new profiles; light follows the official light module. Native stock token data
|
||||
@@ -265,14 +249,18 @@ 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.
|
||||
- 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`.
|
||||
- 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).
|
||||
|
||||
## Do's and Don'ts
|
||||
|
||||
- **Do** take every new value from the installed client and cite its offset in the evidence specs.
|
||||
- **Do** cite the source build and offset or measured scene for new values. Keep 5163 extractions
|
||||
separate from 5232 capture evidence.
|
||||
- **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.
|
||||
|
||||
+397
-3
@@ -1,5 +1,397 @@
|
||||
# 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
|
||||
@@ -222,9 +614,11 @@ 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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
@@ -26,14 +26,3 @@
|
||||
`teamspeak-client-sounds-PROVENANCE.md`. They are not relicensed by TeamsPeach.
|
||||
- TeamSpeak is a trademark of TeamSpeak Systems GmbH. TeamsPeach is an independent client and is not
|
||||
affiliated with or endorsed by TeamSpeak Systems GmbH.
|
||||
- Android uses Rust Mobile `ndk` 0.9.0 (MIT OR Apache-2.0; the MIT alternative is reproduced in
|
||||
`native/vendor/ndk-0.9.0/LICENSE-MIT` from upstream revision
|
||||
`49bbbba16c58ff63cb8a0ad0eca5a9fb7ecaec25`). The vendored archive is
|
||||
`https://static.crates.io/crates/ndk/ndk-0.9.0.crate`, SHA-256
|
||||
`c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4`.
|
||||
Its only source patch exposes and documents the existing builder/stream `as_ptr` methods in
|
||||
`src/audio.rs`; no struct layout, dependency, feature or Android API-level requirement changes.
|
||||
The archive hash identifies the pristine upstream package, not the locally patched directory.
|
||||
Cargo uses the root `[patch.crates-io]` path, so its lockfile path entry must not retain the
|
||||
upstream registry `source`/`checksum`; no fabricated `.cargo-checksum.json` is added.
|
||||
CPAL remains the single audio backend and resolves optional API28 attribute functions at runtime.
|
||||
File diff suppressed because it is too large.
Load diff
+16
-10
@@ -7,22 +7,27 @@ 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.2.0, BSD-3-Clause):
|
||||
Pinned Sonora packages include (all 0.3.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: a024d6ef8351add55be5e8b1d6cc35f555787660 (per the published crates'
|
||||
Commit: 1632d47c1e77d0857f9145bd175134b348541e11 (per the published crates'
|
||||
.cargo_vcs_info.json)
|
||||
Registry: crates.io; package checksums (SHA-256 of the .crate files)
|
||||
sonora 0.2.0 2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250
|
||||
sonora-ns 0.2.0 d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f
|
||||
sonora-fft 0.2.0 27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012
|
||||
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 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 with local mono AGC2 and
|
||||
limiter channel-adapter allocation/copy reductions. Exact modified files,
|
||||
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,
|
||||
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
|
||||
@@ -30,9 +35,10 @@ 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. 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.
|
||||
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.
|
||||
|
||||
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 Rust 1.96.0, Python 3, LLVM/libclang, CMake, Ninja,
|
||||
`teamspeach-native-linux-arm64`. Provision the Rust version from `rust-toolchain.toml`, 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,172 +78,56 @@ 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, separate Linux build host)
|
||||
### Android development (Windows, Linux CI)
|
||||
|
||||
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. Gitea automatically builds the test APK on trusted mobile-branch pushes.
|
||||
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.
|
||||
|
||||
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,
|
||||
states “Android development is only supported on Linux.” This is a build-host requirement for CI,
|
||||
not a requirement to run Linux locally. A Windows WebRTC Android source build is not a supported
|
||||
alternative. Keep the full **Skia + WebRTC** feature set and pinned-source/receipt checks.
|
||||
alternative. CI keeps the full **Skia + WebRTC** feature set and pinned-source/receipt checks.
|
||||
|
||||
#### Automatic Gitea Android APK builds
|
||||
#### CI administrator prerequisites
|
||||
|
||||
[`android-ci`](.gitea/workflows/android.yml) runs on every push to **`feature/mobile-port`**.
|
||||
It does not run on main, release tags or pull requests, and never publishes releases or uses a phone.
|
||||
It selects the existing `ubuntu-latest` runner and an isolated official `ubuntu:24.04` job container.
|
||||
The owner authorized Android SDK license acceptance and tool installation **inside that container only**.
|
||||
No Android repository variables or preinstalled Android runner label are required.
|
||||
The manual [`android-ci`](.gitea/workflows/android.yml) workflow is separate from the Linux desktop
|
||||
workflows above. Before dispatch, an administrator must enable Gitea Actions and artifact support,
|
||||
register a dedicated **Linux x64** runner labelled `teamspeach-android-linux-x64`, and provision its
|
||||
toolchains and repository variables. Their presence is not established merely by committing the workflow.
|
||||
|
||||
Before checkout, cache restore or package installation, the job requires a conservative **100 GiB free
|
||||
disk** on workspace and container root, and **8 GiB available RAM**. Setup additionally accounts for
|
||||
visible ancestor cgroup limits. This is a provisioning floor, not a measured maximum or a memory cap;
|
||||
runner administrators must provide resource isolation/storage. The earlier runner had only about21GiB
|
||||
free, so a job can stop at this gate until an administrator expands build storage. No automatic disk
|
||||
expansion, host installation, privileged Docker socket or deletion of other jobs' files is performed.
|
||||
|
||||
`.gitea/setup-android-ci.sh` installs Ubuntu JDK21/LLVM18/libclang/CMake/Ninja prerequisites, then
|
||||
checksummed pinned downloads listed in `.gitea/android-ci-tools.json`: Rust1.96.0, SDK36,
|
||||
build-tools36.0.0, NDK28.2.13676358, Gradle8.14.3, synced Skia m153-0.101.2 and bundletool.
|
||||
The output environment also supplies full NDK, ANDROID_JAR and Skia inputs needed by the real first build.
|
||||
CI uses every CPU available to its container (`nproc`) for Cargo/Ninja/CMake, with a six-hour job deadline;
|
||||
the developer PC's one-job memory policy and Windows-only optimization overrides do not apply here. `xtask deps`
|
||||
regenerates dependency provenance; `build/package/verify-package` use the
|
||||
existing full Skia+WebRTC path. Production signing environment is rejected.
|
||||
Android CI uses normal workspace release optimization with runner-wide parallelism.
|
||||
Only if a new build demonstrates memory exhaustion may the separately authorized low-memory
|
||||
fallback be enabled: `TEAMSPEACH_ANDROID_LOW_MEMORY=true` selects codegen-units256/lto=off for only
|
||||
`teamspeach_native/aarch64-linux-android` through `.gitea/android-rustc-low-memory.sh`. All features stay
|
||||
enabled and `build-info.json` records the variant. Other targets and Windows settings remain unchanged.
|
||||
|
||||
Before APK compilation, CI runs actual native audio-worker, capture-transition and core-audio tests
|
||||
on Linux x64 with `--no-default-features`. These offline test binaries use a separate
|
||||
`.android-ci/host-audio-target` cache and test-only opt-level1/debug0 to exercise long SRC histories;
|
||||
they do not alter Android release settings. Container-only host prerequisites include PipeWire/SPA
|
||||
development libraries. A failed host test blocks packaging; logs are retained as
|
||||
`native-audio-tests-linux-x64-<SHA>`. Host tests do not establish physical-device or voice acceptance.
|
||||
|
||||
Tools/downloads/SDK/Skia/Gradle/Cargo caches live under ignored `.android-ci/`. Tools-v3 keys
|
||||
separate pinned tool/setup compatibility from Cargo.lock and source SHA: a changed lock first looks
|
||||
for matching registry sources, then falls back within the same tool contract. Provisioning still
|
||||
verifies the pinned tools and resolves any newly required sources. Tool/Cargo state is checkpointed
|
||||
after successful dependency provisioning, before compiling the app; the final successful job saves
|
||||
a newer checkpoint. Private signing keys and profiles are excluded.
|
||||
A separate application-v2 cache keeps the actual `.android-ci/cargo-target` and a content snapshot.
|
||||
Its compatibility identity is computed **after setup** from toolchain, target, optimization profiles,
|
||||
Cargo config and the stable build environment, not Cargo.lock, dependency declarations or source
|
||||
contents. Cargo fingerprints invalidate changed inputs. Only path/SHA-256/type/mode-matched inputs
|
||||
regain their recorded mtimes; changed inputs are never backdated and fail closed if their timestamp
|
||||
predates the cached compilation. Verified WebRTC inputs are considered only after the mandatory
|
||||
`xtask deps` run. Cargo build-start timestamps are recorded/reported, never rewritten. Every hit
|
||||
still runs revision checks, dependency provenance regeneration and full build/package verification.
|
||||
The old tools-v2/application-v1 opaque hashes cannot prove this independent compatibility contract,
|
||||
so this migration needs one cold cache generation; there is no unverified legacy fallback.
|
||||
A separate exact-key cache keeps `target/native-deps/aarch64-linux-android`, including pinned Git
|
||||
checkouts and Ninja objects. Its key excludes completed build receipts but includes source policy,
|
||||
tool pins and dependency drivers; there is no cross-policy fallback. Every cache hit still runs
|
||||
`xtask deps`: checkouts, patches, GN inputs and artifacts are checked and current provenance is
|
||||
regenerated before use. The repository lock is never overwritten by a cached copy.
|
||||
Before gclient sync, CI reverses only source diffs byte-identical to the restored provenance receipt;
|
||||
unexpected modifications fail closed. Pinned patches are then reapplied by xtask. No reset/clean of
|
||||
cached source or object outputs is used.
|
||||
These potentially large checkpoints require runner cache storage/capacity; cache misses remain valid
|
||||
cold builds. Before/after cgroup counters and `/usr/bin/time -v` data are retained as a separate
|
||||
`android-build-resources-<SHA>` artifact even when native compilation fails, to diagnose SIGKILL
|
||||
without assuming OOM. No host kernel logs, credentials or process argument dumps are collected.
|
||||
|
||||
The artifact is **`android-harness-arm64-<full commit SHA>`**, retained14days, containing the test APK
|
||||
and revision/hash/build/dependency/package receipts. Unsigned production APK/AAB remain available via
|
||||
the explicit local Linux helper, not built automatically on every push.
|
||||
|
||||
For a separately prepared Linux/WSL host, use these existing inputs instead of CI provisioning:
|
||||
|
||||
| Environment variable | Required existing input |
|
||||
| Repository variable | Required existing runner installation/input |
|
||||
| --- | --- |
|
||||
| `ANDROID_SDK_ROOT` | SDK API36, build-tools36.0.0, NDK28.2.13676358 |
|
||||
| `JAVA_HOME` | JDK21 |
|
||||
| `LLVM_HOME`, `LIBCLANG_PATH` | Matching Linux LLVM/libclang |
|
||||
| `SKIA_SOURCE_DIR` | Dependency-synchronized Skia m153-0.101.2 with bin/gn |
|
||||
| `TEAMSPEACH_GRADLE_DISTRIBUTION` | Local wrapper-checksummed Gradle8.14.3 ZIP |
|
||||
| `TEAMSPEACH_BUNDLETOOL` | Local bundletool JAR |
|
||||
| `ANDROID_SDK_ROOT` | Android SDK with API 36, `build-tools/36.0.0` and `ndk/28.2.13676358` |
|
||||
| `ANDROID_JAVA_HOME` | JDK 17+ including `keytool` (JDK 21 is acceptable) |
|
||||
| `NATIVE_LLVM_HOME` | LLVM tool directory used by `xtask` |
|
||||
| `NATIVE_LIBCLANG_PATH` | libclang library directory |
|
||||
| `NATIVE_SKIA_SOURCE_DIR` | Dependency-synchronized Skia source checkout containing `bin/gn` |
|
||||
| `ANDROID_GRADLE_DISTRIBUTION` | Local `gradle-8.14.3-bin.zip`; bootstrap verifies its committed SHA-256 |
|
||||
| `ANDROID_BUNDLETOOL` | Local `bundletool.jar` for AAB inspection |
|
||||
|
||||
|
||||
#### 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.
|
||||
Also provision the pinned Rust toolchain and `aarch64-linux-android` target, Python 3, Git, CMake,
|
||||
Ninja and required Linux native-build dependencies. The workflow does not install system SDKs or
|
||||
download a Gradle distribution. It source-builds pinned WebRTC via `xtask deps`, builds the ARM64
|
||||
application, packages both variants and runs `verify-package`. Its explicit `--gradle-online true`
|
||||
allows Gradle dependency resolution on CI; the ordinary packaging default remains offline.
|
||||
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.
|
||||
|
||||
#### Dispatch, download and install from Windows
|
||||
|
||||
1. Push the authorized source changes to `feature/mobile-port`; **android-ci** starts automatically.
|
||||
For a manual run select the intended ref and **build** (default), or **inventory** to inspect only
|
||||
basic resources without checkout/provisioning. Main and release publishing are separate routes.
|
||||
2. After an actual successful build, download **`android-harness-arm64-<full commit SHA>`**.
|
||||
The bundle includes root `build-info.json` identifying the exact revision and SHA256 hashes, plus
|
||||
`aarch64-linux-android` package-verification, native-build and dependency receipts. Match run/ref
|
||||
and APK SHA256 before installing; a bare APK is not provenance.
|
||||
For version0.1.7 the harness is `TeamsPeach-0.1.7-android-arm64-harness-test.apk`.
|
||||
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.
|
||||
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,
|
||||
native-build and dependency JSON receipts. Match the run/ref and APK SHA-256 to that evidence
|
||||
before installing; a bare APK is not provenance.
|
||||
For version `0.1.7`, the harness APK is `TeamsPeach-0.1.7-android-arm64-harness-test.apk`; the
|
||||
production bundle contains `TeamsPeach-0.1.7-android-arm64-unsigned.apk` and `.aab`.
|
||||
Use the version actually recorded by the selected run, not a stale download.
|
||||
3. Use a separate **ARM64 Android 8/API 26+ test device**, enable USB debugging and approve this
|
||||
PC's debugging authorization. From the extracted harness APK directory in PowerShell, with
|
||||
@@ -267,12 +151,10 @@ does not establish phone UI, permissions, audio routes, foreground behavior or t
|
||||
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 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.
|
||||
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.
|
||||
|
||||
**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
|
||||
@@ -368,9 +250,12 @@ 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.
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
@@ -399,7 +284,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; HTTPFT/S3 storage is not silently treated as an empty icon collection.
|
||||
the panel's mutation grant. Ordinary-channel S3 browsing does not enable S3 or HTTPFT server icons.
|
||||
- **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.
|
||||
@@ -472,8 +357,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.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
## Product and design
|
||||
|
||||
@@ -526,6 +411,12 @@ 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.
|
||||
|
||||
+9
-7
@@ -16,15 +16,19 @@ 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.22"
|
||||
base64 = "0.23.1"
|
||||
bytes = "1"
|
||||
chrono = { version = "0.4", default-features = false }
|
||||
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"] }
|
||||
sha-1 = "0.10"
|
||||
md-5 = "0.10"
|
||||
sha1 = "0.11.0"
|
||||
md-5 = "0.11.0"
|
||||
base16ct.workspace = true
|
||||
# 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.
|
||||
@@ -34,10 +38,8 @@ tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
fs2 = "=0.4.3"
|
||||
|
||||
[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",
|
||||
@@ -61,5 +63,5 @@ windows-sys = { version = "0.61", features = [
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
dbus = { version = "0.9", features = ["vendored"] }
|
||||
x11rb = "0.13"
|
||||
x11rb = "0.14.0"
|
||||
|
||||
+3651
-328
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,848 @@
|
||||
//! 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
+279
-58
@@ -24,6 +24,10 @@ 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;
|
||||
|
||||
@@ -89,7 +93,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(u64::MAX)),
|
||||
("channel_order", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("channel_codec_is_unencrypted", Kind::Bool),
|
||||
("channel_delete_delay", Kind::Uint(u32::MAX as u64)),
|
||||
("channel_flag_maxclients_unlimited", Kind::Bool),
|
||||
@@ -102,7 +106,7 @@ const CHANNEL_CREATE: &[(&str, Kind)] = &[
|
||||
];
|
||||
/// Fields of `channeledit` (`ChannelEdit` declaration, minus `cid`).
|
||||
const CHANNEL_EDIT: &[(&str, Kind)] = &[
|
||||
("channel_order", Kind::Uint(u64::MAX)),
|
||||
("channel_order", Kind::Uint(MAX_SAFE_INTEGER)),
|
||||
("channel_name", CHANNEL_NAME),
|
||||
("channel_topic", Kind::Str(255)),
|
||||
("channel_flag_default", Kind::Bool),
|
||||
@@ -147,18 +151,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(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_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_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(u64::MAX)),
|
||||
("virtualserver_default_channel_group", Kind::Uint(u64::MAX)),
|
||||
("virtualserver_default_channel_admin_group", Kind::Uint(u64::MAX)),
|
||||
("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_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)),
|
||||
@@ -353,11 +357,18 @@ fn check_opt(field: &str, value: &Option<String>, max: usize) -> Result<(), Erro
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn positive(field: &str, v: u64) -> Result<u64, ErrorObj> {
|
||||
if v == 0 { Err(bad(format!("{field} must be positive"))) } else { Ok(v) }
|
||||
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 generation(v: u64) -> Result<u64, ErrorObj> { positive("generation", 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)
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
@@ -442,11 +453,11 @@ struct GroupArgs { group_id: u64 }
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct AwayArgs { away: bool, #[serde(default)] message: Option<String> }
|
||||
struct AwayArgs { away: bool, #[serde(default, deserialize_with = "crate::protocol::present_string")] message: Option<String> }
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TalkRequestArgs { request: bool, #[serde(default)] message: Option<String> }
|
||||
struct TalkRequestArgs { request: bool, #[serde(default, deserialize_with = "crate::protocol::present_string")] message: Option<String> }
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -612,14 +623,20 @@ 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, .. } => properties.check_scope(PropertyScope::ChannelCreate)?,
|
||||
C::ChannelCreate { properties, parent_id, .. } => {
|
||||
properties.check_scope(PropertyScope::ChannelCreate)?;
|
||||
nonnegative("parent_id", *parent_id)?;
|
||||
}
|
||||
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, .. } => {
|
||||
C::ChannelMove { channel_id, parent_id, order, .. } => {
|
||||
nonnegative("parent_id", *parent_id)?;
|
||||
if let Some(order) = order { nonnegative("order", *order)?; }
|
||||
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, .. }
|
||||
@@ -653,6 +670,7 @@ 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)?;
|
||||
@@ -669,21 +687,62 @@ 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 of `notify` collected until the command result; `key` filters rows by the first
|
||||
/// entry's id (list notifications carry it there only).
|
||||
/// Rows without an explicit scope inherit the last scope in this reply.
|
||||
Rows { notify: &'static str, key: Option<(&'static str, String)>, rows: Vec<Row>, overflow: bool, accept: bool },
|
||||
/// `channelcreate`: the id comes from our own `notifychannelcreated` with that name.
|
||||
Created { name: String, invoker: u16, channel_id: Option<u64> },
|
||||
/// 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 },
|
||||
/// `tokenadd`: the key comes from `notifytokenadd`.
|
||||
Token { token: Option<String> },
|
||||
GroupCreated { notify: &'static str, key: &'static str, name: String, group_id: Option<u64>, ambiguous: bool },
|
||||
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 },
|
||||
/// `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,
|
||||
}
|
||||
@@ -699,7 +758,9 @@ impl Reply {
|
||||
Reply::Rows { notify, .. } => Some(notify),
|
||||
Reply::Token { .. } => Some("notifytokenadd"),
|
||||
Reply::GroupCreated { notify, .. } => Some(notify),
|
||||
Reply::ChannelInfo { .. } | Reply::Description { .. } => Some("notifychanneledited"),
|
||||
Reply::DatabaseId { .. } => Some("notifyclientdbidfromuid"),
|
||||
Reply::ClientInfo(_) => Some("notifyclientupdated"),
|
||||
Reply::ChannelInfo { .. } | Reply::Description { .. } | Reply::ChannelReadDeleted => Some("notifychanneledited"),
|
||||
Reply::Created { .. } => Some("notifychannelcreated"),
|
||||
_ => None,
|
||||
}
|
||||
@@ -708,47 +769,66 @@ 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 => {
|
||||
// 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 let Some((k, v)) = key {
|
||||
if let Some(id) = row.get(*k) { *accept = id == v; }
|
||||
if !*accept { continue; }
|
||||
}
|
||||
if rows.len() >= MAX_ROWS { *overflow = true; return; }
|
||||
rows.push(row.clone());
|
||||
}
|
||||
}
|
||||
Reply::Created { name, invoker, channel_id } if raw.name == "notifychannelcreated" && channel_id.is_none() => {
|
||||
Reply::Created { name, parent, invoker, channel_id, ambiguous } if raw.name == "notifychannelcreated" => {
|
||||
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").map(String::as_str) == Some(name.as_str()) {
|
||||
*channel_id = row.get("cid").and_then(|v| v.parse().ok());
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reply::GroupCreated { notify, key, name, group_id, ambiguous } if *notify == raw.name => {
|
||||
Reply::GroupCreated { notify, key, name, group_type, existing, group_id, ambiguous } if *notify == raw.name => {
|
||||
for row in &raw.items {
|
||||
if row.get("name") == Some(name) {
|
||||
if let Some(id) = row.get(*key).and_then(|v| v.parse::<u64>().ok()) {
|
||||
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 group_id.is_some_and(|old| old != id) { *ambiguous = true; }
|
||||
*group_id = Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Reply::Token { token } if raw.name == "notifytokenadd" => {
|
||||
*token = raw.items.first().and_then(|i| i.get("token")).cloned();
|
||||
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::Description { channel_id, description } if raw.name == "notifychanneledited" => {
|
||||
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") => {
|
||||
for row in &raw.items {
|
||||
if row.get("cid").and_then(|v| v.parse::<u64>().ok()) == Some(*channel_id) {
|
||||
if let Some(d) = row.get("channel_description") { *description = Some(d.clone()); }
|
||||
if raw.name == "notifychanneldescriptionchanged" { *description = None; }
|
||||
else if let Some(d) = row.get("channel_description") { *description = Some(d.clone()); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -771,14 +851,18 @@ 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 { .. } => 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(
|
||||
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(
|
||||
ErrorCode::ServerError,
|
||||
"the server accepted the privilege key but did not send it; reload the list",
|
||||
"the server accepted the privilege key but did not return one unique key; reload the list",
|
||||
)
|
||||
.with_detail(json!({ "created": true }))),
|
||||
Reply::Description { description, .. } => Ok(json!({ "description": description })),
|
||||
@@ -793,6 +877,7 @@ 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.
|
||||
@@ -821,7 +906,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, invoker: live.own_client, channel_id: None })
|
||||
(menu::command("channelcreate", &a), Reply::Created { name, parent: *parent_id, invoker: live.own_client, channel_id: None, ambiguous: false })
|
||||
}
|
||||
C::ChannelEdit { channel_id, properties, .. } => {
|
||||
channel_exists(live, *channel_id, "channel")?;
|
||||
@@ -885,7 +970,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 })
|
||||
(menu::command("tokenadd", &a), Reply::Token { token: None, ambiguous: false })
|
||||
}
|
||||
C::PrivilegeKeyDelete { token, confirm: c, .. } => {
|
||||
confirm(c, token)?;
|
||||
@@ -965,6 +1050,7 @@ 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)) },
|
||||
@@ -992,7 +1078,72 @@ 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 }
|
||||
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})));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1068,7 +1219,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, invoker: 7, channel_id: None } if name == "Lobby"));
|
||||
assert!(matches!(reply, Reply::Created { ref name, parent: 0, invoker: 7, channel_id: None, .. } if name == "Lobby"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1153,6 +1304,49 @@ 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)));
|
||||
@@ -1162,14 +1356,41 @@ mod tests {
|
||||
let rows = finish(r).unwrap();
|
||||
assert_eq!(rows["rows"].as_array().unwrap().len(), 3);
|
||||
|
||||
let mut c = Reply::Created { name: "A b".into(), invoker: 7, channel_id: None };
|
||||
let created = || Reply::Created { name: "A b".into(), parent: 0, invoker: 7, channel_id: None, ambiguous: false };
|
||||
let mut c = created();
|
||||
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=12 cpid=0 channel_name=A\sb invokerid=7").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);
|
||||
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);
|
||||
|
||||
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"}));
|
||||
}
|
||||
|
||||
#[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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-12
@@ -56,26 +56,28 @@ 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| 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)?;}
|
||||
let positive=|id:u64| super::positive("target ID",id);
|
||||
if let Some(g)=self.generation(){super::generation(g)?;}
|
||||
match self {
|
||||
Self::ServerLog{lines,..} if !(1..=1000).contains(lines)=>return Err(menu::bad("lines must be 1..1000")),
|
||||
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::ClientDatabaseList{duration,..} if !(1..=200).contains(duration)=>return Err(menu::bad("duration must be 1..200")),
|
||||
Self::ClientDatabaseFind{pattern,..}=>text(pattern,255)?,
|
||||
Self::ClientDatabaseId{uid}=>text(uid,128)?,
|
||||
Self::ClientDatabaseFind{pattern,..}=>super::check_str("pattern",pattern,255,false)?,
|
||||
Self::ClientDatabaseId{uid}=>super::check_str("uid",uid,128,false)?,
|
||||
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,..}=>{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::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::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))?;text(uid,128)?;},
|
||||
Self::ClientInfo{client_id,uid}=>{positive(u64::from(*client_id))?;super::check_str("uid",uid,128,false)?;},
|
||||
Self::ServerGroupAddClient{group_id,client_database_id,..}=>{positive(*group_id)?;positive(*client_database_id)?;},
|
||||
Self::ServerGroupMemberAddUid{group_id,uid,..}=>{positive(*group_id)?;text(uid,128)?;},
|
||||
Self::ServerGroupMemberAddUid{group_id,uid,..}=>{positive(*group_id)?;super::check_str("uid",uid,128,false)?;},
|
||||
_=>{},
|
||||
} Ok(())
|
||||
}
|
||||
@@ -86,12 +88,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::rows("notifyclientdbidfromuid",None)),
|
||||
Self::ClientDatabaseId{uid}=>(menu::command("clientgetdbidfromuid",&[("cluid",uid.clone())]),Reply::DatabaseId{uid:uid.clone(),id:None,ambiguous:false}),
|
||||
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_id:None,ambiguous:false})
|
||||
(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})
|
||||
},
|
||||
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)},
|
||||
|
||||
+128
-6
@@ -1,6 +1,105 @@
|
||||
//! 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()?;
|
||||
@@ -11,15 +110,25 @@ 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, _)| c.extras.channel_properties(id.0).cloned()).collect();
|
||||
.filter_map(|(id, _)| {
|
||||
let channel = book.channels.get(&id)?;
|
||||
c.extras.channel_properties(id, channel.parent, channel.order)
|
||||
}).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(json!({ "rows": rows })));
|
||||
return Ok(Some(Value::from_iter([("rows", Value::Array(rows))])));
|
||||
}
|
||||
admin::AdminCommand::Extra(admin::extra::Command::ChannelInfo { channel_id }) => {
|
||||
if !book.channels.contains_key(&ChannelId(*channel_id)) {
|
||||
@@ -31,7 +140,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::rows("notifyclientupdated", Some(("clid", u64::from(*client_id)))))
|
||||
(menu::command("clientgetvariables", &[("clid", client_id.to_string())]), admin::Reply::ClientInfo(admin::ClientInfoReply::new(*client_id, uid.clone())))
|
||||
}
|
||||
admin::AdminCommand::TalkPower { target, grant, .. } => {
|
||||
let client = book
|
||||
@@ -46,7 +155,11 @@ 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 live = admin::Live { own_client: book.own_client.0, server_uid: &server_uid, channel: &channel };
|
||||
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 };
|
||||
admin::build(other, &live)?
|
||||
}
|
||||
};
|
||||
@@ -68,14 +181,23 @@ 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| c.extras.channel_properties(channel_id))
|
||||
.map(|row| json!({ "rows": [row] }))
|
||||
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]))]))
|
||||
.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),
|
||||
|
||||
+83
-24
@@ -390,12 +390,14 @@ impl Receiver {
|
||||
if !deny {
|
||||
return Vec::new();
|
||||
}
|
||||
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.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
|
||||
});
|
||||
self.whisper_starts.clear();
|
||||
removed
|
||||
}
|
||||
@@ -421,6 +423,13 @@ 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);
|
||||
@@ -429,15 +438,7 @@ impl Receiver {
|
||||
// An empty whisper packet ends the whisper spurt; ordinary voice ends whispering.
|
||||
self.whisperers.remove(&from);
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
started.map_or(RxEvent::None, |id| RxEvent::Started(id.0))
|
||||
}
|
||||
|
||||
/// Pull 20 ms from every speaker's jitter buffer, apply local gains, and mix to mono.
|
||||
@@ -537,6 +538,30 @@ 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};
|
||||
@@ -582,6 +607,30 @@ 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]
|
||||
@@ -974,16 +1023,26 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_rearms_unsupported_codec_report() {
|
||||
fn legacy_codecs_neither_select_an_encoder_nor_enter_the_mix() {
|
||||
let mut rx = Receiver::new();
|
||||
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, .. }));
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+16
-1
@@ -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!(last);
|
||||
v["from_channel_id"] = json!(num::<u64>(row, "cfid").filter(|c| *c != 0).or(last));
|
||||
v["to_channel_id"] = json!(num::<u64>(row, "ctid"));
|
||||
out.push(v);
|
||||
}
|
||||
@@ -165,6 +165,21 @@ 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();
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
//! Descriptor-owned advisory locks. Rust 1.96 std lacks Android flock support.
|
||||
//! Other platforms keep std semantics; dropping the File releases the lock.
|
||||
use std::{fs::{File, TryLockError}, io};
|
||||
|
||||
pub fn lock(file: &File, shared: bool) -> io::Result<()> {
|
||||
#[cfg(target_os = "android")]
|
||||
{ if shared { fs2::FileExt::lock_shared(file) } else { fs2::FileExt::lock_exclusive(file) } }
|
||||
#[cfg(not(target_os = "android"))]
|
||||
{ if shared { file.lock_shared() } else { file.lock() } }
|
||||
}
|
||||
|
||||
pub fn try_lock(file: &File, shared: bool) -> Result<(), TryLockError> {
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
let result = if shared { fs2::FileExt::try_lock_shared(file) } else { fs2::FileExt::try_lock_exclusive(file) };
|
||||
result.map_err(|error| if error.kind() == io::ErrorKind::WouldBlock {
|
||||
TryLockError::WouldBlock
|
||||
} else { TryLockError::Error(error) })
|
||||
}
|
||||
#[cfg(not(target_os = "android"))]
|
||||
{ if shared { file.try_lock_shared() } else { file.try_lock() } }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::{fs::{self, OpenOptions}, sync::atomic::{AtomicU64, Ordering}};
|
||||
|
||||
#[test]
|
||||
fn owners_exclude_writers_share_readers_and_release_on_drop() {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let path = std::env::temp_dir().join(format!("teamspeach-lock-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let open = || OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path).unwrap();
|
||||
let writer = open();
|
||||
try_lock(&writer, false).unwrap();
|
||||
let contender = open();
|
||||
assert!(matches!(try_lock(&contender, false), Err(TryLockError::WouldBlock)));
|
||||
assert!(matches!(try_lock(&contender, true), Err(TryLockError::WouldBlock)));
|
||||
drop(writer);
|
||||
lock(&contender, true).unwrap();
|
||||
let reader = open();
|
||||
try_lock(&reader, true).unwrap();
|
||||
let next_writer = open();
|
||||
assert!(matches!(try_lock(&next_writer, false), Err(TryLockError::WouldBlock)));
|
||||
drop(reader);
|
||||
drop(contender);
|
||||
try_lock(&next_writer, false).unwrap();
|
||||
drop(next_writer);
|
||||
fs::remove_file(path).unwrap();
|
||||
}
|
||||
}
|
||||
+306
-77
@@ -1,4 +1,4 @@
|
||||
//! Channel file browser over the legacy TeamSpeak file transfer protocol.
|
||||
//! Channel file browser over classic TeamSpeak storage and S3 storage.
|
||||
//!
|
||||
//! 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.
|
||||
//!
|
||||
//! 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.
|
||||
//! Servers advertising `s3` support browsing and HTTPS uploads/downloads for ordinary channels;
|
||||
//! mutations of the directory tree, legacy pause/resume and HTTPFT remain unsupported.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fs::{File, OpenOptions};
|
||||
@@ -43,7 +43,10 @@ use tokio::sync::{mpsc, watch};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use crate::protocol::{ErrorCode, ErrorObj};
|
||||
use crate::rawcmd::RawNotification;
|
||||
use crate::rawcmd::{RawNotification, S3FileList};
|
||||
|
||||
pub(crate) mod s3;
|
||||
pub(crate) mod s3_http;
|
||||
|
||||
/// Longest remote path accepted (characters).
|
||||
pub const MAX_PATH_CHARS: usize = 512;
|
||||
@@ -218,6 +221,11 @@ 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;
|
||||
@@ -235,7 +243,10 @@ fn args<T: serde::de::DeserializeOwned>(raw: Option<&RawValue>) -> Result<T, Err
|
||||
}
|
||||
|
||||
fn channel(id: u64) -> Result<u64, ErrorObj> {
|
||||
if id == 0 { Err(bad("channel_id must be a channel (not 0)")) } else { Ok(id) }
|
||||
if !(1..=9_007_199_254_740_991).contains(&id) {
|
||||
return Err(bad("channel_id must be a positive safe integer"));
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn check_password(p: &str) -> Result<(), ErrorObj> {
|
||||
@@ -255,7 +266,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 Ok(id); }
|
||||
if id != 0 { return channel(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)
|
||||
@@ -354,7 +365,10 @@ 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 { .. } | Request::Pause { .. } | Request::Resume { .. } | Request::Transfers => {}
|
||||
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 => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -457,19 +471,58 @@ 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,
|
||||
pub entries: Vec<Value>,
|
||||
pub malformed: usize,
|
||||
pub overflow: bool,
|
||||
pub finished: bool,
|
||||
data: ListData,
|
||||
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)
|
||||
@@ -616,6 +669,12 @@ 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.
|
||||
@@ -677,12 +736,15 @@ 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,
|
||||
@@ -706,7 +768,8 @@ pub struct Transfer {
|
||||
impl Transfer {
|
||||
pub fn ftid(&self) -> Option<u16> {
|
||||
match self.stage {
|
||||
Stage::Queued | Stage::Paused => None,
|
||||
Stage::Queued | Stage::Paused | Stage::S3Init { .. } | Stage::S3Running { .. }
|
||||
| Stage::S3Confirming { .. } => None,
|
||||
Stage::Init { ftid, .. }
|
||||
| Stage::Running { ftid, .. }
|
||||
| Stage::Pausing { ftid, .. }
|
||||
@@ -720,15 +783,18 @@ impl Transfer {
|
||||
pub fn state(&self) -> &'static str {
|
||||
match self.stage {
|
||||
Stage::Queued => "queued",
|
||||
Stage::Init { .. } => "starting",
|
||||
Stage::Running { .. } | Stage::Pausing { .. } | Stage::Lost { .. } => "running",
|
||||
Stage::Confirming { .. } => "confirming",
|
||||
Stage::Init { .. } | Stage::S3Init { .. } => "starting",
|
||||
Stage::Running { .. } | Stage::Pausing { .. } | Stage::Lost { .. } | Stage::S3Running { .. } => "running",
|
||||
Stage::Confirming { .. } | Stage::S3Confirming { .. } => "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 { .. }) }
|
||||
pub fn in_progress(&self) -> bool {
|
||||
matches!(self.stage, Stage::Init { .. } | Stage::Running { .. } | Stage::Confirming { .. }
|
||||
| Stage::S3Init { .. } | Stage::S3Running { .. } | Stage::S3Confirming { .. })
|
||||
}
|
||||
|
||||
/// `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`).
|
||||
@@ -814,8 +880,9 @@ impl Transfer {
|
||||
"path": self.path,
|
||||
"name": file_name(&self.path),
|
||||
"state": state,
|
||||
"bytes": self.progress.load(Ordering::Relaxed),
|
||||
"total": self.total,
|
||||
"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)),
|
||||
});
|
||||
if let Some(e) = error {
|
||||
v["error"] = serde_json::to_value(e).expect("error serializes");
|
||||
@@ -824,12 +891,12 @@ impl Transfer {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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).
|
||||
/// Dropping a transfer stops its I/O 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, .. } = &self.stage {
|
||||
if let Stage::Running { task, .. } | Stage::Pausing { task, .. } | Stage::S3Running { task } = &self.stage {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
@@ -858,8 +925,9 @@ pub struct Files {
|
||||
pub stops: HashMap<u16, ()>,
|
||||
pub transfers: Vec<Transfer>,
|
||||
pub tombstones: HashMap<u16, Tombstone>,
|
||||
/// Last `virtualserver_capability_extensions` seen (`None` until the server sent it).
|
||||
pub capability_extensions: Option<String>,
|
||||
/// Display text is bounded; backend selection uses the complete announcement.
|
||||
capability_extensions: Option<String>,
|
||||
storage_extensions: (bool, bool),
|
||||
pub slots: Option<[usize; 2]>,
|
||||
/// Increments whenever a transfer starts.
|
||||
pub start_seq: u64,
|
||||
@@ -902,30 +970,56 @@ 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> {
|
||||
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()));
|
||||
}
|
||||
if self.storage_extensions != (false, false) { return Err(self.unsupported_storage()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `virtualserver_capability_extensions` tokens relevant to file storage.
|
||||
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.
|
||||
pub fn storage(&self) -> Value {
|
||||
// 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");
|
||||
let (httpft, s3) = self.storage_extensions;
|
||||
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;
|
||||
@@ -934,8 +1028,10 @@ impl Files {
|
||||
}
|
||||
match raw.name.as_str() {
|
||||
"initserver" | "notifyserverupdated" | "notifyserveredited" => {
|
||||
if let Some(v) = items[0].get("virtualserver_capability_extensions") {
|
||||
self.capability_extensions = Some(v.chars().take(1024).collect());
|
||||
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());
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
@@ -955,13 +1051,14 @@ 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");
|
||||
if job.entries.len() >= MAX_LIST_ENTRIES {
|
||||
job.overflow = true;
|
||||
let ListData::Legacy { entries, malformed, overflow, .. } = &mut job.data else { unreachable!() };
|
||||
if entries.len() >= MAX_LIST_ENTRIES {
|
||||
*overflow = true;
|
||||
continue;
|
||||
}
|
||||
match list_entry(items, i) {
|
||||
Some(v) => job.entries.push(v),
|
||||
None => job.malformed += 1,
|
||||
Some(v) => entries.push(v),
|
||||
None => *malformed += 1,
|
||||
}
|
||||
}
|
||||
Vec::new()
|
||||
@@ -970,9 +1067,7 @@ impl Files {
|
||||
let mut done = Vec::new();
|
||||
for i in 0..items.len() {
|
||||
if let Some(handle) = self.list_for(items, i) {
|
||||
let job = self.lists.get_mut(&handle).expect("found");
|
||||
job.finished = true;
|
||||
if job.result_ok {
|
||||
if self.lists.get_mut(&handle).expect("found").finish_legacy() {
|
||||
done.push(handle);
|
||||
}
|
||||
}
|
||||
@@ -987,13 +1082,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(|j| !j.finished) {
|
||||
if self.lists.get(&h).is_some_and(ListJob::accepts_legacy_rows) {
|
||||
return Some(h);
|
||||
}
|
||||
}
|
||||
let cid: u64 = field(items, i, "cid")?.parse().ok()?;
|
||||
let path = field(items, i, "path")?;
|
||||
self.lists.iter().find(|(_, j)| !j.finished && j.channel_id == cid && same_dir(&j.path, path)).map(|(h, _)| *h)
|
||||
self.lists.iter().find(|(_, j)| j.accepts_legacy_rows() && j.channel_id == cid && same_dir(&j.path, path)).map(|(h, _)| *h)
|
||||
}
|
||||
|
||||
pub fn list_pending(&self, channel_id: u64, path: &str) -> bool {
|
||||
@@ -1026,9 +1121,11 @@ impl Files {
|
||||
/// for an explicit resume).
|
||||
pub fn next_startable(&self, direction: Direction) -> Option<usize> {
|
||||
self.transfers.iter().position(|q| {
|
||||
q.direction == direction
|
||||
&& matches!(q.stage, Stage::Queued)
|
||||
&& self.in_progress_of(direction, q.channel_id).len() < self.limit(direction, q.channel_id)
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1043,7 +1140,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 !matches!(self.transfers[i].stage, Stage::Confirming { .. }) {
|
||||
if self.transfers[i].backend == ListBackend::Legacy && !matches!(self.transfers[i].stage, Stage::Confirming { .. }) {
|
||||
out.push(self.transfers[i].id);
|
||||
}
|
||||
}
|
||||
@@ -1063,7 +1160,7 @@ impl Files {
|
||||
let excess = (running.len() + 1).saturating_sub(limit).min(running.len());
|
||||
running[..excess]
|
||||
.iter()
|
||||
.filter(|&&i| !matches!(self.transfers[i].stage, Stage::Confirming { .. }))
|
||||
.filter(|&&i| self.transfers[i].backend == ListBackend::Legacy && !matches!(self.transfers[i].stage, Stage::Confirming { .. }))
|
||||
.map(|&i| self.transfers[i].id)
|
||||
.collect()
|
||||
}
|
||||
@@ -1071,14 +1168,17 @@ impl Files {
|
||||
|
||||
/// Final answer for a completed listing.
|
||||
pub fn list_result(job: ListJob, capabilities: Value, storage: Value) -> Result<Value, ErrorObj> {
|
||||
if job.overflow {
|
||||
return Err(ErrorObj::new(ErrorCode::ServerError, format!("the folder has more than {MAX_LIST_ENTRIES} entries; listing not complete")));
|
||||
}
|
||||
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")?,
|
||||
};
|
||||
Ok(json!({
|
||||
"channel_id": job.channel_id,
|
||||
"path": job.path,
|
||||
"entries": job.entries,
|
||||
"malformed": job.malformed,
|
||||
"entries": entries,
|
||||
"malformed": malformed,
|
||||
"capabilities": capabilities,
|
||||
"storage": storage,
|
||||
}))
|
||||
@@ -1086,16 +1186,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>) -> Value {
|
||||
pub fn capabilities(hints: Option<u64>, s3: bool) -> 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": bit(256),
|
||||
"rename": bit(512),
|
||||
"delete": !s3 && bit(256),
|
||||
"rename": !s3 && bit(512),
|
||||
"browse": bit(1024),
|
||||
"create_directory": bit(2048),
|
||||
"create_directory": !s3 && bit(2048),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1187,6 +1287,8 @@ 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,
|
||||
@@ -1234,6 +1336,10 @@ 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;
|
||||
@@ -1245,6 +1351,9 @@ 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 => {
|
||||
@@ -1255,7 +1364,7 @@ fn disk_writer(
|
||||
}
|
||||
Err(cancelled())
|
||||
})();
|
||||
if foreign {
|
||||
if foreign || (result.is_err() && !names_file(guard.0.as_ref().expect("armed"), &file)) {
|
||||
guard.0 = None;
|
||||
}
|
||||
match result {
|
||||
@@ -1600,10 +1709,7 @@ mod tests {
|
||||
#[test]
|
||||
fn listing_merges_shared_arguments_and_bounds_rows() {
|
||||
let mut f = Files::default();
|
||||
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(),
|
||||
});
|
||||
f.lists.insert(7, ListJob::new("r", 4, "/".into(), ListBackend::Legacy));
|
||||
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")],
|
||||
@@ -1612,13 +1718,14 @@ mod tests {
|
||||
&[("name", "nested/file"), ("size", "1"), ("type", "1")],
|
||||
]));
|
||||
assert!(done.is_empty());
|
||||
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;
|
||||
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());
|
||||
assert_eq!(f.apply_raw(&raw("notifyfilelistfinished", &[&[("cid", "4"), ("path", "/")]])), vec![7]);
|
||||
}
|
||||
|
||||
@@ -1631,11 +1738,119 @@ 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!(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);
|
||||
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 },
|
||||
]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1729,7 +1944,7 @@ mod tests {
|
||||
|
||||
fn md5_hex(b: &[u8]) -> String {
|
||||
use md5::{Digest, Md5};
|
||||
format!("{:x}", Md5::digest(b))
|
||||
base16ct::lower::encode_string(&Md5::digest(b))
|
||||
}
|
||||
|
||||
fn parts(dir: &Path) -> usize {
|
||||
@@ -1894,26 +2109,34 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn upload_sends_exact_bytes_and_sees_server_close() {
|
||||
let dir = scratch("ul");
|
||||
let data = pattern(2 * CHUNK + 999);
|
||||
let data = pattern(5 * CHUNK);
|
||||
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 ended = upload(keyed(addr).await, file, size, 0, progress.clone(), Arc::default(), quiet()).await.unwrap();
|
||||
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();
|
||||
assert!(matches!(ended, Ended::Complete { closed: true }));
|
||||
let got = server.await.unwrap();
|
||||
assert_eq!(md5_hex(&got), md5_hex(&data));
|
||||
@@ -2019,12 +2242,14 @@ 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,
|
||||
@@ -2075,12 +2300,14 @@ 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,
|
||||
@@ -2124,12 +2351,14 @@ 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,
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
//! 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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
//! 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();
|
||||
}
|
||||
}
|
||||
+132
-38
@@ -9,9 +9,12 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use futures::FutureExt;
|
||||
use tsclientlib::{FileDownloadResult, FileUploadResult};
|
||||
|
||||
use crate::file_transfer::{self as ft, Direction, Ended, ListJob, Local, Partial, Request, Stage, Tombstone, Transfer};
|
||||
use crate::file_transfer::{self as ft, Direction, Ended, ListBackend, 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()) }
|
||||
@@ -55,6 +58,15 @@ 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
|
||||
@@ -81,6 +93,9 @@ 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);
|
||||
}
|
||||
@@ -119,6 +134,18 @@ 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);
|
||||
@@ -187,7 +214,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::Cancel { .. } | Request::Pause { .. } | Request::Resume { .. } | Request::Transfers | Request::Config { .. }) {
|
||||
if matches!(&request, Request::Mkdir { .. } | Request::Rename { .. } | Request::Delete { .. } | Request::FetchImage { .. }) {
|
||||
self.connected_conn()?.files.require_legacy()?;
|
||||
}
|
||||
match request {
|
||||
@@ -197,8 +224,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);
|
||||
// Official updateConcurrentTransferLimits: a changed limit pauses each channel's
|
||||
// excess in-progress transfers; they wait for an explicit resume.
|
||||
// Legacy transfers pause when their slots are removed. S3 transfers cannot resume;
|
||||
// they drain before the queue starts any more above the new limit.
|
||||
let mut events = Vec::new();
|
||||
if changed {
|
||||
for transfer_id in c.files.over_limit() {
|
||||
@@ -216,6 +243,9 @@ 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"));
|
||||
}
|
||||
@@ -230,23 +260,14 @@ 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 = menu::command("ftgetfilelist", &[("cid", channel_id.to_string()), ("cpw", cpw(&password)), ("path", path.clone())]);
|
||||
let cmd = list_command(backend, channel_id, &path, &password);
|
||||
let handle = c.send(cmd).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
|
||||
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(),
|
||||
});
|
||||
c.files.lists.insert(handle, ListJob::new(id, channel_id, path, backend));
|
||||
Ok(None)
|
||||
}
|
||||
Request::Mkdir { channel_id, path, password } => {
|
||||
@@ -269,16 +290,16 @@ impl Session {
|
||||
self.files_simple(id, channel_id, cmd)
|
||||
}
|
||||
Request::Download { channel_id, password, path, dest_dir, subdirs, overwrite } => {
|
||||
if channel_id != 0 { self.connected_conn().and_then(|c| channel_known(c, channel_id))?; }
|
||||
let backend = self.files_transfer_backend(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(Direction::Download, channel_id, path, &password, overwrite, Local::Download { dir, name, overwrite, partial: None }, 0)
|
||||
self.files_enqueue(backend, Direction::Download, channel_id, path, &password, overwrite, Local::Download { dir, name, overwrite, partial: None }, 0)
|
||||
}
|
||||
Request::Upload { channel_id, password, path, source, overwrite } => {
|
||||
if channel_id != 0 { self.connected_conn().and_then(|c| channel_known(c, channel_id))?; }
|
||||
let backend = self.files_transfer_backend(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());
|
||||
@@ -287,7 +308,7 @@ impl Session {
|
||||
})
|
||||
.await
|
||||
.map_err(internal)??;
|
||||
self.files_enqueue(Direction::Upload, channel_id, path, &password, overwrite, Local::Upload { file: Some(file), size, modified }, size)
|
||||
self.files_enqueue(backend, 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 } => {
|
||||
@@ -302,6 +323,13 @@ 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.
|
||||
@@ -315,6 +343,7 @@ impl Session {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn files_enqueue(
|
||||
&mut self,
|
||||
backend: ListBackend,
|
||||
direction: Direction,
|
||||
channel_id: u64,
|
||||
path: String,
|
||||
@@ -331,6 +360,7 @@ impl Session {
|
||||
let now = Instant::now();
|
||||
let t = Transfer {
|
||||
id,
|
||||
backend,
|
||||
direction,
|
||||
channel_id,
|
||||
path,
|
||||
@@ -338,6 +368,7 @@ impl Session {
|
||||
overwrite,
|
||||
local,
|
||||
total,
|
||||
s3_total: None,
|
||||
stage: Stage::Queued,
|
||||
server_ftid: None,
|
||||
confirmed: false,
|
||||
@@ -363,10 +394,13 @@ impl Session {
|
||||
.files
|
||||
.index_of_id(transfer_id)
|
||||
.ok_or_else(|| not_active(transfer_id))?;
|
||||
if matches!(c.files.transfers[i].stage, Stage::Confirming { .. }) {
|
||||
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())
|
||||
{
|
||||
return Err(menu::bad("the upload is complete and awaiting the server's confirmation"));
|
||||
}
|
||||
if !c.files.transfers[i].commit.cancel() {
|
||||
if !t.commit.cancel() {
|
||||
return Err(menu::bad("the download is being committed and can no longer be cancelled"));
|
||||
}
|
||||
let t = c.files.transfers.remove(i);
|
||||
@@ -382,6 +416,9 @@ 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"));
|
||||
}
|
||||
@@ -441,8 +478,10 @@ 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), c.files.storage()) {
|
||||
match ft::list_result(job, ft::capabilities(hints, s3), storage) {
|
||||
Ok(v) => self.out.ok(&req, v).await,
|
||||
Err(e) => self.out.err(&req, e).await,
|
||||
}
|
||||
@@ -450,21 +489,27 @@ 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) {
|
||||
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;
|
||||
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()
|
||||
}
|
||||
Err(e) => {
|
||||
let req = c.files.lists.remove(&handle).expect("present").req;
|
||||
self.out.err(&req, command_error(&e)).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if job.finished {
|
||||
};
|
||||
if ready {
|
||||
self.files_answer_list(handle).await;
|
||||
}
|
||||
return;
|
||||
@@ -496,6 +541,13 @@ 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) {
|
||||
@@ -503,6 +555,13 @@ 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) {
|
||||
@@ -655,19 +714,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 t in transfers {
|
||||
let event = t.event("failed", Some(&err));
|
||||
drop(t);
|
||||
for event in events {
|
||||
self.out.json(&event).await;
|
||||
}
|
||||
}
|
||||
@@ -697,10 +756,16 @@ 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>),
|
||||
@@ -708,6 +773,12 @@ 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,
|
||||
@@ -720,6 +791,12 @@ 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"))
|
||||
}
|
||||
@@ -738,13 +815,21 @@ impl Session {
|
||||
match outcome {
|
||||
Outcome::Done => {
|
||||
let t = c.files.transfers.remove(i);
|
||||
t.progress.store(t.total, Ordering::Relaxed);
|
||||
if t.backend == ListBackend::Legacy { 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 { .. });
|
||||
let ended = !matches!(t.stage, Stage::Running { .. } | Stage::Pausing { .. } | Stage::Init { .. } | Stage::Lost { .. }
|
||||
| Stage::S3Init { .. } | Stage::S3Confirming { .. });
|
||||
if ended {
|
||||
drop(t);
|
||||
} else {
|
||||
@@ -776,7 +861,7 @@ impl Session {
|
||||
}
|
||||
Outcome::Keep => {
|
||||
let t = &mut c.files.transfers[i];
|
||||
if matches!(t.stage, Stage::Running { .. }) && bytes != t.reported && now - t.last_emit >= ft::PROGRESS_INTERVAL {
|
||||
if matches!(t.stage, Stage::Running { .. } | Stage::S3Running { .. }) && bytes != t.reported && now - t.last_emit >= ft::PROGRESS_INTERVAL {
|
||||
t.reported = bytes;
|
||||
t.last_emit = now;
|
||||
events.push(t.event("running", None));
|
||||
@@ -802,6 +887,15 @@ 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();
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ pub mod admin;
|
||||
pub mod app_audio;
|
||||
pub mod audio;
|
||||
mod events;
|
||||
pub mod file_lock;
|
||||
pub mod file_transfer;
|
||||
pub mod hotkeys;
|
||||
mod keyfmt;
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ pub fn lock_dir(dir: &Path, shared: bool) -> Result<File, String> {
|
||||
let path = dir.join("core.lock");
|
||||
let file = OpenOptions::new().create(true).truncate(false).write(true).open(&path)
|
||||
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
||||
match crate::file_lock::try_lock(&file, shared) {
|
||||
match if shared { file.try_lock_shared() } else { file.try_lock() } {
|
||||
Ok(()) => Ok(file),
|
||||
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
|
||||
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
|
||||
|
||||
+30
-8
@@ -59,6 +59,11 @@ 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(())
|
||||
@@ -74,16 +79,16 @@ pub fn parse_action(mut value: Value) -> Result<ActionRequest, ErrorObj> {
|
||||
|
||||
pub(crate) fn validate_action(request: &ActionRequest) -> Result<(), ErrorObj> {
|
||||
validate_target(&request.target)?;
|
||||
if request.generation == 0 { return Err(bad("generation is required")); }
|
||||
crate::admin::generation(request.generation)?;
|
||||
match &request.action {
|
||||
Action::Poke{message} if message.is_empty() || message.len()>1024 || message.chars().any(char::is_control) =>return Err(bad("poke message must be 1..1024 bytes without controls")),
|
||||
Action::Poke{message} if !valid_poke_message(message) =>return Err(bad("poke message must be 1..1024 UTF-8 bytes without ASCII 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: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::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::Avatar{data}=>{avatar_bytes(data)?;},
|
||||
_=>{},
|
||||
}
|
||||
@@ -190,7 +195,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(bad("client identity changed; reopen the menu"));}
|
||||
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"));}
|
||||
Ok(())
|
||||
}
|
||||
fn target_hint(own:bool,key:&str,hints:Option<u64>,bit:u64)->Value {
|
||||
@@ -208,6 +213,13 @@ 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::*;
|
||||
@@ -248,6 +260,16 @@ 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"),
|
||||
@@ -284,9 +306,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());
|
||||
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());
|
||||
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);
|
||||
}
|
||||
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(menu::bad("connection changed; reopen the menu"));}
|
||||
if request.generation!=c.generation{return Err(ErrorObj::new(ErrorCode::TargetChanged,"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=format!("{:x}",Md5::digest(&data));
|
||||
let hash=base16ct::lower::encode_string(&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))?;
|
||||
|
||||
+12
-1
@@ -84,7 +84,8 @@ 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.insert("generation".into(), Value::from(self.inner.generation.load(Ordering::Acquire)));
|
||||
object.entry("generation".to_owned())
|
||||
.or_insert_with(|| Value::from(self.inner.generation.load(Ordering::Acquire)));
|
||||
}
|
||||
let _ = self.inner.control.send(value).await;
|
||||
}
|
||||
@@ -122,6 +123,16 @@ 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();
|
||||
|
||||
+32
-7
@@ -561,7 +561,7 @@ impl Store {
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.map_err(io_err(format!("opening {}", path.display())))?;
|
||||
crate::file_lock::lock(&file, false).map_err(io_err(format!("locking {}", path.display())))?;
|
||||
file.lock().map_err(io_err(format!("locking {}", path.display())))?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
@@ -584,7 +584,7 @@ impl Store {
|
||||
/// True while a connection core holds the identity (informational; delete re-checks).
|
||||
fn in_use(&self, uid: &str) -> bool {
|
||||
let Ok(file) = fs::OpenOptions::new().write(true).open(self.use_path(uid)) else { return false };
|
||||
match crate::file_lock::try_lock(&file, false) {
|
||||
match file.try_lock() {
|
||||
Ok(()) => false,
|
||||
Err(TryLockError::WouldBlock) => true,
|
||||
Err(TryLockError::Error(_)) => false,
|
||||
@@ -674,7 +674,7 @@ impl Store {
|
||||
};
|
||||
let lock = self.open_use_file(&uid)?;
|
||||
// Blocks only while a delete of this identity holds it exclusively (a few file operations).
|
||||
crate::file_lock::lock(&lock, true).map_err(io_err(format!("locking {}", self.use_path(&uid).display())))?;
|
||||
lock.lock_shared().map_err(io_err(format!("locking {}", self.use_path(&uid).display())))?;
|
||||
// A delete that finished while we waited has removed it.
|
||||
let vault = self.load_vault()?;
|
||||
let e = vault.find(&uid).ok_or_else(|| StoreError::NotFound(uid.clone()))?;
|
||||
@@ -833,7 +833,7 @@ impl Store {
|
||||
return Err(StoreError::DeleteRefused("the default identity cannot be deleted; choose another default first".into()));
|
||||
}
|
||||
let guard = self.open_use_file(uid)?;
|
||||
match crate::file_lock::try_lock(&guard, false) {
|
||||
match guard.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(TryLockError::WouldBlock) => return Err(StoreError::InUse),
|
||||
Err(TryLockError::Error(e)) => return Err(io_err(format!("locking {}", self.use_path(uid).display()))(e)),
|
||||
@@ -874,9 +874,6 @@ 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 {
|
||||
@@ -893,6 +890,9 @@ 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,6 +1419,31 @@ 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");
|
||||
|
||||
+199
-34
@@ -104,6 +104,10 @@ 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 {
|
||||
@@ -120,7 +124,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>, message: String },
|
||||
SendText { target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<String>, expected_channel_id: Option<u64>, 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> },
|
||||
@@ -190,12 +194,23 @@ impl Command {
|
||||
}
|
||||
|
||||
/// A command whose transport-independent arguments have been checked and normalized.
|
||||
/// Only the core can unwrap it; callers must use [`validate_command`].
|
||||
/// Callers can inspect it without changing it; only the core can unwrap it.
|
||||
#[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 }
|
||||
}
|
||||
|
||||
@@ -203,20 +218,25 @@ impl ValidatedCommand {
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ConnectArgs {
|
||||
pub address: String,
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
pub server_password: Option<String>,
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
pub channel: Option<String>,
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
pub channel_password: Option<String>,
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
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)]
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
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 {
|
||||
@@ -242,10 +262,15 @@ struct Envelope<'a> {
|
||||
id: Option<Cow<'a, str>>,
|
||||
#[serde(borrow)]
|
||||
cmd: Cow<'a, str>,
|
||||
#[serde(default, borrow)]
|
||||
#[serde(default, borrow, deserialize_with = "present_args")]
|
||||
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 {}
|
||||
@@ -259,7 +284,7 @@ struct NicknameArgs {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct DisconnectArgs {
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "present_string")]
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
@@ -279,18 +304,24 @@ 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)]
|
||||
#[serde(default, deserialize_with = "present_bool")]
|
||||
input_muted: Option<bool>,
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "present_bool")]
|
||||
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 {
|
||||
@@ -414,6 +445,28 @@ 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];
|
||||
@@ -436,6 +489,9 @@ 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) => {
|
||||
@@ -448,6 +504,11 @@ 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" => {
|
||||
@@ -510,7 +571,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, message: a.message }
|
||||
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 }
|
||||
}
|
||||
"set_audio" => {
|
||||
let a: SetAudioArgs = args_owned(raw)?;
|
||||
@@ -583,15 +644,28 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
|
||||
let update = matches!(&command, Command::StreamUpdate(_));
|
||||
match &mut command {
|
||||
Command::Connect(a) => {
|
||||
check_text("address", &a.address, 255, false)?;
|
||||
check_opt("server_password", &a.server_password)?;
|
||||
check_opt("channel", &a.channel)?;
|
||||
check_opt("channel_password", &a.channel_password)?;
|
||||
check_opt("identity_id", &a.identity_id)?;
|
||||
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)?; }
|
||||
}
|
||||
Command::Disconnect { message } => check_opt("message", message)?,
|
||||
Command::JoinChannel { password, .. } => check_opt("password", password)?,
|
||||
Command::SendText { target, client_id, expected_client_uid, message } => {
|
||||
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"));
|
||||
}
|
||||
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")),
|
||||
@@ -606,11 +680,19 @@ 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::StreamJoin { stream_id, message, .. } => { check_stream_id(stream_id)?; check_opt("message", message)?; }
|
||||
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::StreamSignal { stream_id, json, .. } => {
|
||||
check_stream_id(stream_id)?;
|
||||
let value: Value = serde_json::from_str(json).map_err(|e| bad(format!("json is not valid JSON: {e}")))?;
|
||||
if !value.is_object() { return Err(bad("json must be an object")); }
|
||||
check_signal(&value)?;
|
||||
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;
|
||||
@@ -625,18 +707,15 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
|
||||
return Err(bad("invalid stream metadata (only P2P is supported)"));
|
||||
}
|
||||
}
|
||||
Command::StreamRespond { stream_id, client_id, decision, offer, message } => {
|
||||
Command::StreamRespond { stream_id, decision, offer, message, .. } => {
|
||||
check_stream_id(stream_id)?;
|
||||
check_text("message", message, 200, true)?;
|
||||
if *client_id == 0 || *decision == offer.is_empty() || offer.len() > 60000
|
||||
if *decision == offer.is_empty() || offer.len() > 60000
|
||||
|| offer.chars().any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t')) || message.chars().any(char::is_control) {
|
||||
return Err(bad("invalid stream join response"));
|
||||
}
|
||||
}
|
||||
Command::StreamRemove { stream_id, client_id } => {
|
||||
check_stream_id(stream_id)?;
|
||||
if *client_id == 0 { return Err(bad("client_id must be nonzero")); }
|
||||
}
|
||||
Command::StreamRemove { stream_id, .. } => check_stream_id(stream_id)?,
|
||||
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)?,
|
||||
@@ -748,6 +827,37 @@ 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());
|
||||
@@ -798,10 +908,19 @@ 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, message: "hello".into(),
|
||||
target: TextTarget::Client, client_id, expected_client_uid, expected_channel_id: None, message: "hello".into(),
|
||||
};
|
||||
assert_bad(private(None, Some("uid".into())));
|
||||
assert_bad(private(Some(0), Some("uid".into())));
|
||||
@@ -812,27 +931,73 @@ 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, message: "hello".into() });
|
||||
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: Some("uid".into()), message: "hello".into() });
|
||||
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() });
|
||||
for message in [String::new(), "я".repeat(MAX_TEXT_BYTES / 2 + 1)] {
|
||||
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: None, message });
|
||||
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: None, expected_channel_id: 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 compact = format!(r#"{{"x":"{}"}}"#, "x".repeat(MAX_SIGNAL_JSON_BYTES - 8));
|
||||
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 padded = format!(" {compact}{}", " ".repeat(MAX_SIGNAL_JSON_BYTES));
|
||||
assert_eq!(validate_command(signal(padded)).unwrap().into_inner(), signal(compact));
|
||||
assert_bad(signal(format!(r#"{{"x":"{}"}}"#, "x".repeat(MAX_SIGNAL_JSON_BYTES - 7))));
|
||||
assert_bad(signal(format!("{prefix}{payload}x{suffix}")));
|
||||
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,
|
||||
|
||||
+152
-3
@@ -6,7 +6,7 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use tsproto_packets::commands::{CommandItem, CommandParser};
|
||||
use tsproto_packets::commands::{CommandArgumentValue, CommandItem, CommandParser};
|
||||
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
|
||||
|
||||
/// Outgoing verbs the bridge may send (never caller-chosen names).
|
||||
@@ -80,7 +80,8 @@ pub fn publish_stream(a: &crate::protocol::StreamPublishArgs) -> OutCommand {
|
||||
}
|
||||
|
||||
pub fn stop_stream(stream_id: &str) -> OutCommand {
|
||||
build(StreamVerb::StopStream, &[("id", stream_id)])
|
||||
// beta14 requires the reason even for a publisher ending its own stream (LEFT = 1).
|
||||
build(StreamVerb::StopStream, &[("id", stream_id), ("reason", "1")])
|
||||
}
|
||||
|
||||
pub fn respond_stream(stream_id: &str, client_id: u16, decision: bool, offer: &str, message: &str) -> OutCommand {
|
||||
@@ -108,11 +109,13 @@ 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"
|
||||
@@ -126,6 +129,152 @@ 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 {
|
||||
@@ -218,7 +367,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");
|
||||
assert_eq!(std::str::from_utf8(&content(stop_stream("7"))).unwrap(), "stopstream id=7 reason=1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1064,6 +1064,12 @@ 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; FRAME_SAMPLES];
|
||||
let f: Frame = [((tick as i16) + 1) * 256; FRAME_SAMPLES];
|
||||
match rec.end_tick(&f, ident, &LOBBY) {
|
||||
TickOutcome::Overflow { .. } => dropped_reports += 1,
|
||||
TickOutcome::Ok => {}
|
||||
@@ -395,6 +395,7 @@ 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);
|
||||
@@ -413,7 +414,8 @@ 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 }, "tick {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}");
|
||||
}
|
||||
let _ = fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
+6
-2
@@ -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}, session::Session};
|
||||
use crate::{audio::{AudioIn, AudioInQueue, CapturedFrame}, locks, output::{Out, PlaybackReceiver}, profile::Store, protocol::{validate_command, Command, ErrorCode, ErrorObj, Input, ValidatedCommand}, session::Session};
|
||||
|
||||
pub struct CoreConfig { pub data_dir: PathBuf, pub connection_dir: PathBuf }
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -43,7 +43,11 @@ impl Drop for PendingRequest {
|
||||
|
||||
impl CoreHandle {
|
||||
pub async fn request(&self, command: Command) -> Result<Value, ErrorObj> {
|
||||
let command = validate_command(command)?;
|
||||
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 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();
|
||||
|
||||
+200
-33
@@ -115,6 +115,16 @@ 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 },
|
||||
@@ -164,6 +174,7 @@ struct Conn {
|
||||
gains: menu::LocalVolumes,
|
||||
avatar: Option<AvatarUpload>,
|
||||
files: crate::file_transfer::Files,
|
||||
s3_receipts: HashMap<u16, files_session::s3::Receipt>,
|
||||
}
|
||||
|
||||
struct AvatarUpload {
|
||||
@@ -363,8 +374,11 @@ impl Session {
|
||||
self.out.json(&v).await;
|
||||
}
|
||||
|
||||
async fn emit_state(&self, state: &str, address: Option<&str>, reason: Option<ErrorObj>) {
|
||||
async fn emit_state(&self, state: &str, address: Option<&str>, reason: Option<ErrorObj>, previous: Option<&Phase>) {
|
||||
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);
|
||||
}
|
||||
@@ -422,7 +436,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, message } => self.send_text(&id, target, client_id, expected_client_uid.as_deref(), &message),
|
||||
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::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),
|
||||
@@ -571,13 +585,14 @@ 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).await;
|
||||
self.emit_state("connecting", Some(&args.address), None, None).await;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
@@ -606,7 +621,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).await;
|
||||
self.emit_state("disconnecting", Some(&address), None, None).await;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -632,7 +647,7 @@ impl Session {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn send_text(&mut self, id: &str, target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<&str>, message: &str) -> Result<Option<Value>, ErrorObj> {
|
||||
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> {
|
||||
let target = match (target, client_id) {
|
||||
(TextTarget::Server, _) => MessageTarget::Server,
|
||||
(TextTarget::Channel, _) => MessageTarget::Channel,
|
||||
@@ -641,6 +656,11 @@ 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) {
|
||||
@@ -654,7 +674,11 @@ impl Session {
|
||||
}
|
||||
|
||||
async fn set_audio(&mut self, id: &str, input_muted: Option<bool>, output_muted: Option<bool>) -> Result<Option<Value>, ErrorObj> {
|
||||
if input_muted.is_some() || output_muted.is_some() { self.audio_in.invalidate(); }
|
||||
if input_muted.is_none() && output_muted.is_none() {
|
||||
self.emit_audio_state().await;
|
||||
return Ok(Some(self.audio_state()));
|
||||
}
|
||||
self.audio_in.invalidate();
|
||||
if let Some(m) = input_muted {
|
||||
self.flags.input_muted = m;
|
||||
}
|
||||
@@ -680,13 +704,9 @@ impl Session {
|
||||
if let Some(m) = output_muted {
|
||||
part = part.set_output_muted(m);
|
||||
}
|
||||
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)
|
||||
}
|
||||
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())),
|
||||
@@ -963,13 +983,19 @@ 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 whisper_starts {
|
||||
// Official `onWhisperStart`: feeds the reply history and the whisper notification.
|
||||
self.out.json(&json!({ "event": "whisper_received", "client_id": cid })).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;
|
||||
}
|
||||
match event {
|
||||
RxEvent::None => {}
|
||||
@@ -990,6 +1016,10 @@ 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);
|
||||
@@ -1047,7 +1077,15 @@ impl Session {
|
||||
self.ft_finish(handle.0, err).await;
|
||||
}
|
||||
StreamItem::UnknownCommand(cmd) => {
|
||||
let Some(raw) = rawcmd::parse(cmd.data().packet().content()) else { return };
|
||||
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 };
|
||||
if rawcmd::is_stream_notification(&raw.name) {
|
||||
// Payloads (SDP/ICE/tokens) are never logged.
|
||||
debug!(name = %raw.name, entries = raw.items.len(), "stream notification");
|
||||
@@ -1057,6 +1095,12 @@ 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;
|
||||
@@ -1075,7 +1119,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)))
|
||||
self.emit_state("connecting", Some(&address), Some(ErrorObj::new(ErrorCode::NotConnected, msg)), None)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
@@ -1105,6 +1149,8 @@ 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 {
|
||||
@@ -1134,10 +1180,13 @@ impl Session {
|
||||
info!(own_client = ?own_id, "connected");
|
||||
self.emit_snapshot().await;
|
||||
self.emit_audio_state().await;
|
||||
self.emit_state("connected", Some(&address), None).await;
|
||||
self.emit_state("connected", Some(&address), None, 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;
|
||||
@@ -1145,7 +1194,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)) {
|
||||
if self.conn.as_ref().is_some_and(|c| c.files.owns_handle(handle) || c.s3_receipts.contains_key(&handle)) {
|
||||
self.files_result(handle, res).await;
|
||||
return;
|
||||
}
|
||||
@@ -1177,11 +1226,13 @@ impl Session {
|
||||
Err(e)=>self.out.err(&req,e).await,
|
||||
}
|
||||
},
|
||||
Pending::MenuRead { req, target, rows, .. } => match res {
|
||||
Pending::MenuRead { req, target, response, 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(|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,
|
||||
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,
|
||||
Err(e)=>self.out.err(&req,e).await,
|
||||
},
|
||||
},
|
||||
@@ -1328,7 +1379,7 @@ impl Session {
|
||||
self.out.err(r, err).await;
|
||||
}
|
||||
self.tx.encoder = None;
|
||||
self.emit_state("disconnected", Some(&c.address), reason).await;
|
||||
self.emit_state("disconnected", Some(&c.address), reason, Some(&c.phase)).await;
|
||||
if let Some((r, v)) = respond {
|
||||
self.out.ok(&r, v).await;
|
||||
}
|
||||
@@ -1452,8 +1503,8 @@ impl Session {
|
||||
async fn tx_frame(&mut self, frame: &CapturedFrame) {
|
||||
if !self.audio_in.validate(frame) { return; }
|
||||
let whisper = frame.whisper;
|
||||
// Capture queued before push-to-whisper must not escape to the ordinary channel.
|
||||
if whisper.is_none() && self.whisper.active_epoch().is_some() {
|
||||
// Neither stale whisper audio nor pre-whisper ordinary audio may alter the current spurt.
|
||||
if whisper != self.whisper.active_epoch() {
|
||||
return;
|
||||
}
|
||||
self.tx.burst_open = true;
|
||||
@@ -1598,11 +1649,9 @@ impl Session {
|
||||
if c.connected() {
|
||||
let end = match spurt {
|
||||
None => Some(audio::end_of_voice(enc.codec())),
|
||||
// A cleared route has nobody left to tell.
|
||||
Some(epoch) => self
|
||||
.whisper
|
||||
.route_mut(epoch, c.generation)
|
||||
.filter(|r| !r.is_empty())
|
||||
// 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))
|
||||
.map(|r| audio::end_of_whisper(enc.codec(), r)),
|
||||
};
|
||||
if let Some(end) = end {
|
||||
@@ -1688,6 +1737,14 @@ 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),
|
||||
@@ -1708,3 +1765,113 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+80
-14
@@ -31,8 +31,6 @@ 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
|
||||
@@ -67,10 +65,8 @@ struct ChannelExtra {
|
||||
impl ChannelExtra {
|
||||
fn merge(&mut self, item: &BTreeMap<String, String>) {
|
||||
for (key, value) in item {
|
||||
if key.starts_with("channel_") || matches!(key.as_str(), "cid" | "cpid") {
|
||||
if key == "cid" || (key.starts_with("channel_") && key != "channel_order") {
|
||||
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") {
|
||||
@@ -159,9 +155,14 @@ 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 }
|
||||
/// 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)
|
||||
/// 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))
|
||||
}
|
||||
/// myTeamSpeak avatar URLs of a client (`(variant, url)`), empty if none.
|
||||
pub fn client_myts_avatars(&self, client_id: u16) -> &[(u32, String)] {
|
||||
@@ -198,13 +199,11 @@ 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;
|
||||
}
|
||||
@@ -222,14 +221,22 @@ 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::default();
|
||||
let mut e = ClientExtra { channel: shared_channel, ..ClientExtra::default() };
|
||||
e.merge(item);
|
||||
self.clients.insert(clid, e);
|
||||
changed = true;
|
||||
@@ -478,6 +485,7 @@ 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,
|
||||
@@ -501,8 +509,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": extras.capability_extensions,
|
||||
"features": server_features(extras.capability_extensions.as_deref()),
|
||||
"capability_extensions": extensions,
|
||||
"features": server_features(extensions),
|
||||
},
|
||||
"own_client_id": own,
|
||||
"own_channel_id": own_channel,
|
||||
@@ -518,6 +526,64 @@ 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,6 +478,46 @@ 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,20 +10,19 @@ 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> {
|
||||
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 })),
|
||||
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");
|
||||
}
|
||||
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");
|
||||
|
||||
+26
-5
@@ -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) {
|
||||
for c in view.clients.iter().filter(|c| c.channel == channel && c.uid.is_some_and(|uid| !uid.is_empty())) {
|
||||
ids.client(c.id);
|
||||
}
|
||||
}
|
||||
@@ -528,10 +528,13 @@ 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 || group_id.is_empty() || group_id == "0" {
|
||||
if server_uuid.is_empty() || *server_uuid != view.server_uid {
|
||||
return Err(invalid_list("group whisper list targets another server or no group"));
|
||||
}
|
||||
group_id.parse::<u64>().map_err(|_| invalid_list("group id is not a number"))?
|
||||
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()
|
||||
} else {
|
||||
// Protocol: the id is ignored for channel commander / all clients (ts3protocol.md).
|
||||
0
|
||||
@@ -541,8 +544,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 expected = r.uid.as_deref().map(uid_bytes);
|
||||
if view.client(r.id).is_some_and(|c| c.uid == expected.as_deref()) {
|
||||
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)) {
|
||||
ids.client(r.id);
|
||||
}
|
||||
}
|
||||
@@ -797,6 +800,12 @@ 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" })));
|
||||
}
|
||||
@@ -821,6 +830,18 @@ 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,6 +99,36 @@ 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");
|
||||
@@ -230,7 +260,21 @@ 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"}),
|
||||
@@ -246,6 +290,8 @@ 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}),
|
||||
@@ -260,6 +306,350 @@ 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");
|
||||
|
||||
+26
-1
@@ -33,13 +33,38 @@ 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, message: "private".into() }).await.unwrap_err();
|
||||
expected_client_uid: None, expected_channel_id: 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
+22
-3
@@ -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` 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.
|
||||
- `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.
|
||||
|
||||
### Local modifications
|
||||
|
||||
@@ -41,6 +41,7 @@ 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/`
|
||||
|
||||
@@ -51,3 +52,21 @@ 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,6 +209,13 @@ 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
@@ -0,0 +1,172 @@
|
||||
# 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
@@ -0,0 +1,28 @@
|
||||
[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
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+3
-1
@@ -1,4 +1,6 @@
|
||||
MIT License
|
||||
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
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
# 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
@@ -0,0 +1,10 @@
|
||||
# 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
@@ -0,0 +1,294 @@
|
||||
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
@@ -0,0 +1,62 @@
|
||||
//! `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
@@ -0,0 +1,48 @@
|
||||
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());
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+124
-33
@@ -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.
|
||||
Unknown argument keys are rejected (`bad_request`).
|
||||
Explicit `null`, positional arrays and 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 answered a command with an error (`ts_error` set) |
|
||||
| `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) |
|
||||
| `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.
|
||||
- `server_password`: optional string.
|
||||
- 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.
|
||||
- `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,6 +198,8 @@ 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
|
||||
@@ -205,12 +207,13 @@ pending connect attempt was abandoned. `not_connected` if idle. Emits
|
||||
|
||||
### 4.6 `join_channel` — `{channel_id: number, password?: string}`
|
||||
|
||||
Moves self (`clientmove`). Result `{}` after the server confirms; snapshot follows.
|
||||
Moves self (`clientmove`). A zero channel ID returns `bad_request` before checking the connection or sending anything. Result `{}` after the server confirms; snapshot follows.
|
||||
|
||||
### 4.7 `send_text` — `{target: "channel"|"server"|"client", client_id?: number, expected_client_uid?: string, message: string}`
|
||||
### 4.7 `send_text` — `{target: "channel"|"server"|"client", client_id?: number, expected_client_uid?: string, expected_channel_id?: number, 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.
|
||||
@@ -222,6 +225,9 @@ 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)
|
||||
@@ -260,12 +266,19 @@ 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
|
||||
@@ -295,7 +308,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.
|
||||
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.
|
||||
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}`.
|
||||
@@ -325,6 +338,8 @@ 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:
|
||||
|
||||
@@ -341,6 +356,7 @@ 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>`).
|
||||
|
||||
@@ -351,6 +367,7 @@ 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}`
|
||||
@@ -369,7 +386,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` |
|
||||
| `stream_stop` | only `stream_id` | `stopstream id reason=1` (publisher left) |
|
||||
| `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` |
|
||||
|
||||
@@ -498,7 +515,12 @@ 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`
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -514,17 +536,48 @@ 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` 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.
|
||||
**`file_list`: status and data**
|
||||
|
||||
**`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.
|
||||
- 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.
|
||||
|
||||
**`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.
|
||||
**`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.
|
||||
|
||||
**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.
|
||||
@@ -537,7 +590,8 @@ Remote paths are UTF-8, start with `/`, are at most 512 characters, and every co
|
||||
- `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`.
|
||||
|
||||
**Transfers**
|
||||
**Legacy TCP 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`.
|
||||
@@ -556,10 +610,27 @@ Remote paths are UTF-8, start with `/`, are at most 512 characters, and every co
|
||||
- A grant that arrives after the cancel is dropped and stopped.
|
||||
- Progress is emitted at most every 250 ms while bytes move.
|
||||
|
||||
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.
|
||||
**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.
|
||||
|
||||
### `file_transfer` (event)
|
||||
|
||||
@@ -567,7 +638,10 @@ Not implemented (explicit limits):
|
||||
|
||||
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/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 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 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.
|
||||
|
||||
@@ -594,18 +668,26 @@ 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 own channel-created event |
|
||||
| `channel_edit` | `{generation,channel_id,properties}` |
|
||||
| `channel_move` | `{generation,channel_id,parent_id,order?}` |
|
||||
| `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_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}` |
|
||||
| `channel_list` / `channel_info` | `{}` / `{channel_id}`; observed channel wire properties, info refreshes description |
|
||||
| `client_info` | `{client_id,uid}`; checks current UID, requests `clientgetvariables` |
|
||||
| `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. |
|
||||
| `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 |
|
||||
@@ -615,7 +697,7 @@ Every mutation below is answered only after its real server command result. Perm
|
||||
| `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; → `{token}` |
|
||||
| `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_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 |
|
||||
@@ -624,12 +706,12 @@ Every mutation below is answered only after its real server command result. Perm
|
||||
| `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}`; rows with `cluid/cldbid` |
|
||||
| `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. |
|
||||
| `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}`; missing/ambiguous resulting ID fails with created detail |
|
||||
| `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_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}]}` |
|
||||
@@ -650,9 +732,13 @@ 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. 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.
|
||||
`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.
|
||||
|
||||
### Local recording (`recording_*`)
|
||||
|
||||
@@ -671,6 +757,8 @@ 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.
|
||||
@@ -698,6 +786,9 @@ 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,4 +1,79 @@
|
||||
# TeamsPeach selector → official TeamSpeak 6 source map (visual cutover, 2026-11-01)
|
||||
# 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)
|
||||
|
||||
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` =
|
||||
|
||||
+349
-124
@@ -1,154 +1,379 @@
|
||||
# Мобильный порт: архитектура и ограничения
|
||||
# Оценка мобильного порта TeamsPeach: Android и iOS
|
||||
|
||||
Актуально на **2026-11-15**. Device-база `8074343` / APK4955; TX-кандидат прошёл CI4959, но headset TX не принят.
|
||||
Room UI `87265a3` прошёл CI4972; уточнения кандидата и device-проверки — в [handoff](mobile-port-progress.md).
|
||||
Этот документ — карта действующей системы, не история расследований.
|
||||
Предел: 200 строк / 16 KiB; обновлять разделы, а не дописывать каждый запуск CI.
|
||||
## Актуализация: native-only cutover, 2026-11-10
|
||||
|
||||
## 1. Архитектура
|
||||
По прямому решению владельца удаляется Electron-клиент, npm manifests и его browser-only tooling. Единственный application host — Rust/Slint в `native/`; core подключается как Rust-библиотека. Это архитектурное переключение, не утверждение о пройденной мобильной приёмке.
|
||||
|
||||
| Граница | Реализация и ответственность |
|
||||
- Сохраняются `core::runtime`, нативный CPAL/Sonora/Opus аудиотракт, Slint UI, Android/iOS OS adapters и безопасный импорт прежних профилей.
|
||||
- Ресурсы клиента переходят в `native/resources/`, версия и команды сборки — Cargo/xtask. Renderer-only WASM ABI и npm/Electron packaging больше не являются частью продукта.
|
||||
- Текущие команды и build prerequisites см. в [README](../README.md), результаты последней проверки — в [передаче состояния](mobile-port-progress.md). Исследовательский запрет первой стадии не относится к отдельно разрешённому cutover.
|
||||
- Прежние выводы о двух действующих hosts и выборе между ними ниже **исторические**. Rust/Slint теперь выбранная архитектура; Android/iOS runtime, interruption resume, Bluetooth и лицензионные вопросы по-прежнему требуют отдельных доказательств.
|
||||
- Весь исходный разбор ниже сохранён как снимок `eb24965076599267687c8c4dd6f24f22953b15f6`; source citations закреплены за этой ревизией, включая удалённые файлы. Не использовать старые npm-команды и Electron passes для текущего дерева.
|
||||
|
||||
---
|
||||
|
||||
## Исторический первичный разбор
|
||||
|
||||
## 1. Ревизия, метод и границы доказательства
|
||||
|
||||
- **Дата исследования:** 2026-11-10 (UTC).
|
||||
- **Репозиторий:** TeamsPeach/client; публичный адрес указан в [AboutService](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/services/about.rs#L10-L12).
|
||||
- **Изученный HEAD:** `eb24965076599267687c8c4dd6f24f22953b15f6`, ветка `main`.
|
||||
- **Исходное рабочее дерево:** чистое по `git status --porcelain=v1`; 2221 tracked-файл. Корень и разрешённые выходные каталоги проверены по метаданным; среди tracked-путей не обнаружено symlink/junction/reparse points.
|
||||
- **Вопрос:** что реально можно переиспользовать для одинакового по функциям клиента Android/iOS, какие OS-адаптеры уже существуют и что нужно проверить до выбора окончательного UI и начала реализации.
|
||||
- **Охват:** Electron reference-клиент, Rust `core/`, `dsp/`, `native/`, Android/iOS hosts, build/CI/test recipes; точечно — манифесты, provenance и значимые локальные изменения vendored-зависимостей. История коммитов и пользовательские профили не исследовались.
|
||||
- **Исключено:** значения секретов, `.env*`, приватные ключи и identity-файлы, runtime-хранилища, бинарные ресурсы, массовое чтение стороннего vendor, запуск приложения, сборок, установочных скриптов и тестов. Наличие кода хранилища `secrets.rs` не означает чтение самого хранилища.
|
||||
- **Метод:** первичное статическое картирование установленным Understand-Anything; затем отдельные трассировки Codebase Knowledge Builder. Существенные выводы основаны на исходниках, не на графе. Официальные документы зависимостей проверены отдельно, ссылки — в §8 и §9.
|
||||
- **Обозначения:** **Факт** — непосредственно наблюдается в коде/конфигурации или официальной документации; **Вывод** — инженерная интерпретация с основанием; **Неизвестно** — нужен отсутствующий результат сборки, запуска, измерения или правовое разрешение; **План** — предлагаемая работа, не выполненная реализация.
|
||||
- Ссылки `../path#Lx-Ly` относятся к указанному HEAD. Локальный Markdown viewer может не поддерживать line anchors; путь, символ и номера строк остаются координатами доказательства.
|
||||
|
||||
**Ни статический разбор, ни граф, ни наличие теста не доказывают работоспособность на телефоне. В этой сессии нет результатов Android/iOS-сборки, подключения к серверу или голосового обмена.**
|
||||
|
||||
## 2. Главный вывод
|
||||
|
||||
**Факт:** это уже не только Electron-приложение. В репозитории сосуществуют Electron reference-клиент и существенная Rust/Slint-реализация с Android/iOS-платформенными мостами. `native` зависит от `teamspeach-core` как Rust-библиотеки; Android использует `cdylib`/`android_main`, iOS — Rust executable и Winit/Skia. См. [workspace](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/Cargo.toml#L1-L41), [native manifest](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/Cargo.toml#L8-L30), [mobile target dependencies](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/Cargo.toml#L82-L100), [entry points](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/lib.rs#L115-L125), [iOS project](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/ios/project.yml#L50-L74).
|
||||
|
||||
**Вывод:** исходная стратегия — не переписывать клиент с нуля, а сначала проверить существующее embedded Rust-ядро и мобильную ветку. Наименьший объём новой архитектуры даёт продолжение Rust/Slint **при условии** прохождения сборочных, аудио-, accessibility- и лицензионных гейтов. Это рекомендация после установления границ ядра, а не заранее выбранный UI.
|
||||
|
||||
**Факт:** `native/compatibility.json` прямо обозначен как pending acceptance inventory, а не реестр работающих функций; 718 пунктов не являются 718 пройденными проверками. [Статус и ограничения](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/compatibility.json#L1-L36). README также называет native migration незавершённой: [README](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/README.md#L22-L26).
|
||||
|
||||
**Основные препятствия:**
|
||||
|
||||
1. Нет мобильного completed-build record в `native/native-deps.lock.json#/builds`: на момент чтения там только `x86_64-pc-windows-msvc`. Штатный `xtask build` откажет без per-target provenance: [deps::verify](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L729-L747).
|
||||
2. Штатный source-build требует Linux для Android и macOS для iOS; текущая Windows-среда не подходит для этих маршрутов: [Target::check_host](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L28-L50).
|
||||
3. В цепочке восстановления iOS аудиосессии найден незадействованный `CallLease::resume`; общий обработчик окончания interruption сам не восстанавливает output. Подробности и оговорки — §7.
|
||||
4. Не подтверждены двусторонний голос, AEC, Bluetooth, фон, сетевой handoff и доступность интерфейса на физических телефонах.
|
||||
5. Для распространения нет предоставленной open-source лицензии собственного кода; у заимствованных иконок и звуков не установлены права на redistribution: §9.
|
||||
|
||||
## 3. Архитектура и реальные границы повторного использования
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
N1["Electron UI и AudioWorklet"] --> N2["preload и Electron main"]
|
||||
N2 -->|"JSON-lines и PCM base64"| N3["core CLI stdio"]
|
||||
N4["Общий Slint UI"] -->|"типизированные намерения"| N5["AppRuntime и ConnectionManager"]
|
||||
N6["Android / iOS lifecycle"] --> N5
|
||||
N5 -->|"CoreHandle / Command"| N7["Session и протокол TeamSpeak"]
|
||||
N3 --> N7
|
||||
N8["CPAL и Sonora DSP"] -->|"CapturedFrame"| N5
|
||||
N7 -->|"decoded PCM"| N8
|
||||
N7 <-->|"TeamSpeak UDP / Opus"| N9["Сервер TeamSpeak"]
|
||||
N10["WebRTC peers трансляций"] -->|"декодированное аудио"| N8
|
||||
```
|
||||
|
||||
Основания: [core embedded API](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L7-L26), [spawn](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L81-L138), [AppRuntime](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/lib.rs#L43-L110), [AudioSessionBinding](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/media_binding.rs#L18-L65), [Electron IPC](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/main/main.js#L498-L548), [отдельный WebRTC peer](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/stream/peer.rs#L45-L56).
|
||||
|
||||
| Компонент | Что подтверждено | Решение для мобильного клиента |
|
||||
|---|---|---|
|
||||
| `core::runtime::{CoreHandle,CoreEvents}` | `request(Command)`, `push_audio(CapturedFrame)`, control/playback receivers, управляемое shutdown; один worker/current-thread Tokio runtime на core. [API](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L44-L78), [spawn](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L81-L138) | **Переиспользовать.** Это существующая граница без UI и stdio; не нужно делать subprocess на телефоне. |
|
||||
| `Session`, `protocol`, identity, channels, Opus/VAD | Общие для двух хостов; OS capture находится вне Session. [lib modules](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/lib.rs#L1-L28), [connect/join](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L505-L632) | **Переиспользовать с проверкой cross-build.** Сам crate не целиком platform-free: содержит desktop hotkeys/app-audio, файловую работу и нативный Opus. |
|
||||
| `ConnectionManager` | До 8 соединений, отдельные `SessionKey`, выбранный input owner, capture permit после подтверждений core. [типы](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/connections.rs#L23-L108), [input acknowledgement](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/connections.rs#L503-L539) | **Переиспользовать.** Видимая вкладка не должна неявно менять получателя микрофона. |
|
||||
| `native` app/services | Shared runtime, snapshots, intents; UI generation отделён от process runtime. [AppRuntime](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/lib.rs#L43-L103) | **Переиспользовать**, проверить storage/lifecycle/platform policy. Наличие ссылок на типы `ui::shell` означает, что app layer ещё не отдельный UI-neutral FFI SDK. |
|
||||
| Sonora capture DSP, VAD, mixer, SRC | Rust-обработка отделена от device callback; 10/20-мс блоки, временные метки и epochs. §6 | **Переиспользовать**, но измерить CPU, drift, reference и акустическое качество на ARM64. |
|
||||
| CPAL devices, Android/iOS audio session | Есть native device abstraction и OS callbacks. [hosts](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/devices.rs#L89-L110), [lifecycle](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/lifecycle.rs#L5-L32) | **Адаптеры уже есть; требуется доведение и проверка**, а не замена всего аудиоядра. |
|
||||
| Slint UI | Общие `.slint` и Rust projections, platform-specific backend dependencies. [manifest](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/Cargo.toml#L82-L96), [binding](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/ui/application.rs#L31-L69) | **Первый кандидат на сохранение.** Функциональная и визуальная идентичность Android/iOS должна быть проверена сценарием, не выводится из общего исходника. |
|
||||
| Electron main/preload/stdio transport | Зависит от Electron/Node, BrowserWindow, IPC, child process. [package](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/package.json#L5-L26), [CoreProcess](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/main/core-process.js#L169-L214) | **Заменить хост**, уже имеющимся native runtime. Не переносить Electron на Android/iOS. |
|
||||
| HTML/CSS/JS reference UI | DOM и браузерные API; логика взаимодействия распределена по UI и main. [voice](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/voice.js#L129-L191), [capture](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/audio/engine.js#L279-L399) | Использовать как **reference поведения**, тексты/схемы — после проверки лицензии и эквивалентности. Не обещать прямой перенос DOM в Flutter/React Native. |
|
||||
| Desktop OS-сервисы | rfd/arboard/open/tray отделены target cfg; Linux DBus/X11, Windows APIs и desktop capture. [dependencies](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/Cargo.toml#L65-L96), [platform modules](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/mod.rs#L1-L12), [core OS deps](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/Cargo.toml#L37-L61) | **Заменить OS-эквивалентами:** SAF/document picker, Keystore/Keychain, notification/service, touch PTT. Не имитировать tray/autostart/global hooks на мобильных. |
|
||||
| WebRTC screenshare | Отдельные media peers, не транспорт основного TS-голоса; default native features включают `webrtc`. [features](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/Cargo.toml#L16-L20), [provenance](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/vendor/provenance.json#L170-L179) | Для полной версии сохранить отдельную проверочную очередь. Для первого voice proof **не реализовывать новый WebRTC-голос**; минимизация feature set возможна только как явно проверяемый эксперимент. |
|
||||
|
||||
### UI-решение после границы ядра
|
||||
|
||||
| Вариант | Что сохраняет | Что добавляет / риск | Условие выбора |
|
||||
|---|---|---|---|
|
||||
| Продолжить Rust/Slint | Core, app/services, PCM-тракт, большая часть UI, existing Android/iOS hosts | Зависимость от мобильной зрелости Slint, custom accessibility, лицензия и тяжёлая native сборка | **Рекомендуемый первый прототип**, если проверены реальные UI/audio/lifecycle сценарии. |
|
||||
| Flutter или React Native поверх Rust | Core и DSP; часть app/services после отделения UI-типов | Новый FFI/async-event ABI, UI-переписывание, владение Rust runtime и платформенные плагины; DOM не становится переносимым автоматически | Только если установлен конкретный непреодолимый недостаток текущего UI, а не ради популярности стека. Поддержка конкретного bridge ещё **не исследована**. |
|
||||
| Kotlin/Swift UI поверх Rust | Core/DSP и явные OS-интеграции | Два presentation слоя и риск расхождения UX; та же необходимость стабильного FFI | Если системная интеграция/accessibility перевешивает цену двух UI. Сейчас нет доказательства такой необходимости. |
|
||||
|
||||
**План паритета:** Android и iOS должны иметь общий каталог действий, ошибок, mute/PTT-состояний, экранов и EN/RU-текстов, общие серверные сценарии и одинаковую семантику подтверждений. System permission dialogs, маршрутизация и фон будут различаться по OS; «идентичная версия» не означает невозможное равенство системных окон. Никакие функции полной версии не исключаются молча: ограничения требуют явной записи и решения владельца.
|
||||
|
||||
## 4. Стек, входы, сборка и тесты
|
||||
|
||||
### Подтверждённый стек
|
||||
|
||||
- Cargo workspace: `core`, `dsp`, `native`, `xtask`; версия приложения `0.1.7`; Rust toolchain `1.96.0`, workspace edition 2024, core edition 2021. [workspace](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/Cargo.toml#L1-L24), [toolchain](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/rust-toolchain.toml#L1-L4), [core](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/Cargo.toml#L1-L18).
|
||||
- Electron `44.9.3`, plain JavaScript/HTML/CSS, electron-builder `26.15.3`, Playwright tooling. [package.json](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/package.json#L5-L26).
|
||||
- Slint `1.18.1`, CPAL `0.18.2`, Rubato `5.0.1`, Sonora `0.2.0`, libwebrtc `0.4.0`, webrtc-sys `0.3.53`; локальные patches перечислены в workspace. [pins](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/Cargo.toml#L17-L41). Core использует audiopus `0.3.0-rc.0`, earshot `1.2.2`, vendored tsclientlib с pinned upstream `ee3bc6…`. [core deps](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/Cargo.toml#L14-L35).
|
||||
- Android: API 26+, compile/target 36, NDK `28.2.13676358`, Java 17, AGP `8.10.1`, ARM64 production и x86_64 emulator. [Gradle](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/build.gradle.kts#L5-L43).
|
||||
- iOS/iPadOS: deployment target 16.0, ARM64 device и ARM64 simulator, XcodeGen host + ReplayKit extension. [project](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/ios/project.yml#L1-L26), [supported targets](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L28-L43).
|
||||
|
||||
### Точки входа
|
||||
|
||||
| Путь / символ | Роль |
|
||||
|---|---|
|
||||
| Клиент | Rust/Slint `native/`; UI отправляет typed intents, не выполняет device/network I/O |
|
||||
| Протокол | Embedded `core::runtime`; TeamSpeak UDP/Opus для голоса |
|
||||
| Трансляции | Отдельный libwebrtc тракт; не замена TeamSpeak-голосу |
|
||||
| Сервисы | `native/src/app/runtime/`, `native/src/services/`: профиль, разрешения, соединения, настройки |
|
||||
| Аудио | `native/src/media/audio/`: CPAL callback → bounded rings → worker/SRC/DSP |
|
||||
| Android | `native/src/platform/android.rs` + `platform/android/.../mobile/` Java bridges; AAudio backend |
|
||||
| iOS | Существующий платформенный адаптер; требует отдельной macOS/Xcode/signing/device проверки |
|
||||
| Сборка | Cargo/`xtask`; Android workflow `.gitea/workflows/android.yml` |
|
||||
| [app/main/main.js](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/main/main.js#L498-L548), `package.json.main` | Electron composition root и проверяемый IPC. |
|
||||
| [core/src/main.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/main.rs#L1-L40), [core/src/stdio.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/stdio.rs#L101-L114) | CLI/stdio host; не требование мобильного embedded runtime. |
|
||||
| [core/src/runtime.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L81-L138), `spawn` | Типизированный embedded host с command/control/playback очередями. |
|
||||
| [native/src/main.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/main.rs#L8-L29), `run` | Desktop/iOS executable; `AppRuntime::start(...).and_then(attach_ui)`. |
|
||||
| [native/src/lib.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/lib.rs#L123-L125), `android_main` | Android library entry через Slint Android backend. |
|
||||
| [native/build.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/build.rs#L1-L8) | Компиляция `.slint` и platform glue; **не запускался**. |
|
||||
| [xtask/src/main.rs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/main.rs#L25-L68) | `deps`, `build`, `package`, `smoke`, `verify-package`; **не запускались**. |
|
||||
|
||||
Electron/Node/npm удалены. Не возвращать второй host или параллельный стек.
|
||||
Версия — Cargo workspace; ресурсы — `native/resources/`; toolchain/dependency pins —
|
||||
`rust-toolchain.toml`, `.gitea/android-ci-tools.json`, `native/native-deps.lock.json`.
|
||||
### Сборочные ограничения
|
||||
|
||||
## 2. Что действительно проверено
|
||||
**Факт:** старый Electron recipe строит core и DSP WASM, затем запускает Electron: [README development](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/README.md#L12-L26). Он не создаёт APK/IPA.
|
||||
|
||||
- Windows0.1.7: владелец принял connect, channel join и двусторонний голос. База — `main`,
|
||||
`desktop-baseline-0.1.7-20261111`. Поздние мобильные изменения не равны новой Windows-приёмке.
|
||||
- Android: реальные Linux CI builds, ARM64 APK, установка и запуск на TECNO KJ7.
|
||||
- Обычный Android voice ранее принят на `f403dd5` / run4931; фон Home/screen-off принят отдельно.
|
||||
- На **4955** владелец подтвердил **RX через G435**. TX при headset unmute ещё ломается;
|
||||
успешные host fixtures не доказывают физический duplex.
|
||||
- Два независимых мобильных input/output-селектора стоят рядом. Unified combination picker отменён.
|
||||
- Полный функциональный parity, реальный Wi-Fi↔cellular handover, длительный endurance, iOS и
|
||||
повторный вход после Recents не считать принятыми. Длительность — наблюдение обычного использования.
|
||||
**Факт:** native recipe source-build-only: `xtask deps` provision-ит pinned WebRTC, `build` проверяет provenance и устанавливает `LK_CUSTOM_WEBRTC`; тихой загрузки случайного prebuilt нет. [deps policy](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L1-L19), [verify](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L729-L747), [build](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/build_native.rs#L238-L307). Для Android нужны SDK36/NDK r28+, JDK и Linux source-build host; для iOS — macOS/Xcode SDK. [prerequisites](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/build_native.rs#L170-L198). iOS на данной Windows-машине штатным маршрутом не собирается; Android также требует другого build host, хотя Android вообще не ограничен Linux вне этого recipe.
|
||||
|
||||
## 3. Аудиотракт и инварианты
|
||||
**Факт:** `.cargo/config.toml` принуждает static bundled Opus/CMake. WebRTC имеет свой Opus; `namespace_opus` специально разделяет символы, чтобы линкер не выбирал случайную реализацию. [Opus flags](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.cargo/config.toml#L1-L9), [изоляция символов](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L464-L468). Android также требует согласованный prefixed `libwebrtc.jar` и ARM64 ELF alignment 16 KiB. [Gradle input gates](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/build.gradle.kts#L61-L74), [binary gates](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/build_native.rs#L274-L322).
|
||||
|
||||
### Владение и данные
|
||||
**Неизвестно:** доступность SDK, source-build artifacts, signing, физического Android/iPhone и Mac/Linux host для следующего этапа. Секреты signing не читались, подключённые устройства не опрашивались. Единственный Windows record в lock — не гарантия наличия даже его локальных бинарников и тем более не доказательство мобильной сборки.
|
||||
|
||||
- Core voice boundary: mono `i16`,48kHz,960 samples/20ms. Native mixer/DSP работают блоками10ms.
|
||||
- `engine.rs::Worker` обслуживает PCM; `lifecycle.rs` отдельно владеет CPAL construct/start/drop,
|
||||
тяжёлой подготовкой DSP и уведомлений. `StreamOwner` не переносится между потоками.
|
||||
- `devices.rs` callbacks используют готовые буферы и bounded rings, без I/O/выделений в нормальном пути.
|
||||
- `resample.rs` выполняет SRC и отслеживание аппаратных часов. Hardware timestamps не заменять
|
||||
временем worker; реальные пропуски/реверсы кадров не скрывать автосбросом.
|
||||
- Sonora — владелец AEC/NS/AGC capture. Reference берётся из реально записанного выходного PCM;
|
||||
не добавлять второй AEC поверх него без отдельного проектного решения.
|
||||
### Команды, найденные или выведенные из существующих test entry points
|
||||
|
||||
### Разрешения и приватность
|
||||
Все команды ниже — **справка для следующего разрешённого этапа; не выполнены**.
|
||||
|
||||
- Разрешение ОС само не включает запись. Нужны текущий владелец, acknowledged CapturePermit,
|
||||
поколение/epoch, явное намерение и допустимое состояние focus/lifecycle.
|
||||
- Более поздний mute, revocation, permission loss или завершение звонка всегда сильнее позднего ACK.
|
||||
- Не перепривязывать старый PCM к новому epoch, не проигрывать старую очередь после восстановления.
|
||||
- Удаление из Recents завершает call/capture; нет sticky restart. Home/screen-off сохраняют уже
|
||||
разрешённый обычный звонок, но отпускают PTT/whisper holds.
|
||||
- Точный выбор устройства не заменять default/другим устройством молча. Capability failure явный.
|
||||
| Команда | Что проверяет / ограничение | Основание |
|
||||
|---|---|---|
|
||||
| `npm test` | Node tests `test/*.test.*`; часть desktop-path tests использует Electron/harness, не mobile proof | [package scripts](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/package.json#L10-L21), [CI](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.gitea/workflows/ci.yml#L45-L71) |
|
||||
| `cargo test --manifest-path core/Cargo.toml --locked` | Core unit/integration: protocol, identity, audio, embedded runtime | [CI](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.gitea/workflows/ci.yml#L53-L63), [embedded](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/tests/embedded.rs#L16-L57), [runtime_failures](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/tests/runtime_failures.rs#L40-L111) |
|
||||
| `cargo test --manifest-path dsp/Cargo.toml --locked` | DSP tests, не акустика реального speakerphone | [CI](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.gitea/workflows/ci.yml#L45-L48), [capture tests](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/dsp/src/capture/tests.rs#L34-L145) |
|
||||
| `cargo test -p teamspeach-native --test connections --locked` | Offline identity/session/generation ownership; требуется native build environment | [connections tests](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/tests/connections.rs#L37-L145) |
|
||||
| `cargo test -p teamspeach-native --test audio_binding --locked` | Подтверждения input reset и корректное освобождение audio/manager | [audio_binding](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/tests/audio_binding.rs#L6-L36) |
|
||||
| `cargo run -p xtask -- smoke --target <triple> --scenario offline-ui --device <explicit-id> --app <test-app> --out <fresh-dir>` | Имеющийся mobile smoke: Android выбранный APK/device; iOS выбранный simulator. Не живой голос | [CLI](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/main.rs#L35-L49), [Android/iOS smoke](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/smoke.rs#L61-L103) |
|
||||
|
||||
### Принятый Android RX — сохранять
|
||||
Штатный smoke требует `test-harness` build, запрещает network/OS actions/physical capture в отчёте; `media-loopback` не равен live TeamSpeak interoperability. [guards](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/smoke.rs#L13-L49). `codec-fixtures` CLI прямо не выполняется на Android/iOS: [mobile rejection](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/smoke.rs#L104-L106). CI в просмотренном workflow покрывает Linux x64 и GNU ARM64/qemu, **не Android и не iOS**: [jobs](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.gitea/workflows/ci.yml#L16-L20), [ARM job](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/.gitea/workflows/ci.yml#L81-L130).
|
||||
|
||||
- Голосовой выход использует VOICE_COMMUNICATION/SPEECH на API28+; отдельные notification streams — MEDIA.
|
||||
- API26 остаётся minimum: дополнительные AAudio symbols разрешаются динамически через vendored
|
||||
`ndk0.9` borrowed-pointer accessors. На26/27 явно остаётся LegacyMediaDefault.
|
||||
- AAudio `play()` требует Started и аппаратный output timestamp до публикации потока.
|
||||
Во время получения timestamp — тишина; бюджет старта2s, без ложного перехода now→hardware time.
|
||||
Startup xrun baseline отделён от новых live xruns; последующие faults не замалчиваются.
|
||||
- Android проверяет исходную свежесть PCM при передаче в callback, не добавляя downstream Bluetooth
|
||||
latency к сроку200ms. Epoch/mute/queue guards сохраняются; desktop presentation policy прежняя.
|
||||
- Начало switch/CLEAR, OS callbacks и caller recovery согласуются по ревизиям; startup ACK не
|
||||
возвращает отозванный focus. Ошибка playback не должна называться ошибкой микрофона.
|
||||
## 5. Подключение, авторизация, каналы и сеть
|
||||
|
||||
## 4. Текущая проблема TX и неподтверждённая правка
|
||||
### Нормальный путь — подтверждён по исходникам
|
||||
|
||||
### Наблюдения владельца и устройства
|
||||
1. **UI → host.** Electron `submitConnect/connectTo` → IPC allowlist → `ConnectionManager.request` → `CoreProcess.request`/stdin. Native Slint intent → AppRuntime worker → `connect_with_audio` → embedded `Command::Connect`. [Electron](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/app.js#L699-L766), [IPC](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/main/main.js#L498-L521), [native](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/local_actions/connections.rs#L42-L79).
|
||||
2. **Identity вместо облачной учётной записи.** `Store::open_for_connect` выбирает identity/default и nickname, удерживает use-lock. Создание P-256 identity и security-level work — локальные операции; пароль сервера/канала не заменяет identity. [Store](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/profile.rs#L665-L708), [улучшение](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/profile.rs#L765-L783). Runtime-профили и приватные ключи не открывались.
|
||||
3. **Session::connect** передаёт identity, nickname, mute state, пароли и initial channel в `Connection::build`; автоматическое unbounded повышение security level отключено. [connect](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L505-L581), [bounded task](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/identity_improve.rs#L26-L61).
|
||||
4. **TeamSpeak transport.** Vendored библиотека разрешает адрес, создаёт UDP socket, делает tsproto handshake, отправляет `clientinit`, ждёт `initserver`. Это не WebSocket/REST и не WebRTC voice. [transport](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/tsclientlib/src/lib.rs#L461-L605). Resolver также имеет TS DNS/TCP и nickname lookup/HTTPS: [resolver](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/tsclientlib/src/resolver.rs#L72-L84), [DNS](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/tsclientlib/src/resolver.rs#L203-L217).
|
||||
5. **Connected подтверждается событием**, затем `channelsubscribeall`, snapshot/audio/state и reply исходному request. [Session events](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L1105-L1144).
|
||||
6. **Вход в канал:** `Session::join_channel` отправляет `client_move` с паролем и хранит pending request до server `MessageResult`; UI browsing не должен подменять voice join. [join](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L622-L632), [result](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L1187-L1206), [native password path](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/local_actions/connections.rs#L127-L143).
|
||||
7. **Разрешение TX:** OS grant + mobile call lease + подтверждения `SetTransmit`/`SetAudio` → `CapturePermit { SessionKey, capture_epoch }`. [controller](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/controller.rs#L17-L29), [manager](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/connections.rs#L503-L539), [permit publication](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/connections.rs#L755-L769). Не смешивать viewed server с input owner.
|
||||
|
||||
- На4955 headset RX слышен; `nonzero_frames` растёт, output активен без xruns/time discards.
|
||||
- Headset microphone: несколько StartInput достигают Started/ok, затем появляется FramePositionGap.
|
||||
- Отдельный выбранный телефонно-названный `Audio device`: Disconnected и затем Open Internal.
|
||||
Текст продукта не доказывает физический builtin microphone; generation/session — только контекст.
|
||||
- Первоначальные подробности gap уже отсутствуют в retained app log. Не выдавать кодовую модель
|
||||
сбоя за доказанную полную последовательность конкретного аппаратного события.
|
||||
### Ошибки и границы
|
||||
|
||||
### Исправления прошли CI4959; аппаратная TX-приёмка остаётся открытой
|
||||
- Неверный пароль, channel permissions и прочие TS failures сохраняют `ts_error`/`missing_permission`; недостаточный identity security level возвращается явно, а не запускает бесконтрольную нагрузку. [error mapping](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L56-L80).
|
||||
- Connect не означает успешный subscribe-all: внутренняя ошибка подписки может стать отдельным error event. Проверять сервер с ограниченными правами: [pending results](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L1198-L1206).
|
||||
- При временном разрыве core завершает pending/media, сбрасывает TX/RX, меняет generation и переходит в Connecting. Vendored tsclientlib содержит reconnect-путь; старый upstream README с фразой об отсутствии reconnect не описывает полностью локальную реализацию. [core transition](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L1059-L1080), [vendored reconnect](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/tsclientlib/src/lib.rs#L1166-L1183).
|
||||
- **Неизвестно:** фактический Wi-Fi↔cellular handoff, NAT/IPv6/DNS и время восстановления. `NetworkChanged` сам не переподключает socket — он отзывает capture; reconnect принадлежит протокольной библиотеке. [handler](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/event_handlers.rs#L60-L63).
|
||||
- **Факт / риск доверия:** рассматриваемый `ConnectArgs` не содержит ожидаемый server UID, а builder его не задаёт; в vendored библиотеке проверка предусмотрена только при заполненном `options.server`. Это не утверждение о найденной эксплуатации, но TOFU/pinning policy пока не установлена. [args](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/protocol.rs#L188-L208), [builder](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L514-L525), [UID check](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/tsclientlib/src/lib.rs#L523-L532).
|
||||
|
||||
1. **Capture tail:** callback320 frames при16kHz делится на256+64. Если первая метка0ms, arrival10ms,
|
||||
хвост имеет метку16ms. Раньше он выбрасывался; следующий callback начинался с позиции320,
|
||||
создавая программный64-frame gap. Android теперь сохраняет порядок в bounded ring и держит
|
||||
один будущий head block до наступления его исходного captured_at, прежде чем передавать в SRC/DSP/TX.
|
||||
Expiry200ms, boundary, epoch, mute и настоящие missing-frame errors остаются; desktop не меняется.
|
||||
2. **Каталог:** TYPE_ECHO_REFERENCE28 — внутренний AEC reference, не микрофон. В сохранённом
|
||||
AudioPolicy он присутствует; отсутствовал в enum и мог выглядеть как generic Audio device.
|
||||
Добавлены точная классификация и исключение из capture-кандидатов. Другие неизвестные vendor
|
||||
sources не скрываются; сохранённый exact ID не подменяется автоматически.
|
||||
## 6. Полный аудиотракт
|
||||
|
||||
Код: `native/src/media/audio/{devices,engine}.rs`, соответствующие tests;
|
||||
`native/vendor/cpal-0.18.2/src/host/aaudio/device_catalog.rs`.
|
||||
Приёмка: новые deterministic regressions → Linux CI/APK → согласованная проверка headset TX,
|
||||
затем допустимой пары phone mic/headset output, при сохранённом RX. Никаких blind retries.
|
||||
### Общий формат и кодеки
|
||||
|
||||
## 5. Диагностика: что означает доказательство
|
||||
**Факт:** core boundary — mono `i16`, 48 кГц, 960 samples / 20 мс / 1920 bytes. TX-очередь ограничена 10 кадрами; максимальный возраст capture 200 мс. [protocol frame](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/protocol.rs#L1-L35), [queue](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L20-L63).
|
||||
|
||||
| Сигнал | Что доказывает / чего не доказывает |
|
||||
**Факт:** TX поддерживает OpusVoice (mono/VoIP) и OpusMusic (stereo/Audio с дублированием mono); bitrate mapping проекта: 8–48 и 24–104 кбит/с для quality 0–10. Это не заявленная официальная таблица TeamSpeak. Speex Narrow/Wide/Ultra и CELT не реализованы как fallback. [TxCodec/TxEncoder](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L204-L301). RX также отвергает неподдержанный codec: [Receiver](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L403-L430).
|
||||
|
||||
### От микрофона до сети
|
||||
|
||||
| Этап | Electron reference — факт | Native/mobile — факт |
|
||||
|---|---|---|
|
||||
| Захват | `getUserMedia`, mono, Chromium AEC/AGC по профилю; browser NS выключен; отдельный capture AudioContext 48 кГц. [engine](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/audio/engine.js#L279-L349) | CPAL callback → mono `f32`, bounded блоки ≤256 samples, hardware timestamps; SRC в worker → 480 samples/10 мс при 48 кГц. [devices](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/devices.rs#L468-L501), [conversion](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/engine.rs#L300-L345) |
|
||||
| Обработка | Typing attenuation; WASM Denoiser — NS по 480 samples, затем 960-sample `i16`; AEC/AGC остаются Chromium. [worklet](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/audio/capture-worklet.js#L111-L188) | Sonora AEC3 → NS → adaptive digital AGC2; независимые настройки; обработка на worker, не в callback. [CaptureProcessor](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/dsp/src/capture.rs#L85-L169) |
|
||||
| Echo reference | Управляется Chromium; приложение не передаёт свой CPAL post-render reference | CPAL output callback публикует реально выданный устройству, уже квантованный сигнал; timestamps выравнивают reference и capture. [output callback](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/devices.rs#L546-L583), [timeline](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/engine.rs#L418-L449), [worker](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/engine.rs#L891-L943) |
|
||||
| Сборка и guards | Worklet → renderer gate → IPC → base64/stdin. Renderer отбрасывает сообщения старше 200 мс; stdio назначает новый `Instant::now()`, исходный hardware timestamp не сохраняется сквозь IPC. [voice](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/voice.js#L230-L281), [stdio](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/stdio.rs#L101-L114) | Два 10-мс блока → `CapturedFrame`; сохраняются capture time, connection generation, privacy epoch. Передача через embedded handle без JSON/base64 PCM. [capture](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/capture.rs#L61-L80), [manager](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/connections.rs#L211-L226), [handle](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/runtime.rs#L55-L59) |
|
||||
| Gate и кодирование | Общий core, выбранный input connection; PTT/mute/deafen до отправки | То же ядро плюс native capture permit; неверная session/epoch или старое PCM отклоняются |
|
||||
|
||||
**Общий TX:** direct либо VAD automatic/volume/hybrid; earshot анализирует downsampled 16-кГц окна 256 samples, поддерживаются onset/preroll/hangover. Whisper имеет отдельный route и обходит обычный VAD, но не epoch/permission checks. [VAD constants](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/vad.rs#L25-L58), [VAD implementation](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/vad.rs#L290-L389), [TX path](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L1405-L1564). Серверное `can_send_audio()` не обходится локальной кнопкой PTT. Кадр Opus становится TS voice/whisper packet; пустой packet завершает burst. [encoder](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L277-L310).
|
||||
|
||||
**Факт:** локальный patch протокола сохраняет timestamps/epoch вплоть до deferred UDP send и повторяет guard при backpressure/retry. Нельзя заменить vendored tsclientlib vanilla-upstream без анализа этого контракта. [patch provenance](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/README.md#L14-L53), [AudioSendGuard](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L190-L200).
|
||||
|
||||
### От сети до динамика
|
||||
|
||||
1. `StreamItem::Audio` → `Receiver::handle_packet` → tsclientlib `AudioHandler`: per-speaker jitter/decode. Output mute прекращает этот путь. [Session RX](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/session.rs#L958-L993).
|
||||
2. Раз в 20 мс `mix_tapped` берёт decoded stereo float, применяет UID-громкость и отдельный playback AGC на говорящего, смешивает, downmix `(L+R)/2`, ограничивает и отдаёт mono `i16[960]`. [Receiver](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L388-L490), [playback AGC](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/voice_dsp.rs#L217-L299).
|
||||
3. Electron: base64 `audio` event → отдельный per-server playback ring (200 мс, prebuffer 40 мс, до 16 rings) → worklet mix → gain/ducking/sink. [serialization](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/src/audio.rs#L492-L510), [worklet](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/audio/playback-worklet.js#L1-L65), [playback](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/app/renderer/js/audio/playback-worklet.js#L139-L189).
|
||||
4. Native: `CoreEvents.playback` → `AudioSessionBinding` проверяет session/output epoch → mixer разделяет 960 mono на два stereo 480-блока → output SRC/Rubato → CPAL. Voice, stream и notifications имеют отдельные маршруты. [binding](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/media_binding.rs#L18-L57), [mixer](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/mixer.rs#L323-L410), [output worker](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/engine.rs#L893-L979).
|
||||
|
||||
### Мобильные риски DSP
|
||||
|
||||
- Sonora требует **единственного владельца AEC/NS/AGC** и актуального post-gain reference; нельзя просто добавить OS VoiceProcessingIO поверх него. [контракт](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/dsp/src/capture.rs#L1-L8). iOS bridge намеренно выбирает `AVAudioSessionModeDefault`, а не voiceChat: [configureCall](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L115-L120). Официальная документация Apple различает voiceChat mode и реально включённый voice processing — [voiceChat](https://developer.apple.com/documentation/avfaudio/avaudiosession/mode-swift.struct/voicechat).
|
||||
- Раздельные input/output clocks и Rubato correction ±1000 ppm уже предусмотрены, но качество CPAL hardware timestamps на конкретных маршрутах **неизвестно**. [ClockTracker](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/audio/resample.rs#L105-L196).
|
||||
- **Неизвестно:** эффект Bluetooth HFP/LE, speakerphone double-talk, latency, battery/thermal load, реальная задержка OS DSP, reference при нескольких sinks. Pure Rust и NEON support — не акустическая приёмка.
|
||||
- WebRTC stream audio — отдельная ветка; platform ADM recording/playout отключены, чтобы не становиться вторым владельцем микрофона/вывода. [peer](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/stream/peer.rs#L45-L56), [stream sink](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/media/stream/frames.rs#L323-L375).
|
||||
|
||||
## 7. Мобильные ограничения и фактический статус адаптеров
|
||||
|
||||
| Область | Android: наблюдается в коде | iOS: наблюдается в коде | Что остаётся проверить |
|
||||
|---|---|---|---|
|
||||
| Permission | `RECORD_AUDIO`, FGS declarations, prompt из видимой Activity, повторная проверка grant. [manifest](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/AndroidManifest.xml#L2-L24), [request](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/TeamsPeachActivity.java#L128-L143) | Usage descriptions и `requestRecordPermission`; receive-only не требует mic grant. [plist](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/ios/Host/Info.plist#L34-L39), [bridge](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L108-L127) | Deny, permanent deny, Settings revoke, one-time permissions; никакой передачи до разрешения. |
|
||||
| Фон | `VoiceService`, notification, mediaPlayback/microphone types, START_NOT_STICKY. [service](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/VoiceService.java#L19-L85) | `UIBackgroundModes=audio`, активная AVAudioSession и удержание runtime call lease. [plist](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/ios/Host/Info.plist#L39), [lease](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple.rs#L61-L83) | Lock screen, task recreation, OS termination, реальный фон; не обещать вечную жизнь процесса. |
|
||||
| Interruption/focus | AudioFocusRequest; loss/gain → platform events, permanent loss останавливает service. [focus](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/VoiceService.java#L61-L85) | Observer interruption, prior capture intent, shouldResume, native resume API. [observer](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L74-L80), [resume](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L130-L138) | Цепочка safe resume неполна, см. ниже. |
|
||||
| Bluetooth/routes | AudioDeviceCallback есть; явного `setCommunicationDevice` в просмотренном `native/src`/Android source не найдено | AllowBluetooth/AllowBluetoothA2DP и route-change observer; explicit input-port selection не найдена в этих адаптерах | Реальный input и output headset, HFP/LE, unplug, speaker/receiver, confirmation route; CPAL enumeration не равна communication routing. |
|
||||
| Network | `registerDefaultNetworkCallback`. [bridge](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/PlatformBridge.java#L23-L29) | `nw_path_monitor`. [observer](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L85) | Reconnect после Wi-Fi↔cellular, offline/recovery, IPv6/DNS, отсутствие replay старого capture. |
|
||||
| UI lifecycle | Process-owned Application/runtime, новая UI generation; Activity destruction отменяет prompts. [Rust host](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/android.rs#L64-L116), [Activity](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/TeamsPeachActivity.java#L61-L76) | HostLease/scene lifecycle, detach не тождественен завершению активного звонка. [binding](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/ui/application.rs#L53-L69), [bridge](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L65-L105) | Rotation/recreation и scene reconnect без дублей core/audio worker и без автоматического PTT. |
|
||||
| Touch/accessibility | Общие touch controls, SemanticView/TalkBack virtual nodes. [PTT](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/ui/shell.slint#L264-L275), [SemanticView](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/android/src/main/java/dev/teamspeach/mobile/SemanticView.java#L60-L95) | Safe-area/IME/VoiceOver traits передаются в Slint; эквивалент Android semantic overlay не установлен | Пройти Connect/Join/Mute/PTT/Disconnect TalkBack и VoiceOver; общий UI ещё не доказательство доступного дерева iOS. |
|
||||
| Files/secrets | SAF, URI/grants/private staging; Android Keystore | Security-scoped documents; Keychain ThisDeviceOnly | Providers, cancellation, locked stores, reinstall/backup; не переносить Electron ciphertext. [platform selection](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/services/secrets/backend.rs#L1-L15), [mobile adaptations](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/compatibility.json#L28-L35) |
|
||||
| Updates/capture | direct APK/store branches, MediaProjection/Camera2 | App Store channel, ReplayKit extension | Store review/signing/privacy, real capture capabilities; не обещать desktop capture на мобильных без OS consent. |
|
||||
|
||||
### Конкретный разрыв восстановления аудио
|
||||
|
||||
**Факт:** `event_handlers::platform` при начале interruption вызывает `StopInput` и `StopOutput`; при `should_resume` лишь выставляет строку статуса. Route/network change отзывает capture и вызывает `StopInput`. [handler](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/event_handlers.rs#L60-L63).
|
||||
|
||||
**Факт:** iOS `CallLease::resume(ResumeAuthorization,...)` существует, но текстовый поиск `ResumeAuthorization` и `.resume(` по `native/src` не обнаружил его вызова из runtime; найденные остальные `.resume()` принадлежат CPAL stream state. LSP в проекте не настроен, поэтому это результат ограниченного source search, не whole-program доказательство. [API](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple.rs#L71-L81).
|
||||
|
||||
**Факт:** `ensure_mobile_call` может вернуть успех для прежнего lease по cached флагу либо вызвать `set_capture_enabled`, а не `resume`; ObjC bridge запрещает включение capture при `!callActive`. [mobile_calls](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/mobile_calls.rs#L8-L25), [bridge guard](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/platform/apple/bridge.mm#L140-L149).
|
||||
|
||||
**Вывод:** iOS safe resume — приоритетный blocker непрерывного voice сценария. На Android автоматическое восстановление выхода также отсутствует в общем handler, но отдельное действие пользователя идёт через `set_microphone_owner` → `sync_audio` и может открыть выход снова; **не следует утверждать, что звук невозможно восстановить вообще**. [explicit action](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/src/app/runtime/controller.rs#L17-L29). Проверить и оформить отдельно receive-only resume, capture resume и отказ OS. Не исправлять путём безусловного автозапуска микрофона.
|
||||
|
||||
### Официальные ограничения OS
|
||||
|
||||
- Android 14+: appropriate FGS type/permission; microphone FGS требует `RECORD_AUDIO` и подчинён while-in-use ограничениям. Старт из фона обычно запрещён без документированного исключения. [FGS types](https://developer.android.com/develop/background-work/services/fgs/service-types), [background restrictions](https://developer.android.com/develop/background-work/services/fgs/restrictions-bg-start).
|
||||
- Target Android 15+: audio focus доступен top app либо foreground service. В service сначала вызывается foreground, затем requestAudioFocus — порядок соответствует этому требованию, но не подтверждает все runtime-переходы. [audio focus](https://developer.android.com/media/optimize/audio-focus).
|
||||
- Android BLE Audio: официальный путь communication-device selection, callback фактической смены и очистка выбора; старый SCO-путь не заменяет BLE routing. [AudioManager guide](https://developer.android.com/develop/connectivity/bluetooth/ble-audio/audio-manager). Нельзя считать notification audio usage настройкой CPAL stream mode.
|
||||
- iOS: microphone permission, корректная audio category, background audio capability, interruption и route-change handling. Background mode не отменяет прерывания/системное завершение. [interruptions](https://developer.apple.com/documentation/avfaudio/handling-audio-interruptions), [route changes](https://developer.apple.com/documentation/avfaudio/responding-to-audio-route-changes), [voice processing distinction](https://developer.apple.com/documentation/avfaudio/avaudiosession/mode-swift.struct/voicechat). Документы могут описывать будущие/newer SDK APIs: availability проверять относительно deployment target 16, не вводить новые API без guards.
|
||||
|
||||
## 8. Поддержка мобильных платформ ключевыми зависимостями
|
||||
|
||||
Проверено по официальным источникам 2026-11-10. «Поддерживается upstream» не означает «проверен этот fork, patch set и artifact». Для pure-Rust библиотек отсутствие отдельного mobile support statement не заменено догадкой.
|
||||
|
||||
| Зависимость | Официальное основание | Оценка для данного дерева |
|
||||
|---|---|---|
|
||||
| Rust | [Target tiers](https://doc.rust-lang.org/rustc/platform-support.html): Android ARM64 и iOS ARM64/device/simulator имеют std, Tier 2 | Toolchain target возможен; Tier 2 не гарантирует исполнение приложения/всех C-deps. |
|
||||
| Electron 44.9.3 | [Versioned README](https://raw.githubusercontent.com/electron/electron/v44.9.3/README.md): binaries только Windows/macOS/Linux | Хост нельзя взять как Android/iOS shell. |
|
||||
| Slint 1.18.1 | [Android guide source](https://github.com/slint-ui/slint/blob/v1.18.1/docs/astro/src/content/docs/guide/platforms/mobile/android.mdx): Rust/C++, android-activity, min API26. [iOS guide source](https://github.com/slint-ui/slint/blob/v1.18.1/docs/astro/src/content/docs/guide/platforms/mobile/ios.mdx): Rust, Winit/Skia, macOS/Xcode/XcodeGen | Соответствует текущему направлению native. [Mobile guide](https://github.com/slint-ui/slint/blob/v1.18.1/docs/astro/src/content/docs/guide/platforms/mobile/general.mdx) отдельно требует touch scrolling, safe area и IME. |
|
||||
| CPAL 0.18.2 | [Published crate README](https://docs.rs/crate/cpal/0.18.2): Android AAudio API26+, iOS CoreAudio | Используется локальный patch; official support не покрывает автоматически изменения timing/route handling. |
|
||||
| Sonora 0.2.0 | [Pinned upstream README](https://github.com/dignifiedquire/sonora/blob/a024d6ef8351add55be5e8b1d6cc35f555787660/README.md): Android architectures и iOS ARM64, NEON/scalar; [crate](https://docs.rs/crate/sonora/0.2.0) | Portable DSP реалистичен; локальные sonora/AGC2 patches и real-time workload нуждаются в проверке. |
|
||||
| ReSpeak tsclientlib/tsproto | [Pinned upstream README](https://github.com/ReSpeak/tsclientlib/blob/ee3bc6f45a7137db7793ba5593a321df400d53e5/README.md) описывает TeamSpeak library, но не даёт mobile acceptance matrix | **Неизвестна официально подтверждённая Android/iOS-совместимость этой ревизии.** Проверить build/UDP/DNS/auth на обеих OS; patch set обязателен. |
|
||||
| audiopus 0.3.0-rc.0 / audiopus_sys | [Published README](https://docs.rs/crate/audiopus/0.3.0-rc.0): CMake, bundled/preinstalled Opus, заявлены Windows/Linux/macOS; отдельной Android/iOS гарантии нет | **Cross-build gate**, а не доказанный mobile blocker и не гарантированная поддержка. Собирать target-native static Opus, не брать host library. |
|
||||
| libwebrtc 0.4.0 / webrtc-sys 0.3.53 | [Pinned SDK README](https://github.com/livekit/rust-sdks/blob/88705b15086ecbe2c26ee91ede6203f974a0fc62/README.md) включает Android/iOS; [published crate](https://docs.rs/crate/libwebrtc/0.4.0) | Есть upstream mobile support, но локальная source-build-only интеграция, prefixed JNI и codec patches — отдельные гейты. Не требует LiveKit server для текущего standalone peer. |
|
||||
| Tokio/Serde, earshot, Rubato | Использование и pins подтверждены манифестами; отдельный официальный mobile runtime certificate для данной комбинации не установлен | **Вывод:** кандидаты на reuse, не основания для обещания запуска. Основные проверки — compilation, timings, resampling/VAD и cancellation. |
|
||||
| rfd/arboard/open, DBus/X11, Win32 | В манифесте исключены из мобильного target graph либо ограничены desktop cfg | Не тащить в мобильный UI; использовать существующие platform adapters. |
|
||||
|
||||
Публичные Slint web pages через static fetch отвечали timeout; использованы доступные **официальные versioned исходники документации** на GitHub и docs.rs, а не пересказ поисковой выдачи. Browser relay также дал timeout; проверка dashboard выполнена отдельным managed browser, без использования пользовательского аккаунта.
|
||||
|
||||
## 9. Лицензии и распространение
|
||||
|
||||
Это техническая инвентаризация рисков, **не юридическое заключение**.
|
||||
|
||||
| Объект | Подтверждённое ограничение | Действие до распространения |
|
||||
|---|---|---|
|
||||
| Собственный код TeamsPeach | `UNLICENSED`, rights reserved до выбора лицензии владельцем. [package](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/package.json#L7-L9), [NOTICE](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/NOTICE.md#L1-L4) | Получить документированное право на модификацию/распространение либо лицензию владельца. Публичный git сам по себе такого права не даёт. |
|
||||
| Иконки TeamSpeak | Нет найденного redistribution grant; provenance не является лицензией. [icons](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/teamspeak-client-icons-PROVENANCE.md#L3-L12) | Заменить собственной/разрешённой графикой или получить права. |
|
||||
| WAV notifications | Та же проблема с официальными sounds. [sounds](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/teamspeak-client-sounds-PROVENANCE.md#L3-L10) | Заменить/лицензировать, включая ресурсы в собранном mobile package. |
|
||||
| Slint | [Royalty-free 2.0](https://github.com/slint-ui/slint/blob/v1.18.1/LICENSES/LicenseRef-Slint-Royalty-free-2.0.md) явно разрешает mobile при attribution; ограничения на standalone redistribution/API exposure; GPL/commercial — альтернативные условия | Зафиксировать выбранную лицензию; обеспечить доступный AboutSlint/badge и notices. [AboutWindow](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/native/ui/about.slint#L1-L24) содержит widget, но фактическую доступность в обоих mobile UI ещё надо проверить. |
|
||||
| ReSpeak и Rust deps | MIT/Apache-2.0 и другие permissive licenses; earshot MIT/Apache, audiopus ISC; inventory не ограничен одной платформой. [vendor](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/vendor/README.md#L5-L12), [notices](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/THIRD_PARTY_NOTICES.md#L3-L15), [earshot](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/core/THIRD_PARTY_NOTICES.md#L52) | Сохранить copyright/license/NOTICE и условия модификаций, сверить именно финальный dependency graph. |
|
||||
| Sonora | BSD-3-Clause; native использует больше pipeline, чем reference WASM. [notice](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/sonora-NOTICE.txt#L20-L49), [native DSP](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/dsp/Cargo.toml#L16-L21) | Старый WASM notice с «AEC/AGC never constructed» нельзя выдавать за описание native DSP; подготовить notices по фактической поставке. |
|
||||
| Fonts | Noto Sans OFL-1.1, отдельные KaTeX font notices | Сохранить лицензии; проверить модификации/renaming rules и конечные assets. [NOTICE](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/NOTICE.md#L11-L13). |
|
||||
| WebRTC/кодеки | Generated third-party licenses обязательны; software H264 patent/license review отмечен в dependency lock `/verification/licensing`; GN включает H264/FFmpeg и другие codecs. [GN](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/xtask/src/deps.rs#L199-L219), [iOS notice staging](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/platform/ios/project.yml#L68-L74) | Проверить фактически слинкованные компоненты, license obligations и patent policy по регионам. Не объявлять пакет «весь MIT» и не выводить правомерность из успешного build. |
|
||||
| Название/марки/магазины | Независимый клиент, TeamSpeak trademark; endorsement отсутствует. [NOTICE](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/LICENSES/NOTICE.md#L23-L24) | Проверить branding, privacy disclosures, microphone/background declarations и App Store/Play distribution policy перед релизом. |
|
||||
|
||||
**Вывод:** публичный mobile release сейчас юридически не обоснован имеющимися документами. Внутренний технический прототип не решает эти вопросы автоматически. Полная лицензия конечного APK/IPA неизвестна до фиксации разрешений и dependency/assets inventory.
|
||||
|
||||
## 10. Минимальный сквозной прототип — только план
|
||||
|
||||
### Цель и ограничения
|
||||
|
||||
**Цель:** физический Android и физический iPhone подключаются к разрешённому тестовому TeamSpeak-серверу, входят в один Opus-канал и обмениваются двусторонним голосом друг с другом и с контрольным desktop/официальным peer. Не заменять живую сеть synthetic signaling и не выдавать loopback за interoperability.
|
||||
|
||||
Минимальный UI: адрес/порт, nickname/identity, ввод пароля без записи в лог, список каналов/Join, статус соединения и актуального канала, receive-only, microphone permission, Mute/Deafen/PTT, Disconnect, ясные ошибки. Это ограничение **первого доказательного эксперимента**, а не отказ от остальных функций конечной идентичной версии.
|
||||
|
||||
### Порядок проверки технических препятствий
|
||||
|
||||
| Шаг | Что проверять | Наблюдаемый критерий успеха / остановки |
|
||||
|---|---|---|
|
||||
| 0. Условия эксперимента | Отдельное разрешение на build/install/run/network; Linux Android build host, Mac/Xcode для iOS; явные test devices и сервер/канал; disposable profiles; права на используемые assets | Задокументированы target triples, toolchain/SDK versions, test endpoints без секретов и разрешённые действия. Нет автоматического использования production identities. |
|
||||
| 1. Реальный mobile build chain | Сначала Rust/core+static Opus на обоих targets; затем существующий native app/source-built WebRTC, matching JNI jar, iOS framework/link/signing, Android 16 KiB ELF | Получены воспроизводимые target artifacts, SHA/revision/recipe и новые per-target provenance. Package verifier подтверждает архитектуру; приложение действительно запускается. Никаких фиктивных completed records. |
|
||||
| 2. Foreground audio boundary | CPAL enumerate/open input+output с разрешением, timestamps, SRC, full-duplex, один DSP owner. Сначала earphones, затем speakerphone | Receive-only работает без mic grant; deny/revoke не включает capture. Fresh PCM доходит через штатный DSP, нет stale-frame/repeated-init ошибок, выход не молчит после корректного start. |
|
||||
| 3. Handshake и канал | Embedded `CoreHandle`, identity, password/no-password, security-level rejection, Join ACK, неподдержанный codec | Сервер и peer видят ожидаемого клиента/канал; UI отражает подтверждённое состояние. Неверный пароль/права отображаются как ошибки, не как connected/joined. |
|
||||
| 4. Двусторонний голос | Android↔iOS, затем каждый ↔ desktop peer; OpusVoice, позже OpusMusic, PTT/mute/deafen | Два независимых слушателя/измерения подтверждают речь в обе стороны. Предлагаемый gate: 10 минут разговора без устойчивого одностороннего звука/зависания; зафиксировать loss/jitter, CPU и измеренную задержку. Предварительная цель mouth-to-ear p95 ≤250 мс в контролируемой LAN, метод и акустическую погрешность указать отдельно. Это цель, не текущий результат. |
|
||||
| 5. Privacy и смена владения | Release PTT, mute, channel/input owner switch, disconnect/reconnect, permission revoke | После boundary не передаётся ранее захваченный PCM: проверить capture timestamps/epochs и получателя. Допуск сетевого хвоста измерять отдельно; не требовать физически мгновенного исчезновения уже доставленного звука. |
|
||||
| 6. Lifecycle — устранить найденный разрыв | Safe interruption/resume, foreground service/session lease, receive-only восстановление; не только открыть микрофон заново | После звонка/потери focus разрешённое явное resume восстанавливает RX и TX на обеих OS; отказ OS остаётся видимым, mic не включается сам. iOS resume должен реально вызываться с актуальным SessionKey и авторизацией. |
|
||||
| 7. Routing и сеть | Speaker↔wired↔Bluetooth HFP/LE, unplug; Wi-Fi↔cellular/offline; background/lock и UI recreation | Фактический mic/output соответствует выбору; нет старого PCM/двойных workers. Предварительный recovery gate: ≤30 с либо явное состояние ошибки с рабочим manual reconnect, без ложного connected. Фон: 10 минут активного разрешённого звонка с locked screen на каждой OS; ограничения OEM/OS записать. |
|
||||
| 8. Доказать общий UX | Одинаковый сценарий/состояния на Android/iOS, safe area, IME, compact layout, TalkBack/VoiceOver | Все минимальные действия доступны touch и screen reader, release/cancel PTT безопасен. Скриншоты одинаковых app-состояний и отдельная фиксация ожидаемых OS-различий. |
|
||||
|
||||
**Решение после прототипа:** если ядро и OS-аудио работают, но Slint surface имеет доказанный blocker, сравнить замену presentation слоя, сохраняя `CoreHandle`, session ownership, DSP и callbacks. Если blocker находится в codec/capture/session, смена UI его не решит. Проверять iOS с первых шагов, не откладывать его до «готового Android».
|
||||
|
||||
### После минимального proof — план полной идентичной версии
|
||||
|
||||
1. Превратить existing compatibility inventory в исполняемый acceptance checklist, не наследуя historical passes; сравнивать актуальный Electron-контракт и native implementation.
|
||||
2. Одна shared feature-модель для channels/admin/chat/files/whisper/recording/settings; для каждой фичи Android/iOS verdict, adapter и честный unsupported/error state.
|
||||
3. Отдельно принять WebRTC screenshare/camera/notifications/file providers/secure storage/update channels на устройствах; не расширять первый voice proof до этих зависимых сценариев.
|
||||
4. Проверить мобильный layout, performance/battery/thermal, accessibility, back navigation, recovery и migration без изменения identity/потери данных.
|
||||
5. Закрыть лицензии, assets, signing/store privacy и конечный dependency inventory; только после этого обсуждать распространение.
|
||||
|
||||
## 11. Проверки, артефакты и неизвестное
|
||||
|
||||
### Реально выполнено в исследовательской сессии
|
||||
|
||||
- Metadata-only git preflight: HEAD/branch/status/tracked inventory; метаданные путей без чтения секретов.
|
||||
- Статическое чтение перечисленных исходников, manifest/CI/test recipes и точечных vendor contracts; приложение не исполнялось.
|
||||
- Установленные Understand scripts: ignore generation, scan, import extraction, semantic batching, structural extraction, merge, fingerprint baseline.
|
||||
- Карта: **679 текстовых файлов**, **5233 узла**, **13204 связи**, **9 слоёв**, **9 шагов**. Scan/fingerprint inventory содержит 680 entries: один бинарный WAV без graph node. 872 resolved imports сохранены; штатный merge удалил 15 некорректных `tested_by` связей. Наличие ребра `tested_by` не означает test pass.
|
||||
- `validateGraph` установленного core + проверка layer/tour references: success, без issues. Проверена фактическая загрузка и отрисовка русского графа в understand-dashboard; verification browser tabs закрыты.
|
||||
- Официальные dependency/OS/license источники прочитаны; Slint timeout обойдён чтением официальных versioned docs sources.
|
||||
- LSP status: **No language servers configured for this project**. Он не настраивался; Cargo/rust-analyzer checks не запускались.
|
||||
- Финальная проверка: 179 ссылок на исходники в 82 файлах — пути и диапазоны строк корректны после исправления четырёх диапазонов; локальные ссылки документов разрешаются, code fences сбалансированы. Итоговый git status показывает только новые `.ua/`, `AGENTS.md`, `docs/mobile-port-assessment.md`, `docs/mobile-port-progress.md`; tracked и staged diff пусты. Исходники приложения не изменены. Промежуточные артефакты перемещены в стандартный `.ua/.trash-*`, scan inventory сохранён.
|
||||
|
||||
### Стандартные артефакты Understand-Anything
|
||||
|
||||
`.ua/knowledge-graph.json`, `.ua/meta.json`, `.ua/fingerprints.json`, `.ua/config.json`, `.ua/.understandignore`, `.ua/intermediate/scan-result.json`. `autoUpdate=false`, `outputLanguage=ru`. Граф — снимок исходников указанной ревизии; созданные вслед за ним `AGENTS.md` и документы исследования не являются архитектурными узлами этого первичного снимка. Dashboard может честно показывать working-tree changes из-за новых документов — это не нужно скрывать изменением commit metadata или запускать полный анализ повторно.
|
||||
|
||||
Для следующего просмотра: `/understand-dashboard C:/Dev/TeamsPeach`. В этой сессии использован уже установленный Vite dashboard без install/build; runtime access token в документы не сохраняется. Автообновление графа не включалось.
|
||||
|
||||
### Открытые вопросы
|
||||
|
||||
| Неизвестное | Как получить ответ |
|
||||
|---|---|
|
||||
| Compile/package SUCCESS | Сборка/упаковка, не работа на телефоне |
|
||||
| Android route ACK | Выбор маршрута, не Started и не слышимость |
|
||||
| voice_nonzero_blocks | Сигнал после микшера; не post-SRC/callback/hardware |
|
||||
| submitted_frames | Кадры очереди, включая нули |
|
||||
| nonzero_frames | Ненулевые квантованные кадры в CPAL buffer; не OS/HAL gain или слышимость |
|
||||
| AudioFlinger latency `k` | Kernel/server estimate в ms, не акустическое измерение |
|
||||
| Подтверждение владельца | Реальный результат только названного сценария/кандидата |
|
||||
| Сборка и запуск данного patch set на Android/iOS | Разрешённые реальные source-build/package/start с per-target receipts. |
|
||||
| Server/official peer interoperability | Изолированный live сервер и контрольный peer; тесты §10. |
|
||||
| iOS safe resume и Android explicit recovery | Точечное исправление после разрешения, затем interruption scenario на устройствах. |
|
||||
| Bluetooth/AAudio/CoreAudio timestamps, AEC, latency/battery | Полный duplex acoustic/device test, а не desktop loopback. |
|
||||
| Full feature/visual/accessibility parity | Общая acceptance matrix и реальные Android/iOS UI checks. |
|
||||
| Разрешение на распространение кода и TS assets | Решение правообладателей/лицензия или замена assets; проверка конечного пакета. |
|
||||
|
||||
Снимать ограниченные `audio_route`, `audio_command`, `audio_summary`, `audio_stream`,
|
||||
`audio_backend`, `audio_first_fault` и app-owned system state. Не сохранять PCM, credentials,
|
||||
identity/profile contents, device addresses или чужую активность. Первое fault-событие может
|
||||
вытесниться из logcat; уже сохранённые файлы разбирать без повторного удержания телефона.
|
||||
Последние локальные артефакты и APK/hash указаны в handoff.
|
||||
Краткая передача следующей сессии: [mobile-port-progress.md](mobile-port-progress.md). Порядок актуализации знаний: [AGENTS.md](../AGENTS.md).
|
||||
|
||||
## 6. Сборка и границы платформ
|
||||
---
|
||||
|
||||
- Android build/package — Linux CI, Windows — редактирование и согласованный adb install.
|
||||
Команды, provisioning и caches: `.gitea/workflows/android.yml` и связанные helpers; не дублировать
|
||||
их параметры в этом документе. Ресурсная политика рабочей станции — только `mobile-build.local.md`.
|
||||
- Test signing одноразовый по решению владельца; production signing/release не разрешены.
|
||||
- iOS требует macOS/Xcode/Apple SDK/signing и собственного runtime proof; Android CI ничего из этого
|
||||
не подтверждает. Не обещать проверенные interruptions/routes/background до соответствующих тестов.
|
||||
- `.ua/knowledge-graph.json` старый; использовать как навигацию, выводы проверять source. Без полного
|
||||
перескана/автообновления и без перезапуска Understand на каждую небольшую правку.
|
||||
## Текущее решение: Android all-ci, 2026-11-10
|
||||
|
||||
## 7. Android Room UI — выбранное направление
|
||||
Этот раздел дополняет, а не исправляет исторический снимок выше. Владелец выбрал маршрут
|
||||
**Windows-разработка → ручной Gitea Actions → вся Android-сборка на Linux CI → скачивание
|
||||
артефактов → установка тестового APK через Windows `adb`**. Точные workflow, runner label,
|
||||
repository variables и имена артефактов указаны в [актуальном README](../README.md#android-development-windows-linux-ci).
|
||||
Существующие Linux desktop workflows остаются отдельными: Linux desktop package не является Android APK.
|
||||
|
||||
- Владелец выбрал Room целиком; Android-only исключение из desktop-паритета записано в `DESIGN.md`.
|
||||
- `runtime/model.rs::Snapshot.room` проецирует всех участников своего канала, независимо от collapsed tree.
|
||||
`ui/shell.rs` владеет Room-навигацией/Back и captured targets; `ui/shell.slint` — сеткой участников,
|
||||
постоянным voice dock, каналами/чатом/профилем и доступом к прежним secondary-функциям.
|
||||
- `services/prefs.rs` валидирует `androidPalette`; `runtime/settings_actions/themes.rs` владеет preview,
|
||||
атомарным сохранением и отменой. `ui/theme.rs` отделяет контрастный текст акцента от цвета заливки.
|
||||
Null сохраняет штатную/package-тему; desktop override не применяет. Preview не должен переживать уход из Settings.
|
||||
- Каталог EN/RU общий; default **English**, Russian выбирается в Appearance, сохранённый язык сохраняется.
|
||||
- Integrated Slint compile и реальные i18n tests3 прошли локально. Полный Rust/APK кандидата `87265a3`
|
||||
прошёл CI4972; prefs-палитра2 и shell4 регрессии подтверждены журналом. Preview-tests были отфильтрованы
|
||||
неверным именем модуля; имя исправлено для следующего CI. Новая device-проверка ещё не завершена.
|
||||
### Где выполняется сборка
|
||||
|
||||
## 8. Ссылки и архив
|
||||
- На Windows-ПК нужны исходники/редактор, браузер для Gitea и Android SDK Platform-Tools для
|
||||
явно выбранного тестового устройства. WSL, Docker и локальный Linux для этого маршрута **не нужны**;
|
||||
Android SDK/NDK, JDK и тяжёлые native source-build tools размещаются на CI runner, а не на ПК разработчика.
|
||||
- Вся цепочка Android выполняется на выделенном Linux x64 runner: pinned source WebRTC,
|
||||
Skia, Rust ARM64 application, Gradle APK/AAB и проверки пакетов/receipts. Полная конфигурация
|
||||
`skia + webrtc` сохраняется; это не обход зависимости отключением функций или случайным prebuilt.
|
||||
- Linux — требование pinned WebRTC Android source-build, а не требование к рабочему месту:
|
||||
[официальный upstream README на используемой ревизии `9c3a1386f07e4348c28cd85c066821cebc3b56e4`](https://github.com/webrtc-sdk/webrtc/blob/9c3a1386f07e4348c28cd85c066821cebc3b56e4/docs/native-code/android/README.md)
|
||||
прямо говорит: **“Android development is only supported on Linux.”** Windows source-build WebRTC
|
||||
для Android не объявляется поддерживаемым маршрутом.
|
||||
- До первого dispatch администратор должен включить нужные возможности Gitea Actions/artifacts,
|
||||
предоставить runner с указанным label, установить SDK/toolchains и настроить repository variables.
|
||||
Наличие workflow в дереве не означает, что эти prerequisites уже provisioned или что job успешно исполнен.
|
||||
|
||||
- [Handoff](mobile-port-progress.md) — текущий кандидат, открытая работа и правила продолжения.
|
||||
- [Android AudioManager](https://developer.android.com/reference/android/media/AudioManager),
|
||||
[AAudio](https://developer.android.com/ndk/guides/audio/aaudio/aaudio),
|
||||
[latency](https://developer.android.com/ndk/guides/audio/audio-latency),
|
||||
[device types](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/main/media/java/android/media/AudioDeviceInfo.java).
|
||||
- [Архив исследований](archive/2026-11-14-mobile-port-assessment.md),
|
||||
[архив хронологии](archive/2026-11-14-mobile-port-progress.md).
|
||||
**Не читать целиком по умолчанию.** Это неизменённые старые снимки; относительные ссылки исходно
|
||||
относились к `docs/`, а исторические статусы/разрешения не заменяют текущий handoff.
|
||||
### Артефакты и установка с Windows
|
||||
|
||||
1. После доставки исходников обычным разрешённым процессом выбрать нужный ref в ручном Android
|
||||
workflow через Gitea Actions. CI не публикует release и не подключается к физическому телефону.
|
||||
2. После успешного завершения **фактического** run скачать test-harness и production bundles вместе
|
||||
с manifests, hashes, build/dependency и package-verification receipts. Проверить соответствие ref/run
|
||||
и SHA-256 выбранного APK данным bundle; наличие файла без receipts не заменяет provenance.
|
||||
3. На отдельном ARM64 Android-телефоне включить USB debugging, подтвердить авторизацию ПК и
|
||||
выбрать serial из `adb devices -l`. Установить только явно выбранный `*-harness-test.apk`:
|
||||
`adb -s <serial> install -t -r <path-to-harness-test.apk>`. Флаг `-t` нужен для `testOnly` APK;
|
||||
это debug/test signing, не production signing. Не удалять установленную production-версию или
|
||||
пользовательские данные ради обхода несовпадения ключей; использовать отдельное тестовое устройство.
|
||||
Debug key изолирован для каждой CI-упаковки: следующий run может дать другую подпись, и `-r`
|
||||
тогда не обновит прежний harness. Удаление только прежней disposable test-установки возможно
|
||||
лишь по отдельному явному решению пользователя: **uninstall удаляет данные приложения**,
|
||||
включая локальные identities и настройки. Автоматически удалять приложение нельзя.
|
||||
4. Unsigned production ARM64 APK **не устанавливается**, пока не выполнены production signing и
|
||||
проверка подписи; AAB вообще не устанавливается напрямую через `adb install`. Production AAB
|
||||
предназначен для отдельно разрешённого signing/store-процесса, а не является готовым APK.
|
||||
|
||||
**Граница доказательства:** конфигурация CI, receipts проверки пакета и даже успешная установка
|
||||
test-only APK не доказывают полноценную Android-приёмку, живой голос с официальным клиентом,
|
||||
Bluetooth, lifecycle/background, screenshare, доступность или право на распространение. Тестовый
|
||||
host ограничен smoke/harness-сценариями и не подменяет проверку production build. Этот раздел
|
||||
не заявляет успешного 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.
|
||||
+601
-66
@@ -1,80 +1,615 @@
|
||||
# Мобильный порт: текущее состояние
|
||||
# Мобильный порт: передача состояния
|
||||
|
||||
Обновлено: **2026-11-15**. Это handoff, не журнал работ.
|
||||
**Не дописывать хронологию:** заменять устаревшее состояние. Предел: 100 строк / 8 KiB.
|
||||
Обновлено: **2026-11-11**. Принятая Windows-база фиксируется тегом **`desktop-baseline-0.1.7-20261111`** в `main` (предыдущий HEAD `5ce12714acc306f6055bf1e9db3282c5af7704cb`). Дальнейшая мобильная разработка — `feature/mobile-port` от этой базы. Единственный application host — Rust/Slint; результаты ниже отделены от первоначального read-only исследования.
|
||||
|
||||
## База и правила
|
||||
## Возврат к разработке на ПК, 2026-11-26
|
||||
|
||||
- Единственный клиент — Rust/Slint `native/`, ядро — `core::runtime`. Без Electron/Node/npm.
|
||||
- Ветка `feature/mobile-port`; Room-кандидат `956b464` прошёл CI4973; последняя принятая RX/device-база — APK4955.
|
||||
- Windows0.1.7 принята владельцем; `main`/тег `desktop-baseline-0.1.7-20261111`, база `05e8d34`.
|
||||
Desktop-поведение не менять; общие изменения проверять на регрессии.
|
||||
- Android build/package — Linux CI. Локальные ограничения читать в **`mobile-build.local.md`**;
|
||||
тяжёлые Windows-сборки без разрешения не запускать. Не удалять caches, не устанавливать WSL/Docker.
|
||||
- Продолжение mobile commit/push/CI разрешено. Git — отдельное PowerShell-окно с ручной авторизацией;
|
||||
не читать credentials, не считать GCM исправленным. Без merge main, release или новых секретов.
|
||||
- Телефон: ранее выбран TECNO KJ7. Каждую установку/сброс согласовать; одноразовая TEST-подпись
|
||||
обычно требует disposable reinstall. Стабильную TEST-подпись владелец отложил.
|
||||
- Не включать микрофон/сервер самостоятельно, не читать профиль/identities/секреты и не сохранять PCM.
|
||||
Windows, база `815c7c4`: закрыто поле admin-property:channel_create.channel_description. На локальном beta14 гостю добавлено право b_channel_create_with_description. Адресный тест формы Slint прошёл: после создания многострочный текст совпал с отдельным ответом ядра по ID канала и значением в заново открытом редакторе. Стенд остановлен.
|
||||
|
||||
## Последние подтверждённые device-результаты
|
||||
Windows, база `dd433fa`: после отзыва скачанного релиза повторная проверка обнуляет прогресс, удаляет кэш и не предлагает текущую либо более старую версию. Прошли шесть адресных тестов. Вместе с проверками канала и целостности закрыты preload:checkForUpdates и preference:updateChannel на локальном стенде; установка не выполнялась.
|
||||
|
||||
| Проверка | Результат |
|
||||
|---|---|
|
||||
| Linux CI4955, job5551, `8074343edc78a684764bbe07fc128532a645ca04` | SUCCESS; APK собран |
|
||||
| Тесты | audio173, capture18, lifecycle14, authorization9; clock acquisition3; прочие suites прошли |
|
||||
| Установка | APK-хеш совпал; cold launch успешен |
|
||||
| Bluetooth RX | **Владелец подтвердил звук через G435**; callback пишет ненулевые сэмплы |
|
||||
| Bluetooth TX | **Не принят:** при включении микрофона `FramePositionGap` |
|
||||
| Телефонный источник | Выбранный `Audio device` получил Disconnected / Open Internal; не доказан builtin mic |
|
||||
| UI | Два независимых селектора расположены рядом; проверено скрином |
|
||||
| Фон | Ранее владелец подтвердил Home/screen-off; удаление из Recents завершает звонок |
|
||||
| Повторный вход из Recents / iOS / полный parity | Не приняты; не подменять результатами CI |
|
||||
Windows, база `fa0546e`: закрыт preload:downloadUpdate на локальном HTTP-стенде. Семь адресных тестов прошли: ручная загрузка при активном соединении, отложенная автоматическая загрузка, отказ при неверном размере или SHA512, отмена старого запроса. Укороченный пакет не попал в кэш и не изменил тестовый исполняемый файл; установка не проверялась.
|
||||
|
||||
APK4955 SHA256: `6092ff8801bf38cd6d91f666920fe21162737f51c5425899fd3f6a491a3b85a5`.
|
||||
[CI4955](https://git.eeee.moe/TeamsPeach/client/actions/runs/4955).
|
||||
Windows, база `20e99f0`: при переключении канала обновлений сбрасывается время проверки старого канала. Закрыт preload:setUpdateChannel: выбор Stable из панели «О программе», два перезапуска, отказ записи и устаревшие ответы Preview проверены. Девять адресных тестов прошли на временном профиле и loopback; установщик не запускался.
|
||||
|
||||
## TX-кандидат: CI пройден, headset TX не принят
|
||||
Windows, база `d2617e4`: исправлены предупреждения о конфликте клавиш между разными профилями и подписи безымянных папок в диалоге перемещения закладок. Прошли девять адресных тестов нативного клиента; закрыты поля id, name и parent папок закладок. Проверены маршрутизация клавиш после перезапуска и локальная блокировка сообщений по UID. Системная регистрация клавиш, физическая клавиатура и живой чат в этот прогон не входили.
|
||||
|
||||
- `a0a9b14`: Android capture сохраняет будущий timestamp-хвост callback до SRC/DSP/TX;
|
||||
возраст200ms, epoch/mute/boundary и desktop-путь сохранены (`native/src/media/audio/{devices,engine}.rs`).
|
||||
- EchoReference28 исключён из микрофонов; неизвестные vendor-источники и exact selection не подменяются
|
||||
(`native/vendor/cpal-0.18.2/src/host/aaudio/device_catalog.rs`).
|
||||
- Повтор **CI4959 / `057bfae`: SUCCESS**, APK и тестовые артефакты готовы. Это не приёмка headset TX.
|
||||
- Не откатывать кандидат и не трогать постороннее изменение `.ua/meta.json`.
|
||||
Windows, база `17089bc`: в панели базы клиентов можно выбрать ник или UID и отправить запрос по Enter. На beta14 оба режима вернули ту же запись, что и список. Прошли три теста: поиск, защита от устаревшего ответа, локальный фильтр файлов. Тест нашёл переключатель в дереве Slint и вызвал обработчик отправки; выбор мышью и Enter не имитировались. Стенд остановлен.
|
||||
|
||||
## Android UI — выбор направления
|
||||
Windows, база `bf6adcd`: закрыты client_database_list и client_database_find. На приватном beta14 список и поиск Slint показали одинаковую запись гостя (имя, UID, ID базы). Отдельный CLI-прогон подтвердил совпадение поиска по UID и нику. Прошли четыре нативных теста и два теста stdio. Записи базы не менялись, стенд остановлен; действие client_database_id из UI этим не проверено.
|
||||
|
||||
- На ревизии `057bfae` владелец выбрал voice-first и разрешил собственный Android-стиль:
|
||||
исходная палитра TS6, редактирование цветов в настройках. Windows остаётся без изменений.
|
||||
- До реализации Slint запрошено HTML-сравнение пяти вариантов с одинаковыми сценариями.
|
||||
Локальный прототип: `target/tmp/android-ui-concepts/index.html` (+ CSS, JS, bundled Noto Sans).
|
||||
**Владелец выбрал «Комнату» целиком**, без смешивания вариантов; начат перенос в Android Slint.
|
||||
- В Android Slint перенесены Room-навигация/участники/voice dock, чат и формы; реальные данные идут из
|
||||
`Snapshot.room`, выбор канала/участника и команды остаются typed intents. DSP/media/platform не менялись.
|
||||
- Добавлен `androidPalette`: preview/save/cancel/reset, hex/RGB, контрастные роли; desktop не применяет override.
|
||||
По умолчанию **English**, Russian — через настройки; сохранённый язык не сбрасывается.
|
||||
- Проверено локально: integrated Slint compile PASS; реальные `ui/i18n.rs` tests **3/3 PASS**.
|
||||
- **CI4973 / `956b464`: SUCCESS**, поправка программной навигации включена; APK скачивается для UI-проверки.
|
||||
Preview-tests исправлены под CI-фильтр (только имя тестового модуля); им предстоит отдельный подтверждённый запуск.
|
||||
Android Room-исключение записано в DESIGN.md; desktop baseline сохраняется.
|
||||
Windows, база `f453f48`: при просмотре соседней вкладки кнопки микрофона и динамика Slint меняли флаги владельца ввода. Оба списка участников beta14 подтвердили выключение микрофона, включение и выключение звука; у наблюдателя флаги не изменились. Прошёл один адресный тест. Включение физического микрофона не проверялось, стенд остановлен.
|
||||
|
||||
## Следующее действие
|
||||
Windows, база `6dfaf45`: заглушение и повторное включение звука другой вкладки не отзывают разрешение захвата отправителя. На beta14 проверены сохранение разрешения, продолжение передачи и смена состояния получателя. Прошли три нативных теста; стенд остановлен. Физические устройства не использовались.
|
||||
|
||||
- Проверить хеши APK4973 и UI на TECNO KJ7; отдельно дождаться CI тестового переименования.
|
||||
- **Владелец разрешил установку без удаления данных и offline UI-проверку.** При несовпадении TEST-подписи
|
||||
остановиться и отдельно согласовать переустановку; не подключаться к серверу/микрофону самостоятельно.
|
||||
- Принимать headset TX отдельно от принятого RX. Затем остаются reconnect, Recents first-reopen и
|
||||
совместимые input/output-пары. Сначала использовать сохранённую диагностику, не переписывать RX.
|
||||
Windows, база `a47bebf`: пустой set_audio во время передачи вернул transmitting=true и сохранил действующее разрешение захвата. Частичное обновление оставляет второй флаг без изменений; явный null отклоняется. Прошли один тест stdio и два нативных теста, включая передачу через beta14. Физические устройства не открывались, стенд остановлен.
|
||||
|
||||
## Навигация и доказательства
|
||||
Windows, база `0064353`: закрыт preload:onAudio. После первого сигнала и паузы до тишины получатель отсоединил UI; второй сигнал через beta14 дал новые ненулевые блоки на тестовом выходе без повторного подключения. Прошли четыре адресных нативных теста, включая усиление голоса и изоляцию вкладок. Физические устройства не открывались, стенд остановлен.
|
||||
|
||||
- [Текущая архитектура и ограничения](mobile-port-assessment.md) — читать только нужный раздел.
|
||||
- Последняя диагностика: `target/tmp/android-4955-audio-only.log`,
|
||||
`android-4955-headset-system-summary.json`, `android-4955-rx-working-mic-gap-now.png`.
|
||||
Это локальные артефакты; не считать гарантированно доступными в другом checkout.
|
||||
- `.ua/knowledge-graph.json` — старый snapshot, только навигация. Не пересканировать весь проект;
|
||||
auto-update выключен. Существенные выводы проверять исходниками.
|
||||
- [Архив хронологии](archive/2026-11-14-mobile-port-progress.md) и
|
||||
[архив исследований](archive/2026-11-14-mobile-port-assessment.md) — **не читать при старте**.
|
||||
Открывать нужный участок только по конкретному вопросу; старые ссылки/статусы исторические.
|
||||
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 относятся к этапу до приёмки.
|
||||
- До изменения установки сохранён побайтово проверенный 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 проверки.
|
||||
- Для продолжения нужен безопасный запас свободной RAM по локальной политике; не закрывать пользовательские приложения и не повышать предел автоматически. NSIS 3.13 установлен для будущего native packaging. Backup installation сохранён, профили не читались/не менялись, push после запроса desktop-приёмки не выполнялся.
|
||||
- Пользователь попросил исходить из доступной RAM. Пересчитанный вниз локальный budget успешно выдержал **полный WebRTC source-build**: после timeout на 4010/4305 шагах build возобновлён с cache и завершился exit0; `xtask deps` выдал verified source dependency provenance и обновил реальный Windows record в `native/native-deps.lock.json`. SDK Debugging Tools установлен, dbghelp.dll присутствует. Это dependency compile/inspection pass, не UI/device acceptance. Следом запущен полный Rust/Slint `xtask build --test-harness true` под тем же guard; production install пока не изменён.
|
||||
- Пользователь явно снял паузу («запускай… снимаю с паузы»). Full native harness build возобновлён под сохранённым локальным guard и одним заданием; WebRTC provenance уже готова. До успешных native smoke/package checks установленный 0.1.4 и профиль не менять. Push по-прежнему запрещён до пользовательской приёмки.
|
||||
- Возобновлённая Rust/Slint build дошла до skia-bindings0.153.3: matching prebuilt URL вернул404, source extraction упала на Windows symlink privilege1314. Подготовлен отдельный Skia `m153-0.101.2` в `target/tools`, archive SHA256 `30c8b51a0a32fae63562c303bdc91605519a9598951422610e3fb8685b3c4f6f`; проверены archive paths/symlink target, только extraction выполнен elevated (exit0), global Developer Mode не менялся. Pinned git-sync-deps/GN выполнен serial под guard (exit0). Full build возобновлён с явным --skia-source и локальным Ninja wrapper -j1; установка/профиль не затронуты.
|
||||
- Пользователь после обсуждения длительности явно разрешил продолжить первый Windows-native build («поехали дальше»). Возобновлён тот же cached full Rust/Slint build под локальным guard/-j1/below-normal; готовые WebRTC/Skia объекты не удаляются. Текущая установка и профиль до smoke/package pass не заменяются, push запрещён до desktop-приёмки.
|
||||
- Full harness build **завершился exit0**; `target/x86_64-pc-windows-msvc/release/teamspeach.exe` получен с default Skia+WebRTC. До успешной попытки main rustc получил allocation failure/LLVM OOM под локальными пределами; согласованный пользователем локальный workaround записан только в `mobile-build.local.md`, общие optimization defaults не менялись.
|
||||
- Реальный `xtask smoke --scenario offline-ui` **passed=true**, 8 checks, 28 screenshots: `target/desktop-acceptance/offline-ui/result.json`. Disposable profile, network/OS actions/physical capture выключены; Slint software offscreen. Проверены callback/runtime/settings, rich rendering, PTT focus, draft retention и profile restart; onboarding screenshot просмотрен. Это не GPU/on-device/двусторонний голос acceptance.
|
||||
- Production build **без test-harness** и `xtask package` **exit0**; NSIS и ZIP прошли встроенный `verify-package`: `target/desktop-acceptance/production/x86_64-pc-windows-msvc/verification.json`, `passed=true`, `unsigned-local`, публикация не разрешена. Тот же локальный optimization override; не выдавать пакет за стандартный CI release.
|
||||
- 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*`; публикация установщика не выполняется.
|
||||
|
||||
|
||||
## Текущий маршрут: Android в CI, Windows без WSL
|
||||
|
||||
- После пользовательского входа в Git Credential Manager push **успешен**: `origin/main` обновлён с `eb24965` до `5ce1271` (включая cutover, handoff и граф). Указанный ниже прежний auth blocker снят. Секреты не читались и в документы не записывались.
|
||||
- По отдельному разрешению установлен rustup и toolchain `1.96.0-x86_64-pc-windows-msvc` (`minimal`). Реально выполнены `rustc --version` и `cargo --version`: обе версии 1.96.0. Инструменты находятся в `%USERPROFILE%/.cargo/bin`; уже запущенной оболочке может понадобиться обновление PATH.
|
||||
- По выбору пользователя **весь Android APK/AAB build/package выполняется на Linux CI**; Windows используется для разработки и установки test APK через Platform-Tools. Локальные WSL/Docker/Linux и виртуализация для этого маршрута не нужны. Pinned WebRTC Android source-build официально Linux-only — это требование CI, а не компьютера разработчика. iOS по-прежнему требует macOS/Xcode локально или на CI.
|
||||
- Пользователь возобновил работу после паузы. LLVM 23.1.5 установлен, `clang --version` и `rustc --version` после перезагрузки успешны; CMake/Ninja найдены в Visual Studio Build Tools. `cargo test --locked -p xtask -p teamspeach-core -p teamspeach-denoise` завершился успешно: **246 passed, 1 ignored, 0 failed** (core unit 207; bridge 5; embedded 3; runtime failures 4; DSP 18; xtask 9). Это Windows-проверки core/DSP/упаковщика, не full native UI/WebRTC или device acceptance.
|
||||
- Visual Studio Build Tools **2022 17.14.44** установлен повторной попыткой (официальный актуальный bootstrapper с проверенной подписью Microsoft, exit 0). `vswhere -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64` подтвердил C++ workload, `isComplete=true`, `isLaunchable=true`, `isRebootRequired=false`. Путь: `C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools`. Первая попытка winget завершилась 5008; её результат не считать итоговым.
|
||||
- WSL удалён штатными Appx/MSI uninstall (exit0); проверено AppxPackages=0, MsiPackages=0, DistroCount=0. Удалены его runtime directory, пустое хранилище неудавшейся Ubuntu, `.wslconfig` и пустой WSL installer cache. Windows optional features `VirtualMachinePlatform` и `Microsoft-Windows-Subsystem-Linux` отключены (CIM InstallState=2). Измеренный удалённый runtime payload — около 828 MiB; Windows system launcher/общие Installer caches вручную не удалялись.
|
||||
- Локальные ограничения памяти остаются только в `mobile-build.local.md` и `.git/info/exclude`; не переносить их в общие настройки/граф. Не устанавливать WSL снова для мобильной цели без нового запроса.
|
||||
- Добавлен ручной `.gitea/workflows/android.yml`: ARM64 harness APK и отдельные unsigned production APK/AAB, default Skia+WebRTC, pinned dependencies, receipts и `build-info.json` с revision/SHA256. Для чистого CI Gradle cache добавлен явный Android-package-only `--gradle-online true`; default offline сохранён, SDK downloads выключены, build/project caches изолированы по package.
|
||||
- Проверено после изменения: `cargo test --locked -p xtask` **10 passed, 0 failed**, фактический CLI `--help`, YAML manual trigger, syntax четырёх bash steps и двух Python scripts, локальные ссылки docs. Реальный Android CI/Gradle/APK/device запуск **не выполнен**: нужен provisioned `teamspeach-android-linux-x64` runner и переменные из README. Неавторизованный read-only Actions API вернул HTTP401; наличие/готовность runner неизвестны. Credentials не извлекались.
|
||||
- Изменения текущего CI-маршрута не закоммичены/не отправлены. Граф обновлён по рабочему дереву: **3702 узла, 9131 связей, 7 native-слоёв**, добавлены Android CI, `parse_options`, `android_gradle_command` и текущий маршрут без WSL. Штатный incremental updater отказал из-за dirty tree; использованы установленные scan/import/structure scripts и targeted reconciliation без commit/stash. `meta.json` явно помечен `workingTreeSnapshot=true`; прежние fingerprints/scan baseline не выданы за clean HEAD. Schema/refs проверены, actual dashboard на :5173 отрисовал native+Android CI без Electron-слоёв. Предупреждение working-tree changes остаётся корректным до коммита. Автообновление выключено.
|
||||
|
||||
|
||||
## Native-only cutover
|
||||
|
||||
- Выбранная архитектура: Rust/Slint `native/` + embedded `core::runtime`; Electron/Node application host, `app/`, browser-only `test/`, `scripts/`, npm manifests удалены. Профильный import и защитные проверки устаревшего ciphertext сохранены — это пользовательская совместимость данных, не Electron runtime.
|
||||
- Native icon и 54 WAV перенесены в `native/resources/`; перед удалением старого дерева SHA-256 каждой пары проверен на точное совпадение. Native DSP больше не экспортирует renderer-only WASM ABI; Cargo `denoise` profile удалён.
|
||||
- Build/CI/release переключены на Cargo/xtask и явно подготовленные native Linux x64/ARM64 runners; версия приложения/core/xtask берётся из Cargo workspace. Публикация отдельной командой: проверка artifacts → draft → upload/readback hashes → publish. Историческое исследование в assessment сохранено с immutable ссылками на базовую ревизию.
|
||||
- **Ограничение проверки:** `cargo`, `rustc`, `rustup`, `cl`, `clang`, `cmake`, `ninja` отсутствуют в PATH; стандартные пользовательские каталоги Rust также отсутствуют, CARGO_HOME/RUSTUP_HOME не заданы. Сборочный toolchain автоматически не устанавливался. Нельзя выдавать static checks за native build или device proof.
|
||||
- Мобильные blockers из первоначального исследования не исправляются удалением Electron. Не считать interruption/Bluetooth/background/official-peer сценарии пройденными.
|
||||
- Выполнены 4 Python-теста release transport с mocked HTTP (OK), parse 8 TOML/lock и 3 YAML, проверка 718 сохранённых pending acceptance cases, отсутствие удалённых деревьев и разрешение 21 literal embedded-resource path. Rust unit/build/UI/device checks не выполнены: toolchain отсутствует; `wsl --list --quiet` подтвердил, что WSL не установлен. Новые runner labels/configurations ещё не проверены реальным CI запуском.
|
||||
- Source cutover закоммичен: `220852f8cb7ccb4b912f988f603c23267808626d` (`Remove Electron and make Rust Slint the sole native client`). `git push origin main` завершился ошибкой авторизации: `could not read Username ... terminal prompts disabled`; удалённая ветка этой попыткой не изменена. Авторизовать Git через credential manager/обычный терминал, не передавать токены в чат.
|
||||
- Следующий проверочный шаг для текущей архитектуры: предоставить Rust 1.96.0 и native C/C++/SDK source-build prerequisites, выполнить Cargo/native smoke из README, затем мобильный voice prototype. Старый read-only этап ниже сохранён только как история.
|
||||
- Understand update preflight выбрал `FULL_UPDATE` (314 удалённых граф-файлов, 38 файлов для нового анализа). Итоговая native-only карта: 371 текстовый файл, 3699 узлов, 9120 связей, 7 слоёв, 9 шагов на русском; один binary WAV из 372 scan entries исключён. Schema/path/layer/tour validation прошла без issues, 263 resolved imports сохранены; merger удалил 45 некорректных tested_by связей. Electron runtime/framework/layers отсутствуют, `autoUpdate=false`. Application source — `220852f8`; `meta.json` фиксирует конкретный snapshot после передачи состояния.
|
||||
|
||||
## Историческое исследование до cutover
|
||||
|
||||
## Решения и основания
|
||||
|
||||
- Не начинать переписывание на Flutter/React Native/двух native UI: сначала проверить уже существующие `core::runtime::{CoreHandle,CoreEvents}`, Rust app/services и Android/iOS-адаптеры. Rust/Slint — первый кандидат для прототипа **после** установления этой границы, не безусловный окончательный выбор.
|
||||
- Основной голос — TeamSpeak UDP/Opus; WebRTC используется отдельно для трансляций. Не подменять серверный протокол WebRTC-голосом.
|
||||
- Android и iOS проверять с первого сквозного эксперимента. Общий UI не доказывает одинаковый UX, accessibility или background behaviour.
|
||||
- Не переносить subprocess/stdio/PCM-base64 Electron в мобильный runtime: embedded API уже существует. Сохранять SessionKey, capture epochs, timestamps и единственного владельца микрофона.
|
||||
- Никаких исходников приложения не менять на исследовательском этапе; build/install/test/run/network-to-test-server требуют отдельного разрешения.
|
||||
|
||||
## Выполнено
|
||||
|
||||
- Создан [подробный разбор](mobile-port-assessment.md): стек/входы/build/tests, connect/auth/channels, оба аудиотракта, переносимость, OS-ограничения, официальные dependency references, лицензии и последовательность прототипа с наблюдаемыми критериями.
|
||||
- Однократно проведён первичный Understand-Anything: `.ua/knowledge-graph.json`, `meta.json`, `fingerprints.json`, config и scan inventory. 679 текстовых файлов, 5233 узла, 13204 связи, 9 слоёв и 9 шагов на русском. Scan/fingerprints: 680 entries; один бинарный WAV исключён из графа. `autoUpdate=false`.
|
||||
- Создан корневой [AGENTS.md](../AGENTS.md) с порядком чтения/актуализации переносимой памяти. До сессии корневого файла не было; вложенные инструкции не изменены.
|
||||
|
||||
## Реально проведённые проверки
|
||||
|
||||
- Git metadata/inventory: HEAD, branch, initial porcelain status, 2221 tracked-файл; метаданные путей проверены на reparse links. Пользовательские профили и секреты не открывались.
|
||||
- Статическое чтение исходников и test/build recipes; официальные Slint/CPAL/Sonora/Rust/Electron/LiveKit/Android/Apple/license документы.
|
||||
- Штатные installed Understand scanner/import/batching/structure/merge/fingerprint scripts. `validateGraph` и layer/tour integrity — success, issues отсутствуют; все 872 resolved imports сохранены. Merge удалил 15 некорректных `tested_by` связей.
|
||||
- Проверена фактическая загрузка и отрисовка русского графа в installed understand-dashboard через managed browser; tabs закрыты. Dashboard service запущен на loopback в текущей сессии; для следующей использовать `/understand-dashboard C:/Dev/TeamsPeach`, не сохранять access token.
|
||||
- Проверка путей/диапазонов цитат обнаружила четыре выходивших за EOF диапазона; они сверены с исходниками и исправлены.
|
||||
- Финальная проверка: все 179 source citations к 82 файлам имеют существующие пути и допустимые диапазоны; локальные ссылки документов корректны, code fences сбалансированы. Финальный git status содержит только новые `.ua/`, `AGENTS.md` и два разрешённых документа; tracked/staged diff пуст. Промежуточные файлы Understand перемещены в стандартный `.ua/.trash-*`, scan inventory сохранён.
|
||||
- **Не выполнялись:** сборка/установка/запуск приложения, Node/Cargo tests, мобильный smoke, подключение к серверу, измерение звука, проверка телефона, signing/publishing. Нельзя записывать эти проверки как пройденные.
|
||||
- LSP не настроен (`No language servers configured for this project`). Static Slint site fetch и browser relay дали timeout; официальные versioned docs прочитаны через GitHub, dashboard — через отдельный managed browser. Навыки доступны и реально использованы.
|
||||
|
||||
## Блокеры и риски
|
||||
|
||||
1. **Сборки:** в `native/native-deps.lock.json#/builds` только Windows x64 record. Native recipe требует Linux source-build host для Android и macOS/Xcode для iOS; наличия этих hosts, SDK, signing и test devices не установлено. Не создавать fake provenance.
|
||||
2. **iOS interruption resume:** API `CallLease::resume` есть, вызова из runtime в просмотренном дереве не найдено; common handler останавливает input/output, окончание лишь сообщает статус. Cached mobile lease не равен активной AVAudioSession. Android explicit microphone action может восстановить output через `sync_audio`, но автоматический handler этого не делает. См. assessment §7, не упрощать до «resume нигде невозможен».
|
||||
3. **Реальный audio/runtime:** неизвестны speakerphone AEC, Bluetooth mic/output, timestamps/drift, фон, permission revoke, Wi-Fi↔cellular и VoiceOver parity. Upstream support не доказывает эту сборку.
|
||||
4. **Распространение:** код `UNLICENSED`; разрешение на redistribution заимствованных TeamSpeak icons/sounds не установлено. Slint attribution и полный native dependency/codec notices inventory требуют проверки конечного пакета.
|
||||
5. **Паритет:** `native/compatibility.json` — pending inventory, не доказательство 718 работающих функций; legacy Speex/CELT и перечисленные unsupported services не считать реализованными.
|
||||
|
||||
## Следующий шаг
|
||||
|
||||
После отдельного разрешения на исполнение — подготовить **изолированные** Android/Linux и iOS/macOS build/test среды и пройти assessment §10 по порядку: native dependency/core build → foreground capture/playback → реальный connect и Join ACK → двусторонний голос Android↔iOS↔контрольный desktop peer → privacy/lifecycle/routes/network. Минимальный proof не сокращает требования к полной версии; остальные функции получают отдельную parity-приёмку.
|
||||
|
||||
В новой сессии сначала сопоставить HEAD и uncommitted изменения с этой записью. Перепроверять только затронутые выводы. Новые docs/AGENTS созданы после первичного scan и могут давать честный working-tree warning в dashboard; исходники приложения в этой сессии не менялись. Не перезапускать полный Understand ради новых документов; обновлять граф при архитектурных изменениях, предпочитая incremental.
|
||||
@@ -55,6 +55,8 @@ 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 = "=0.2.0"
|
||||
sonora.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
sonora-ns = "=0.2.0"
|
||||
sonora-ns.workspace = true
|
||||
|
||||
+5
-5
@@ -3,9 +3,9 @@
|
||||
//! 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 public PCM boundaries are normalized `f32` in [-1, 1], not FloatS16.
|
||||
//! Sonora's AudioBuffer performs the internal FloatS16 conversion for AEC/NS/AGC;
|
||||
//! scaling by 32768 here would double-convert and saturate ordinary microphone PCM.
|
||||
//! 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 +27,7 @@ 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/noise-aware gain and limiter; does not add fixed pre-gain.
|
||||
/// Uses Sonora's speech- and noise-aware gain and limiter, without fixed pre-gain.
|
||||
pub automatic_gain_control: bool,
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@ impl CaptureProcessor {
|
||||
})
|
||||
}
|
||||
|
||||
/// Analyze normalized, actual post-gain playout PCM; never modify the supplied frame.
|
||||
/// Analyze the actual, normalized post-gain playout PCM without modifying it.
|
||||
///
|
||||
/// `delay_ms` includes hardware delay, queued samples and resampler latency. Reject
|
||||
/// out-of-range delay rather than silently continuing with Sonora's clamped estimate.
|
||||
|
||||
+94
-67
@@ -275,70 +275,84 @@ fn invalid_settings_never_construct_a_processor() {
|
||||
}
|
||||
}
|
||||
|
||||
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() {
|
||||
// The independent i16 entry point consumes FloatS16 units without the float
|
||||
// API's normalization conversion. This catches both missing and double scaling,
|
||||
// including reverse/AEC scaling, rather than comparing two float wrappers.
|
||||
for echo_cancellation in [false, true] {
|
||||
for noise_suppression in [None, Some(0), Some(1), Some(2), Some(3)] {
|
||||
for automatic_gain_control in [false, true] {
|
||||
let settings = CaptureSettings { echo_cancellation, noise_suppression, automatic_gain_control };
|
||||
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_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 = noise(&mut seed, 0.15).map(|sample| (sample * 32768.0).round() as i16);
|
||||
let input: [i16; FRAME_SAMPLES] = match frame {
|
||||
0..=9 | 90..=119 => [0; FRAME_SAMPLES],
|
||||
10..=39 => harmonic(frame, 0.002).map(|sample| (sample * 32768.0).round() as i16),
|
||||
40..=69 => harmonic(frame, 0.08).map(|sample| (sample * 32768.0).round() as i16),
|
||||
70..=79 => std::array::from_fn(|index| if index % 2 == 0 { i16::MAX } else { i16::MIN }),
|
||||
_ => [512; FRAME_SAMPLES],
|
||||
};
|
||||
let normalized_render = render.map(|sample| f32::from(sample) / 32768.0);
|
||||
let mut actual = input.map(|sample| f32::from(sample) / 32768.0);
|
||||
processor.process_render(&normalized_render, 20).unwrap();
|
||||
integer.set_stream_delay_ms(20).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 (&actual, &expected) in actual.iter().zip(&expected) {
|
||||
assert!((actual * 32768.0 - f32::from(expected)).abs() <= 1.5,
|
||||
"float/i16 scale mismatch: {settings:?}, frame {frame}");
|
||||
}
|
||||
output_energy += energy(&actual);
|
||||
// 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])))
|
||||
}
|
||||
assert!(output_energy > 0.001, "pipeline discarded the entire probe: {settings:?}");
|
||||
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 echo_cancellation in [false, true] {
|
||||
for noise_suppression in [None, Some(0), Some(1), Some(2), Some(3)] {
|
||||
for automatic_gain_control in [false, true] {
|
||||
let settings = CaptureSettings { echo_cancellation, noise_suppression, automatic_gain_control };
|
||||
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_eq!(silence, [0.0; FRAME_SAMPLES], "generated audio: {settings:?}, frame {frame}");
|
||||
}
|
||||
}
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -348,10 +362,10 @@ 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 _ in 0..silent_frames {
|
||||
for frame in 0..silent_frames {
|
||||
let mut silence = [0.0; FRAME_SAMPLES];
|
||||
processor.process_capture(&mut silence).unwrap();
|
||||
assert_eq!(silence, [0.0; FRAME_SAMPLES]);
|
||||
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;
|
||||
@@ -365,10 +379,14 @@ fn agc_does_not_wind_up_in_silence_and_quiet_onset_does_not_clip() {
|
||||
output_energy += energy(&samples);
|
||||
}
|
||||
let gain_db = 10.0 * (output_energy / input_energy).log10();
|
||||
// Default initial gain is 15 dB, at most 6 dB/s adaptation. Silence
|
||||
// must not turn a -50 dBFS onset into a near-full-scale burst.
|
||||
// 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -380,10 +398,15 @@ fn full_scale_impulses_and_polarity_steps_remain_bounded_and_decay_to_silence()
|
||||
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 => std::array::from_fn(|index| if index == 0 { if frame == 0 { 1.0 } else { -1.0 } } else { 0.0 }),
|
||||
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 }),
|
||||
@@ -391,13 +414,16 @@ fn full_scale_impulses_and_polarity_steps_remain_bounded_and_decay_to_silence()
|
||||
};
|
||||
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);
|
||||
// A full-scale onset can legitimately engage Sonora's hard limiter;
|
||||
// do not mistake finite bounded output for proof of no hard clipping.
|
||||
if frame >= 300 {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -421,11 +447,12 @@ fn integrated_noise_suppression_attenuates_dc_without_rail_clipping() {
|
||||
tail_energy += energy(&samples);
|
||||
}
|
||||
}
|
||||
// The split-band HPF has finite DC rejection, not exact DC zeros (see
|
||||
// its biquad numerators). Use the upstream HPF's 47.3 dB DC rejection
|
||||
// criterion rather than an absolute sum that scales with probe length.
|
||||
// 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");
|
||||
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": "a024d6ef8351add55be5e8b1d6cc35f555787660",
|
||||
"upstream_revision": "1632d47c1e77d0857f9145bd175134b348541e11",
|
||||
"packages": [
|
||||
{
|
||||
"name": "sonora",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"registry": "https://crates.io",
|
||||
"archive": "https://static.crates.io/crates/sonora/sonora-0.2.0.crate",
|
||||
"sha256": "2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250",
|
||||
"archive": "https://static.crates.io/crates/sonora/sonora-0.3.0.crate",
|
||||
"sha256": "d461e6c9ad112f8728919387a4bc5639fd28631f2070171efad38676e907edd8",
|
||||
"path_in_vcs": "crates/sonora",
|
||||
"modified_sources": ["src/gain_controller2.rs"],
|
||||
"patch": "Mono AGC2 noise analysis uses a stack channel descriptor. Adaptive gain, fixed gain and limiter borrow AudioBuffer::channel_mut(0), eliminating caller-side per-frame channel/sample Vec allocation and copy-back. Multichannel processing remains the upstream path. Includes mono-vs-identical-stereo signal equivalence test."
|
||||
"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."
|
||||
},
|
||||
{
|
||||
"name": "sonora-agc2",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"registry": "https://crates.io",
|
||||
"archive": "https://static.crates.io/crates/sonora-agc2/sonora-agc2-0.2.0.crate",
|
||||
"sha256": "9a93a9fa8373a33e61a7fb441d8a9e725ac6024079d2c77a845cf6abe1790b9f",
|
||||
"archive": "https://static.crates.io/crates/sonora-agc2/sonora-agc2-0.3.0.crate",
|
||||
"sha256": "501b5dd3f8bdc8c983dc64a131cef22a429f3ff879d6f0007b8bfe46ec7b96aa",
|
||||
"path_in_vcs": "crates/sonora-agc2",
|
||||
"modified_sources": ["src/limiter.rs"],
|
||||
"patch": "Mono limiter level estimation uses a stack immutable channel descriptor rather than collecting Vec<&[f32]>. Multichannel processing and numerical operations remain unchanged."
|
||||
"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."
|
||||
}
|
||||
],
|
||||
"scope": "This removes the inspected AGC2 mono channel-adapter allocations/copies; it is not an allocation-free guarantee for the complete Sonora APM or its other dependencies.",
|
||||
"source": "Copied installed pinned registry sources, retaining upstream Cargo manifests, lockfiles, license, README and VCS metadata; registry .cargo-ok extraction markers omitted.",
|
||||
"verification": "Tests added, not executed by delegated worker. Parent runs verification after integration."
|
||||
"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."
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "a024d6ef8351add55be5e8b1d6cc35f555787660"
|
||||
"sha1": "1632d47c1e77d0857f9145bd175134b348541e11"
|
||||
},
|
||||
"path_in_vcs": "crates/sonora-agc2"
|
||||
}
|
||||
+214
-110
@@ -10,24 +10,52 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.8.0"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
|
||||
checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"
|
||||
dependencies = [
|
||||
"bit-vec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-vec"
|
||||
version = "0.8.0"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269"
|
||||
dependencies = [
|
||||
"borsh",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.1"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
||||
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",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
@@ -40,26 +68,55 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck_derive"
|
||||
version = "1.11.0"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5"
|
||||
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
name = "bytes"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
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"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.0"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
|
||||
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
@@ -73,7 +130,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta",
|
||||
"syn",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -94,10 +151,16 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rustc_version",
|
||||
"syn",
|
||||
"syn 2.0.119",
|
||||
"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"
|
||||
@@ -120,18 +183,6 @@ 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"
|
||||
@@ -140,14 +191,31 @@ checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi 6.0.0",
|
||||
"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",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.189"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
@@ -155,6 +223,12 @@ 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"
|
||||
@@ -177,12 +251,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
name = "proc-macro-crate"
|
||||
version = "3.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -196,16 +270,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "proptest"
|
||||
version = "1.11.0"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
|
||||
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"bit-vec",
|
||||
"bitflags",
|
||||
"chacha20",
|
||||
"core_detect",
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand_chacha",
|
||||
"rand_xorshift",
|
||||
"regex-syntax",
|
||||
"rusty-fork",
|
||||
@@ -228,12 +303,6 @@ 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"
|
||||
@@ -242,38 +311,25 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"getrandom",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
|
||||
|
||||
[[package]]
|
||||
name = "rand_xorshift"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
|
||||
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
|
||||
dependencies = [
|
||||
"rand_core",
|
||||
]
|
||||
@@ -295,9 +351,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
version = "1.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
@@ -324,9 +380,39 @@ 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.2.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"derive_more",
|
||||
@@ -340,9 +426,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-common-audio"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc"
|
||||
checksum = "2c05dfa300c14dc8498751ce2c5b87aad2acf1892d4f9d66b92ae2f372a83410"
|
||||
dependencies = [
|
||||
"derive_more",
|
||||
"sonora-simd",
|
||||
@@ -350,15 +436,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-fft"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012"
|
||||
checksum = "ec3529f2cf748f1acc85d9403ffa08a3fe69dec6bf22383910b3bd21aca2fd26"
|
||||
dependencies = [
|
||||
"sonora-simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-simd"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868"
|
||||
checksum = "f939d8e63a2a0baa7555294d7b09c5e3d382f28358755b920e13ad527658c8fa"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
]
|
||||
@@ -372,7 +461,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta-derive",
|
||||
"syn",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -383,7 +472,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -397,6 +486,17 @@ 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"
|
||||
@@ -404,7 +504,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"getrandom",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys",
|
||||
@@ -420,7 +520,37 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"structmeta",
|
||||
"syn",
|
||||
"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",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -442,7 +572,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -462,9 +592,9 @@ checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
@@ -481,15 +611,6 @@ 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"
|
||||
@@ -506,27 +627,10 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
name = "winnow"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
|
||||
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"memchr",
|
||||
]
|
||||
Vendored
+8
-4
@@ -13,7 +13,7 @@
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
name = "sonora-agc2"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
@@ -37,6 +37,10 @@ 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"]
|
||||
@@ -46,13 +50,13 @@ version = "2"
|
||||
features = ["debug"]
|
||||
|
||||
[dependencies.sonora-common-audio]
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
|
||||
[dependencies.sonora-fft]
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
|
||||
[dependencies.sonora-simd]
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
|
||||
[dependencies.tracing]
|
||||
version = "0.1"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sonora-agc2"
|
||||
version = "0.2.0"
|
||||
version = "0.3.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,6 +122,19 @@ 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());
|
||||
|
||||
@@ -174,7 +187,7 @@ impl AdaptiveDigitalGainController {
|
||||
.set_gain_factor(db_to_ratio(self.last_gain_db + gain_change_this_frame_db));
|
||||
}
|
||||
|
||||
self.gain_applier.apply_gain(frame);
|
||||
self.gain_applier.apply_gain_to_channels(frame);
|
||||
|
||||
// Remember that the gain has changed for the next iteration.
|
||||
self.last_gain_db += gain_change_this_frame_db;
|
||||
|
||||
@@ -45,14 +45,22 @@ 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].len(), self.samples_in_frame as usize);
|
||||
debug_assert_eq!(frame[0].as_ref().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];
|
||||
|
||||
+19
-7
@@ -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(signal: &mut [&mut [f32]]) {
|
||||
fn clip_signal<C: AsMut<[f32]>>(signal: &mut [C]) {
|
||||
for channel in signal.iter_mut() {
|
||||
for sample in channel.iter_mut() {
|
||||
for sample in channel.as_mut().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(
|
||||
fn apply_gain_with_ramping<C: AsMut<[f32]>>(
|
||||
last_gain: f32,
|
||||
gain_at_end: f32,
|
||||
inverse_samples_per_channel: f32,
|
||||
signal: &mut [&mut [f32]],
|
||||
signal: &mut [C],
|
||||
) {
|
||||
// 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(
|
||||
// Gain is constant and different from 1.
|
||||
if last_gain == gain_at_end {
|
||||
for channel in signal.iter_mut() {
|
||||
for sample in channel.iter_mut() {
|
||||
for sample in channel.as_mut().iter_mut() {
|
||||
*sample *= gain_at_end;
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ fn apply_gain_with_ramping(
|
||||
let increment = (gain_at_end - last_gain) * inverse_samples_per_channel;
|
||||
for channel in signal.iter_mut() {
|
||||
let mut gain = last_gain;
|
||||
for sample in channel.iter_mut() {
|
||||
for sample in channel.as_mut().iter_mut() {
|
||||
*sample *= gain;
|
||||
gain += increment;
|
||||
}
|
||||
@@ -81,7 +81,19 @@ impl GainApplier {
|
||||
|
||||
/// Applies gain to the signal with linear ramping between frames.
|
||||
pub fn apply_gain(&mut self, signal: &mut [&mut [f32]]) {
|
||||
let spc = signal.first().map_or(0, |ch| ch.len()) as i32;
|
||||
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;
|
||||
if spc != self.samples_per_channel {
|
||||
self.initialize(spc);
|
||||
}
|
||||
|
||||
+17
-11
@@ -53,11 +53,14 @@ fn compute_per_sample_subframe_factors(
|
||||
}
|
||||
}
|
||||
|
||||
fn scale_samples(per_sample_scaling_factors: &[f32], signal: &mut [&mut [f32]]) {
|
||||
let samples_per_channel = signal.first().map_or(0, |ch| ch.len());
|
||||
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());
|
||||
debug_assert_eq!(samples_per_channel, per_sample_scaling_factors.len());
|
||||
for channel in signal.iter_mut() {
|
||||
for (sample, &factor) in channel.iter_mut().zip(per_sample_scaling_factors) {
|
||||
for (sample, &factor) in channel.as_mut().iter_mut().zip(per_sample_scaling_factors) {
|
||||
*sample = (*sample * factor).clamp(MIN_FLOAT_S16_VALUE, MAX_FLOAT_S16_VALUE);
|
||||
}
|
||||
}
|
||||
@@ -91,16 +94,19 @@ impl Limiter {
|
||||
|
||||
/// Applies limiter and hard-clipping to the signal.
|
||||
pub fn process(&mut self, signal: &mut [&mut [f32]]) {
|
||||
let samples_per_channel = signal.first().map_or(0, |ch| ch.len());
|
||||
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());
|
||||
debug_assert!(samples_per_channel <= MAXIMAL_NUMBER_OF_SAMPLES_PER_CHANNEL);
|
||||
|
||||
// Mono capture needs only a stack descriptor; keep the generic multichannel path.
|
||||
let level_estimate = if signal.len() == 1 {
|
||||
self.level_estimator.compute_level(&[&*signal[0]])
|
||||
} else {
|
||||
let signal_refs: Vec<&[f32]> = signal.iter().map(|ch| &**ch).collect();
|
||||
self.level_estimator.compute_level(&signal_refs)
|
||||
};
|
||||
let level_estimate = self.level_estimator.compute_level_of_channels(signal);
|
||||
|
||||
debug_assert_eq!(level_estimate.len() + 1, self.scaling_factors.len());
|
||||
self.scaling_factors[0] = self.last_scaling_factor;
|
||||
|
||||
+12
-3
@@ -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(audio: &[&[f32]]) -> f32 {
|
||||
fn frame_energy<C: AsRef<[f32]>>(audio: &[C]) -> f32 {
|
||||
let mut energy = 0.0_f32;
|
||||
for channel in audio {
|
||||
let channel_energy: f32 = channel.iter().map(|&s| s * s).sum();
|
||||
let channel_energy: f32 = channel.as_ref().iter().map(|&s| s * s).sum();
|
||||
energy = energy.max(channel_energy);
|
||||
}
|
||||
energy
|
||||
@@ -76,8 +76,17 @@ 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].len();
|
||||
let samples_per_channel = frame[0].as_ref().len();
|
||||
|
||||
// Detect sample rate changes.
|
||||
let sample_rate_hz = samples_per_channel as i32 * FRAMES_PER_SECOND;
|
||||
|
||||
+4
-2
@@ -101,8 +101,10 @@ mod tests {
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes).unwrap();
|
||||
bytes
|
||||
.chunks_exact(4)
|
||||
.map(|c| f32::from_le_bytes(c.try_into().unwrap()))
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| f32::from_le_bytes(*c))
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -540,8 +540,10 @@ mod tests {
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes).unwrap();
|
||||
let floats: Vec<f32> = bytes
|
||||
.chunks_exact(4)
|
||||
.map(|c| f32::from_le_bytes(c.try_into().unwrap()))
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| f32::from_le_bytes(*c))
|
||||
.collect();
|
||||
|
||||
let mut offset = 0;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! 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": "a024d6ef8351add55be5e8b1d6cc35f555787660"
|
||||
"sha1": "1632d47c1e77d0857f9145bd175134b348541e11"
|
||||
},
|
||||
"path_in_vcs": "crates/sonora"
|
||||
}
|
||||
+120
-118
@@ -4,9 +4,9 @@ version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.4"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
|
||||
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
@@ -112,9 +112,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.1"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
@@ -142,13 +142,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck_derive"
|
||||
version = "1.11.0"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5"
|
||||
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -165,9 +165,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.4.0"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"
|
||||
checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
@@ -175,9 +175,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
@@ -214,9 +214,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.4"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d91e0c145792ef73a6ad36d27c75ac09f1832222a3c209689d90f534685ee5b7"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@@ -224,9 +224,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.2"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f09628afdcc538b57f3c6341e9c8e9970f18e4a481690a64974d7023bd33548b"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -236,21 +236,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.4"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"
|
||||
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.3",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.0"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
@@ -260,9 +260,9 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.7"
|
||||
version = "4.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"
|
||||
checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"memchr",
|
||||
@@ -284,9 +284,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cpal"
|
||||
version = "0.18.1"
|
||||
version = "0.18.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f77b11176c37874be37e8d691c946e31b2b8c357abce9526f6a99eb469e1028"
|
||||
checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1"
|
||||
dependencies = [
|
||||
"alsa",
|
||||
"block2",
|
||||
@@ -314,9 +314,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.0"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
|
||||
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
@@ -358,9 +358,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.7"
|
||||
version = "0.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"
|
||||
checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
|
||||
dependencies = [
|
||||
"crossbeam-epoch",
|
||||
"crossbeam-utils",
|
||||
@@ -368,18 +368,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-epoch"
|
||||
version = "0.9.20"
|
||||
version = "0.9.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
|
||||
checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.22"
|
||||
version = "0.8.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "crunchy"
|
||||
@@ -440,39 +440,39 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.17.0"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.9"
|
||||
version = "0.1.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.33"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"
|
||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.33"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109"
|
||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.33"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
@@ -511,9 +511,9 @@ checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.0"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
@@ -552,7 +552,7 @@ dependencies = [
|
||||
"jni-sys 0.4.1",
|
||||
"log",
|
||||
"simd_cesu8",
|
||||
"thiserror 2.0.19",
|
||||
"thiserror 2.0.21",
|
||||
"walkdir",
|
||||
"windows-link",
|
||||
]
|
||||
@@ -600,9 +600,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.103"
|
||||
version = "0.3.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"
|
||||
checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-util",
|
||||
@@ -611,21 +611,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.189"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.33"
|
||||
version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "mach2"
|
||||
@@ -742,9 +742,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.4"
|
||||
version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
|
||||
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
|
||||
dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
@@ -866,9 +866,9 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.33"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "plotters"
|
||||
@@ -900,15 +900,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.14.0"
|
||||
version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d20d5497ef88037a52ff98267d066e7f11fcc5e99bbfbd58a42336193aacec3"
|
||||
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic-util"
|
||||
version = "0.2.7"
|
||||
version = "0.2.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"
|
||||
checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
|
||||
dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
@@ -974,9 +974,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.16"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
@@ -991,9 +991,9 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "ringbuf"
|
||||
version = "0.5.1"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a158e09ede21a14b172ca6cdd6208386c6ae2cb6acef58d774368ef8c450dfa7"
|
||||
checksum = "b58b631e416dd7d84549d7e6a50f767e111f9b03e30d04f40072f6618f386aaf"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
"portable-atomic",
|
||||
@@ -1057,14 +1057,14 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.3",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.151"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
@@ -1112,13 +1112,13 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.15.2"
|
||||
version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
|
||||
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
|
||||
|
||||
[[package]]
|
||||
name = "sonora"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
@@ -1139,9 +1139,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-aec3"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "50280e31256d09f7838aff6715ed4b7640e514dc1092a1e14013c01e552380db"
|
||||
checksum = "f2809c3fda13f71deac22d0ddb6c02c493f254d3da2afe59a7e256a8f15bcffe"
|
||||
dependencies = [
|
||||
"sonora-common-audio",
|
||||
"sonora-fft",
|
||||
@@ -1150,7 +1150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-agc2"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"derive_more",
|
||||
@@ -1162,9 +1162,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-common-audio"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc"
|
||||
checksum = "2c05dfa300c14dc8498751ce2c5b87aad2acf1892d4f9d66b92ae2f372a83410"
|
||||
dependencies = [
|
||||
"derive_more",
|
||||
"sonora-simd",
|
||||
@@ -1172,24 +1172,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sonora-fft"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012"
|
||||
checksum = "ec3529f2cf748f1acc85d9403ffa08a3fe69dec6bf22383910b3bd21aca2fd26"
|
||||
dependencies = [
|
||||
"sonora-simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-ns"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f"
|
||||
checksum = "31c0a62e78419a174dbf9c9c01943c1ecd8c298a68d15c4fb4906cb19f0428b9"
|
||||
dependencies = [
|
||||
"sonora-fft",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sonora-simd"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868"
|
||||
checksum = "f939d8e63a2a0baa7555294d7b09c5e3d382f28358755b920e13ad527658c8fa"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
]
|
||||
@@ -1213,9 +1216,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.3"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -1233,11 +1236,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.19"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl 2.0.19",
|
||||
"thiserror-impl 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1253,13 +1256,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.19"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.3",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1283,18 +1286,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.1+spec-1.1.0"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
|
||||
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_edit"
|
||||
version = "0.25.13+spec-1.1.0"
|
||||
version = "0.25.19+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"
|
||||
checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"toml_datetime",
|
||||
@@ -1304,9 +1307,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
version = "1.1.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
|
||||
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
|
||||
dependencies = [
|
||||
"winnow",
|
||||
]
|
||||
@@ -1374,9 +1377,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
@@ -1408,12 +1411,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.126"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"
|
||||
checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"rustversion",
|
||||
"wasm-bindgen-macro",
|
||||
"wasm-bindgen-shared",
|
||||
@@ -1421,9 +1423,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.126"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"
|
||||
checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
@@ -1431,31 +1433,31 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.126"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"
|
||||
checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"syn 3.0.9",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.126"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"
|
||||
checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-sys"
|
||||
version = "0.3.103"
|
||||
version = "0.3.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"
|
||||
checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
@@ -1613,27 +1615,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.4"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
||||
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.55"
|
||||
version = "0.8.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
|
||||
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.55"
|
||||
version = "0.8.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"
|
||||
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
||||
Vendored
+15
-7
@@ -13,7 +13,7 @@
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
name = "sonora"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
@@ -61,6 +61,14 @@ 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"
|
||||
@@ -93,19 +101,19 @@ version = "0.5"
|
||||
optional = true
|
||||
|
||||
[dependencies.sonora-aec3]
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
|
||||
[dependencies.sonora-agc2]
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
|
||||
[dependencies.sonora-common-audio]
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
|
||||
[dependencies.sonora-ns]
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
|
||||
[dependencies.sonora-simd]
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
|
||||
[dependencies.tracing]
|
||||
version = "0.1"
|
||||
@@ -115,7 +123,7 @@ version = "0.8"
|
||||
features = ["html_reports"]
|
||||
|
||||
[dev-dependencies.sonora-fft]
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
|
||||
[dev-dependencies.tracing-subscriber]
|
||||
version = "0.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sonora"
|
||||
version = "0.2.0"
|
||||
version = "0.3.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,6 +111,69 @@ 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
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -204,6 +267,7 @@ 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,
|
||||
|
||||
+27
-26
@@ -43,6 +43,10 @@ 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 {
|
||||
@@ -120,6 +124,7 @@ impl AudioBuffer {
|
||||
output_resamplers,
|
||||
downmix_by_averaging: true,
|
||||
channel_for_downmixing: 0,
|
||||
scratch: vec![0.0; input_num_frames.max(output_num_frames)],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,9 +232,8 @@ impl AudioBuffer {
|
||||
let resampling_needed = self.input_num_frames != self.buffer_num_frames;
|
||||
|
||||
if downmix_needed {
|
||||
let mut downmix = vec![0.0f32; self.input_num_frames];
|
||||
|
||||
if self.downmix_by_averaging {
|
||||
let downmixed_data: &[f32] = if self.downmix_by_averaging {
|
||||
let downmix = &mut self.scratch[..self.input_num_frames];
|
||||
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];
|
||||
@@ -238,14 +242,7 @@ impl AudioBuffer {
|
||||
}
|
||||
*d = value * scale;
|
||||
}
|
||||
} else {
|
||||
downmix.copy_from_slice(
|
||||
&stacked_data[self.channel_for_downmixing][..self.input_num_frames],
|
||||
);
|
||||
}
|
||||
|
||||
let downmixed_data = if self.downmix_by_averaging {
|
||||
&downmix
|
||||
downmix
|
||||
} else {
|
||||
&stacked_data[self.channel_for_downmixing][..self.input_num_frames]
|
||||
};
|
||||
@@ -318,10 +315,14 @@ 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 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);
|
||||
let written = self.output_resamplers[i]
|
||||
.resample(src, &mut buffer.channel_mut(i)[..buf_frames]);
|
||||
debug_assert_eq!(written, buf_frames);
|
||||
}
|
||||
} else {
|
||||
for i in 0..self.num_channels {
|
||||
@@ -362,13 +363,13 @@ impl AudioBuffer {
|
||||
if self.input_num_channels == 1 {
|
||||
// Mono to mono.
|
||||
if resampling_required {
|
||||
let mut float_buffer = vec![0.0f32; self.input_num_frames];
|
||||
let float_buffer = &mut self.scratch[..self.input_num_frames];
|
||||
audio_util::s16_to_float_s16_slice(
|
||||
&interleaved_data[..self.input_num_frames],
|
||||
&mut float_buffer,
|
||||
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(
|
||||
@@ -378,7 +379,7 @@ impl AudioBuffer {
|
||||
}
|
||||
} else {
|
||||
// Multi-channel to mono (downmix).
|
||||
let mut downmixed = vec![0.0f32; self.input_num_frames];
|
||||
let downmixed = &mut self.scratch[..self.input_num_frames];
|
||||
|
||||
if self.downmix_by_averaging {
|
||||
for (j, sample) in downmixed.iter_mut().enumerate().take(self.input_num_frames)
|
||||
@@ -399,15 +400,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 mut float_buffer = vec![0.0f32; self.input_num_frames];
|
||||
let float_buffer = &mut self.scratch[..self.input_num_frames];
|
||||
for i in 0..self.num_channels {
|
||||
// Deinterleave channel i.
|
||||
for (j, sample) in float_buffer
|
||||
@@ -418,7 +419,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 {
|
||||
@@ -444,11 +445,11 @@ impl AudioBuffer {
|
||||
let resampling_required = self.buffer_num_frames != self.output_num_frames;
|
||||
|
||||
if self.num_channels == 1 {
|
||||
let mut float_buffer = vec![0.0f32; self.output_num_frames];
|
||||
let float_buffer = &mut self.scratch[..self.output_num_frames];
|
||||
|
||||
if resampling_required {
|
||||
let ch0 = self.data.bands(0);
|
||||
self.output_resamplers[0].resample(ch0, &mut float_buffer);
|
||||
self.output_resamplers[0].resample(ch0, float_buffer);
|
||||
} else {
|
||||
float_buffer.copy_from_slice(&self.data.bands(0)[..self.output_num_frames]);
|
||||
}
|
||||
@@ -470,9 +471,9 @@ impl AudioBuffer {
|
||||
} else {
|
||||
if resampling_required {
|
||||
for i in 0..self.num_channels {
|
||||
let mut float_buffer = vec![0.0f32; self.output_num_frames];
|
||||
let float_buffer = &mut self.scratch[..self.output_num_frames];
|
||||
let ch = self.data.bands(i);
|
||||
self.output_resamplers[i].resample(ch, &mut float_buffer);
|
||||
self.output_resamplers[i].resample(ch, float_buffer);
|
||||
for (k, sample) in float_buffer.iter().enumerate().take(self.output_num_frames)
|
||||
{
|
||||
interleaved_data[k * config_num_channels + i] =
|
||||
|
||||
+42
-1
@@ -10,7 +10,7 @@ use std::error;
|
||||
use std::fmt;
|
||||
|
||||
use crate::audio_processing_impl::AudioProcessingImpl;
|
||||
use crate::config::{Config, PlayoutAudioDeviceInfo, RuntimeSetting};
|
||||
use crate::config::{Config, EchoCanceller3Config, PlayoutAudioDeviceInfo, RuntimeSetting};
|
||||
use crate::stats::AudioProcessingStats;
|
||||
use crate::stream_config::StreamConfig;
|
||||
/// Errors returned by audio processing operations.
|
||||
@@ -313,6 +313,7 @@ pub struct AudioProcessingBuilder {
|
||||
capture_config: StreamConfig,
|
||||
render_config: StreamConfig,
|
||||
echo_detector: bool,
|
||||
echo_canceller3_config: Option<EchoCanceller3Config>,
|
||||
}
|
||||
|
||||
impl Default for AudioProcessingBuilder {
|
||||
@@ -322,6 +323,7 @@ impl Default for AudioProcessingBuilder {
|
||||
capture_config: DEFAULT_STREAM_CONFIG,
|
||||
render_config: DEFAULT_STREAM_CONFIG,
|
||||
echo_detector: false,
|
||||
echo_canceller3_config: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -361,9 +363,24 @@ 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();
|
||||
@@ -413,6 +430,30 @@ 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
|
||||
|
||||
+64
-6
@@ -11,6 +11,7 @@ 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,
|
||||
@@ -165,6 +166,8 @@ 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 {
|
||||
@@ -193,11 +196,20 @@ 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()`.
|
||||
@@ -322,6 +334,7 @@ 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]],
|
||||
@@ -329,6 +342,12 @@ 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();
|
||||
@@ -353,6 +372,7 @@ 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]],
|
||||
@@ -360,6 +380,12 @@ 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);
|
||||
|
||||
@@ -387,6 +413,7 @@ impl AudioProcessingImpl {
|
||||
}
|
||||
|
||||
/// Processes a capture audio frame (int16, interleaved).
|
||||
#[inline(never)]
|
||||
pub(crate) fn process_stream_i16(
|
||||
&mut self,
|
||||
src: &[i16],
|
||||
@@ -394,6 +421,12 @@ 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();
|
||||
@@ -429,6 +462,7 @@ 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],
|
||||
@@ -436,6 +470,12 @@ 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();
|
||||
@@ -683,10 +723,11 @@ impl AudioProcessingImpl {
|
||||
.capture_multi_band_processing_active(ec_active)
|
||||
{
|
||||
// Copy the multi-band processed audio to the fullband buffer.
|
||||
// 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);
|
||||
self.capture
|
||||
.capture_audio
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.copy_to_buffer(fullband);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1277,9 +1318,26 @@ impl AudioProcessingImpl {
|
||||
let num_render_channels = self.num_reverse_channels();
|
||||
let num_capture_channels = self.num_proc_channels();
|
||||
|
||||
let mut config = EchoCanceller3Config::default();
|
||||
// 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(),
|
||||
};
|
||||
config.echo_removal_control.transparent_mode = ec.transparent_mode;
|
||||
let multichannel_config = Some(EchoCanceller3Config::create_default_multichannel_config());
|
||||
// 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()),
|
||||
};
|
||||
|
||||
self.submodules.echo_controller = Some(EchoCanceller3::new(
|
||||
config,
|
||||
|
||||
Vendored
+4
-2
@@ -173,8 +173,7 @@ 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). Has no effect
|
||||
/// in mobile mode.
|
||||
/// Enforce the highpass filter to be on (default: true).
|
||||
pub enforce_high_pass_filtering: bool,
|
||||
/// Which transparent mode algorithm to use (default: `Legacy`).
|
||||
///
|
||||
@@ -195,6 +194,9 @@ 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
@@ -0,0 +1,640 @@
|
||||
//! 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:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-15
@@ -560,15 +560,11 @@ 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_sub_frame_and_extract_block(&sub_frame_refs, &mut self.capture_block);
|
||||
.insert_owned_sub_frame_and_extract_block(
|
||||
&self.capture_sub_frame_view,
|
||||
&mut self.capture_block,
|
||||
);
|
||||
|
||||
// Process through block processor.
|
||||
let echo_path_gain_change = level_change || aec_reference_is_downmixed_stereo;
|
||||
@@ -679,14 +675,11 @@ 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_sub_frame_and_extract_block(&sub_frame_refs, &mut self.render_block);
|
||||
.insert_owned_sub_frame_and_extract_block(
|
||||
&self.render_sub_frame_view,
|
||||
&mut self.render_block,
|
||||
);
|
||||
self.block_processor.buffer_render(&self.render_block);
|
||||
}
|
||||
|
||||
|
||||
+29
-24
@@ -104,11 +104,14 @@ fn compute_audio_levels(audio: &AudioBuffer) -> AudioLevels {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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()
|
||||
/// 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes channel data back into an AudioBuffer.
|
||||
@@ -132,6 +135,9 @@ 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 {
|
||||
@@ -201,6 +207,13 @@ 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()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,14 +271,17 @@ 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 {
|
||||
let num_ch = audio.num_channels();
|
||||
let channels: Vec<&[f32]> = (0..num_ch).map(|ch| audio.channel(ch)).collect();
|
||||
Some(nle.analyze(&channels))
|
||||
Some(nle.analyze_owned_frame(&self.channel_data))
|
||||
}
|
||||
} else {
|
||||
None
|
||||
@@ -311,15 +327,10 @@ 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 {
|
||||
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);
|
||||
adc.process_owned_frame(&info, &mut self.channel_data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -327,22 +338,16 @@ impl GainController2 {
|
||||
if audio.num_channels() == 1 {
|
||||
self.fixed_gain_applier.apply_gain(&mut [audio.channel_mut(0)]);
|
||||
} else {
|
||||
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);
|
||||
self.fixed_gain_applier
|
||||
.apply_gain_to_owned_signal(&mut self.channel_data);
|
||||
}
|
||||
|
||||
// Limiter.
|
||||
if audio.num_channels() == 1 {
|
||||
self.limiter.process(&mut [audio.channel_mut(0)]);
|
||||
} else {
|
||||
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);
|
||||
self.limiter.process_owned_signal(&mut self.channel_data);
|
||||
write_back_channels(audio, &self.channel_data);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 736 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user