Compare commits

...
Author SHA1 Message Date
Edison Jwa d97118bb6a docs: update spec and plan for Docusaurus consistency 2026-06-13 03:39:23 +09:00
Edison Jwa 033cf2d7aa chore: update docs submodule to latest (723/723 traceability) 2026-06-13 03:35:30 +09:00
Edison Jwa bba6273af7 refactor: restructure docs as submodule, add dev-docs/ and AGENTS.md
- Move ASPICE docs to chanoraapp/docs submodule at docs/
- Move development docs to dev-docs/ (superpowers, offline-knowledge, impl-mapping)
- Add AGENTS.md with project conventions for AI agents
- Add impl-mapping.md (SAD component → source file mapping)
- Archive completed plans to dev-docs/superpowers/plans/_archived/
- Remove AGENTS.md from .gitignore (now tracked)
2026-06-13 03:32:33 +09:00
Edison Jwa 5765e9cf6f docs: fix final 3 count errors (Dart tests, integration tests, doc count)
- Dart tests: 233→221 (verified with rg count)
- Rust integration tests: 6→5 (5 .rs files in tests/ dirs)
- Doc file count: 86→66 (excluding offline-knowledge/)
2026-06-13 02:36:22 +09:00
Edison Jwa 2e07d5fd4a docs: fix all remaining review issues for 10/10 accuracy
function-inventory.md:
- Fix SnapshotStateMapper → OwnClientSnapshotState + add 3 missing functions
- Fix enum variant counts: CoreError 7→12, ProtocolError 9→10, BridgeError 8→7, AudioError 7→8

coverage-analysis.md:
- Fix total Dart tests 221→233
- Fix chat_views_test.dart count 18→29
- Fix widget test count 13→14, add audio_device_list_tile_test.dart
- Fix total doc count 55→86

doc-quality-analysis.md:
- Relabel 'Useless Content' → 'Path Record Files (DV Navigation Aids)'
- Soften 'identical' → 'overlapping' for commit examples

README.md:
- Update Dart test count 221→233
2026-06-13 02:30:23 +09:00
Edison Jwa f7b0e841f4 docs: apply review corrections and add second-pass review reports
Corrections:
- README: add 6 missing files to index, fix integration test count (2→6)
- coverage-analysis: fix chanora_audio tests (221→333), chanora_core (11→38), integration tests (2→6)
- docs-out-of-date: remove false maintainability-review claim
- link-coverage-report + docs-link-not-covered: fix line number (12→11)

New review reports (5):
- function-inventory-review.md (score: 7/10)
- coverage-docquality-review.md (coverage: 4/10, docquality: 7/10)
- mismatch-outofdate-review.md (mismatch: 8/10, outofdate: 9/10)
- link-reports-review.md (link: 8/10, notcovered: 7/10)
- external-index-review.md (external: 8-9/10, index: 6/10)
2026-06-13 02:26:58 +09:00
Edison Jwa dce6607317 docs: add deep doc-code analysis (mismatch, out-of-date, link coverage)
- docs-code-mismatch.md: 17 mismatches found (2 critical, 4 major, 11 minor)
- docs-out-of-date.md: 12 outdated docs, 8 undocumented recent changes
- docs-link-not-covered.md: 2 broken links, 9 missing targets, 18 orphaned docs
- reviews/: cross-validation for all 3 analyses, corrections applied

Key findings:
- LICENSE-APACHE/LICENSE-MIT files missing (DEC-020 non-compliance)
- README missing 3 crates (resolver, prefetch, cache)
- CHANGELOG missing v0.3.0+ entries
- SAD/SDD missing file transfer, poke, desktop VAD, chanora_cache
2026-06-13 02:14:37 +09:00
Edison Jwa dd6e80f72a docs: add offline knowledge library with project analysis and external references
- function-inventory: complete public API for 10 Rust crates + 56 Dart files
- coverage-analysis: 312 Rust tests, 221 Dart tests, doc coverage gaps
- doc-quality-analysis: duplications, broken refs, useless content audit
- link-coverage-report: all internal/external links validated
- external/teaspeak: TeaSpeak voice server architecture & protocol
- external/respeak: ReSpeak org, tsclientlib, tsproto, crypto docs
- external/yatqa-en/de: yat.qa admin tool (English + German)
- reviews/: cross-validation reports for all analyses

All documentation only, no code changes.
2026-06-13 02:00:26 +09:00
Edison Jwa 89bbfa1e18 fix(ios): activate AVAudioSession before connect to fix voice
Root cause: OSStatus 561145187 (!rec) - AVAudioSession was not in
.playAndRecord mode when VoiceProcessingIO tried to start.

Two changes:
1. Activate session BEFORE rust.connect() so it's ready when auto-join runs
2. Defensive activation in Connected handler as backup

This fixes both the !rec error and the subsequent 'voice_in already taken'
error that occurred after auto-join consumed voice_in on failure.
2026-06-10 18:38:11 +09:00
Edison Jwa 0a6ef55937 fix(ios): unblock iOS Debug builds + regenerate FRB for file transfer API (#41)
* fix(ios): preserve Silero VAD symbols in Flutter Debug builds

Flutter Debug builds split user code into a sibling Chanora.debug.dylib
alongside a minimal launcher executable; the six @_cdecl symbols
chanora_silero_vad_* land in the dylib, not the main binary. Two
problems were hiding behind that:

1. Debug.xcconfig only carried -exported_symbol flags, missing the
   load-bearing -u force-undefined flags Release.xcconfig already had.
   Without -u, the linker dropped the Swift @_cdecl symbols (no Swift
   caller exists) before -exported_symbol could re-export them, so the
   dylib shipped without the VAD entry points.

2. verify_silero_exports.sh inspected only ${EXECUTABLE_PATH}, which in
   Debug builds is the launcher stub. Even with the symbols correctly
   landing in the debug dylib, the script falsely reported them missing.

Mirror Release.xcconfig's -u + -exported_symbol pair in Debug.xcconfig
and teach the verify script to prefer Chanora.debug.dylib when it sits
next to the launcher. Release builds are unaffected (single fat binary
remains the inspected target).

* build(flutter): regenerate FRB bindings for file transfer API

Run flutter_rust_bridge_codegen against the post-PR-#40 chanora_bridge
to emit typed Dart bindings for initCache, downloadAvatar, downloadIcon,
clearFileCache, and fileCacheSize. Replaces the dynamic-cast +
NoSuchMethodError-swallowing shims that lib/src/rust/api.dart shipped
as a pre-regen safety net.

Functional change: downloadAvatar/downloadIcon now return Uint8List?
(was List<int>?) directly through the typed dispatch table. Existing
consumers stay source-compatible because Uint8List extends List<int>;
no call sites needed updates.

* fix(ios): set ITSAppUsesNonExemptEncryption to false

App uses only standard/exempt encryption (HTTPS, system-provided crypto);
declaring exempt status removes the App Store export-compliance prompt
at every TestFlight/release upload.
2026-06-10 15:20:59 +09:00
Edison Jwa aa796d7395 feat: file transfer system (avatar/icon download with cacache) (#40)
* docs(architecture): add file transfer design, research, and implementation plan

* feat(cache): add chanora_cache crate with cacache-backed blob cache

- New chanora_cache crate: content-addressed blob store wrapping cacache
- BlobCache API: async put/get/remove/clear/total_size/evict
- Key validation: av_ prefix (32 hex chars), ic_ prefix (decimal digits)
- Cacache provides crash safety, SSRI integrity, content dedup
- Mtime-based eviction via cacache::list_sync + sort by timestamp
- 7 unit tests all passing
- Added to workspace members

* feat(protocol): add file download support for avatars and icons

- Add Request::DownloadFile variant with oneshot reply
- Add ProtocolClient::download_avatar(client_uid) and download_icon(icon_id)
- Track pending file downloads by FiletransferHandle
- Handle StreamItem::FileDownload: read bytes from TCP stream
- Handle StreamItem::FiletransferFailed: map to ProtocolError
- Add ProtocolError::FileTransfer(String) variant
- Add path helper tests for avatar/icon download paths
- No tsclientlib types leak across the adapter boundary

* feat(core): add blob cache wiring and avatar download orchestration

- Add chanora_cache dependency to Cargo.toml
- Add blob_cache field to ChanoraSession (Arc<Mutex<Option<BlobCache>>>)
- Add init_cache() method: creates BlobCache, runs eviction
- Add get_avatar() method: cache-first, download on miss, store in cache
- Add clear_cache() and cache_size() methods for cache management
- Add CoreError::Cache variant for BlobCacheError conversion
- Add avatar_cache integration test

* feat(bridge): add init_cache, download_avatar, and cache management functions

- Add init_cache(dir) bridge function
- Add download_avatar(avatar_hash, client_uid) bridge function
- Add clear_file_cache() and file_cache_size() bridge functions
- Map CoreError::Cache and ProtocolError::FileTransfer in BridgeError

* feat(flutter): add cache initialization wiring and avatar download shims

- Add wireCache() to app_bootstrap using getApplicationCacheDirectory()
- Call wireCache() after wireStorage() in main bootstrap flow
- Add Dart-side initCache and downloadAvatar wrapper shims in api.dart
- Update Cargo.lock for new chanora_cache dependency

* feat(core): FileTransferService with coalescing, throttling, negative cache

- New file_transfer module with FileTransferService struct
- Semaphore(2) throttles concurrent downloads
- In-flight HashMap coalesces duplicate avatar requests
- 5-min negative cache short-circuits ServerRejected misses
- ChanoraSession delegates get_avatar through the service
- connect/disconnect update shared protocol handle
- clear_cache/cache_size delegate to service
- 2 new unit tests (cached hit, negative cache)

* feat(core,bridge): add get_icon with coalescing and negative cache

- FileTransferService::get_icon() mirrors get_avatar pattern
- ChanoraSession::get_icon() delegates through FileTransferService
- Bridge download_icon() exposed for Flutter
- Dart downloadIcon() shim added
- Uses PREFIX_ICON (ic_<crc32u>) cache key format
- 1 new unit test (cached icon hit)

* fix(core,protocol): simplify store_protocol and add download size cap

- store_protocol: always write to shared Arc<Mutex<Option<ProtocolClient>>>;
  the FileTransferService holds the same Arc so it sees updates automatically
- read_download_bytes: reject downloads exceeding 10 MB to prevent
  malicious servers from causing OOM
2026-06-10 11:45:14 +09:00
Edison Jwa 08d7ace25d fix(audio,flutter): restore VAD on iOS and fix Android build
- Add iOS to voiceActivityTransmitAvailable — iOS has CoreML Silero
  VAD pipeline (AppleCoreMlVadWorker) but was excluded by DEC-030
  gating that predated the CoreML integration
- Inline deleted VadWorkerPolicy in android_voice_unit.rs — PR #37
  removed the enum from vad/mod.rs but missed updating Android
2026-06-10 09:18:32 +09:00
Edison Jwa ddd977796f Merge pull request #39 from EdisonJwa/refactor/remove-ios-raw-unit
refactor(audio): remove experimental iOS RemoteIO+WebRTC APM path
2026-06-10 00:53:43 +09:00
Edison Jwa 2b285491d0 refactor(bridge): remove SonoraExperimental from bridge API and regenerate FRB
Remove SonoraExperimental variant from BridgeIosVoiceProcessingMode
and collapse all match arms in the bridge config builder. Regenerate
flutter_rust_bridge bindings and update Podfile.lock.
2026-06-10 00:51:52 +09:00
Edison Jwa 413f247378 fix(audio): inline VAD worker policy for iOS capture callback
PR #37 inlined VadWorkerPolicy into the desktop capture path but missed
the iOS files. Instead of restoring the deleted types, inline the same
direct if-let-Some pattern into ios_voice_unit.rs (the only remaining
iOS backend) and permanently remove VadWorkerPolicy and
callback_vad_worker_policy from vad/mod.rs.

iOS uses Option<AppleCoreMlVadWorker> with &mut self (no Mutex), so the
inline is simpler than the desktop's try_lock pattern.
2026-06-10 00:47:30 +09:00
Edison Jwa 3f9ea4f7b8 refactor(audio): remove experimental iOS RemoteIO+WebRTC APM path
Delete ios_raw_unit.rs (538 lines) and all SonoraExperimental references
from the core audio crate. The experimental RemoteIO path that bypassed
Apple VPIO in favor of software WebRTC APM was never shipped and is no
longer needed. VPIO is the sole production iOS audio backend.

- Delete ios_raw_unit.rs entirely
- Remove Raw variant from IosVoiceBackend enum in engine.rs
- Remove SonoraExperimental from IosVoiceProcessingMode enum
- Simplify validate_for_ios() (single-variant enum, no mode check)
- Remove 2 SonoraExperimental validation tests
- Remove ios_raw_unit module declaration from lib.rs
- Remove include_str!-based debug_wav test for the deleted file
2026-06-10 00:47:09 +09:00
Edison Jwa 2f6d45fb04 feat(audio): desktop Silero ONNX VAD + Windows PTT modernization + MSVC CRT build fix (#37)
* feat(audio): add Silero ONNX VAD with WebRTC fallback

Introduce SileroOnnxVad and SileroOnnxVadWorker for desktop targets. The worker runs Silero v6 ONNX inference on a dedicated thread, accumulating 10 ms frames into the 512-sample 16 kHz input the model expects. Add VadOutput, VoiceActivityDetector trait, and WebRtcFallbackVad to provide a uniform VAD interface with graceful fallback when the ONNX model is unavailable. Wire the new VadBackend variants through AudioProcessingConfig and the snapshot stats so the bridge can report which detector is active.

* feat(audio): integrate desktop VAD worker into capture engine

Wire SileroOnnxVadWorker into the desktop capture path so voice activity can open the transmit gate before encoding. The capture callback now processes all audio through resample, downmix, and VAD unconditionally; transmit_active still gates Opus encoding.

Add new_desktop_audio_processing_state() to construct the config/stats/worker triple, and apply_desktop_vad_backend() to synchronously load or clear the worker on config changes. Override processing_backend to Noop for desktop so bridge diagnostics report the correct backend rather than the iOS-oriented PlatformVoiceProcessing default.

Includes review-driven cleanups: StreamConfig clone to deref per clippy, and a comment explaining why two try_lock calls on silero_vad_worker are structurally necessary (borrow checker requires the policy probe and the fallback path to not share a lock guard because mark_vad_fallback_active takes &mut self).

* fix(audio): modernize Windows PTT to current windows-rs API

Port the Raw Input plus low-level keyboard hook PTT backend to the newer windows-rs patterns: OptionalHandle, Result-returning CreateWindowExW, and None for CallNextHookEx. Replaces the old HHOOK(0) pointer casts. Add deterministic tests for mouse button 4 and 5 press and release driving the gate.

* build(windows): force MSVC release CRT for audiopus cmake builds

audiopus_sys calls cmake::build(opus_path), so downstream Cargo env cannot use cmake-rs Config::define() to override CMake's MSVC Debug CRT defaults. Point cmake-rs at a small wrapper that injects the policy and cache variables during configure while passing cmake --build, --version, and -E through unchanged. Keeps Opus Debug builds on Rust's release dynamic CRT (/MD) instead of CMake's default debug CRT (/MDd), which otherwise pulls in unresolved __imp__CrtDbgReportW symbols at test link.

Document that the iOS deployment target is intentionally absent from this file. It is enforced by tools/build-ios.sh and the Xcode project; setting it globally here would make native macOS cargo check runs try to link iPhone objects against the macOS SDK.

* build(flutter): update pubspec.lock after plugin additions

Regenerated lockfile reflecting the local_notifications and connectivity_plus plugin additions from the poke-notifications feature.

* fix(audio): address PR #37 review findings

Six fixes from independent PR review:

1. BLOCKER: Replace Windows-only cmake .cmd wrapper with cross-platform
   CMake env vars. Setting CMAKE=tools/cmake-msvc-release-crt.cmd
   globally broke non-Windows hosts because cmake-rs would try to
   execute a .cmd file on macOS/Linux. Instead, set
   CMAKE_POLICY_DEFAULT_CMP0091=NEW and CMAKE_MSVC_RUNTIME_LIBRARY=
   MultiThreadedDLL as env vars that CMake reads natively. MSVC-
   specific vars are safely ignored by GCC/Clang toolchains. Delete
   the now-unnecessary wrapper script.

2. IMPORTANT: Join the Silero worker thread in Drop instead of
   detaching it. The old code dropped the JoinHandle which detaches
   the thread; the new code calls handle.join() after closing the
   channel, ensuring the ONNX session is cleaned up before the
   worker is replaced during config changes.

3. IMPORTANT: Single-try_lock refactor of the capture VAD callback.
   The double try_lock (policy probe + send) is replaced by a single
   scoped try_lock that both probes availability and sends the frame.
   The guard is dropped before the fallback path, which needs &mut
   self for mark_vad_fallback_active. This also eliminates the
   VadWorkerPolicy enum and callback_vad_worker_policy function,
   whose behavior is now inlined into the callback.

4. IMPORTANT: Remove tracing from the realtime capture callback.
   mark_vad_fallback_active and sync_vad_backend emitted info!/warn!
   from the audio thread. Replace with silent atomic state
   publishing via SharedAudioProcessingStats; the bridge stats
   stream already exposes vad_fallback_active for diagnostics.

5. IMPORTANT: Defer ONNX model load outside the worker mutex.
   apply_desktop_vad_backend_to_worker now constructs the new worker
   before taking the lock, then swaps it in under a short hold.
   This prevents the realtime callback from being blocked during
   model I/O + thread spawn.

6. MINOR: Remove unused VadBackend import from vad/mod.rs after
   deleting the policy code.

* fix(audio): address PR #37 second-pass review findings

5-agent review found 5 blocking issues. All addressed:

1. BLOCKER: CMake env vars don't reach CMake cache. Restored .cmd wrapper
   but scoped to Windows MSVC targets only via [target.x86_64-pc-windows-msvc]
   and [target.aarch64-pc-windows-msvc] in .cargo/config.toml. Non-Windows
   hosts are unaffected.

2. BLOCKER: processing_backend normalized in set_audio_processing_config
   on desktop (cfg-gated override to Noop), mirroring startup default.

3. BLOCKER: Model-path reload was already wired via reload_audio_processing_config.
   Fixed misleading doc comment in core/lib.rs.

4. BLOCKER: DEC-030 updated to reflect desktop VoiceActivity enablement.
   Traceability docs (SRS, SysDes, SAD, SDD, implementation-status) updated.

5. Silero ONNX cfg narrowed to desktop-only (excludes macOS/Android).
   Cargo.toml ort dependency target cfg narrowed similarly.

6. Realtime callback debt documented as TODO at CaptureState::ingest.

* fix(audio): exclude ort dep on Android target

ort does not provide first-class Android prebuilts in our pin, mirror the
iOS/macOS exclusion so cargo metadata succeeds for android targets.

* test(audio): fix stale select_ptt_backend import in ptt_privacy

The helper moved out of the ptt_backends submodule onto the crate root;
update the integration test imports so the test compiles again.

* build(windows): scope MSVC release CRT cmake wrapper via Cargo [env]

Cargo's [target.<triple>] table only forwards a fixed allowlist
(linker, runner, rustflags, rustdocflags, ar), so setting CMAKE there
was silently dropped and audiopus_sys kept linking the debug CRT,
producing LNK4098 'MSVCRTD conflicts' and __imp__CrtDbgReportW errors
on x86_64-pc-windows-msvc test builds.

Move the override to Cargo's [env] table using cc/cmake-rs's
target-suffixed CMAKE_<triple> lookup (force=true, relative=true) so it
applies to MSVC targets only and not to host tooling. Add stdout
markers to the wrapper so its invocation is provable in cargo -vv logs.

Verified: cargo test -p chanora_audio --target x86_64-pc-windows-msvc
--lib --no-run now links cleanly; CMakeCache.txt records
CMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDLL and CMP0091=NEW.

* fix(flutter): gate VoiceActivity transmit mode by platform support

VoiceActivity relies on the native VAD worker, which is only wired up
on Windows, Linux, and Android. Showing the option on iOS, macOS, or
web let users select a mode that silently never transmitted.

Add voiceActivityTransmitAvailable + transmitModeSegmentsFor() helpers
in voice_settings_controls.dart, hide the VAD row in voice_compact.dart
and drop the VAD segment from the settings dialog when unsupported.
Keep the legacy const transmitModeSegments for the existing widget test
and add two new tests covering the gated helper.
2026-06-09 20:47:16 +09:00
Edison Jwa 5c3dd70bba fix(ios-audio): activate session before voice joins (#38)
* fix(ios-audio): add voice join session coordinator

* fix(ios-audio): activate session before voice joins

* docs(ios-audio): align activation lifecycle comments

* fix(ios-audio): keep session active when already-in-channel

The 'already in channel' server response (code 0x0302) is treated as a
successful join by _onJoinChannel: the user stays in the channel and
local state is updated to reflect the joined target. But the underlying
voiceJoin call still raises BridgeError_ServerRejected, which the
joinVoiceChannelWithIosAudioSession helper used to interpret as a join
failure and deactivate the iOS audio session. Result: the UI shows the
user as joined while the audio session is dead and capture/playback
remain silent.

Add an isJoinSuccess predicate to the ordering helper. When the
predicate matches, the helper rethrows (so the caller can still run its
success-on-already-joined branch) without deactivating the session.
Wire _onJoinChannel to pass _isAlreadyInChannel as the predicate so the
0x0302 path keeps the session active.

Adds two regression tests covering the success-on-rethrow and the
predicate-false-still-deactivates paths.

* docs(security): regenerate license inventories

Cargo inventory: pick up chanora_resolver bump from 0.1.0 to
0.2.0-beta.1 so it matches the workspace; also adds a trailing newline
so 'cargo about generate' is idempotent in CI license-drift checks.

Flutter inventory: pick up flutter_local_notifications (+ platform
interfaces) and timezone pulled in by the prior notification
permission work.
2026-06-09 19:58:19 +09:00
Edison Jwa ef14c22300 Merge pull request #36 from EdisonJwa/docs/poke-without-message-design
Allow pokes without messages
2026-06-09 09:33:58 +09:00
Edison Jwa b841d3f3e4 docs(security): refresh license inventories 2026-06-09 07:30:23 +09:00
Edison Jwa eca77ece81 fix(chat): allow empty poke messages 2026-06-09 01:47:23 +09:00
Edison Jwa 3462de1eee fix(core): allow empty poke dispatch 2026-06-09 01:44:03 +09:00
Edison Jwa f66118f5bb docs: add poke-without-message design 2026-06-09 00:53:14 +09:00
Edison Jwa 3ef540ae37 Merge pull request #35 from EdisonJwa/feat/poke-notifications
feat: add poke notifications
2026-06-08 23:52:13 +09:00
Edison Jwa e0edcc89ac Merge pull request #34 from EdisonJwa/simplify-project-review
Maintainability continuation and Android smoke evidence
2026-06-08 23:46:37 +09:00
Edison Jwa 7922eabcf0 build(android): keep notification icon resource 2026-06-08 23:38:55 +09:00
Edison Jwa 82bfa0ea1f docs: remove trailing whitespace from continuation design 2026-06-08 23:36:05 +09:00
Edison Jwa dc52092654 docs: remove trailing whitespace from continuation design 2026-06-08 23:32:18 +09:00
Edison Jwa b565663645 feat(chat): route pokes through notifications 2026-06-08 22:56:52 +09:00
Edison Jwa 34a5247457 feat(ui): add poke notification settings dialog 2026-06-08 22:56:04 +09:00
Edison Jwa 9a5f82565d feat(l10n): add poke notification settings copy 2026-06-08 22:55:38 +09:00
Edison Jwa 409cd11c21 feat(flutter): persist poke notification preferences 2026-06-08 22:55:12 +09:00
Edison Jwa 4f1b85cf76 feat(flutter): add poke notification service 2026-06-08 22:54:46 +09:00
Edison Jwa b7cc4d2336 build(apple): declare notification permission usage 2026-06-08 22:54:18 +09:00
Edison Jwa 44f91a2ea4 build(android): configure local notifications 2026-06-08 22:53:53 +09:00
Edison Jwa cc6db18199 build(flutter): add local notification plugin 2026-06-08 22:53:29 +09:00
Edison Jwa 6af2ed9ab5 feat(flutter): regenerate poke strength bridge 2026-06-08 22:53:01 +09:00
Edison Jwa cf64274fe6 feat(bridge): expose poke strength to Flutter 2026-06-08 22:52:33 +09:00
Edison Jwa 5c7a4b64c9 feat(core): propagate poke strength events 2026-06-08 22:52:08 +09:00
Edison Jwa 31cf45ce35 feat(protocol): classify poke notification strength 2026-06-08 22:51:41 +09:00
Edison Jwa a644770488 docs: record Android verification evidence 2026-06-08 21:26:20 +09:00
Edison Jwa 5a1d902795 fix(audio): migrate Android JNI paths 2026-06-08 21:24:16 +09:00
Edison Jwa 901369b072 docs: align core split verification notes 2026-06-08 20:20:48 +09:00
Edison Jwa 57a4d9767b refactor: align bridge state resolver metadata 2026-06-08 20:20:18 +09:00
Edison Jwa 8c4f85ee70 refactor: reuse built-ins and shared helpers 2026-06-08 20:19:17 +09:00
Edison Jwa 7c341d42e5 fix(core,protocol): bound disconnect shutdown 2026-06-08 20:15:50 +09:00
Edison Jwa 8487acf167 docs: align review findings and verification gates 2026-06-08 19:52:16 +09:00
Edison Jwa 8606eb48c8 fix(audio): harden realtime callback paths 2026-06-08 19:40:03 +09:00
Edison Jwa d83539436e fix(voice): preserve mute owners and release touch ptt 2026-06-08 18:00:32 +09:00
Edison Jwa e4fdf8414a docs: add maintainability continuation plan 2026-06-08 17:04:29 +09:00
Edison Jwa 0f41993ed0 docs: add maintainability continuation design 2026-06-08 17:01:59 +09:00
Edison Jwa a0ff17b935 fix(voice,ios): scope AVAudioSession VoiceChat to call lifetime (#33)
Adopt a call-scoped VoIP audio session lifecycle so other apps' audio is
not stopped while Chanora is idle and the in-call session does not get
clobbered by media-server resets unrelated to voice.

AppDelegate.swift
- Set .ambient + .mixWithOthers as the idle baseline so the app does not
  hold a VoiceChat session when no call is active.
- Switch to .playAndRecord + .voiceChat + .mixWithOthers + .duckOthers
  on demand via the new chanora/ios_audio_session MethodChannel, and
  revert to .ambient on deactivate.
- Gate the media-services-reset rebuild on voiceSessionActive so a
  stray reset during idle no longer reactivates VoiceChat.

ios_audio_session_controller.dart (new)
- Thin Dart wrapper around chanora/ios_audio_session with activate/
  deactivate; no-op on non-iOS; swallows PlatformException to keep
  audio start/stop resilient to platform-side races.

main.dart
- Activate the iOS audio session on BridgeEvent_AudioStarted, deactivate
  on BridgeEvent_AudioStopped, fire-and-forget via unawaited().

ios_voice_unit.rs
- Add the 10 local bindings required by the render-callback closure
  preamble (wav_recorder_for_render, render_recorder_active,
  render_ref_len, render_ref_accum, cb_count, last_num_frames,
  num_frames_changes, callbacks_with_audio, callbacks_with_silence)
  so the iOS target compiles cleanly with the new lifecycle wiring.

Tests
- 5 unit tests in test/services/ios_audio_session_controller_test.dart
  cover activate/deactivate on iOS, no-op on non-iOS, and graceful
  PlatformException handling.

Docs
- SRS SRS-110 expanded to cover the call-scoped lifecycle invariant.
- SysDes mobile-voice row updated to reflect the MethodChannel and
  .ambient idle baseline.
- implementation-status-2026-05-28 voiceChat row flipped to done.

Verification
- flutter analyze: No issues found (2.8s)
- flutter test: 195 passed / 2 skipped / 0 failed
- cargo build -p chanora_audio --target aarch64-apple-ios: clean
- cargo build -p chanora_audio (macOS host): clean

Device QA matrix (Spotify-keeps-playing-while-idle, mix-during-call,
revert-on-call-end, media-services-reset-during-idle) remains pending
on physical hardware.
2026-06-08 06:02:12 +09:00
176 changed files with 15121 additions and 28464 deletions
+46 -31
View File
@@ -1,34 +1,49 @@
# Environment variables set for all cargo invocations in this workspace. # audiopus_sys calls cmake::build(opus_path), so downstream Cargo env cannot
# CMAKE_POLICY_VERSION_MINIMUM is required for audiopus_sys's bundled # call cmake-rs Config::define() to override CMake's MSVC Debug CRT defaults.
# Opus CMake build to succeed on CMake 4.x (which removed compatibility # Instead, point cmake-rs at a small wrapper that injects -D cache/policy
# with cmake_minimum_required < 3.5). audiopus_sys v0.2.2 bundles # variables during configure while passing cmake --build / --version / -E /
# Opus 1.3.1 whose CMakeLists.txt uses a very old minimum version. # --install / --open through unchanged. This keeps Opus Debug builds on
# Rust's release dynamic CRT (/MD) instead of CMake's default debug CRT
# (/MDd), which otherwise pulls in unresolved __imp__CrtDbgReportW symbols
# at test link.
#
# IMPORTANT: Cargo's `[target.<triple>]` config sections only forward a
# fixed allowlist of keys (linker, runner, rustflags, rustdocflags, ar)
# to build scripts. Arbitrary keys such as `CMAKE` placed under
# `[target.<triple>]` are silently ignored and never reach the
# audiopus_sys build script. cmake-rs (via cc-style env resolution)
# looks up CMAKE in this order:
# 1. CMAKE_<target-triple-with-dashes>
# 2. CMAKE_<target_triple_with_underscores>
# 3. TARGET_CMAKE (or HOST_CMAKE when host == target)
# 4. CMAKE
# We therefore scope the wrapper to Windows MSVC targets by setting the
# target-suffixed variant in the global [env] section. Non-Windows
# hosts (macOS, Linux, iOS, Android) never see CMAKE set and invoke
# `cmake` directly.
#
# NOTE: CMAKE_POLICY_DEFAULT_CMP0091 and CMAKE_MSVC_RUNTIME_LIBRARY cannot
# be set via the process environment because CMake does NOT auto-import
# them into its cache; they must be passed as `-D` definitions, which the
# wrapper does.
#
# iOS deployment target (DEC-003: iOS 13.0 minimum) is NOT set here. It is
# enforced in two places that own the iOS build:
# 1. tools/build-ios.sh — sets IPHONEOS_DEPLOYMENT_TARGET for the cargo
# invocation and bypasses audiopus_sys's CMake build via
# LIBOPUS_STATIC=1 / LIBOPUS_NO_PKG=1 / LIBOPUS_LIB_DIR.
# 2. apps/chanora_flutter/ios/Runner.xcodeproj — sets the Xcode
# IPHONEOS_DEPLOYMENT_TARGET build setting for the final link.
# Setting it globally here would make native macOS `cargo check` runs try
# to link iPhone objects against the macOS SDK.
[env] [env]
CMAKE_POLICY_VERSION_MINIMUM = "3.5" CMAKE_POLICY_VERSION_MINIMUM = "3.5"
# iOS builds must set IPHONEOS_DEPLOYMENT_TARGET in the invoking script # Scope the cmake wrapper to Windows MSVC targets only via the
# or Xcode build phase. Do not set it globally here: native macOS cargo # target-suffixed env var name that cc/cmake-rs already resolve.
# checks also compile bundled C/C++ dependencies, and a global iOS # Force = true so a developer's pre-existing CMAKE_x86_64-pc-windows-msvc
# deployment target makes clang try to link iPhone objects against the # does not silently bypass the wrapper. Relative = true so the path
# macOS SDK. # resolves from the workspace root regardless of where cargo is invoked.
CMAKE_x86_64-pc-windows-msvc = { value = "tools/cmake-msvc-release-crt.cmd", force = true, relative = true }
# iOS target linker flags (DEC-003: minimum deployment target iOS 13.0). CMAKE_aarch64-pc-windows-msvc = { value = "tools/cmake-msvc-release-crt.cmd", force = true, relative = true }
#
# These rustflags pass -miphoneos-version-min=13.0 to the linker, ensuring
# the final binary targets iOS 13.0+. This is defense-in-depth alongside
# the IPHONEOS_DEPLOYMENT_TARGET env var above — the env var affects C
# compilation (cc crate, CMake), while these rustflags affect the final
# link step.
#
# NOTE: The canonical iOS build is done via tools/build-ios.sh, which
# sets LIBOPUS_STATIC=1, LIBOPUS_NO_PKG=1, and LIBOPUS_LIB_DIR to
# bypass audiopus_sys's CMake build entirely.
[target.aarch64-apple-ios]
rustflags = ["-C", "link-arg=-miphoneos-version-min=13.0"]
[target.aarch64-apple-ios-sim]
rustflags = ["-C", "link-arg=-miphonesimulator-version-min=13.0"]
[target.x86_64-apple-ios]
rustflags = ["-C", "link-arg=-miphonesimulator-version-min=13.0"]
-1
View File
@@ -125,7 +125,6 @@ opencode.json
/apps/chanora_flutter/macos/Frameworks/ /apps/chanora_flutter/macos/Frameworks/
.opencode/ .opencode/
.omo/ .omo/
AGENTS.md
Screenshot 2026-05-17 at 22.23.07.png Screenshot 2026-05-17 at 22.23.07.png
# Xcode archive / export bundles (generated by Product > Archive > Distribute) # Xcode archive / export bundles (generated by Product > Archive > Distribute)
+3
View File
@@ -1,3 +1,6 @@
[submodule "silero-coreml"] [submodule "silero-coreml"]
path = silero-coreml path = silero-coreml
url = git@github.com:chanoraapp/silero-coreml.git url = git@github.com:chanoraapp/silero-coreml.git
[submodule "docs"]
path = docs
url = git@github.com:chanoraapp/docs.git
+111
View File
@@ -0,0 +1,111 @@
# AGENTS.md — Chanora Project Conventions
## Project Overview
Chanora is a cross-platform voice client (Flutter + Rust) targeting TeamSpeak-compatible servers. The project follows ASPICE engineering processes with full traceability from system requirements through verification.
## Repository Structure
```
chanora/ ← Code repo (this one)
├── docs/ → chanoraapp/docs ← Git submodule: ASPICE docs, Docusaurus doc site
├── dev-docs/ ← Local-only development docs
│ ├── superpowers/ ← AI agent specs and plans
│ │ ├── specs/ ← Feature/design specs (active)
│ │ └── plans/ ← Implementation plans (active)
│ │ └── _archived/ ← Completed plans
│ ├── offline-knowledge/ ← Doc maintenance tools, link coverage
│ ├── implementation-status-* ← Code state snapshots
│ └── release/ios-build.md ← Operational build instructions
├── apps/chanora_flutter/ ← Flutter application
├── core/chanora_core/ ← Rust core API + orchestration
├── crates/ ← Rust crates (protocol, audio, state, etc.)
└── dev-docs/impl-mapping.md ← SAD component → source file mapping
```
## Documentation Two-Repo Model
**`docs/` is a git submodule** pointing to the `chanoraapp/docs` repository. It serves a Docusaurus doc site with ASPICE traceability. It is NOT a local directory you can freely create files in.
### What lives where
| Content | Location | Reason |
|---|---|---|
| SysRS, SysDes, SRS, SAD, SDD | `docs/` (submodule) | ASPICE baselines, served on doc site |
| Verification plans (SWE.4/5/6, SYS.4) | `docs/` (submodule) | ASPICE verification evidence |
| Governance, traceability, decision register | `docs/` (submodule) | ASPICE governance |
| Security, privacy, legal | `docs/` (submodule) | Stakeholder-facing |
| UI/UX guidelines, i18n architecture | `docs/` (submodule) | Design references |
| Feature specs and implementation plans | `dev-docs/superpowers/` | Code-coupled, agent working files |
| Link coverage, doc quality analysis | `dev-docs/offline-knowledge/` | Maintenance tools |
| Implementation status snapshots | `dev-docs/` | Code state tracking |
| Source file path references | `dev-docs/impl-mapping.md` | Developer convenience, not ASPICE |
### Rules for agents
1. **Never create or edit files in `docs/`** without understanding it's a submodule. Changes there require committing in the `chanoraapp/docs` repo first, then updating the submodule pointer in this repo.
2. **ASPICE documents do not contain code file paths.** ASPICE traces requirement IDs (e.g., `SysRS-233`, `SRS-045`, `SDD-MOD-009`), not source file paths. If you need to map a component to its source, use or update `dev-docs/impl-mapping.md`.
3. **Specs and plans go in `dev-docs/superpowers/`.** Follow the naming convention: `YYYY-MM-DD-<topic>-design.md` for specs, `YYYY-MM-DD-<topic>.md` for plans.
4. **Completed plans move to `_archived/`.** Once a plan is fully implemented and verified, move it to `dev-docs/superpowers/plans/_archived/`.
5. **Doc site uses Docusaurus.** The `chanoraapp/docs` repo uses Docusaurus 3.10 (Meta-maintained). Do not add MkDocs, mdBook, or other doc site generators.
## ASPICE Traceability Chain
```text
SysRS → SysDes → SRS → SAD (SWE.2) → SDD (SWE.3) → Verification
↓ ↓
SWE.4 (unit) SWE.4/5/6/SYS.4
```
- Requirement IDs are the traceability mechanism, not file paths.
- Every downstream document must reference upstream IDs it traces from.
- Verification plans map to their upstream design/requirements level:
- SYS.4 ← SysDes, SysRS
- SWE.5 ← SAD (SWE.2)
- SWE.4 ← SDD (SWE.3)
- SWE.6 ← SRS
- Requirement IDs should be added to doc front matter `tags:` for traceability browsing.
## Code Architecture
| Component | Location | Responsibility |
|---|---|---|
| Flutter app shell | `apps/chanora_flutter/` | UI, Material 3, navigation, localization |
| Rust core | `core/chanora_core/` | Session orchestration, bridge events |
| Protocol adapter | `crates/chanora_protocol/` | TeamSpeak protocol via tsclientlib |
| State sync | `crates/chanora_state/` | Snapshots, deltas, reducers |
| Audio subsystem | `crates/chanora_audio/` | Capture, DSP, Opus, PTT |
| Storage | `crates/chanora_storage/` | Bookmarks, identity, encryption |
| Diagnostics | `crates/chanora_diagnostics/` | Redaction, logs, export |
| Resolver | `crates/chanora_resolver/` | SRV/TSDNS/DNS resolution |
| Prefetch | `crates/chanora_prefetch/` | Resolution warming, TTL cache |
| Bridge | `crates/chanora_bridge/` | Flutter/Rust typed DTO boundary |
| Cache | `crates/chanora_cache/` | Avatar/icon blob cache |
## Coding Conventions
- **Rust:** Follow workspace `Cargo.toml` structure. Run `cargo check`, `cargo clippy`, `cargo test` before committing.
- **Flutter:** Run `flutter analyze`, `flutter test` before committing.
- **No code comments** unless explicitly requested.
- **Git commits:** Follow convention in `docs/governance/git-commit-message-convention.md` (accessible via submodule).
- **Bridge boundary:** Flutter must not directly depend on protocol-library internals. All cross-boundary communication goes through `chanora_bridge` typed DTOs.
## Verification Commands
```bash
cargo check && cargo clippy && cargo test
cd apps/chanora_flutter && flutter analyze && flutter test
```
## Important References
- Traceability matrix: `docs/governance/traceability-matrix.md`
- Decision register: `docs/governance/product-decision-register.md`
- Security guidelines: `docs/security/security-privacy-legal-guideline.md`
- Release readiness: `docs/release/release-readiness-go-nogo-record.md`
- Doc site repo: `chanoraapp/docs` (Docusaurus)
- Doc site local preview: `cd docs && npm run start`
+16 -12
View File
@@ -8,8 +8,10 @@ This project follows a Conventional Commits style workflow.
The v0.3.0 milestone transitions Chanora from an internal-beta voice The v0.3.0 milestone transitions Chanora from an internal-beta voice
prototype to a cross-platform baseline client with event-driven UI, prototype to a cross-platform baseline client with event-driven UI,
per-user audio controls, non-self client info parity, and CI-hardened visible per-client audio state, non-self client info parity, and
Android / iOS / macOS / Linux builds. documented host Rust workspace plus Flutter validation gates. Android
target compile/install/smoke evidence remains blocked locally pending the
required NDK compiler and an authorized ADB target.
### Added ### Added
@@ -17,10 +19,9 @@ Android / iOS / macOS / Linux builds.
deltas (client join/leave/move/update, channel add/remove/update) deltas (client join/leave/move/update, channel add/remove/update)
flow through a typed `ProtocolDelta` enum and update the Flutter UI flow through a typed `ProtocolDelta` enum and update the Flutter UI
in real time. Channel switching is instant. in real time. Channel switching is instant.
- **Per-user volume controls.** Each client in the snapshot gets an - **Per-client audio state visibility.** Client rows surface
independent volume slider persisted in the bridge layer. Avatar muted/deafened state in avatar badges. Per-user volume UI, persistence,
badges show muted/deafened state. Volume adjustments take effect and mixer wiring remain tracked as follow-up work.
immediately on the audio mix.
- **Non-self client info parity with Qint.** The Info tab now populates - **Non-self client info parity with Qint.** The Info tab now populates
connection metadata (name, description, created, last connected, connection metadata (name, description, created, last connected,
connections, transfer, ping deviation) for other clients via an connections, transfer, ping deviation) for other clients via an
@@ -29,9 +30,10 @@ Android / iOS / macOS / Linux builds.
- **Ping deviation in client profiles.** `ping_deviation_milliseconds` - **Ping deviation in client profiles.** `ping_deviation_milliseconds`
propagated from protocol DTO through bridge API to Dart, with a propagated from protocol DTO through bridge API to Dart, with a
conditional l10n row in the client info sheet (en + zh). conditional l10n row in the client info sheet (en + zh).
- **Apple CoreML Silero VAD** as the preferred voice activity detector - **Apple CoreML Silero VAD scaffolding/assets** for iOS / macOS when
on iOS / macOS when the private `silero-coreml` SwiftPM submodule is the private `silero-coreml` SwiftPM package is available. Product
available. WebRTC VAD remains the runtime fallback. `VoiceActivity` remains reserved/disabled per DEC-030 until a later
baseline enables and verifies it.
- **TeamSpeak address resolver** (`chanora_resolver`) for DNS SRV - **TeamSpeak address resolver** (`chanora_resolver`) for DNS SRV
lookups and `ts3server://` URI handling. lookups and `ts3server://` URI handling.
- **Per-ABI Android APK splitting.** `flutter build apk - **Per-ABI Android APK splitting.** `flutter build apk
@@ -50,8 +52,9 @@ Android / iOS / macOS / Linux builds.
- **iOS / macOS audio lifecycle hardened.** Voice unit restart-in-place, - **iOS / macOS audio lifecycle hardened.** Voice unit restart-in-place,
serialized lifecycle events, WebRTC VAD on iOS, unblocked connect-time serialized lifecycle events, WebRTC VAD on iOS, unblocked connect-time
audio startup. audio startup.
- **Linux native audio path promoted** with ONNX Runtime bundled for - **Linux native audio path promoted** with ONNX Runtime VAD assets
VAD. Desktop voice I/O works on PipeWire / PulseAudio. bundled for future `VoiceActivity` work. Desktop voice I/O works on
PipeWire / PulseAudio; product `VoiceActivity` remains disabled.
- **Android audio routing** uses `MODE_IN_COMMUNICATION`, proper - **Android audio routing** uses `MODE_IN_COMMUNICATION`, proper
startup permission flow, and system back-button integration. startup permission flow, and system back-button integration.
- **`SnapshotChanged` event removed.** Replaced by the typed delta - **`SnapshotChanged` event removed.** Replaced by the typed delta
@@ -59,7 +62,8 @@ Android / iOS / macOS / Linux builds.
Flutter). Flutter).
- **Prefetch crate renamed** from the PoC-era name to - **Prefetch crate renamed** from the PoC-era name to
`chanora_prefetch`. All docs, specs, and code updated. `chanora_prefetch`. All docs, specs, and code updated.
- **Build number bumped to 76.** - **Flutter app version/build bumped to `0.3.0+100`.** Rust workspace
packages remain versioned separately at `0.2.0-beta.1`.
- **Flutter bridge regenerated** for `flutter_rust_bridge` 2.12.0. - **Flutter bridge regenerated** for `flutter_rust_bridge` 2.12.0.
### Fixed ### Fixed
Generated
+368 -16
View File
@@ -148,12 +148,111 @@ version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
dependencies = [ dependencies = [
"event-listener", "event-listener 5.4.1",
"event-listener-strategy", "event-listener-strategy",
"futures-core", "futures-core",
"pin-project-lite", "pin-project-lite",
] ]
[[package]]
name = "async-channel"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35"
dependencies = [
"concurrent-queue",
"event-listener 2.5.3",
"futures-core",
]
[[package]]
name = "async-channel"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
dependencies = [
"concurrent-queue",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-executor"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
dependencies = [
"async-task",
"concurrent-queue",
"fastrand",
"futures-lite",
"pin-project-lite",
"slab",
]
[[package]]
name = "async-global-executor"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c"
dependencies = [
"async-channel 2.5.0",
"async-executor",
"async-io",
"async-lock",
"blocking",
"futures-lite",
"once_cell",
]
[[package]]
name = "async-io"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
dependencies = [
"autocfg",
"cfg-if",
"concurrent-queue",
"futures-io",
"futures-lite",
"parking",
"polling",
"rustix",
"slab",
"windows-sys 0.61.2",
]
[[package]]
name = "async-lock"
version = "3.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
dependencies = [
"event-listener 5.4.1",
"event-listener-strategy",
"pin-project-lite",
]
[[package]]
name = "async-process"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
dependencies = [
"async-channel 2.5.0",
"async-io",
"async-lock",
"async-signal",
"async-task",
"blocking",
"cfg-if",
"event-listener 5.4.1",
"futures-lite",
"rustix",
]
[[package]] [[package]]
name = "async-recursion" name = "async-recursion"
version = "1.1.1" version = "1.1.1"
@@ -165,6 +264,57 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "async-signal"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
dependencies = [
"async-io",
"async-lock",
"atomic-waker",
"cfg-if",
"futures-core",
"futures-io",
"rustix",
"signal-hook-registry",
"slab",
"windows-sys 0.61.2",
]
[[package]]
name = "async-std"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b"
dependencies = [
"async-channel 1.9.0",
"async-global-executor",
"async-io",
"async-lock",
"async-process",
"crossbeam-utils",
"futures-channel",
"futures-core",
"futures-io",
"futures-lite",
"gloo-timers",
"kv-log-macro",
"log",
"memchr",
"once_cell",
"pin-project-lite",
"pin-utils",
"slab",
"wasm-bindgen-futures",
]
[[package]]
name = "async-task"
version = "4.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
[[package]] [[package]]
name = "async-trait" name = "async-trait"
version = "0.1.89" version = "0.1.89"
@@ -257,6 +407,12 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
[[package]]
name = "base64"
version = "0.21.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
[[package]] [[package]]
name = "base64" name = "base64"
version = "0.22.1" version = "0.22.1"
@@ -308,6 +464,19 @@ dependencies = [
"objc2", "objc2",
] ]
[[package]]
name = "blocking"
version = "1.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"
dependencies = [
"async-channel 2.5.0",
"async-task",
"futures-io",
"futures-lite",
"piper",
]
[[package]] [[package]]
name = "build-target" name = "build-target"
version = "0.4.0" version = "0.4.0"
@@ -352,6 +521,32 @@ version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "cacache"
version = "13.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c5063741c7b2e260bbede781cf4679632dd90e2718e99f7715e46824b65670b"
dependencies = [
"async-std",
"digest 0.10.7",
"either",
"futures",
"hex",
"libc",
"memmap2",
"miette",
"reflink-copy",
"serde",
"serde_derive",
"serde_json",
"sha1",
"sha2",
"ssri",
"tempfile",
"thiserror 1.0.69",
"walkdir",
]
[[package]] [[package]]
name = "cast" name = "cast"
version = "0.3.0" version = "0.3.0"
@@ -475,11 +670,23 @@ dependencies = [
"tracing-subscriber", "tracing-subscriber",
] ]
[[package]]
name = "chanora_cache"
version = "0.2.0-beta.1"
dependencies = [
"cacache",
"tempfile",
"thiserror 2.0.18",
"tokio",
"tracing",
]
[[package]] [[package]]
name = "chanora_core" name = "chanora_core"
version = "0.2.0-beta.1" version = "0.2.0-beta.1"
dependencies = [ dependencies = [
"chanora_audio", "chanora_audio",
"chanora_cache",
"chanora_diagnostics", "chanora_diagnostics",
"chanora_prefetch", "chanora_prefetch",
"chanora_protocol", "chanora_protocol",
@@ -515,7 +722,7 @@ name = "chanora_protocol"
version = "0.2.0-beta.1" version = "0.2.0-beta.1"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"base64", "base64 0.22.1",
"chanora_resolver", "chanora_resolver",
"futures", "futures",
"reqwest 0.13.4", "reqwest 0.13.4",
@@ -532,7 +739,7 @@ dependencies = [
[[package]] [[package]]
name = "chanora_resolver" name = "chanora_resolver"
version = "0.1.0" version = "0.2.0-beta.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"hickory-resolver", "hickory-resolver",
@@ -554,7 +761,7 @@ dependencies = [
name = "chanora_storage" name = "chanora_storage"
version = "0.2.0-beta.1" version = "0.2.0-beta.1"
dependencies = [ dependencies = [
"base64", "base64 0.22.1",
"chacha20poly1305", "chacha20poly1305",
"keyring", "keyring",
"rand 0.8.6", "rand 0.8.6",
@@ -1239,6 +1446,12 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "event-listener"
version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
[[package]] [[package]]
name = "event-listener" name = "event-listener"
version = "5.4.1" version = "5.4.1"
@@ -1256,7 +1469,7 @@ version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
dependencies = [ dependencies = [
"event-listener", "event-listener 5.4.1",
"pin-project-lite", "pin-project-lite",
] ]
@@ -1559,6 +1772,18 @@ dependencies = [
"time", "time",
] ]
[[package]]
name = "gloo-timers"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994"
dependencies = [
"futures-channel",
"futures-core",
"js-sys",
"wasm-bindgen",
]
[[package]] [[package]]
name = "group" name = "group"
version = "0.13.0" version = "0.13.0"
@@ -1837,7 +2062,7 @@ version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [ dependencies = [
"base64", "base64 0.22.1",
"bytes", "bytes",
"futures-channel", "futures-channel",
"futures-util", "futures-util",
@@ -2142,6 +2367,15 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "kv-log-macro"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f"
dependencies = [
"log",
]
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
version = "1.5.0" version = "1.5.0"
@@ -2226,6 +2460,9 @@ name = "log"
version = "0.4.31" version = "0.4.31"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "113b30b4cd05f7c06868fdb2854f66a7b9fece9a48425351cd532e810d74024f" checksum = "113b30b4cd05f7c06868fdb2854f66a7b9fece9a48425351cd532e810d74024f"
dependencies = [
"value-bag",
]
[[package]] [[package]]
name = "lru-slab" name = "lru-slab"
@@ -2274,6 +2511,15 @@ version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
[[package]]
name = "memmap2"
version = "0.5.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83faa42c0a078c393f6b29d5db232d8be22776a891f8f56e5284faee4a20b327"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "memoffset" name = "memoffset"
version = "0.9.1" version = "0.9.1"
@@ -2283,6 +2529,29 @@ dependencies = [
"autocfg", "autocfg",
] ]
[[package]]
name = "miette"
version = "5.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59bb584eaeeab6bd0226ccf3509a69d7936d148cf3d036ad350abe35e8c6856e"
dependencies = [
"miette-derive",
"once_cell",
"thiserror 1.0.69",
"unicode-width",
]
[[package]]
name = "miette-derive"
version = "5.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49e7bc1560b95a3c4a25d03de42fe76ca718ab92d1a22a55b9b4cf67b3ae635c"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "mime" name = "mime"
version = "0.3.17" version = "0.3.17"
@@ -2813,6 +3082,17 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "piper"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
dependencies = [
"atomic-waker",
"fastrand",
"futures-io",
]
[[package]] [[package]]
name = "pkcs8" name = "pkcs8"
version = "0.10.2" version = "0.10.2"
@@ -2857,6 +3137,20 @@ dependencies = [
"plotters-backend", "plotters-backend",
] ]
[[package]]
name = "polling"
version = "3.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
dependencies = [
"cfg-if",
"concurrent-queue",
"hermit-abi",
"pin-project-lite",
"rustix",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "poly1305" name = "poly1305"
version = "0.8.0" version = "0.8.0"
@@ -3183,6 +3477,18 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "reflink-copy"
version = "0.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13362233b147e57674c37b802d216b7c5e3dcccbed8967c84f0d8d223868ae27"
dependencies = [
"cfg-if",
"libc",
"rustix",
"windows",
]
[[package]] [[package]]
name = "regex" name = "regex"
version = "1.12.3" version = "1.12.3"
@@ -3218,7 +3524,7 @@ version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [ dependencies = [
"base64", "base64 0.22.1",
"bytes", "bytes",
"futures-core", "futures-core",
"http", "http",
@@ -3256,7 +3562,7 @@ version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"
dependencies = [ dependencies = [
"base64", "base64 0.22.1",
"bytes", "bytes",
"encoding_rs", "encoding_rs",
"futures-core", "futures-core",
@@ -3672,6 +3978,17 @@ dependencies = [
"digest 0.10.7", "digest 0.10.7",
] ]
[[package]]
name = "sha1"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]] [[package]]
name = "sha2" name = "sha2"
version = "0.10.9" version = "0.10.9"
@@ -3851,6 +4168,23 @@ dependencies = [
"der", "der",
] ]
[[package]]
name = "ssri"
version = "9.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7a2b3c2bc9693bcb40870c4e9b5bf0d79f9cb46273321bf855ec513e919082"
dependencies = [
"base64 0.21.7",
"digest 0.10.7",
"hex",
"miette",
"serde",
"sha-1",
"sha2",
"thiserror 1.0.69",
"xxhash-rust",
]
[[package]] [[package]]
name = "stable_deref_trait" name = "stable_deref_trait"
version = "1.2.1" version = "1.2.1"
@@ -4349,7 +4683,7 @@ name = "ts-bookkeeping"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/ReSpeak/tsclientlib.git?rev=04aa2491#04aa24917abbf6a0c8442a79742d6d2d40ecf71e" source = "git+https://github.com/ReSpeak/tsclientlib.git?rev=04aa2491#04aa24917abbf6a0c8442a79742d6d2d40ecf71e"
dependencies = [ dependencies = [
"base64", "base64 0.22.1",
"heck", "heck",
"itertools 0.14.0", "itertools 0.14.0",
"num-derive", "num-derive",
@@ -4370,7 +4704,7 @@ version = "0.2.0"
source = "git+https://github.com/ReSpeak/tsclientlib.git?rev=04aa2491#04aa24917abbf6a0c8442a79742d6d2d40ecf71e" source = "git+https://github.com/ReSpeak/tsclientlib.git?rev=04aa2491#04aa24917abbf6a0c8442a79742d6d2d40ecf71e"
dependencies = [ dependencies = [
"audiopus", "audiopus",
"base64", "base64 0.22.1",
"futures", "futures",
"git-testament", "git-testament",
"hickory-net", "hickory-net",
@@ -4398,7 +4732,7 @@ version = "0.2.0"
source = "git+https://github.com/ReSpeak/tsclientlib.git?rev=04aa2491#04aa24917abbf6a0c8442a79742d6d2d40ecf71e" source = "git+https://github.com/ReSpeak/tsclientlib.git?rev=04aa2491#04aa24917abbf6a0c8442a79742d6d2d40ecf71e"
dependencies = [ dependencies = [
"aes", "aes",
"base64", "base64 0.22.1",
"curve25519-dalek-ng", "curve25519-dalek-ng",
"eax", "eax",
"futures", "futures",
@@ -4427,7 +4761,7 @@ name = "tsproto-packets"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/ReSpeak/tsclientlib.git?rev=04aa2491#04aa24917abbf6a0c8442a79742d6d2d40ecf71e" source = "git+https://github.com/ReSpeak/tsclientlib.git?rev=04aa2491#04aa24917abbf6a0c8442a79742d6d2d40ecf71e"
dependencies = [ dependencies = [
"base64", "base64 0.22.1",
"bitflags 2.12.1", "bitflags 2.12.1",
"num-derive", "num-derive",
"num-traits", "num-traits",
@@ -4442,7 +4776,7 @@ name = "tsproto-structs"
version = "0.2.0" version = "0.2.0"
source = "git+https://github.com/EdisonJwa/tsclientlib.git?branch=fix%2Fp256-short-coordinate-pad#8b7a3226c692319b714ea1d32fd5ded05911aa40" source = "git+https://github.com/EdisonJwa/tsclientlib.git?branch=fix%2Fp256-short-coordinate-pad#8b7a3226c692319b714ea1d32fd5ded05911aa40"
dependencies = [ dependencies = [
"base64", "base64 0.22.1",
"csv", "csv",
"heck", "heck",
"once_cell", "once_cell",
@@ -4455,7 +4789,7 @@ name = "tsproto-structs"
version = "0.2.0" version = "0.2.0"
source = "git+https://github.com/ReSpeak/tsclientlib.git?rev=04aa2491#04aa24917abbf6a0c8442a79742d6d2d40ecf71e" source = "git+https://github.com/ReSpeak/tsclientlib.git?rev=04aa2491#04aa24917abbf6a0c8442a79742d6d2d40ecf71e"
dependencies = [ dependencies = [
"base64", "base64 0.22.1",
"csv", "csv",
"heck", "heck",
"once_cell", "once_cell",
@@ -4468,7 +4802,7 @@ name = "tsproto-types"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/EdisonJwa/tsclientlib.git?branch=fix%2Fp256-short-coordinate-pad#8b7a3226c692319b714ea1d32fd5ded05911aa40" source = "git+https://github.com/EdisonJwa/tsclientlib.git?branch=fix%2Fp256-short-coordinate-pad#8b7a3226c692319b714ea1d32fd5ded05911aa40"
dependencies = [ dependencies = [
"base64", "base64 0.22.1",
"bitflags 2.12.1", "bitflags 2.12.1",
"curve25519-dalek-ng", "curve25519-dalek-ng",
"elliptic-curve", "elliptic-curve",
@@ -4512,6 +4846,12 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-width"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.6" version = "0.2.6"
@@ -4570,6 +4910,12 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "value-bag"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"
[[package]] [[package]]
name = "vcpkg" name = "vcpkg"
version = "0.2.15" version = "0.2.15"
@@ -5256,6 +5602,12 @@ version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
[[package]]
name = "xxhash-rust"
version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3"
[[package]] [[package]]
name = "yoke" name = "yoke"
version = "0.8.2" version = "0.8.2"
@@ -5289,7 +5641,7 @@ dependencies = [
"async-recursion", "async-recursion",
"async-trait", "async-trait",
"enumflags2", "enumflags2",
"event-listener", "event-listener 5.4.1",
"futures-core", "futures-core",
"futures-lite", "futures-lite",
"hex", "hex",
+2
View File
@@ -10,6 +10,7 @@
# crates/chanora_resolver/ — TeamSpeak address resolution # crates/chanora_resolver/ — TeamSpeak address resolution
# crates/chanora_state/ — snapshot, deltas, reducers # crates/chanora_state/ — snapshot, deltas, reducers
# crates/chanora_audio/ — capture, DSP, Opus, jitter, mixer # crates/chanora_audio/ — capture, DSP, Opus, jitter, mixer
# crates/chanora_cache/ — avatar/icon blob cache (cacache-backed)
# crates/chanora_storage/ — bookmarks, settings, identity refs # crates/chanora_storage/ — bookmarks, settings, identity refs
# crates/chanora_diagnostics/ — logs, redaction, export # crates/chanora_diagnostics/ — logs, redaction, export
# crates/chanora_prefetch — server-resolution prefetch cache/policy # crates/chanora_prefetch — server-resolution prefetch cache/policy
@@ -30,6 +31,7 @@ members = [
"crates/chanora_state", "crates/chanora_state",
"crates/chanora_audio", "crates/chanora_audio",
"crates/chanora_storage", "crates/chanora_storage",
"crates/chanora_cache",
"crates/chanora_diagnostics", "crates/chanora_diagnostics",
"crates/chanora_prefetch", "crates/chanora_prefetch",
"crates/chanora_bridge", "crates/chanora_bridge",
+8 -10
View File
@@ -14,10 +14,10 @@ Flutter UI + Rust Core + tsclientlib
## Status ## Status
Chanora is currently in early planning and baseline-candidate design. Chanora is currently a baseline-candidate Flutter + Rust workspace. It is not production-ready and is not approved for public or store release.
```text ```text
Current documentation baseline: v0.9.2 Current documentation baseline: v0.9.x document set
Current status: Baseline Candidate Current status: Baseline Candidate
Implementation status: Not production-ready Implementation status: Not production-ready
``` ```
@@ -25,7 +25,7 @@ Implementation status: Not production-ready
The current engineering focus is: The current engineering focus is:
- defining the system and software architecture; - defining the system and software architecture;
- preparing the Flutter + Rust application structure; - hardening the Flutter + Rust application structure;
- validating TeamSpeak-compatible protocol integration through `tsclientlib`; - validating TeamSpeak-compatible protocol integration through `tsclientlib`;
- defining cross-platform audio behavior; - defining cross-platform audio behavior;
- preparing release, verification, security, privacy, and legal gates. - preparing release, verification, security, privacy, and legal gates.
@@ -49,7 +49,7 @@ Current platform policy:
| iOS / iPadOS runtime target | iOS 16+ while Apple CoreML Silero VAD is linked | | iOS / iPadOS runtime target | iOS 16+ while Apple CoreML Silero VAD is linked |
| macOS runtime target | macOS 13+ while Apple CoreML Silero VAD is linked | | macOS runtime target | macOS 13+ while Apple CoreML Silero VAD is linked |
| App Store Connect upload gate | Xcode 26+ with iOS 26 / iPadOS 26 SDK+ for upload on or after 2026-04-28 | | App Store Connect upload gate | Xcode 26+ with iOS 26 / iPadOS 26 SDK+ for upload on or after 2026-04-28 |
| Android runtime target | Android API 24+ unless Flutter, plugin, audio, or product constraints require raising it | | Android runtime target | Android API 28+ per DEC-004, SysRS-288, SRS-187, and Gradle `minSdk = 28` |
| Google Play target API | Target the Google Play-required API level on upload date | | Google Play target API | Target the Google Play-required API level on upload date |
The App Store / Play Store upload gates are release requirements. They are separate from local development and internal testing requirements. The App Store / Play Store upload gates are release requirements. They are separate from local development and internal testing requirements.
@@ -230,7 +230,7 @@ docs/
aspice-swe2-swe3-integration-note.md aspice-swe2-swe3-integration-note.md
``` ```
Implementation source folders may be added later. A likely structure is: Implementation source folders are present in this workspace. The current high-level structure is:
```text ```text
apps/ apps/
@@ -248,7 +248,7 @@ crates/
chanora_bridge/ chanora_bridge/
``` ```
The exact implementation layout should be finalized when the repository scaffold is created. The exact implementation layout may continue to evolve as maintainability reviews split or merge Modules, but the repository scaffold exists.
--- ---
@@ -395,9 +395,7 @@ docs/governance/git-commit-message-convention.md
## Development ## Development
Implementation commands will be added after the repository scaffold is finalized. Common local commands include:
Expected future commands may include:
```bash ```bash
flutter pub get flutter pub get
@@ -407,7 +405,7 @@ cargo clippy
cargo fmt cargo fmt
``` ```
Do not treat these as authoritative until the actual Flutter/Rust workspace has been created. Android runtime success also requires an available Android NDK toolchain and an authorized device or emulator for build/install/smoke verification.
--- ---
@@ -59,6 +59,7 @@ android {
ndkVersion = flutter.ndkVersion ndkVersion = flutter.ndkVersion
compileOptions { compileOptions {
isCoreLibraryDesugaringEnabled = true
sourceCompatibility = JavaVersion.VERSION_17 sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17
} }
@@ -198,6 +199,7 @@ android {
// armeabi-v7a, x86_64, x86. AGP merges these into the APK/AAB. // armeabi-v7a, x86_64, x86. AGP merges these into the APK/AAB.
dependencies { dependencies {
implementation("com.microsoft.onnxruntime:onnxruntime-android:1.26.0") implementation("com.microsoft.onnxruntime:onnxruntime-android:1.26.0")
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
} }
flutter { flutter {
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@android:color/white"
android:pathData="M12,3C8.69,3 6,5.69 6,9V13C6,16.31 8.69,19 12,19C15.31,19 18,16.31 18,13V9C18,5.69 15.31,3 12,3ZM12,5C14.21,5 16,6.79 16,9V13C16,15.21 14.21,17 12,17C9.79,17 8,15.21 8,13V9C8,6.79 9.79,5 12,5ZM11,20V22H13V20H11Z" />
</vector>
@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
tools:keep="@drawable/ic_chanora_notification" />
@@ -1,6 +1,9 @@
#include? "Pods/Target Support Files/Pods-Chanora/Pods-Chanora.debug.xcconfig" #include? "Pods/Target Support Files/Pods-Chanora/Pods-Chanora.debug.xcconfig"
#include "Generated.xcconfig" #include "Generated.xcconfig"
// Mirror Release.xcconfig (see explanation there). // Mirror Release.xcconfig (see explanation there). `-u` is the load-bearing
OTHER_LDFLAGS = $(inherited) -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_create -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_destroy -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_reset -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_process -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_last_error -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_free_string // flag: without it the linker drops Swift @_cdecl symbols (no Swift caller)
// before `-exported_symbol` can re-export them, and the verify_silero_exports
// build phase fails the build.
OTHER_LDFLAGS = $(inherited) -Xlinker -u -Xlinker _chanora_silero_vad_create -Xlinker -u -Xlinker _chanora_silero_vad_destroy -Xlinker -u -Xlinker _chanora_silero_vad_reset -Xlinker -u -Xlinker _chanora_silero_vad_process -Xlinker -u -Xlinker _chanora_silero_vad_last_error -Xlinker -u -Xlinker _chanora_silero_vad_free_string -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_create -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_destroy -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_reset -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_process -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_last_error -Xlinker -exported_symbol -Xlinker _chanora_silero_vad_free_string
STRIP_STYLE = non-global STRIP_STYLE = non-global
+1 -1
View File
@@ -23,7 +23,7 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/haptic_kit/ios" :path: ".symlinks/plugins/haptic_kit/ios"
SPEC CHECKSUMS: SPEC CHECKSUMS:
chanora_bridge: 26252acdf9ca660ce9c132ad25cd5ad5af467b16 chanora_bridge: 27a03592058709f6f38701343eb51c3a55b02da0
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467 Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
flutter_foreground_task: a159d2c2173b33699ddb3e6c2a067045d7cebb89 flutter_foreground_task: a159d2c2173b33699ddb3e6c2a067045d7cebb89
haptic_kit: b22c4fbb2aa7b0d66f2891f81a9e950ad2de5758 haptic_kit: b22c4fbb2aa7b0d66f2891f81a9e950ad2de5758
+125 -122
View File
@@ -6,6 +6,24 @@ import AVFoundation
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { @objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
private var iosAudioLifecycleChannel: FlutterMethodChannel? private var iosAudioLifecycleChannel: FlutterMethodChannel?
private var iosPlatformChannel: FlutterMethodChannel? private var iosPlatformChannel: FlutterMethodChannel?
private var iosAudioSessionChannel: FlutterMethodChannel?
/// Tracks whether a voice channel is currently active.
///
/// The AVAudioSession is intentionally not configured for VoIP at
/// app launch that would interrupt other apps' audio (Spotify,
/// Apple Music, podcasts) the moment the user opens Chanora, even
/// when they're just reading chat. Production VoIP apps (Telegram
/// group calls, Signal, Discord, Element) only switch the session
/// to `.playAndRecord` + `.voiceChat` when the user actually joins
/// a voice channel. See `docs/architecture/sad.md` and the
/// `chanora/ios_audio_session` MethodChannel contract.
///
/// This flag gates lifecycle handlers (interruption-ended,
/// media-services-reset) so we only rebuild the VoIP session if a
/// call is actually in progress. When false, those handlers leave
/// the session in the inactive `.ambient` baseline.
private var voiceSessionActive: Bool = false
override func application( override func application(
_ application: UIApplication, _ application: UIApplication,
@@ -15,91 +33,28 @@ import AVFoundation
ChanoraSileroSelfTest.run() ChanoraSileroSelfTest.run()
} }
// Configure the iOS AVAudioSession **category + mode** at // AVAudioSession lifecycle policy (DEC-2026-06-08, supersedes
// app-launch time, but DEFER setActive(true) until the scene // the launch-time .playAndRecord setup):
// is foregrounded. Calling setActive in didFinishLaunching is
// racy on iOS 17+ devices: if the user launches the app from a
// cold state, the UIApplication isn't yet `.active` and
// setActive returns `AVAudioSessionErrorCodeCannotStartPlaying`
// (561017449) the iOS audio policy server refuses to grant
// the audio session because the app is not yet considered the
// foreground priority owner. Symptom in production builds:
// 'AVAudioSession setup failed: Error 561017449 "Session
// activation failed"' in NSLog, after which the audio engine
// is unusable until the user backgrounds + foregrounds the
// app.
// //
// The category itself can be set whenever; only the active // At launch we set the category to .ambient and leave the
// state needs to be deferred. We listen for // session INACTIVE matching the Telegram / Signal / Discord /
// didBecomeActiveNotification and activate then. Most // Element / Jitsi pattern and Apple's guidance that "a VoIP
// production iOS voice apps (Discord, Zoom, FaceTime) follow // app's audio session should not be active" while idle.
// this same shape. // Configuring .playAndRecord + .voiceChat at launch stops other
// apps' music (Spotify, Apple Music, podcasts) the moment the
// user opens Chanora, even when they are just reading text chat.
//
// VoIP configuration is engaged on voice-channel join via the
// `chanora/ios_audio_session` MethodChannel, driven from Dart
// before `voiceJoin` starts VoiceProcessingIO and again as an
// idempotent guard on the AudioStarted lifecycle.
do { do {
let session = AVAudioSession.sharedInstance() try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default)
try session.setCategory( logAudioSessionState(context: "launch-ambient")
.playAndRecord,
mode: .voiceChat,
// Mode rationale (May 2026, .voiceChat reinstated):
//
// We previously used .default mode after discovering that
// .voiceChat routed output through iOS's in-call audio
// channel, which made speaker output barely audible. That
// bug was caused by cpal's RemoteIO unit binding to a stale
// physical transducer after migrating to coreaudio-rs +
// kAudioUnitSubType_VoiceProcessingIO (see
// crates/chanora_audio/src/ios_voice_unit.rs) the route
// binding is correct under either mode because VPIO re-binds
// on overrideOutputAudioPort.
//
// .voiceChat advantages over .default:
// * Tells iOS this is a VoIP session other apps' audio
// is properly ducked/paused instead of competing.
// * Enables correct Bluetooth HFP negotiation without
// manual workarounds.
// * iOS treats the audio session as a "call" for priority
// purposes (won't be interrupted by notification sounds).
// * System-level CallKit integration (lock-screen controls).
//
// .defaultToSpeaker ensures output goes to the main speaker
// (not the earpiece) by default when no headphones are
// connected, compensating for the in-call channel's tendency
// to route to the earpiece.
//
// References:
// * https://github.com/twilio/video-quickstart-ios/issues/522
// * https://stackoverflow.com/questions/79834998 (Daily.co)
//
// Options:
// .defaultToSpeaker : route output to the main speaker
// (not the earpiece) by default
// when no headphones are connected.
// .allowBluetoothHFP : permit Bluetooth Hands-Free
// Profile headsets as both input
// and output.
// .allowBluetoothA2DP : permit higher-quality A2DP
// output-only Bluetooth devices.
options: [.defaultToSpeaker, .allowBluetoothHFP, .allowBluetoothA2DP]
)
// Match VPIO / Opus frame cadence to reduce callback pressure.
try session.setPreferredIOBufferDuration(0.02)
try session.setPreferredSampleRate(48000.0)
logAudioSessionState(context: "setCategory")
} catch { } catch {
NSLog("chanora_flutter: AVAudioSession setCategory failed: \(error)") NSLog("chanora_flutter: AVAudioSession .ambient baseline failed: \(error)")
} }
// Activate the session once the app is actually foreground. The
// notification fires immediately after the cold-launch settles,
// and again on every resume-from-background both safe
// moments to call setActive(true). Repeated activation while
// already-active is a no-op per the docs.
NotificationCenter.default.addObserver(
self,
selector: #selector(activateAudioSession),
name: UIApplication.didBecomeActiveNotification,
object: nil
)
NotificationCenter.default.addObserver( NotificationCenter.default.addObserver(
self, self,
selector: #selector(handleRouteChange(_:)), selector: #selector(handleRouteChange(_:)),
@@ -124,37 +79,60 @@ import AVFoundation
return super.application(application, didFinishLaunchingWithOptions: launchOptions) return super.application(application, didFinishLaunchingWithOptions: launchOptions)
} }
/// Called by `didBecomeActiveNotification` (cold-launch settle + /// Activate the VoIP audio session. Called from Dart via the
/// every resume-from-background). Activates the AVAudioSession. /// `chanora/ios_audio_session` channel before a voice channel join
/// Repeated activation is a no-op when the session is already /// starts VoiceProcessingIO. Configures
/// active so this is safe to call on every foreground. /// .playAndRecord + .voiceChat with .mixWithOthers so other apps
@objc private func activateAudioSession() { /// (Spotify, podcasts) can keep playing alongside the voice
/// channel matching the Telegram group-call UX. Idempotent:
/// repeated calls while already active are a no-op.
private func activateVoiceSession() {
do { do {
try AVAudioSession.sharedInstance().setActive(true, options: []) let session = AVAudioSession.sharedInstance()
NSLog("chanora_flutter: AVAudioSession activated on foreground") try session.setCategory(
// Read back the ACTUAL session state. preferredSampleRate / .playAndRecord,
// preferredIOBufferDuration are hints; iOS may pick something mode: .voiceChat,
// else depending on hardware + currently-engaged effects. options: [.defaultToSpeaker, .allowBluetoothHFP, .allowBluetoothA2DP, .mixWithOthers]
// Without these we can't tell whether VPIO is running at )
// 48 kHz mono (what our render callback assumes) or at e.g. try session.setPreferredIOBufferDuration(0.02)
// 44.1 kHz (which would explain the user's broken playback try session.setPreferredSampleRate(48000.0)
// \u2014 our render callback would be writing samples at the try session.setActive(true, options: [])
// wrong rate, causing pitch + timing artifacts). voiceSessionActive = true
logAudioSessionState(context: "setActive") logAudioSessionState(context: "activateVoiceSession")
let s = AVAudioSession.sharedInstance() let ins = session.currentRoute.inputs.map { $0.portType.rawValue }.joined(separator: ",")
let ins = s.currentRoute.inputs.map { $0.portType.rawValue }.joined(separator: ",")
NSLog( NSLog(
"chanora_flutter: AVAudioSession actual: " + "chanora_flutter: voice session active: " +
"sampleRate=\(s.sampleRate) " + "sampleRate=\(session.sampleRate) " +
"ioBufferDuration=\(String(format: "%.4f", s.ioBufferDuration)) " + "ioBufferDuration=\(String(format: "%.4f", session.ioBufferDuration)) " +
"inputs=[\(ins)] " + "inputs=[\(ins)] outputVolume=\(session.outputVolume)"
"outputVolume=\(s.outputVolume)"
) )
} catch { } catch {
NSLog("chanora_flutter: AVAudioSession setActive failed: \(error)") NSLog("chanora_flutter: activateVoiceSession failed: \(error)")
} }
} }
/// Deactivate the VoIP audio session and return to the idle
/// .ambient baseline. Called from Dart on `BridgeEvent::AudioStopped`
/// (intentional leave, disconnect, or connection lost).
/// `.notifyOthersOnDeactivation` lets other audio apps know they
/// can resume best-effort: Apple Music / Podcasts resume
/// reliably, Spotify is not guaranteed.
private func deactivateVoiceSession() {
let session = AVAudioSession.sharedInstance()
do {
try session.setActive(false, options: [.notifyOthersOnDeactivation])
} catch {
NSLog("chanora_flutter: deactivateVoiceSession setActive(false) failed: \(error)")
}
do {
try session.setCategory(.ambient, mode: .default)
} catch {
NSLog("chanora_flutter: deactivateVoiceSession setCategory(.ambient) failed: \(error)")
}
voiceSessionActive = false
logAudioSessionState(context: "deactivateVoiceSession")
}
/// Reads back the actual AVAudioSession state and logs it for /// Reads back the actual AVAudioSession state and logs it for
/// SDD-098 compliance. Called after both setCategory and setActive /// SDD-098 compliance. Called after both setCategory and setActive
/// to verify that the session accepted the requested configuration. /// to verify that the session accepted the requested configuration.
@@ -219,25 +197,30 @@ import AVFoundation
} }
@objc private func handleMediaServicesReset(_ notification: Notification) { @objc private func handleMediaServicesReset(_ notification: Notification) {
NSLog("chanora_flutter: media services reset") NSLog("chanora_flutter: media services reset voiceActive=\(voiceSessionActive)")
do { if voiceSessionActive {
let session = AVAudioSession.sharedInstance() do {
try session.setCategory( let session = AVAudioSession.sharedInstance()
.playAndRecord, try session.setCategory(
mode: .voiceChat, .playAndRecord,
options: [.defaultToSpeaker, .allowBluetoothHFP, .allowBluetoothA2DP] mode: .voiceChat,
) options: [.defaultToSpeaker, .allowBluetoothHFP, .allowBluetoothA2DP, .mixWithOthers]
try session.setPreferredIOBufferDuration(0.02) )
try session.setPreferredSampleRate(48000.0) try session.setPreferredIOBufferDuration(0.02)
try session.setActive(true, options: []) try session.setPreferredSampleRate(48000.0)
logAudioSessionState(context: "mediaServicesWereReset") try session.setActive(true, options: [])
} catch { logAudioSessionState(context: "mediaServicesWereReset-voip")
NSLog("chanora_flutter: AVAudioSession media-services reset rebuild failed: \(error)") } catch {
NSLog("chanora_flutter: AVAudioSession media-services reset rebuild failed: \(error)")
}
} else {
do {
try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default)
logAudioSessionState(context: "mediaServicesWereReset-ambient")
} catch {
NSLog("chanora_flutter: AVAudioSession media-services reset ambient restore failed: \(error)")
}
} }
// P1: After rebuilding the session, send the current route class to
// Rust so it can recompute the processing policy and reset the
// AudioUnit. The Rust side handles this via ios_handle_media_services_reset
// which calls ios_restart_voice_unit.
let routeClass = classifyAudioRoute(AVAudioSession.sharedInstance().currentRoute) let routeClass = classifyAudioRoute(AVAudioSession.sharedInstance().currentRoute)
NSLog("chanora_flutter: media services reset complete, route=\(routeClass)") NSLog("chanora_flutter: media services reset complete, route=\(routeClass)")
iosAudioLifecycleChannel?.invokeMethod("handleMediaServicesReset", arguments: routeClass) iosAudioLifecycleChannel?.invokeMethod("handleMediaServicesReset", arguments: routeClass)
@@ -269,6 +252,26 @@ import AVFoundation
name: "chanora/ios_platform", name: "chanora/ios_platform",
binaryMessenger: engineBridge.applicationRegistrar.messenger() binaryMessenger: engineBridge.applicationRegistrar.messenger()
) )
iosAudioSessionChannel = FlutterMethodChannel(
name: "chanora/ios_audio_session",
binaryMessenger: engineBridge.applicationRegistrar.messenger()
)
iosAudioSessionChannel?.setMethodCallHandler { [weak self] call, result in
guard let self = self else {
result(FlutterError(code: "delegate_gone", message: "AppDelegate deallocated", details: nil))
return
}
switch call.method {
case "activateVoiceSession":
self.activateVoiceSession()
result(nil)
case "deactivateVoiceSession":
self.deactivateVoiceSession()
result(nil)
default:
result(FlutterMethodNotImplemented)
}
}
iosPlatformChannel?.setMethodCallHandler { call, result in iosPlatformChannel?.setMethodCallHandler { call, result in
switch call.method { switch call.method {
case "getMicrophonePermissionState": case "getMicrophonePermissionState":
+3 -1
View File
@@ -25,7 +25,7 @@
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string> <string>$(FLUTTER_BUILD_NUMBER)</string>
<key>ITSAppUsesNonExemptEncryption</key> <key>ITSAppUsesNonExemptEncryption</key>
<true/> <false/>
<key>LSRequiresIPhoneOS</key> <key>LSRequiresIPhoneOS</key>
<true/> <true/>
<key>LSSupportsOpeningDocumentsInPlace</key> <key>LSSupportsOpeningDocumentsInPlace</key>
@@ -34,6 +34,8 @@
<string>Chanora needs local network access to connect to your voice servers.</string> <string>Chanora needs local network access to connect to your voice servers.</string>
<key>NSMicrophoneUsageDescription</key> <key>NSMicrophoneUsageDescription</key>
<string>Chanora needs microphone access so you can talk on your voice server.</string> <string>Chanora needs microphone access so you can talk on your voice server.</string>
<key>NSUserNotificationsUsageDescription</key>
<string>Chanora sends you a notification when another user pokes you.</string>
<key>UIApplicationSceneManifest</key> <key>UIApplicationSceneManifest</key>
<dict> <dict>
<key>UIApplicationSupportsMultipleScenes</key> <key>UIApplicationSupportsMultipleScenes</key>
+19 -8
View File
@@ -242,19 +242,30 @@
"clientInfoUnknown": "Unknown", "clientInfoUnknown": "Unknown",
"clientInfoHidden": "Hidden", "clientInfoHidden": "Hidden",
"clientInfoNone": "None", "clientInfoNone": "None",
"pokeSnackBarClearAction": "Clear", "pokeSettingsAction": "Poke notifications",
"pokeSnackBarMoreIndicator": "...", "pokeSettingsTitle": "Poke notifications",
"pokeSnackBarIncomingNoMessage": "{sender} pokes you", "pokeSettingsEnableLabel": "Notify me about pokes",
"@pokeSnackBarIncomingNoMessage": { "pokeSettingsEnableDescription": "Show local notifications for incoming pokes when this is on.",
"pokeSettingsMutedSendersHeader": "Muted senders",
"pokeSettingsMutedSendersEmpty": "No muted poke senders.",
"pokeSettingsMutedSenderLabel": "Client ID {senderId}",
"@pokeSettingsMutedSenderLabel": {
"placeholders": {
"senderId": { "type": "String" }
}
},
"pokeSettingsUnmuteSenderAction": "Unmute",
"pokeOverflowMutePrompt": "Repeated pokes from {sender} were suppressed. Mute this sender?",
"@pokeOverflowMutePrompt": {
"placeholders": { "placeholders": {
"sender": { "type": "String" } "sender": { "type": "String" }
} }
}, },
"pokeSnackBarIncomingWithMessage": "{sender} pokes you: {message}", "pokeOverflowMuteAction": "Mute",
"@pokeSnackBarIncomingWithMessage": { "pokeMutedSenderConfirmation": "Muted pokes from {sender}",
"@pokeMutedSenderConfirmation": {
"placeholders": { "placeholders": {
"sender": { "type": "String" }, "sender": { "type": "String" }
"message": { "type": "String" }
} }
}, },
"pokeHistorySelfNoMessage": "<{time}> You poked \"{target}\".", "pokeHistorySelfNoMessage": "<{time}> You poked \"{target}\".",
+19 -8
View File
@@ -191,19 +191,30 @@
"clientInfoUnknown": "未知", "clientInfoUnknown": "未知",
"clientInfoHidden": "隐藏", "clientInfoHidden": "隐藏",
"clientInfoNone": "无", "clientInfoNone": "无",
"pokeSnackBarClearAction": "清除", "pokeSettingsAction": "戳一戳通知",
"pokeSnackBarMoreIndicator": "...", "pokeSettingsTitle": "戳一戳通知",
"pokeSnackBarIncomingNoMessage": "{sender} 戳了你一下", "pokeSettingsEnableLabel": "接收戳一戳通知",
"@pokeSnackBarIncomingNoMessage": { "pokeSettingsEnableDescription": "开启后,收到戳一戳时会显示本地通知。",
"pokeSettingsMutedSendersHeader": "已静音的发送者",
"pokeSettingsMutedSendersEmpty": "没有已静音的戳一戳发送者。",
"pokeSettingsMutedSenderLabel": "用户 ID {senderId}",
"@pokeSettingsMutedSenderLabel": {
"placeholders": {
"senderId": { "type": "String" }
}
},
"pokeSettingsUnmuteSenderAction": "取消静音",
"pokeOverflowMutePrompt": "来自 {sender} 的重复戳一戳已被抑制。要静音此发送者吗?",
"@pokeOverflowMutePrompt": {
"placeholders": { "placeholders": {
"sender": { "type": "String" } "sender": { "type": "String" }
} }
}, },
"pokeSnackBarIncomingWithMessage": "{sender} 戳了你一下:{message}", "pokeOverflowMuteAction": "静音",
"@pokeSnackBarIncomingWithMessage": { "pokeMutedSenderConfirmation": "已静音来自 {sender} 的戳一戳",
"@pokeMutedSenderConfirmation": {
"placeholders": { "placeholders": {
"sender": { "type": "String" }, "sender": { "type": "String" }
"message": { "type": "String" }
} }
}, },
"pokeHistorySelfNoMessage": "<{time}> 你戳了“{target}”一下。", "pokeHistorySelfNoMessage": "<{time}> 你戳了“{target}”一下。",
@@ -1159,29 +1159,71 @@ abstract class AppL10n {
/// **'None'** /// **'None'**
String get clientInfoNone; String get clientInfoNone;
/// No description provided for @pokeSnackBarClearAction. /// No description provided for @pokeSettingsAction.
/// ///
/// In en, this message translates to: /// In en, this message translates to:
/// **'Clear'** /// **'Poke notifications'**
String get pokeSnackBarClearAction; String get pokeSettingsAction;
/// No description provided for @pokeSnackBarMoreIndicator. /// No description provided for @pokeSettingsTitle.
/// ///
/// In en, this message translates to: /// In en, this message translates to:
/// **'...'** /// **'Poke notifications'**
String get pokeSnackBarMoreIndicator; String get pokeSettingsTitle;
/// No description provided for @pokeSnackBarIncomingNoMessage. /// No description provided for @pokeSettingsEnableLabel.
/// ///
/// In en, this message translates to: /// In en, this message translates to:
/// **'{sender} pokes you'** /// **'Notify me about pokes'**
String pokeSnackBarIncomingNoMessage(String sender); String get pokeSettingsEnableLabel;
/// No description provided for @pokeSnackBarIncomingWithMessage. /// No description provided for @pokeSettingsEnableDescription.
/// ///
/// In en, this message translates to: /// In en, this message translates to:
/// **'{sender} pokes you: {message}'** /// **'Show local notifications for incoming pokes when this is on.'**
String pokeSnackBarIncomingWithMessage(String sender, String message); String get pokeSettingsEnableDescription;
/// No description provided for @pokeSettingsMutedSendersHeader.
///
/// In en, this message translates to:
/// **'Muted senders'**
String get pokeSettingsMutedSendersHeader;
/// No description provided for @pokeSettingsMutedSendersEmpty.
///
/// In en, this message translates to:
/// **'No muted poke senders.'**
String get pokeSettingsMutedSendersEmpty;
/// No description provided for @pokeSettingsMutedSenderLabel.
///
/// In en, this message translates to:
/// **'Client ID {senderId}'**
String pokeSettingsMutedSenderLabel(String senderId);
/// No description provided for @pokeSettingsUnmuteSenderAction.
///
/// In en, this message translates to:
/// **'Unmute'**
String get pokeSettingsUnmuteSenderAction;
/// No description provided for @pokeOverflowMutePrompt.
///
/// In en, this message translates to:
/// **'Repeated pokes from {sender} were suppressed. Mute this sender?'**
String pokeOverflowMutePrompt(String sender);
/// No description provided for @pokeOverflowMuteAction.
///
/// In en, this message translates to:
/// **'Mute'**
String get pokeOverflowMuteAction;
/// No description provided for @pokeMutedSenderConfirmation.
///
/// In en, this message translates to:
/// **'Muted pokes from {sender}'**
String pokeMutedSenderConfirmation(String sender);
/// No description provided for @pokeHistorySelfNoMessage. /// No description provided for @pokeHistorySelfNoMessage.
/// ///
@@ -590,19 +590,43 @@ class AppL10nEn extends AppL10n {
String get clientInfoNone => 'None'; String get clientInfoNone => 'None';
@override @override
String get pokeSnackBarClearAction => 'Clear'; String get pokeSettingsAction => 'Poke notifications';
@override @override
String get pokeSnackBarMoreIndicator => '...'; String get pokeSettingsTitle => 'Poke notifications';
@override @override
String pokeSnackBarIncomingNoMessage(String sender) { String get pokeSettingsEnableLabel => 'Notify me about pokes';
return '$sender pokes you';
@override
String get pokeSettingsEnableDescription =>
'Show local notifications for incoming pokes when this is on.';
@override
String get pokeSettingsMutedSendersHeader => 'Muted senders';
@override
String get pokeSettingsMutedSendersEmpty => 'No muted poke senders.';
@override
String pokeSettingsMutedSenderLabel(String senderId) {
return 'Client ID $senderId';
} }
@override @override
String pokeSnackBarIncomingWithMessage(String sender, String message) { String get pokeSettingsUnmuteSenderAction => 'Unmute';
return '$sender pokes you: $message';
@override
String pokeOverflowMutePrompt(String sender) {
return 'Repeated pokes from $sender were suppressed. Mute this sender?';
}
@override
String get pokeOverflowMuteAction => 'Mute';
@override
String pokeMutedSenderConfirmation(String sender) {
return 'Muted pokes from $sender';
} }
@override @override
@@ -577,19 +577,42 @@ class AppL10nZh extends AppL10n {
String get clientInfoNone => ''; String get clientInfoNone => '';
@override @override
String get pokeSnackBarClearAction => '清除'; String get pokeSettingsAction => '戳一戳通知';
@override @override
String get pokeSnackBarMoreIndicator => '...'; String get pokeSettingsTitle => '戳一戳通知';
@override @override
String pokeSnackBarIncomingNoMessage(String sender) { String get pokeSettingsEnableLabel => '接收戳一戳通知';
return '$sender 戳了你一下';
@override
String get pokeSettingsEnableDescription => '开启后,收到戳一戳时会显示本地通知。';
@override
String get pokeSettingsMutedSendersHeader => '已静音的发送者';
@override
String get pokeSettingsMutedSendersEmpty => '没有已静音的戳一戳发送者。';
@override
String pokeSettingsMutedSenderLabel(String senderId) {
return '用户 ID $senderId';
} }
@override @override
String pokeSnackBarIncomingWithMessage(String sender, String message) { String get pokeSettingsUnmuteSenderAction => '取消静音';
return '$sender 戳了你一下:$message';
@override
String pokeOverflowMutePrompt(String sender) {
return '来自 $sender 的重复戳一戳已被抑制。要静音此发送者吗?';
}
@override
String get pokeOverflowMuteAction => '静音';
@override
String pokeMutedSenderConfirmation(String sender) {
return '已静音来自 $sender 的戳一戳';
} }
@override @override
+148 -172
View File
@@ -22,14 +22,19 @@ import 'l10n/generated/app_localizations.dart';
import 'services/android_permissions_service.dart'; import 'services/android_permissions_service.dart';
import 'services/app_bootstrap.dart'; import 'services/app_bootstrap.dart';
import 'services/audio_lifecycle_service.dart'; import 'services/audio_lifecycle_service.dart';
import 'services/ios_audio_session_controller.dart';
import 'services/channel_join_error_mapper.dart'; import 'services/channel_join_error_mapper.dart';
import 'services/connection_phase_state.dart'; import 'services/connection_phase_state.dart';
import 'services/hard_mute_owners.dart';
import 'services/ios_permissions_service.dart'; import 'services/ios_permissions_service.dart';
import 'services/macos_permissions_service.dart'; import 'services/macos_permissions_service.dart';
import 'services/poke_notification_service.dart';
import 'services/poke_preferences_service.dart';
import 'services/prefetch_debouncer.dart'; import 'services/prefetch_debouncer.dart';
import 'services/snapshot_state_mapper.dart'; import 'services/snapshot_state_mapper.dart';
import 'services/ts3_server_link.dart'; import 'services/ts3_server_link.dart';
import 'services/ui_preferences_service.dart'; import 'services/ui_preferences_service.dart';
import 'services/voice_join_ordering.dart';
import 'src/rust/api.dart' as rust; import 'src/rust/api.dart' as rust;
import 'src/rust/frb_generated.dart'; import 'src/rust/frb_generated.dart';
import 'src/rust/lib.dart' as rust_err; import 'src/rust/lib.dart' as rust_err;
@@ -41,6 +46,7 @@ import 'widgets/client_info_sheet.dart';
import 'widgets/connect_widgets.dart'; import 'widgets/connect_widgets.dart';
import 'widgets/input_dialogs.dart'; import 'widgets/input_dialogs.dart';
import 'widgets/permission_state_banner.dart'; import 'widgets/permission_state_banner.dart';
import 'widgets/poke_notification_settings.dart';
import 'widgets/snapshot_view.dart'; import 'widgets/snapshot_view.dart';
import 'widgets/voice_platform.dart'; import 'widgets/voice_platform.dart';
import 'widgets/voice_bar.dart'; import 'widgets/voice_bar.dart';
@@ -87,7 +93,10 @@ String _kAppVersion = appSemverBaseline;
Future<void> main() async { Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
await RustLib.init(); await RustLib.init();
unawaited(wireStorage()); unawaited(() async {
await wireStorage();
await wireCache();
}());
unawaited(wireConnectivity()); unawaited(wireConnectivity());
wireAudioLifecycle(); wireAudioLifecycle();
await configureBundledVadModels(); await configureBundledVadModels();
@@ -159,10 +168,7 @@ class _ChanoraAppState extends State<ChanoraApp> {
supportedLocales: AppL10n.supportedLocales, supportedLocales: AppL10n.supportedLocales,
home: Stack( home: Stack(
children: [ children: [
_BetaHome( _BetaHome(themeMode: _themeMode, onThemeModeChanged: _setThemeMode),
themeMode: _themeMode,
onThemeModeChanged: _setThemeMode,
),
if (_showAudioDebugOverlay) const AudioDebugStatsPanel(), if (_showAudioDebugOverlay) const AudioDebugStatsPanel(),
], ],
), ),
@@ -200,6 +206,19 @@ extension on ThemeMode {
} }
} }
bool isPokeSenderActiveChat({
required bool chatOpen,
required rust.BridgeMessageTarget? inlineChatTarget,
required BigInt senderId,
}) {
if (!chatOpen) return false;
return switch (inlineChatTarget) {
rust.BridgeMessageTarget_Poke(:final field0) ||
rust.BridgeMessageTarget_Client(:final field0) => field0 == senderId,
_ => false,
};
}
class ChanoraThemeModeMenu extends StatelessWidget { class ChanoraThemeModeMenu extends StatelessWidget {
const ChanoraThemeModeMenu({ const ChanoraThemeModeMenu({
super.key, super.key,
@@ -300,18 +319,6 @@ class _BetaHome extends StatefulWidget {
State<_BetaHome> createState() => _BetaHomeState(); State<_BetaHome> createState() => _BetaHomeState();
} }
class _ReceivedPoke {
const _ReceivedPoke({
required this.senderName,
required this.message,
required this.receivedAt,
});
final String senderName;
final String message;
final DateTime receivedAt;
}
class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver { class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
final _hostCtl = TextEditingController(text: 'cn.teamspeak.app'); final _hostCtl = TextEditingController(text: 'cn.teamspeak.app');
final _nickCtl = TextEditingController(text: 'ChanoraBeta'); final _nickCtl = TextEditingController(text: 'ChanoraBeta');
@@ -338,8 +345,9 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
bool _inChannel = false; bool _inChannel = false;
rust.BridgeTransmitMode _transmitMode = rust.BridgeTransmitMode.ptt; rust.BridgeTransmitMode _transmitMode = rust.BridgeTransmitMode.ptt;
bool _hardMute = false; bool _hardMute = false;
bool _hardMuteByPermission = false; HardMuteOwners _hardMuteOwners = const HardMuteOwners();
bool _hardMuteByTalkPower = false; bool get _hardMuteByPermission => _hardMuteOwners.permission;
bool get _hardMuteByTalkPower => _hardMuteOwners.talkPower;
bool _permissionHardMuteClearInFlight = false; bool _permissionHardMuteClearInFlight = false;
int _releaseTailMs = 200; int _releaseTailMs = 200;
BigInt? _currentVoiceChannelId; BigInt? _currentVoiceChannelId;
@@ -409,11 +417,6 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
/// previous conversation when the user reopens chat. /// previous conversation when the user reopens chat.
rust.BridgeMessageTarget? _lastDismissedTarget; rust.BridgeMessageTarget? _lastDismissedTarget;
String _lastDismissedClientName = ''; String _lastDismissedClientName = '';
final ValueNotifier<List<_ReceivedPoke>> _pokeSnackBarPokes = ValueNotifier(
const [],
);
bool _pokeSnackBarVisible = false;
// SDD-106 / SRS-209: Android RECORD_AUDIO runtime permission service. // SDD-106 / SRS-209: Android RECORD_AUDIO runtime permission service.
// Constructed at startup so cold-launch state is captured before the // Constructed at startup so cold-launch state is captured before the
// first voice_join attempt. On non-Android hosts the service // first voice_join attempt. On non-Android hosts the service
@@ -428,6 +431,9 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
// MethodChannel. // MethodChannel.
final MacOSPermissionsService _macOSPermissions = MacOSPermissionsService(); final MacOSPermissionsService _macOSPermissions = MacOSPermissionsService();
final UiPreferencesService _uiPreferences = const UiPreferencesService(); final UiPreferencesService _uiPreferences = const UiPreferencesService();
final PokeNotificationService _pokeNotifications = PokeNotificationService();
final PokePreferencesService _pokePreferences = PokePreferencesService();
late final Future<void> _pokePreferencesReady;
@override @override
void initState() { void initState() {
@@ -461,6 +467,8 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
_onMacOSPttCapabilityChanged, _onMacOSPttCapabilityChanged,
); );
_macOSPermissions.checkInitialStates(); _macOSPermissions.checkInitialStates();
unawaited(_pokeNotifications.init());
_pokePreferencesReady = _pokePreferences.load();
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(_requestRecordAudioOnStartup()); unawaited(_requestRecordAudioOnStartup());
}); });
@@ -589,8 +597,8 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
await rust.setHardMute(muted: false); await rust.setHardMute(muted: false);
if (!mounted || !_hardMuteByPermission) return; if (!mounted || !_hardMuteByPermission) return;
setState(() { setState(() {
_hardMute = false; _hardMuteOwners = _hardMuteOwners.copyWith(permission: false);
_hardMuteByPermission = false; _hardMute = _hardMuteOwners.effective;
}); });
} catch (e) { } catch (e) {
if (!mounted) return; if (!mounted) return;
@@ -740,6 +748,7 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
_reconnectAttempt = null; _reconnectAttempt = null;
_reconnectDelay = null; _reconnectDelay = null;
}); });
unawaited(iosAudioSessionController.activate());
unawaited(_refreshSnapshot(recordActivity: false, reportErrors: true)); unawaited(_refreshSnapshot(recordActivity: false, reportErrors: true));
case rust.BridgeEvent_Lost(:final reason): case rust.BridgeEvent_Lost(:final reason):
_recordUiDiagnostic('connection', 'lost: $reason'); _recordUiDiagnostic('connection', 'lost: $reason');
@@ -765,8 +774,10 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
_resetConnectionUiState(phase: ConnectionPhase.disconnected); _resetConnectionUiState(phase: ConnectionPhase.disconnected);
}); });
case rust.BridgeEvent_AudioStarted(): case rust.BridgeEvent_AudioStarted():
unawaited(iosAudioSessionController.activate());
_ensureStatsTimer(); _ensureStatsTimer();
case rust.BridgeEvent_AudioStopped(): case rust.BridgeEvent_AudioStopped():
unawaited(iosAudioSessionController.deactivate());
_statsTimer?.cancel(); _statsTimer?.cancel();
_statsTimer = null; _statsTimer = null;
case rust.BridgeEvent_PttCapability( case rust.BridgeEvent_PttCapability(
@@ -795,8 +806,8 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
_voiceStateInitialized = true; _voiceStateInitialized = true;
_inChannel = inChannel; _inChannel = inChannel;
_transmitMode = transmitMode; _transmitMode = transmitMode;
_hardMute = mute; _hardMuteOwners = _hardMuteOwners.withBridgeManualMute(mute);
if (!mute) _hardMuteByPermission = false; _hardMute = _hardMuteOwners.effective;
_releaseTailMs = releaseTailMs; _releaseTailMs = releaseTailMs;
_currentVoiceChannelId = currentChannelId; _currentVoiceChannelId = currentChannelId;
_pendingVoiceChannelId = pendingTargetChannelId; _pendingVoiceChannelId = pendingTargetChannelId;
@@ -862,10 +873,11 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
:final senderName, :final senderName,
:final message, :final message,
:final target, :final target,
:final pokeStrength,
): ):
// Skip echo of self-sent messages (already added locally).
if (senderId == _snapshot?.ownClientId) return;
final isPoke = target is rust.BridgeMessageTarget_Poke; final isPoke = target is rust.BridgeMessageTarget_Poke;
// Skip echo of self-sent non-poke messages (already added locally).
if (!isPoke && senderId == _snapshot?.ownClientId) return;
final receivedAt = DateTime.now(); final receivedAt = DateTime.now();
setState(() { setState(() {
_appendChatEntryUnlocked( _appendChatEntryUnlocked(
@@ -880,10 +892,13 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
); );
}); });
if (isPoke) { if (isPoke) {
_showPokeSnackBar( unawaited(
senderName: senderName, _handleIncomingPoke(
message: message, senderId: senderId,
receivedAt: receivedAt, senderName: senderName,
message: message,
strength: pokeStrength,
),
); );
return; return;
} }
@@ -1083,7 +1098,6 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
_nickCtl.dispose(); _nickCtl.dispose();
_passwordCtl.dispose(); _passwordCtl.dispose();
_chatFeedRevision.dispose(); _chatFeedRevision.dispose();
_pokeSnackBarPokes.dispose();
_androidPermissions.recordAudioState.removeListener( _androidPermissions.recordAudioState.removeListener(
_onRecordAudioPermissionChanged, _onRecordAudioPermissionChanged,
); );
@@ -1100,6 +1114,7 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
_androidPermissions.stop(); _androidPermissions.stop();
_iosPermissions.stop(); _iosPermissions.stop();
_macOSPermissions.stop(); _macOSPermissions.stop();
_pokePreferences.dispose();
super.dispose(); super.dispose();
} }
@@ -1133,7 +1148,9 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
); );
if (accessState == MacOSLocalNetworkState.denied) { if (accessState == MacOSLocalNetworkState.denied) {
if (!mounted) return; if (!mounted) return;
setState(() { _phase = ConnectionPhase.idle; }); setState(() {
_phase = ConnectionPhase.idle;
});
_showLocalNetworkDeniedSnackBar(); _showLocalNetworkDeniedSnackBar();
return; return;
} }
@@ -1145,6 +1162,7 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
_chatMessages.clear(); _chatMessages.clear();
}); });
_releaseFocusedPttIfHeld(); _releaseFocusedPttIfHeld();
await iosAudioSessionController.activate();
try { try {
final snap = await rust.connect( final snap = await rust.connect(
host: (host ?? _hostCtl.text).trim(), host: (host ?? _hostCtl.text).trim(),
@@ -1268,8 +1286,8 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
await rust.setHardMute(muted: true); await rust.setHardMute(muted: true);
if (mounted) { if (mounted) {
setState(() { setState(() {
_hardMute = true; _hardMuteOwners = _hardMuteOwners.copyWith(permission: true);
_hardMuteByPermission = true; _hardMute = _hardMuteOwners.effective;
}); });
} }
} catch (_) { } catch (_) {
@@ -1284,12 +1302,23 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
await rust.setHardMute(muted: false); await rust.setHardMute(muted: false);
if (mounted) { if (mounted) {
setState(() { setState(() {
_hardMute = false; _hardMuteOwners = _hardMuteOwners.copyWith(permission: false);
_hardMuteByPermission = false; _hardMute = _hardMuteOwners.effective;
}); });
} }
} }
await rust.voiceJoin(channelId: ch.id, password: password ?? ''); await joinVoiceChannelWithIosAudioSession(
channelId: ch.id,
password: password ?? '',
voiceJoin: rust.voiceJoin,
activateIosAudioSession: iosAudioSessionController.activate,
deactivateIosAudioSession: iosAudioSessionController.deactivate,
// Server says we are already in the target channel: the user is
// still joined to a voice channel, so the iOS audio session must
// stay active. The catch below converts this rethrow into the
// success-on-already-joined branch.
isJoinSuccess: _isAlreadyInChannel,
);
if (!mounted) return; if (!mounted) return;
setState(() { setState(() {
_currentVoiceChannelId = ch.id; _currentVoiceChannelId = ch.id;
@@ -1353,13 +1382,14 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
final next = !_hardMute; final next = !_hardMute;
final previousInputMuted = _inputMuted; final previousInputMuted = _inputMuted;
final previousHardMute = _hardMute; final previousHardMute = _hardMute;
final previousPermissionMute = _hardMuteByPermission; final previousHardMuteOwners = _hardMuteOwners;
setState(() { setState(() {
_inputMuted = next; _inputMuted = next;
_hardMute = next; _hardMuteOwners = _hardMuteOwners.copyWith(
if (next) { manual: next,
_hardMuteByPermission = false; permission: next ? false : null,
} );
_hardMute = _hardMuteOwners.effective;
}); });
try { try {
// Hard-mute is two coordinated effects: // Hard-mute is two coordinated effects:
@@ -1378,7 +1408,7 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
setState(() { setState(() {
_inputMuted = previousInputMuted; _inputMuted = previousInputMuted;
_hardMute = previousHardMute; _hardMute = previousHardMute;
_hardMuteByPermission = previousPermissionMute; _hardMuteOwners = previousHardMuteOwners;
}); });
_showUiError('hard mute', e); _showUiError('hard mute', e);
} }
@@ -1514,6 +1544,16 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
} }
} }
Future<void> _onOpenPokeSettings() async {
await _pokePreferences.load();
if (!mounted) return;
await showDialog<void>(
context: context,
builder: (ctx) =>
PokeNotificationSettingsDialog(preferences: _pokePreferences),
);
}
Future<String?> _askChannelPassword(AppL10n l10n) async { Future<String?> _askChannelPassword(AppL10n l10n) async {
// Same pattern as _onAddCurrentBookmark: route the dialog // Same pattern as _onAddCurrentBookmark: route the dialog
// through a dedicated StatefulWidget so its // through a dedicated StatefulWidget so its
@@ -1648,8 +1688,7 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
_inputMuted = false; _inputMuted = false;
_outputMuted = false; _outputMuted = false;
_hardMute = false; _hardMute = false;
_hardMuteByPermission = false; _hardMuteOwners = const HardMuteOwners();
_hardMuteByTalkPower = false;
_inChannel = false; _inChannel = false;
_currentVoiceChannelId = null; _currentVoiceChannelId = null;
_pendingVoiceChannelId = null; _pendingVoiceChannelId = null;
@@ -1799,9 +1838,7 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || _inlineChatTarget == null) return; if (!mounted || _inlineChatTarget == null) return;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(content: Text(AppL10n.of(context).chatPanelCollapsedHint)),
content: Text(AppL10n.of(context).chatPanelCollapsedHint),
),
); );
}); });
} }
@@ -1822,52 +1859,68 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
); );
} }
void _showPokeSnackBar({ Future<void> _handleIncomingPoke({
required BigInt senderId,
required String senderName, required String senderName,
required String message, required String message,
required DateTime receivedAt, required rust.BridgePokeStrength? strength,
}) { }) async {
_pokeSnackBarPokes.value = [ if (senderId == _snapshot?.ownClientId) return;
..._pokeSnackBarPokes.value, await _pokePreferencesReady;
_ReceivedPoke( if (!_pokePreferences.pokesEnabled.value) return;
senderName: senderName, if (_pokePreferences.isMuted(senderId)) return;
message: message, final pokeStrength = strength ?? rust.BridgePokeStrength.suppressed;
receivedAt: receivedAt, if (pokeStrength == rust.BridgePokeStrength.suppressedOverflow && mounted) {
), _showPokeOverflowMutePrompt(senderId: senderId, senderName: senderName);
]; }
WidgetsBinding.instance.addPostFrameCallback((_) { if (_isPokeSenderActiveChat(senderId)) return;
if (mounted) _renderPokeSnackBar(); await _pokeNotifications.show(
}); senderName: senderName,
message: message,
senderId: senderId,
strength: pokeStrength,
);
} }
void _renderPokeSnackBar() { bool _isPokeSenderActiveChat(BigInt senderId) {
if (_pokeSnackBarPokes.value.isEmpty || _pokeSnackBarVisible) return; return isPokeSenderActiveChat(
_pokeSnackBarVisible = true; chatOpen: _chatOpen,
inlineChatTarget: _inlineChatTarget,
senderId: senderId,
);
}
void _showPokeOverflowMutePrompt({
required BigInt senderId,
required String senderName,
}) {
final l10n = AppL10n.of(context);
final messenger = ScaffoldMessenger.of(context); final messenger = ScaffoldMessenger.of(context);
final controller = messenger.showSnackBar( messenger.showSnackBar(
SnackBar( SnackBar(
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
margin: _chatSnackBarMargin(), margin: _chatSnackBarMargin(),
duration: const Duration(days: 365), duration: const Duration(seconds: 8),
dismissDirection: DismissDirection.none, content: Text(
content: _PokeSnackBarContent(pokes: _pokeSnackBarPokes), l10n.pokeOverflowMutePrompt(senderName),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
action: SnackBarAction( action: SnackBarAction(
label: AppL10n.of(context).pokeSnackBarClearAction, label: l10n.pokeOverflowMuteAction,
onPressed: () { onPressed: () {
_pokeSnackBarPokes.value = const []; unawaited(_pokePreferences.muteSender(senderId));
_pokeSnackBarVisible = false; messenger.showSnackBar(
SnackBar(
behavior: SnackBarBehavior.floating,
margin: _chatSnackBarMargin(),
content: Text(l10n.pokeMutedSenderConfirmation(senderName)),
),
);
}, },
), ),
), ),
); );
controller.closed.then((_) {
if (!mounted) return;
_pokeSnackBarVisible = false;
if (_pokeSnackBarPokes.value.isEmpty) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _renderPokeSnackBar();
});
});
} }
void _showChatMessageSnackBar({ void _showChatMessageSnackBar({
@@ -1875,7 +1928,6 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
required String message, required String message,
required rust.BridgeMessageTarget target, required rust.BridgeMessageTarget target,
}) { }) {
if (_pokeSnackBarPokes.value.isNotEmpty) return;
final messenger = ScaffoldMessenger.of(context); final messenger = ScaffoldMessenger.of(context);
messenger.hideCurrentSnackBar(); messenger.hideCurrentSnackBar();
messenger.showSnackBar( messenger.showSnackBar(
@@ -2080,8 +2132,8 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
if (!own.talkPowerOk && !_hardMuteByTalkPower) { if (!own.talkPowerOk && !_hardMuteByTalkPower) {
final talkPowerEpoch = _connectionEpoch; final talkPowerEpoch = _connectionEpoch;
_hardMuteByTalkPower = true; _hardMuteOwners = _hardMuteOwners.copyWith(talkPower: true);
_hardMute = true; _hardMute = _hardMuteOwners.effective;
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || if (!mounted ||
_connectionEpoch != talkPowerEpoch || _connectionEpoch != talkPowerEpoch ||
@@ -2094,15 +2146,14 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
}); });
} else if (own.talkPowerOk && _hardMuteByTalkPower) { } else if (own.talkPowerOk && _hardMuteByTalkPower) {
final talkPowerEpoch = _connectionEpoch; final talkPowerEpoch = _connectionEpoch;
_hardMuteByTalkPower = false; _hardMuteOwners = _hardMuteOwners.copyWith(talkPower: false);
if (!_hardMuteByPermission) { _hardMute = _hardMuteOwners.effective;
_hardMute = false; if (!_hardMuteOwners.effective) {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || if (!mounted ||
_connectionEpoch != talkPowerEpoch || _connectionEpoch != talkPowerEpoch ||
!_serverReachable || !_serverReachable ||
_hardMuteByTalkPower || _hardMuteOwners.effective) {
_hardMuteByPermission) {
return; return;
} }
unawaited(rust.setHardMute(muted: false)); unawaited(rust.setHardMute(muted: false));
@@ -2373,6 +2424,11 @@ class _BetaHomeState extends State<_BetaHome> with WidgetsBindingObserver {
themeMode: widget.themeMode, themeMode: widget.themeMode,
onThemeModeChanged: widget.onThemeModeChanged, onThemeModeChanged: widget.onThemeModeChanged,
), ),
IconButton(
tooltip: l10n.pokeSettingsAction,
icon: const Icon(Icons.notifications_outlined),
onPressed: () => unawaited(_onOpenPokeSettings()),
),
if (_phase.canOpenChatWithSnapshot(hasSnapshot: _snapshot != null)) ...[ if (_phase.canOpenChatWithSnapshot(hasSnapshot: _snapshot != null)) ...[
Padding( Padding(
padding: const EdgeInsetsDirectional.only(end: 12), padding: const EdgeInsetsDirectional.only(end: 12),
@@ -2852,83 +2908,3 @@ class _LiveDiagnosticsDialogState extends State<_LiveDiagnosticsDialog> {
); );
} }
} }
class _PokeSnackBarContent extends StatelessWidget {
const _PokeSnackBarContent({required this.pokes});
final ValueListenable<List<_ReceivedPoke>> pokes;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<List<_ReceivedPoke>>(
valueListenable: pokes,
builder: (context, entries, _) {
final l10n = AppL10n.of(context);
final visible = entries.length <= 3
? entries
: entries.sublist(entries.length - 3);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (entries.length > 3)
Padding(
padding: const EdgeInsetsDirectional.only(bottom: 2),
child: Text(
l10n.pokeSnackBarMoreIndicator,
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
for (final poke in visible) _PokeSnackBarRow(poke: poke),
],
);
},
);
}
}
class _PokeSnackBarRow extends StatelessWidget {
const _PokeSnackBarRow({required this.poke});
final _ReceivedPoke poke;
@override
Widget build(BuildContext context) {
final l10n = AppL10n.of(context);
final message = poke.message.trim();
final text = message.isEmpty
? l10n.pokeSnackBarIncomingNoMessage(poke.senderName)
: l10n.pokeSnackBarIncomingWithMessage(poke.senderName, message);
return Padding(
padding: const EdgeInsets.symmetric(vertical: 1),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
const SizedBox(width: 12),
Text(
pokeSnackBarTimeLabel(poke.receivedAt),
style: TextStyle(
color: Theme.of(
context,
).colorScheme.onInverseSurface.withValues(alpha: 0.72),
),
),
],
),
);
}
}
String pokeSnackBarTimeLabel(DateTime timestamp) {
String two(int value) => value.toString().padLeft(2, '0');
return '${two(timestamp.hour)}:${two(timestamp.minute)}';
}
@@ -15,15 +15,22 @@ typedef StorageDirectoryProvider = Future<Directory> Function();
typedef StorageInitializer = Future<void> Function(String dir); typedef StorageInitializer = Future<void> Function(String dir);
Future<void>? _storageInitFuture; Future<void>? _storageInitFuture;
Future<void>? _cacheInitFuture;
Future<void>? _vadBootstrapFuture; Future<void>? _vadBootstrapFuture;
StorageDirectoryProvider _storageDirectoryProvider = StorageDirectoryProvider _storageDirectoryProvider =
getApplicationSupportDirectory; getApplicationSupportDirectory;
StorageDirectoryProvider _cacheDirectoryProvider = getApplicationCacheDirectory;
StorageInitializer _storageInitializer = _defaultStorageInitializer; StorageInitializer _storageInitializer = _defaultStorageInitializer;
StorageInitializer _cacheInitializer = _defaultCacheInitializer;
Future<void> _defaultStorageInitializer(String dir) { Future<void> _defaultStorageInitializer(String dir) {
return rust.initStorage(dir: dir); return rust.initStorage(dir: dir);
} }
Future<void> _defaultCacheInitializer(String dir) {
return rust.initCache(dir: dir);
}
Future<File> _copyBundledAssetToDocuments({ Future<File> _copyBundledAssetToDocuments({
required String assetPath, required String assetPath,
required String fileName, required String fileName,
@@ -121,16 +128,50 @@ Future<void> _wireStorageImpl() async {
} }
} }
Future<void> wireCache() async {
final existing = _cacheInitFuture;
if (existing != null) {
await existing;
return;
}
final initFuture = _wireCacheImpl();
_cacheInitFuture = initFuture;
await initFuture;
}
Future<void> _wireCacheImpl() async {
var initialized = false;
try {
final dir = await _cacheDirectoryProvider();
await _cacheInitializer(dir.path);
initialized = true;
} catch (_) {
// Best-effort; missing cache just means protocol-owned assets are
// re-downloaded this session.
} finally {
if (!initialized) {
_cacheInitFuture = null;
}
}
}
@visibleForTesting @visibleForTesting
void debugResetStorageBootstrap({ void debugResetStorageBootstrap({
StorageDirectoryProvider? storageDirectoryProvider, StorageDirectoryProvider? storageDirectoryProvider,
StorageDirectoryProvider? cacheDirectoryProvider,
StorageInitializer? storageInitializer, StorageInitializer? storageInitializer,
StorageInitializer? cacheInitializer,
}) { }) {
_storageInitFuture = null; _storageInitFuture = null;
_cacheInitFuture = null;
_vadBootstrapFuture = null; _vadBootstrapFuture = null;
_storageDirectoryProvider = _storageDirectoryProvider =
storageDirectoryProvider ?? getApplicationSupportDirectory; storageDirectoryProvider ?? getApplicationSupportDirectory;
_cacheDirectoryProvider =
cacheDirectoryProvider ?? getApplicationCacheDirectory;
_storageInitializer = storageInitializer ?? _defaultStorageInitializer; _storageInitializer = storageInitializer ?? _defaultStorageInitializer;
_cacheInitializer = cacheInitializer ?? _defaultCacheInitializer;
} }
rust.BridgeNetworkState _mapConnectivity(List<ConnectivityResult> results) { rust.BridgeNetworkState _mapConnectivity(List<ConnectivityResult> results) {
@@ -0,0 +1,31 @@
class HardMuteOwners {
const HardMuteOwners({
this.manual = false,
this.permission = false,
this.talkPower = false,
});
final bool manual;
final bool permission;
final bool talkPower;
bool get effective => manual || permission || talkPower;
HardMuteOwners withBridgeManualMute(bool muted) {
return copyWith(
manual: muted && (manual || !permission && !talkPower),
);
}
HardMuteOwners copyWith({
bool? manual,
bool? permission,
bool? talkPower,
}) {
return HardMuteOwners(
manual: manual ?? this.manual,
permission: permission ?? this.permission,
talkPower: talkPower ?? this.talkPower,
);
}
}
@@ -0,0 +1,66 @@
import 'dart:io' show Platform;
import 'package:flutter/services.dart';
const iosAudioSessionChannelName = 'chanora/ios_audio_session';
/// Controls the iOS AVAudioSession VoIP lifecycle from Dart.
///
/// The Swift `AppDelegate` configures the session to `.ambient` at
/// launch and leaves it inactive. The session is only switched to
/// `.playAndRecord` + `.voiceChat` (with `.mixWithOthers`) while a
/// voice channel is actually active. This controller is the Dart
/// side of that contract — call [activate] before the Rust engine
/// starts VoiceProcessingIO and [deactivate] on
/// `BridgeEvent::AudioStopped` or failed joins.
///
/// On non-iOS platforms both methods are no-ops; the platforms
/// handle their own session lifecycle elsewhere (Android via
/// `AndroidAudioLifecycleController`, macOS via
/// `MacOSAudioLifecycle`, desktop has no exclusive session).
class IosAudioSessionController {
IosAudioSessionController({
MethodChannel? channel,
bool? isIos,
}) : _channel = channel ?? const MethodChannel(iosAudioSessionChannelName),
_isIos = isIos ?? Platform.isIOS;
final MethodChannel _channel;
final bool _isIos;
Future<void> activate() async {
if (!_isIos) return;
try {
await _channel.invokeMethod<void>('activateVoiceSession');
} on PlatformException {
// Swift side logs the failure via NSLog; surfacing the
// exception to the event handler would be noise. The Rust
// engine remains alive and will produce silence until the
// next route change or a manual leave/rejoin.
} on MissingPluginException {
// Test hosts and mispackaged builds may not have registered
// the iOS channel. Keep event dispatch alive rather than
// surfacing an unhandled async error.
}
}
Future<void> deactivate() async {
if (!_isIos) return;
try {
await _channel.invokeMethod<void>('deactivateVoiceSession');
} on PlatformException {
// Same rationale as activate(): the Swift side logs.
// Worst case the session stays in .playAndRecord until the
// app is backgrounded — at which point iOS reclaims the
// session automatically.
} on MissingPluginException {
// Same rationale as activate(): missing channel should not
// break bridge event handling.
}
}
}
/// Default singleton used by [main.dart] event dispatch. Tests
/// should construct their own [IosAudioSessionController] with a
/// mocked channel rather than mutating this instance.
final iosAudioSessionController = IosAudioSessionController();
@@ -0,0 +1,179 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import '../src/rust/api.dart' as rust;
class PokeNotificationService {
PokeNotificationService({FlutterLocalNotificationsPlugin? notifications})
: _notifications = notifications ?? FlutterLocalNotificationsPlugin();
static const _strongAndroidChannelId = 'chanora_pokes_strong_v1';
static const _defaultAndroidChannelId = 'chanora_pokes_default_v1';
static const _groupKey = 'chanora.pokes';
static const _darwinThreadId = 'chanora.pokes';
static const _windowsHeader = WindowsHeader(
id: 'chanora.pokes',
title: 'Pokes',
arguments: 'pokes',
);
static const _windowsAppUserModelId = 'Chanora.Client';
static const _windowsGuid = '6B7F3DCB-4418-4E0A-8CC7-02B7C95B675E';
final FlutterLocalNotificationsPlugin _notifications;
bool _initialized = false;
Future<void> init() async {
if (_initialized) return;
await _notifications.initialize(
settings: const InitializationSettings(
android: AndroidInitializationSettings('ic_chanora_notification'),
iOS: DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
// TODO(event-sounds): handled by future EventSoundService, not the OS channel.
requestSoundPermission: false,
// TODO(event-sounds): handled by future EventSoundService, not the OS channel.
defaultPresentSound: false,
),
macOS: DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
// TODO(event-sounds): handled by future EventSoundService, not the OS channel.
requestSoundPermission: false,
// TODO(event-sounds): handled by future EventSoundService, not the OS channel.
defaultPresentSound: false,
),
linux: LinuxInitializationSettings(
defaultActionName: 'Open',
// TODO(event-sounds): handled by future EventSoundService, not the OS channel.
defaultSuppressSound: true,
),
windows: WindowsInitializationSettings(
appName: 'Chanora',
appUserModelId: _windowsAppUserModelId,
guid: _windowsGuid,
),
),
);
_initialized = true;
}
Future<bool> requestPermission() async {
await init();
if (kIsWeb) return true;
final android = _notifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
if (android != null) {
return await android.requestNotificationsPermission() ?? true;
}
final ios = _notifications
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>();
if (ios != null) {
return await ios.requestPermissions(alert: true, badge: true) ?? false;
}
final macOS = _notifications
.resolvePlatformSpecificImplementation<
MacOSFlutterLocalNotificationsPlugin
>();
if (macOS != null) {
return await macOS.requestPermissions(alert: true, badge: true) ?? false;
}
return true;
}
Future<void> show({
required String senderName,
required String message,
required BigInt senderId,
required rust.BridgePokeStrength strength,
}) async {
await init();
final permitted = await requestPermission();
if (!permitted) return;
final trimmedMessage = message.trim();
final body = trimmedMessage.isEmpty
? '$senderName pokes you'
: trimmedMessage;
await _notifications.show(
id: senderId.toUnsigned(31).toInt(),
title: 'Poke from $senderName',
body: body,
notificationDetails: NotificationDetails(
android: _androidDetails(strength),
iOS: _darwinDetails(strength),
macOS: _darwinDetails(strength),
linux: _linuxDetails(strength),
windows: _windowsDetails(strength),
),
payload: 'poke:$senderId',
);
}
AndroidNotificationDetails _androidDetails(rust.BridgePokeStrength strength) {
final isStrong = strength == rust.BridgePokeStrength.strong;
return AndroidNotificationDetails(
isStrong ? _strongAndroidChannelId : _defaultAndroidChannelId,
isStrong ? 'Pokes' : 'Pokes (quiet)',
channelDescription: 'TeamSpeak poke notifications',
importance: isStrong ? Importance.max : Importance.defaultImportance,
priority: isStrong ? Priority.high : Priority.defaultPriority,
// TODO(event-sounds): handled by future EventSoundService, not the OS channel.
playSound: false,
// TODO(event-sounds): handled by future EventSoundService, not the OS channel.
silent: true,
groupKey: _groupKey,
category: AndroidNotificationCategory.message,
visibility: NotificationVisibility.private,
);
}
DarwinNotificationDetails _darwinDetails(rust.BridgePokeStrength strength) {
return DarwinNotificationDetails(
// TODO(event-sounds): handled by future EventSoundService, not the OS channel.
presentSound: false,
threadIdentifier: _darwinThreadId,
interruptionLevel: switch (strength) {
rust.BridgePokeStrength.strong => InterruptionLevel.timeSensitive,
rust.BridgePokeStrength.suppressed => InterruptionLevel.active,
rust.BridgePokeStrength.suppressedOverflow => InterruptionLevel.passive,
},
);
}
LinuxNotificationDetails _linuxDetails(rust.BridgePokeStrength strength) {
return LinuxNotificationDetails(
// TODO(event-sounds): handled by future EventSoundService, not the OS channel.
suppressSound: true,
urgency: switch (strength) {
rust.BridgePokeStrength.strong => LinuxNotificationUrgency.critical,
rust.BridgePokeStrength.suppressed => LinuxNotificationUrgency.normal,
rust.BridgePokeStrength.suppressedOverflow =>
LinuxNotificationUrgency.low,
},
);
}
WindowsNotificationDetails _windowsDetails(rust.BridgePokeStrength strength) {
return WindowsNotificationDetails(
// TODO(event-sounds): handled by future EventSoundService, not the OS channel.
audio: WindowsNotificationAudio.silent(),
header: _windowsHeader,
scenario: strength == rust.BridgePokeStrength.strong
? WindowsNotificationScenario.urgent
: null,
duration: strength == rust.BridgePokeStrength.strong
? WindowsNotificationDuration.long
: WindowsNotificationDuration.short,
);
}
}
@@ -0,0 +1,58 @@
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
class PokePreferencesService {
static const _enabledKey = 'pokes.enabled';
static const _mutedSendersKey = 'pokes.muted_senders';
final ValueNotifier<bool> _pokesEnabled = ValueNotifier<bool>(true);
final ValueNotifier<Set<BigInt>> _mutedSenders = ValueNotifier<Set<BigInt>>(
const <BigInt>{},
);
ValueListenable<bool> get pokesEnabled => _pokesEnabled;
ValueListenable<Set<BigInt>> get mutedSenders => _mutedSenders;
Future<void> load() async {
final prefs = await SharedPreferences.getInstance();
_pokesEnabled.value = prefs.getBool(_enabledKey) ?? true;
_mutedSenders.value = (prefs.getStringList(_mutedSendersKey) ?? const [])
.map(BigInt.parse)
.toSet();
}
Future<void> setPokesEnabled(bool enabled) async {
_pokesEnabled.value = enabled;
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_enabledKey, enabled);
}
Future<void> muteSender(BigInt senderId) async {
if (_mutedSenders.value.contains(senderId)) return;
_mutedSenders.value = {..._mutedSenders.value, senderId};
await _saveMutedSenders();
}
Future<void> unmuteSender(BigInt senderId) async {
if (!_mutedSenders.value.contains(senderId)) return;
_mutedSenders.value = _mutedSenders.value
.where((mutedSender) => mutedSender != senderId)
.toSet();
await _saveMutedSenders();
}
bool isMuted(BigInt senderId) => _mutedSenders.value.contains(senderId);
Future<void> _saveMutedSenders() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList(
_mutedSendersKey,
_mutedSenders.value.map((senderId) => senderId.toString()).toList(),
);
}
void dispose() {
_pokesEnabled.dispose();
_mutedSenders.dispose();
}
}
@@ -0,0 +1,36 @@
typedef VoiceJoinCallback = Future<void> Function({
required BigInt channelId,
required String password,
});
typedef IosVoiceSessionActivation = Future<void> Function();
typedef IosVoiceSessionDeactivation = Future<void> Function();
/// Predicate used to recognise `voiceJoin` errors that the caller treats as a
/// successful join outcome (e.g. the server replied "already in channel").
///
/// When this returns `true` for a thrown error, the iOS audio session is kept
/// active because the user is still considered joined to the channel. The
/// error is still rethrown so the caller can run its success-on-already-joined
/// branch and update local state.
typedef VoiceJoinSuccessPredicate = bool Function(Object error);
Future<void> joinVoiceChannelWithIosAudioSession({
required BigInt channelId,
required String password,
required VoiceJoinCallback voiceJoin,
required IosVoiceSessionActivation activateIosAudioSession,
required IosVoiceSessionDeactivation deactivateIosAudioSession,
VoiceJoinSuccessPredicate? isJoinSuccess,
}) async {
await activateIosAudioSession();
try {
await voiceJoin(channelId: channelId, password: password);
} catch (e) {
if (isJoinSuccess != null && isJoinSuccess(e)) {
rethrow;
}
await deactivateIosAudioSession();
rethrow;
}
}
+113 -9
View File
@@ -11,7 +11,7 @@ part 'api.freezed.dart';
// These functions are ignored because they are not marked as `pub`: `dispatch_platform_audio_event`, `install_panic_diagnostic_hook`, `log_file_path`, `log_sink`, `map_join_error_code`, `map_join_sync_state`, `open_log_file`, `permission_events`, `platform_audio_events`, `process`, `publish_permission_state`, `runtime`, `session`, `task_join_error`, `transmit_mode_from_u8` // These functions are ignored because they are not marked as `pub`: `dispatch_platform_audio_event`, `install_panic_diagnostic_hook`, `log_file_path`, `log_sink`, `map_join_error_code`, `map_join_sync_state`, `open_log_file`, `permission_events`, `platform_audio_events`, `process`, `publish_permission_state`, `runtime`, `session`, `task_join_error`, `transmit_mode_from_u8`
// These types are ignored because they are neither used by any `pub` functions nor (for structs and enums) marked `#[frb(unignore)]`: `PlatformAudioEvent` // These types are ignored because they are neither used by any `pub` functions nor (for structs and enums) marked `#[frb(unignore)]`: `PlatformAudioEvent`
// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from` // These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`
// These functions are ignored (category: IgnoreBecauseExplicitAttribute): `from_kotlin_str`, `to_permission_gate` // These functions are ignored (category: IgnoreBecauseExplicitAttribute): `from_kotlin_str`, `to_permission_gate`
/// Return the platform-conventional log-file path as a string, or /// Return the platform-conventional log-file path as a string, or
@@ -226,6 +226,29 @@ String exportDiagnostics() => RustLib.instance.api.crateApiExportDiagnostics();
Future<void> initStorage({required String dir}) => Future<void> initStorage({required String dir}) =>
RustLib.instance.api.crateApiInitStorage(dir: dir); RustLib.instance.api.crateApiInitStorage(dir: dir);
/// Configure the bridge blob cache root.
Future<void> initCache({required String dir}) =>
RustLib.instance.api.crateApiInitCache(dir: dir);
/// Resolve avatar bytes through the bridge.
Future<Uint8List?> downloadAvatar({
required String avatarHash,
required String clientUid,
}) => RustLib.instance.api.crateApiDownloadAvatar(
avatarHash: avatarHash,
clientUid: clientUid,
);
/// Resolve icon bytes through the bridge.
Future<Uint8List?> downloadIcon({required BigInt iconId}) =>
RustLib.instance.api.crateApiDownloadIcon(iconId: iconId);
/// Purge cached protocol-owned assets.
Future<void> clearFileCache() => RustLib.instance.api.crateApiClearFileCache();
/// Report the configured file-cache size.
Future<BigInt> fileCacheSize() => RustLib.instance.api.crateApiFileCacheSize();
/// List persisted bookmarks. /// List persisted bookmarks.
Future<List<BridgeBookmark>> listBookmarks() => Future<List<BridgeBookmark>> listBookmarks() =>
RustLib.instance.api.crateApiListBookmarks(); RustLib.instance.api.crateApiListBookmarks();
@@ -263,7 +286,8 @@ Future<BridgeAudioStats> audioStats() =>
/// Subscribe to real-time microphone input level at ~30 Hz. /// Subscribe to real-time microphone input level at ~30 Hz.
/// Values are dBFS (-120 = silence, 0 = clipping). The stream ends /// Values are dBFS (-120 = silence, 0 = clipping). The stream ends
/// when the Dart subscriber cancels or the session is dropped. /// when the Dart subscriber cancels, the session is dropped, or
/// the session becomes persistently unavailable.
Stream<double> inputLevelStream() => Stream<double> inputLevelStream() =>
RustLib.instance.api.crateApiInputLevelStream(); RustLib.instance.api.crateApiInputLevelStream();
@@ -1209,6 +1233,9 @@ sealed class BridgeEvent with _$BridgeEvent {
/// Target scope (server/channel/private/poke). /// Target scope (server/channel/private/poke).
required BridgeMessageTarget target, required BridgeMessageTarget target,
/// Poke notification strength, present only for poke messages.
BridgePokeStrength? pokeStrength,
}) = BridgeEvent_ChatMessage; }) = BridgeEvent_ChatMessage;
/// Human-readable server activity surfaced from protocol bookkeeping events. /// Human-readable server activity surfaced from protocol bookkeeping events.
@@ -1219,59 +1246,124 @@ sealed class BridgeEvent with _$BridgeEvent {
/// Audio route changed (speaker/earpiece/BT/wired). /// Audio route changed (speaker/earpiece/BT/wired).
const factory BridgeEvent.audioRouteChanged({ const factory BridgeEvent.audioRouteChanged({
/// New audio output route.
required BridgeAudioRoute route, required BridgeAudioRoute route,
}) = BridgeEvent_AudioRouteChanged; }) = BridgeEvent_AudioRouteChanged;
/// A client moved to a different channel.
const factory BridgeEvent.clientMoved({ const factory BridgeEvent.clientMoved({
/// Unique client identifier.
required BigInt clientId, required BigInt clientId,
/// Destination channel.
required BigInt newChannelId, required BigInt newChannelId,
}) = BridgeEvent_ClientMoved; }) = BridgeEvent_ClientMoved;
/// A new client connected.
const factory BridgeEvent.clientJoined({ const factory BridgeEvent.clientJoined({
/// Unique client identifier.
required BigInt clientId, required BigInt clientId,
/// Channel the client joined.
required BigInt channelId, required BigInt channelId,
/// Display nickname.
required String name, required String name,
/// Microphone muted state.
required bool inputMuted, required bool inputMuted,
/// Speaker muted state.
required bool outputMuted, required bool outputMuted,
/// True for server query (bot) clients.
required bool isServerQuery, required bool isServerQuery,
/// Client's talk power value.
required int talkPower, required int talkPower,
/// Whether the server granted temporary talk power.
required bool talkPowerGranted, required bool talkPowerGranted,
}) = BridgeEvent_ClientJoined; }) = BridgeEvent_ClientJoined;
/// A client disconnected.
const factory BridgeEvent.clientLeft({ const factory BridgeEvent.clientLeft({
/// Unique client identifier.
required BigInt clientId, required BigInt clientId,
/// Display nickname at time of disconnect.
required String name, required String name,
}) = BridgeEvent_ClientLeft; }) = BridgeEvent_ClientLeft;
/// Client properties changed.
const factory BridgeEvent.clientUpdated({ const factory BridgeEvent.clientUpdated({
/// Unique client identifier.
required BigInt clientId, required BigInt clientId,
/// Microphone muted state.
required bool inputMuted, required bool inputMuted,
/// Speaker muted state.
required bool outputMuted, required bool outputMuted,
/// True for server query (bot) clients.
required bool isServerQuery, required bool isServerQuery,
/// Client's talk power value.
required int talkPower, required int talkPower,
/// Whether the server granted temporary talk power.
required bool talkPowerGranted, required bool talkPowerGranted,
}) = BridgeEvent_ClientUpdated; }) = BridgeEvent_ClientUpdated;
/// A new channel appeared.
const factory BridgeEvent.channelAdded({ const factory BridgeEvent.channelAdded({
/// Unique channel identifier.
required BigInt id, required BigInt id,
/// Parent channel ID.
required BigInt parent, required BigInt parent,
/// Channel name.
required String name, required String name,
/// Predecessor channel ID within the same parent (TeamSpeak
/// linked-list ordering hint). Zero means first child.
required PlatformInt64 order, required PlatformInt64 order,
/// Whether the channel requires a password.
required bool hasPassword, required bool hasPassword,
/// Talk power required to speak; `None` means no restriction.
int? neededTalkPower, int? neededTalkPower,
}) = BridgeEvent_ChannelAdded; }) = BridgeEvent_ChannelAdded;
const factory BridgeEvent.channelRemoved({required BigInt id}) =
BridgeEvent_ChannelRemoved; /// A channel was deleted.
const factory BridgeEvent.channelUpdated({ const factory BridgeEvent.channelRemoved({
/// Channel identifier.
required BigInt id, required BigInt id,
}) = BridgeEvent_ChannelRemoved;
/// Channel properties changed.
const factory BridgeEvent.channelUpdated({
/// Unique channel identifier.
required BigInt id,
/// Channel name.
required String name, required String name,
/// Whether the channel requires a password.
required bool hasPassword, required bool hasPassword,
/// Talk power required to speak; `None` means no restriction.
int? neededTalkPower, int? neededTalkPower,
}) = BridgeEvent_ChannelUpdated; }) = BridgeEvent_ChannelUpdated;
} }
/// Bridge iOS voice-processing mode. /// Bridge iOS voice-processing mode.
enum BridgeIosVoiceProcessingMode { enum BridgeIosVoiceProcessingMode {
/// Shipping VPIO path. /// Apple VoiceProcessingIO path.
platformVoiceProcessing, platformVoiceProcessing,
/// Experimental Sonora path.
sonoraExperimental,
} }
@freezed @freezed
@@ -1306,6 +1398,18 @@ enum BridgeNetworkState {
offline, offline,
} }
/// Bridge poke notification strength.
enum BridgePokeStrength {
/// Poke should be surfaced at full strength.
strong,
/// Poke is rate-limited but below overflow severity.
suppressed,
/// Poke remains suppressed after repeated suppressed pokes.
suppressedOverflow,
}
/// Persisted PTT binding display state for the UI. /// Persisted PTT binding display state for the UI.
class BridgePttBinding { class BridgePttBinding {
/// Stable input category string (`""`, `"keyboard"`, or /// Stable input category string (`""`, `"keyboard"`, or
@@ -173,7 +173,7 @@ return channelUpdated(_that);case _:
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>({TResult Function( String serverName)? connected,TResult Function( String reason)? lost,TResult Function( int attempt, int delaySecs)? reconnecting,TResult Function( String reason)? disconnected,TResult Function()? audioStarted,TResult Function()? audioStopped,TResult Function( String level, String backendId, String boundInputClass)? pttCapability,TResult Function( bool inChannel, BridgeTransmitMode transmitMode, bool mute, int releaseTailMs, BigInt? currentChannelId, BigInt? pendingTargetChannelId, bool canJoin, bool canLeave, BridgeVoiceJoinSyncState joinSyncState, BridgeVoiceJoinErrorCode? joinErrorCode)? voiceState,TResult Function( bool began, bool shouldResume)? interruptionState,TResult Function( String permission, PermissionStateKind state)? permissionState,TResult Function( BigInt senderId, String senderName, String message, BridgeMessageTarget target)? chatMessage,TResult Function( String message)? serverActivity,TResult Function( BridgeAudioRoute route)? audioRouteChanged,TResult Function( BigInt clientId, BigInt newChannelId)? clientMoved,TResult Function( BigInt clientId, BigInt channelId, String name, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted)? clientJoined,TResult Function( BigInt clientId, String name)? clientLeft,TResult Function( BigInt clientId, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted)? clientUpdated,TResult Function( BigInt id, BigInt parent, String name, PlatformInt64 order, bool hasPassword, int? neededTalkPower)? channelAdded,TResult Function( BigInt id)? channelRemoved,TResult Function( BigInt id, String name, bool hasPassword, int? neededTalkPower)? channelUpdated,required TResult orElse(),}) {final _that = this; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({TResult Function( String serverName)? connected,TResult Function( String reason)? lost,TResult Function( int attempt, int delaySecs)? reconnecting,TResult Function( String reason)? disconnected,TResult Function()? audioStarted,TResult Function()? audioStopped,TResult Function( String level, String backendId, String boundInputClass)? pttCapability,TResult Function( bool inChannel, BridgeTransmitMode transmitMode, bool mute, int releaseTailMs, BigInt? currentChannelId, BigInt? pendingTargetChannelId, bool canJoin, bool canLeave, BridgeVoiceJoinSyncState joinSyncState, BridgeVoiceJoinErrorCode? joinErrorCode)? voiceState,TResult Function( bool began, bool shouldResume)? interruptionState,TResult Function( String permission, PermissionStateKind state)? permissionState,TResult Function( BigInt senderId, String senderName, String message, BridgeMessageTarget target, BridgePokeStrength? pokeStrength)? chatMessage,TResult Function( String message)? serverActivity,TResult Function( BridgeAudioRoute route)? audioRouteChanged,TResult Function( BigInt clientId, BigInt newChannelId)? clientMoved,TResult Function( BigInt clientId, BigInt channelId, String name, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted)? clientJoined,TResult Function( BigInt clientId, String name)? clientLeft,TResult Function( BigInt clientId, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted)? clientUpdated,TResult Function( BigInt id, BigInt parent, String name, PlatformInt64 order, bool hasPassword, int? neededTalkPower)? channelAdded,TResult Function( BigInt id)? channelRemoved,TResult Function( BigInt id, String name, bool hasPassword, int? neededTalkPower)? channelUpdated,required TResult orElse(),}) {final _that = this;
switch (_that) { switch (_that) {
case BridgeEvent_Connected() when connected != null: case BridgeEvent_Connected() when connected != null:
return connected(_that.serverName);case BridgeEvent_Lost() when lost != null: return connected(_that.serverName);case BridgeEvent_Lost() when lost != null:
@@ -186,7 +186,7 @@ return pttCapability(_that.level,_that.backendId,_that.boundInputClass);case Bri
return voiceState(_that.inChannel,_that.transmitMode,_that.mute,_that.releaseTailMs,_that.currentChannelId,_that.pendingTargetChannelId,_that.canJoin,_that.canLeave,_that.joinSyncState,_that.joinErrorCode);case BridgeEvent_InterruptionState() when interruptionState != null: return voiceState(_that.inChannel,_that.transmitMode,_that.mute,_that.releaseTailMs,_that.currentChannelId,_that.pendingTargetChannelId,_that.canJoin,_that.canLeave,_that.joinSyncState,_that.joinErrorCode);case BridgeEvent_InterruptionState() when interruptionState != null:
return interruptionState(_that.began,_that.shouldResume);case BridgeEvent_PermissionState() when permissionState != null: return interruptionState(_that.began,_that.shouldResume);case BridgeEvent_PermissionState() when permissionState != null:
return permissionState(_that.permission,_that.state);case BridgeEvent_ChatMessage() when chatMessage != null: return permissionState(_that.permission,_that.state);case BridgeEvent_ChatMessage() when chatMessage != null:
return chatMessage(_that.senderId,_that.senderName,_that.message,_that.target);case BridgeEvent_ServerActivity() when serverActivity != null: return chatMessage(_that.senderId,_that.senderName,_that.message,_that.target,_that.pokeStrength);case BridgeEvent_ServerActivity() when serverActivity != null:
return serverActivity(_that.message);case BridgeEvent_AudioRouteChanged() when audioRouteChanged != null: return serverActivity(_that.message);case BridgeEvent_AudioRouteChanged() when audioRouteChanged != null:
return audioRouteChanged(_that.route);case BridgeEvent_ClientMoved() when clientMoved != null: return audioRouteChanged(_that.route);case BridgeEvent_ClientMoved() when clientMoved != null:
return clientMoved(_that.clientId,_that.newChannelId);case BridgeEvent_ClientJoined() when clientJoined != null: return clientMoved(_that.clientId,_that.newChannelId);case BridgeEvent_ClientJoined() when clientJoined != null:
@@ -213,7 +213,7 @@ return channelUpdated(_that.id,_that.name,_that.hasPassword,_that.neededTalkPowe
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult when<TResult extends Object?>({required TResult Function( String serverName) connected,required TResult Function( String reason) lost,required TResult Function( int attempt, int delaySecs) reconnecting,required TResult Function( String reason) disconnected,required TResult Function() audioStarted,required TResult Function() audioStopped,required TResult Function( String level, String backendId, String boundInputClass) pttCapability,required TResult Function( bool inChannel, BridgeTransmitMode transmitMode, bool mute, int releaseTailMs, BigInt? currentChannelId, BigInt? pendingTargetChannelId, bool canJoin, bool canLeave, BridgeVoiceJoinSyncState joinSyncState, BridgeVoiceJoinErrorCode? joinErrorCode) voiceState,required TResult Function( bool began, bool shouldResume) interruptionState,required TResult Function( String permission, PermissionStateKind state) permissionState,required TResult Function( BigInt senderId, String senderName, String message, BridgeMessageTarget target) chatMessage,required TResult Function( String message) serverActivity,required TResult Function( BridgeAudioRoute route) audioRouteChanged,required TResult Function( BigInt clientId, BigInt newChannelId) clientMoved,required TResult Function( BigInt clientId, BigInt channelId, String name, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted) clientJoined,required TResult Function( BigInt clientId, String name) clientLeft,required TResult Function( BigInt clientId, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted) clientUpdated,required TResult Function( BigInt id, BigInt parent, String name, PlatformInt64 order, bool hasPassword, int? neededTalkPower) channelAdded,required TResult Function( BigInt id) channelRemoved,required TResult Function( BigInt id, String name, bool hasPassword, int? neededTalkPower) channelUpdated,}) {final _that = this; @optionalTypeArgs TResult when<TResult extends Object?>({required TResult Function( String serverName) connected,required TResult Function( String reason) lost,required TResult Function( int attempt, int delaySecs) reconnecting,required TResult Function( String reason) disconnected,required TResult Function() audioStarted,required TResult Function() audioStopped,required TResult Function( String level, String backendId, String boundInputClass) pttCapability,required TResult Function( bool inChannel, BridgeTransmitMode transmitMode, bool mute, int releaseTailMs, BigInt? currentChannelId, BigInt? pendingTargetChannelId, bool canJoin, bool canLeave, BridgeVoiceJoinSyncState joinSyncState, BridgeVoiceJoinErrorCode? joinErrorCode) voiceState,required TResult Function( bool began, bool shouldResume) interruptionState,required TResult Function( String permission, PermissionStateKind state) permissionState,required TResult Function( BigInt senderId, String senderName, String message, BridgeMessageTarget target, BridgePokeStrength? pokeStrength) chatMessage,required TResult Function( String message) serverActivity,required TResult Function( BridgeAudioRoute route) audioRouteChanged,required TResult Function( BigInt clientId, BigInt newChannelId) clientMoved,required TResult Function( BigInt clientId, BigInt channelId, String name, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted) clientJoined,required TResult Function( BigInt clientId, String name) clientLeft,required TResult Function( BigInt clientId, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted) clientUpdated,required TResult Function( BigInt id, BigInt parent, String name, PlatformInt64 order, bool hasPassword, int? neededTalkPower) channelAdded,required TResult Function( BigInt id) channelRemoved,required TResult Function( BigInt id, String name, bool hasPassword, int? neededTalkPower) channelUpdated,}) {final _that = this;
switch (_that) { switch (_that) {
case BridgeEvent_Connected(): case BridgeEvent_Connected():
return connected(_that.serverName);case BridgeEvent_Lost(): return connected(_that.serverName);case BridgeEvent_Lost():
@@ -226,7 +226,7 @@ return pttCapability(_that.level,_that.backendId,_that.boundInputClass);case Bri
return voiceState(_that.inChannel,_that.transmitMode,_that.mute,_that.releaseTailMs,_that.currentChannelId,_that.pendingTargetChannelId,_that.canJoin,_that.canLeave,_that.joinSyncState,_that.joinErrorCode);case BridgeEvent_InterruptionState(): return voiceState(_that.inChannel,_that.transmitMode,_that.mute,_that.releaseTailMs,_that.currentChannelId,_that.pendingTargetChannelId,_that.canJoin,_that.canLeave,_that.joinSyncState,_that.joinErrorCode);case BridgeEvent_InterruptionState():
return interruptionState(_that.began,_that.shouldResume);case BridgeEvent_PermissionState(): return interruptionState(_that.began,_that.shouldResume);case BridgeEvent_PermissionState():
return permissionState(_that.permission,_that.state);case BridgeEvent_ChatMessage(): return permissionState(_that.permission,_that.state);case BridgeEvent_ChatMessage():
return chatMessage(_that.senderId,_that.senderName,_that.message,_that.target);case BridgeEvent_ServerActivity(): return chatMessage(_that.senderId,_that.senderName,_that.message,_that.target,_that.pokeStrength);case BridgeEvent_ServerActivity():
return serverActivity(_that.message);case BridgeEvent_AudioRouteChanged(): return serverActivity(_that.message);case BridgeEvent_AudioRouteChanged():
return audioRouteChanged(_that.route);case BridgeEvent_ClientMoved(): return audioRouteChanged(_that.route);case BridgeEvent_ClientMoved():
return clientMoved(_that.clientId,_that.newChannelId);case BridgeEvent_ClientJoined(): return clientMoved(_that.clientId,_that.newChannelId);case BridgeEvent_ClientJoined():
@@ -249,7 +249,7 @@ return channelUpdated(_that.id,_that.name,_that.hasPassword,_that.neededTalkPowe
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({TResult? Function( String serverName)? connected,TResult? Function( String reason)? lost,TResult? Function( int attempt, int delaySecs)? reconnecting,TResult? Function( String reason)? disconnected,TResult? Function()? audioStarted,TResult? Function()? audioStopped,TResult? Function( String level, String backendId, String boundInputClass)? pttCapability,TResult? Function( bool inChannel, BridgeTransmitMode transmitMode, bool mute, int releaseTailMs, BigInt? currentChannelId, BigInt? pendingTargetChannelId, bool canJoin, bool canLeave, BridgeVoiceJoinSyncState joinSyncState, BridgeVoiceJoinErrorCode? joinErrorCode)? voiceState,TResult? Function( bool began, bool shouldResume)? interruptionState,TResult? Function( String permission, PermissionStateKind state)? permissionState,TResult? Function( BigInt senderId, String senderName, String message, BridgeMessageTarget target)? chatMessage,TResult? Function( String message)? serverActivity,TResult? Function( BridgeAudioRoute route)? audioRouteChanged,TResult? Function( BigInt clientId, BigInt newChannelId)? clientMoved,TResult? Function( BigInt clientId, BigInt channelId, String name, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted)? clientJoined,TResult? Function( BigInt clientId, String name)? clientLeft,TResult? Function( BigInt clientId, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted)? clientUpdated,TResult? Function( BigInt id, BigInt parent, String name, PlatformInt64 order, bool hasPassword, int? neededTalkPower)? channelAdded,TResult? Function( BigInt id)? channelRemoved,TResult? Function( BigInt id, String name, bool hasPassword, int? neededTalkPower)? channelUpdated,}) {final _that = this; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({TResult? Function( String serverName)? connected,TResult? Function( String reason)? lost,TResult? Function( int attempt, int delaySecs)? reconnecting,TResult? Function( String reason)? disconnected,TResult? Function()? audioStarted,TResult? Function()? audioStopped,TResult? Function( String level, String backendId, String boundInputClass)? pttCapability,TResult? Function( bool inChannel, BridgeTransmitMode transmitMode, bool mute, int releaseTailMs, BigInt? currentChannelId, BigInt? pendingTargetChannelId, bool canJoin, bool canLeave, BridgeVoiceJoinSyncState joinSyncState, BridgeVoiceJoinErrorCode? joinErrorCode)? voiceState,TResult? Function( bool began, bool shouldResume)? interruptionState,TResult? Function( String permission, PermissionStateKind state)? permissionState,TResult? Function( BigInt senderId, String senderName, String message, BridgeMessageTarget target, BridgePokeStrength? pokeStrength)? chatMessage,TResult? Function( String message)? serverActivity,TResult? Function( BridgeAudioRoute route)? audioRouteChanged,TResult? Function( BigInt clientId, BigInt newChannelId)? clientMoved,TResult? Function( BigInt clientId, BigInt channelId, String name, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted)? clientJoined,TResult? Function( BigInt clientId, String name)? clientLeft,TResult? Function( BigInt clientId, bool inputMuted, bool outputMuted, bool isServerQuery, int talkPower, bool talkPowerGranted)? clientUpdated,TResult? Function( BigInt id, BigInt parent, String name, PlatformInt64 order, bool hasPassword, int? neededTalkPower)? channelAdded,TResult? Function( BigInt id)? channelRemoved,TResult? Function( BigInt id, String name, bool hasPassword, int? neededTalkPower)? channelUpdated,}) {final _that = this;
switch (_that) { switch (_that) {
case BridgeEvent_Connected() when connected != null: case BridgeEvent_Connected() when connected != null:
return connected(_that.serverName);case BridgeEvent_Lost() when lost != null: return connected(_that.serverName);case BridgeEvent_Lost() when lost != null:
@@ -262,7 +262,7 @@ return pttCapability(_that.level,_that.backendId,_that.boundInputClass);case Bri
return voiceState(_that.inChannel,_that.transmitMode,_that.mute,_that.releaseTailMs,_that.currentChannelId,_that.pendingTargetChannelId,_that.canJoin,_that.canLeave,_that.joinSyncState,_that.joinErrorCode);case BridgeEvent_InterruptionState() when interruptionState != null: return voiceState(_that.inChannel,_that.transmitMode,_that.mute,_that.releaseTailMs,_that.currentChannelId,_that.pendingTargetChannelId,_that.canJoin,_that.canLeave,_that.joinSyncState,_that.joinErrorCode);case BridgeEvent_InterruptionState() when interruptionState != null:
return interruptionState(_that.began,_that.shouldResume);case BridgeEvent_PermissionState() when permissionState != null: return interruptionState(_that.began,_that.shouldResume);case BridgeEvent_PermissionState() when permissionState != null:
return permissionState(_that.permission,_that.state);case BridgeEvent_ChatMessage() when chatMessage != null: return permissionState(_that.permission,_that.state);case BridgeEvent_ChatMessage() when chatMessage != null:
return chatMessage(_that.senderId,_that.senderName,_that.message,_that.target);case BridgeEvent_ServerActivity() when serverActivity != null: return chatMessage(_that.senderId,_that.senderName,_that.message,_that.target,_that.pokeStrength);case BridgeEvent_ServerActivity() when serverActivity != null:
return serverActivity(_that.message);case BridgeEvent_AudioRouteChanged() when audioRouteChanged != null: return serverActivity(_that.message);case BridgeEvent_AudioRouteChanged() when audioRouteChanged != null:
return audioRouteChanged(_that.route);case BridgeEvent_ClientMoved() when clientMoved != null: return audioRouteChanged(_that.route);case BridgeEvent_ClientMoved() when clientMoved != null:
return clientMoved(_that.clientId,_that.newChannelId);case BridgeEvent_ClientJoined() when clientJoined != null: return clientMoved(_that.clientId,_that.newChannelId);case BridgeEvent_ClientJoined() when clientJoined != null:
@@ -929,7 +929,7 @@ as PermissionStateKind,
class BridgeEvent_ChatMessage extends BridgeEvent { class BridgeEvent_ChatMessage extends BridgeEvent {
const BridgeEvent_ChatMessage({required this.senderId, required this.senderName, required this.message, required this.target}): super._(); const BridgeEvent_ChatMessage({required this.senderId, required this.senderName, required this.message, required this.target, this.pokeStrength}): super._();
/// Client id of the sender. /// Client id of the sender.
@@ -940,6 +940,8 @@ class BridgeEvent_ChatMessage extends BridgeEvent {
final String message; final String message;
/// Target scope (server/channel/private/poke). /// Target scope (server/channel/private/poke).
final BridgeMessageTarget target; final BridgeMessageTarget target;
/// Poke notification strength, present only for poke messages.
final BridgePokeStrength? pokeStrength;
/// Create a copy of BridgeEvent /// Create a copy of BridgeEvent
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@@ -951,16 +953,16 @@ $BridgeEvent_ChatMessageCopyWith<BridgeEvent_ChatMessage> get copyWith => _$Brid
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is BridgeEvent_ChatMessage&&(identical(other.senderId, senderId) || other.senderId == senderId)&&(identical(other.senderName, senderName) || other.senderName == senderName)&&(identical(other.message, message) || other.message == message)&&(identical(other.target, target) || other.target == target)); return identical(this, other) || (other.runtimeType == runtimeType&&other is BridgeEvent_ChatMessage&&(identical(other.senderId, senderId) || other.senderId == senderId)&&(identical(other.senderName, senderName) || other.senderName == senderName)&&(identical(other.message, message) || other.message == message)&&(identical(other.target, target) || other.target == target)&&(identical(other.pokeStrength, pokeStrength) || other.pokeStrength == pokeStrength));
} }
@override @override
int get hashCode => Object.hash(runtimeType,senderId,senderName,message,target); int get hashCode => Object.hash(runtimeType,senderId,senderName,message,target,pokeStrength);
@override @override
String toString() { String toString() {
return 'BridgeEvent.chatMessage(senderId: $senderId, senderName: $senderName, message: $message, target: $target)'; return 'BridgeEvent.chatMessage(senderId: $senderId, senderName: $senderName, message: $message, target: $target, pokeStrength: $pokeStrength)';
} }
@@ -971,7 +973,7 @@ abstract mixin class $BridgeEvent_ChatMessageCopyWith<$Res> implements $BridgeEv
factory $BridgeEvent_ChatMessageCopyWith(BridgeEvent_ChatMessage value, $Res Function(BridgeEvent_ChatMessage) _then) = _$BridgeEvent_ChatMessageCopyWithImpl; factory $BridgeEvent_ChatMessageCopyWith(BridgeEvent_ChatMessage value, $Res Function(BridgeEvent_ChatMessage) _then) = _$BridgeEvent_ChatMessageCopyWithImpl;
@useResult @useResult
$Res call({ $Res call({
BigInt senderId, String senderName, String message, BridgeMessageTarget target BigInt senderId, String senderName, String message, BridgeMessageTarget target, BridgePokeStrength? pokeStrength
}); });
@@ -988,13 +990,14 @@ class _$BridgeEvent_ChatMessageCopyWithImpl<$Res>
/// Create a copy of BridgeEvent /// Create a copy of BridgeEvent
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') $Res call({Object? senderId = null,Object? senderName = null,Object? message = null,Object? target = null,}) { @pragma('vm:prefer-inline') $Res call({Object? senderId = null,Object? senderName = null,Object? message = null,Object? target = null,Object? pokeStrength = freezed,}) {
return _then(BridgeEvent_ChatMessage( return _then(BridgeEvent_ChatMessage(
senderId: null == senderId ? _self.senderId : senderId // ignore: cast_nullable_to_non_nullable senderId: null == senderId ? _self.senderId : senderId // ignore: cast_nullable_to_non_nullable
as BigInt,senderName: null == senderName ? _self.senderName : senderName // ignore: cast_nullable_to_non_nullable as BigInt,senderName: null == senderName ? _self.senderName : senderName // ignore: cast_nullable_to_non_nullable
as String,message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable as String,message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable
as String,target: null == target ? _self.target : target // ignore: cast_nullable_to_non_nullable as String,target: null == target ? _self.target : target // ignore: cast_nullable_to_non_nullable
as BridgeMessageTarget, as BridgeMessageTarget,pokeStrength: freezed == pokeStrength ? _self.pokeStrength : pokeStrength // ignore: cast_nullable_to_non_nullable
as BridgePokeStrength?,
)); ));
} }
@@ -1084,6 +1087,7 @@ class BridgeEvent_AudioRouteChanged extends BridgeEvent {
const BridgeEvent_AudioRouteChanged({required this.route}): super._(); const BridgeEvent_AudioRouteChanged({required this.route}): super._();
/// New audio output route.
final BridgeAudioRoute route; final BridgeAudioRoute route;
/// Create a copy of BridgeEvent /// Create a copy of BridgeEvent
@@ -1150,7 +1154,9 @@ class BridgeEvent_ClientMoved extends BridgeEvent {
const BridgeEvent_ClientMoved({required this.clientId, required this.newChannelId}): super._(); const BridgeEvent_ClientMoved({required this.clientId, required this.newChannelId}): super._();
/// Unique client identifier.
final BigInt clientId; final BigInt clientId;
/// Destination channel.
final BigInt newChannelId; final BigInt newChannelId;
/// Create a copy of BridgeEvent /// Create a copy of BridgeEvent
@@ -1218,13 +1224,21 @@ class BridgeEvent_ClientJoined extends BridgeEvent {
const BridgeEvent_ClientJoined({required this.clientId, required this.channelId, required this.name, required this.inputMuted, required this.outputMuted, required this.isServerQuery, required this.talkPower, required this.talkPowerGranted}): super._(); const BridgeEvent_ClientJoined({required this.clientId, required this.channelId, required this.name, required this.inputMuted, required this.outputMuted, required this.isServerQuery, required this.talkPower, required this.talkPowerGranted}): super._();
/// Unique client identifier.
final BigInt clientId; final BigInt clientId;
/// Channel the client joined.
final BigInt channelId; final BigInt channelId;
/// Display nickname.
final String name; final String name;
/// Microphone muted state.
final bool inputMuted; final bool inputMuted;
/// Speaker muted state.
final bool outputMuted; final bool outputMuted;
/// True for server query (bot) clients.
final bool isServerQuery; final bool isServerQuery;
/// Client's talk power value.
final int talkPower; final int talkPower;
/// Whether the server granted temporary talk power.
final bool talkPowerGranted; final bool talkPowerGranted;
/// Create a copy of BridgeEvent /// Create a copy of BridgeEvent
@@ -1298,7 +1312,9 @@ class BridgeEvent_ClientLeft extends BridgeEvent {
const BridgeEvent_ClientLeft({required this.clientId, required this.name}): super._(); const BridgeEvent_ClientLeft({required this.clientId, required this.name}): super._();
/// Unique client identifier.
final BigInt clientId; final BigInt clientId;
/// Display nickname at time of disconnect.
final String name; final String name;
/// Create a copy of BridgeEvent /// Create a copy of BridgeEvent
@@ -1366,11 +1382,17 @@ class BridgeEvent_ClientUpdated extends BridgeEvent {
const BridgeEvent_ClientUpdated({required this.clientId, required this.inputMuted, required this.outputMuted, required this.isServerQuery, required this.talkPower, required this.talkPowerGranted}): super._(); const BridgeEvent_ClientUpdated({required this.clientId, required this.inputMuted, required this.outputMuted, required this.isServerQuery, required this.talkPower, required this.talkPowerGranted}): super._();
/// Unique client identifier.
final BigInt clientId; final BigInt clientId;
/// Microphone muted state.
final bool inputMuted; final bool inputMuted;
/// Speaker muted state.
final bool outputMuted; final bool outputMuted;
/// True for server query (bot) clients.
final bool isServerQuery; final bool isServerQuery;
/// Client's talk power value.
final int talkPower; final int talkPower;
/// Whether the server granted temporary talk power.
final bool talkPowerGranted; final bool talkPowerGranted;
/// Create a copy of BridgeEvent /// Create a copy of BridgeEvent
@@ -1442,11 +1464,18 @@ class BridgeEvent_ChannelAdded extends BridgeEvent {
const BridgeEvent_ChannelAdded({required this.id, required this.parent, required this.name, required this.order, required this.hasPassword, this.neededTalkPower}): super._(); const BridgeEvent_ChannelAdded({required this.id, required this.parent, required this.name, required this.order, required this.hasPassword, this.neededTalkPower}): super._();
/// Unique channel identifier.
final BigInt id; final BigInt id;
/// Parent channel ID.
final BigInt parent; final BigInt parent;
/// Channel name.
final String name; final String name;
/// Predecessor channel ID within the same parent (TeamSpeak
/// linked-list ordering hint). Zero means first child.
final PlatformInt64 order; final PlatformInt64 order;
/// Whether the channel requires a password.
final bool hasPassword; final bool hasPassword;
/// Talk power required to speak; `None` means no restriction.
final int? neededTalkPower; final int? neededTalkPower;
/// Create a copy of BridgeEvent /// Create a copy of BridgeEvent
@@ -1518,6 +1547,7 @@ class BridgeEvent_ChannelRemoved extends BridgeEvent {
const BridgeEvent_ChannelRemoved({required this.id}): super._(); const BridgeEvent_ChannelRemoved({required this.id}): super._();
/// Channel identifier.
final BigInt id; final BigInt id;
/// Create a copy of BridgeEvent /// Create a copy of BridgeEvent
@@ -1584,9 +1614,13 @@ class BridgeEvent_ChannelUpdated extends BridgeEvent {
const BridgeEvent_ChannelUpdated({required this.id, required this.name, required this.hasPassword, this.neededTalkPower}): super._(); const BridgeEvent_ChannelUpdated({required this.id, required this.name, required this.hasPassword, this.neededTalkPower}): super._();
/// Unique channel identifier.
final BigInt id; final BigInt id;
/// Channel name.
final String name; final String name;
/// Whether the channel requires a password.
final bool hasPassword; final bool hasPassword;
/// Talk power required to speak; `None` means no restriction.
final int? neededTalkPower; final int? neededTalkPower;
/// Create a copy of BridgeEvent /// Create a copy of BridgeEvent
@@ -67,7 +67,7 @@ class RustLib extends BaseEntrypoint<RustLibApi, RustLibApiImpl, RustLibWire> {
String get codegenVersion => '2.12.0'; String get codegenVersion => '2.12.0';
@override @override
int get rustContentHash => -20394775; int get rustContentHash => 635684021;
static const kDefaultExternalLibraryLoaderConfig = static const kDefaultExternalLibraryLoaderConfig =
ExternalLibraryLoaderConfig( ExternalLibraryLoaderConfig(
@@ -87,6 +87,8 @@ abstract class RustLibApi extends BaseApi {
Future<void> crateApiBridgeInit(); Future<void> crateApiBridgeInit();
Future<void> crateApiClearFileCache();
Future<BridgeClientProfile> crateApiClientProfile({required BigInt clientId}); Future<BridgeClientProfile> crateApiClientProfile({required BigInt clientId});
Future<BridgeSnapshot> crateApiConnect({ Future<BridgeSnapshot> crateApiConnect({
@@ -99,12 +101,21 @@ abstract class RustLibApi extends BaseApi {
Future<void> crateApiDisconnect(); Future<void> crateApiDisconnect();
Future<Uint8List?> crateApiDownloadAvatar({
required String avatarHash,
required String clientUid,
});
Future<Uint8List?> crateApiDownloadIcon({required BigInt iconId});
Future<void> crateApiEnableAudioDebugWavDump({required bool enabled}); Future<void> crateApiEnableAudioDebugWavDump({required bool enabled});
Stream<BridgeEvent> crateApiEventsStream(); Stream<BridgeEvent> crateApiEventsStream();
String crateApiExportDiagnostics(); String crateApiExportDiagnostics();
Future<BigInt> crateApiFileCacheSize();
Future<BridgeAudioProcessingConfig> crateApiGetAudioProcessingConfig(); Future<BridgeAudioProcessingConfig> crateApiGetAudioProcessingConfig();
Future<BridgePttBinding> crateApiGetPttBinding(); Future<BridgePttBinding> crateApiGetPttBinding();
@@ -121,6 +132,8 @@ abstract class RustLibApi extends BaseApi {
void crateApiHandleRouteChange({required BridgeAudioRoute route}); void crateApiHandleRouteChange({required BridgeAudioRoute route});
Future<void> crateApiInitCache({required String dir});
Future<void> crateApiInitStorage({required String dir}); Future<void> crateApiInitStorage({required String dir});
Stream<double> crateApiInputLevelStream(); Stream<double> crateApiInputLevelStream();
@@ -320,6 +333,33 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
TaskConstMeta get kCrateApiBridgeInitConstMeta => TaskConstMeta get kCrateApiBridgeInitConstMeta =>
const TaskConstMeta(debugName: "bridge_init", argNames: []); const TaskConstMeta(debugName: "bridge_init", argNames: []);
@override
Future<void> crateApiClearFileCache() {
return handler.executeNormal(
NormalTask(
callFfi: (port_) {
final serializer = SseSerializer(generalizedFrbRustBinding);
pdeCallFfi(
generalizedFrbRustBinding,
serializer,
funcId: 5,
port: port_,
);
},
codec: SseCodec(
decodeSuccessData: sse_decode_unit,
decodeErrorData: sse_decode_bridge_error,
),
constMeta: kCrateApiClearFileCacheConstMeta,
argValues: [],
apiImpl: this,
),
);
}
TaskConstMeta get kCrateApiClearFileCacheConstMeta =>
const TaskConstMeta(debugName: "clear_file_cache", argNames: []);
@override @override
Future<BridgeClientProfile> crateApiClientProfile({ Future<BridgeClientProfile> crateApiClientProfile({
required BigInt clientId, required BigInt clientId,
@@ -332,7 +372,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 5, funcId: 6,
port: port_, port: port_,
); );
}, },
@@ -366,7 +406,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 6, funcId: 7,
port: port_, port: port_,
); );
}, },
@@ -396,7 +436,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 7, funcId: 8,
port: port_, port: port_,
); );
}, },
@@ -423,7 +463,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 8, funcId: 9,
port: port_, port: port_,
); );
}, },
@@ -441,6 +481,68 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
TaskConstMeta get kCrateApiDisconnectConstMeta => TaskConstMeta get kCrateApiDisconnectConstMeta =>
const TaskConstMeta(debugName: "disconnect", argNames: []); const TaskConstMeta(debugName: "disconnect", argNames: []);
@override
Future<Uint8List?> crateApiDownloadAvatar({
required String avatarHash,
required String clientUid,
}) {
return handler.executeNormal(
NormalTask(
callFfi: (port_) {
final serializer = SseSerializer(generalizedFrbRustBinding);
sse_encode_String(avatarHash, serializer);
sse_encode_String(clientUid, serializer);
pdeCallFfi(
generalizedFrbRustBinding,
serializer,
funcId: 10,
port: port_,
);
},
codec: SseCodec(
decodeSuccessData: sse_decode_opt_list_prim_u_8_strict,
decodeErrorData: sse_decode_bridge_error,
),
constMeta: kCrateApiDownloadAvatarConstMeta,
argValues: [avatarHash, clientUid],
apiImpl: this,
),
);
}
TaskConstMeta get kCrateApiDownloadAvatarConstMeta => const TaskConstMeta(
debugName: "download_avatar",
argNames: ["avatarHash", "clientUid"],
);
@override
Future<Uint8List?> crateApiDownloadIcon({required BigInt iconId}) {
return handler.executeNormal(
NormalTask(
callFfi: (port_) {
final serializer = SseSerializer(generalizedFrbRustBinding);
sse_encode_u_64(iconId, serializer);
pdeCallFfi(
generalizedFrbRustBinding,
serializer,
funcId: 11,
port: port_,
);
},
codec: SseCodec(
decodeSuccessData: sse_decode_opt_list_prim_u_8_strict,
decodeErrorData: sse_decode_bridge_error,
),
constMeta: kCrateApiDownloadIconConstMeta,
argValues: [iconId],
apiImpl: this,
),
);
}
TaskConstMeta get kCrateApiDownloadIconConstMeta =>
const TaskConstMeta(debugName: "download_icon", argNames: ["iconId"]);
@override @override
Future<void> crateApiEnableAudioDebugWavDump({required bool enabled}) { Future<void> crateApiEnableAudioDebugWavDump({required bool enabled}) {
return handler.executeNormal( return handler.executeNormal(
@@ -451,7 +553,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 9, funcId: 12,
port: port_, port: port_,
); );
}, },
@@ -484,7 +586,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 10, funcId: 13,
port: port_, port: port_,
); );
}, },
@@ -510,7 +612,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
SyncTask( SyncTask(
callFfi: () { callFfi: () {
final serializer = SseSerializer(generalizedFrbRustBinding); final serializer = SseSerializer(generalizedFrbRustBinding);
return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 11)!; return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 14)!;
}, },
codec: SseCodec( codec: SseCodec(
decodeSuccessData: sse_decode_String, decodeSuccessData: sse_decode_String,
@@ -526,6 +628,33 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
TaskConstMeta get kCrateApiExportDiagnosticsConstMeta => TaskConstMeta get kCrateApiExportDiagnosticsConstMeta =>
const TaskConstMeta(debugName: "export_diagnostics", argNames: []); const TaskConstMeta(debugName: "export_diagnostics", argNames: []);
@override
Future<BigInt> crateApiFileCacheSize() {
return handler.executeNormal(
NormalTask(
callFfi: (port_) {
final serializer = SseSerializer(generalizedFrbRustBinding);
pdeCallFfi(
generalizedFrbRustBinding,
serializer,
funcId: 15,
port: port_,
);
},
codec: SseCodec(
decodeSuccessData: sse_decode_u_64,
decodeErrorData: sse_decode_bridge_error,
),
constMeta: kCrateApiFileCacheSizeConstMeta,
argValues: [],
apiImpl: this,
),
);
}
TaskConstMeta get kCrateApiFileCacheSizeConstMeta =>
const TaskConstMeta(debugName: "file_cache_size", argNames: []);
@override @override
Future<BridgeAudioProcessingConfig> crateApiGetAudioProcessingConfig() { Future<BridgeAudioProcessingConfig> crateApiGetAudioProcessingConfig() {
return handler.executeNormal( return handler.executeNormal(
@@ -535,7 +664,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 12, funcId: 16,
port: port_, port: port_,
); );
}, },
@@ -565,7 +694,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 13, funcId: 17,
port: port_, port: port_,
); );
}, },
@@ -592,7 +721,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 14, funcId: 18,
port: port_, port: port_,
); );
}, },
@@ -619,7 +748,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 15, funcId: 19,
port: port_, port: port_,
); );
}, },
@@ -643,7 +772,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
SyncTask( SyncTask(
callFfi: () { callFfi: () {
final serializer = SseSerializer(generalizedFrbRustBinding); final serializer = SseSerializer(generalizedFrbRustBinding);
return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 16)!; return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 20)!;
}, },
codec: SseCodec( codec: SseCodec(
decodeSuccessData: sse_decode_unit, decodeSuccessData: sse_decode_unit,
@@ -666,7 +795,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
callFfi: () { callFfi: () {
final serializer = SseSerializer(generalizedFrbRustBinding); final serializer = SseSerializer(generalizedFrbRustBinding);
sse_encode_bool(shouldResume, serializer); sse_encode_bool(shouldResume, serializer);
return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 17)!; return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 21)!;
}, },
codec: SseCodec( codec: SseCodec(
decodeSuccessData: sse_decode_unit, decodeSuccessData: sse_decode_unit,
@@ -692,7 +821,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
callFfi: () { callFfi: () {
final serializer = SseSerializer(generalizedFrbRustBinding); final serializer = SseSerializer(generalizedFrbRustBinding);
sse_encode_String(routeClass, serializer); sse_encode_String(routeClass, serializer);
return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 18)!; return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 22)!;
}, },
codec: SseCodec( codec: SseCodec(
decodeSuccessData: sse_decode_unit, decodeSuccessData: sse_decode_unit,
@@ -718,7 +847,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
callFfi: () { callFfi: () {
final serializer = SseSerializer(generalizedFrbRustBinding); final serializer = SseSerializer(generalizedFrbRustBinding);
sse_encode_bridge_audio_route(route, serializer); sse_encode_bridge_audio_route(route, serializer);
return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 19)!; return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 23)!;
}, },
codec: SseCodec( codec: SseCodec(
decodeSuccessData: sse_decode_unit, decodeSuccessData: sse_decode_unit,
@@ -736,6 +865,34 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
argNames: ["route"], argNames: ["route"],
); );
@override
Future<void> crateApiInitCache({required String dir}) {
return handler.executeNormal(
NormalTask(
callFfi: (port_) {
final serializer = SseSerializer(generalizedFrbRustBinding);
sse_encode_String(dir, serializer);
pdeCallFfi(
generalizedFrbRustBinding,
serializer,
funcId: 24,
port: port_,
);
},
codec: SseCodec(
decodeSuccessData: sse_decode_unit,
decodeErrorData: sse_decode_bridge_error,
),
constMeta: kCrateApiInitCacheConstMeta,
argValues: [dir],
apiImpl: this,
),
);
}
TaskConstMeta get kCrateApiInitCacheConstMeta =>
const TaskConstMeta(debugName: "init_cache", argNames: ["dir"]);
@override @override
Future<void> crateApiInitStorage({required String dir}) { Future<void> crateApiInitStorage({required String dir}) {
return handler.executeNormal( return handler.executeNormal(
@@ -746,7 +903,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 20, funcId: 25,
port: port_, port: port_,
); );
}, },
@@ -776,7 +933,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 21, funcId: 26,
port: port_, port: port_,
); );
}, },
@@ -805,7 +962,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 22, funcId: 27,
port: port_, port: port_,
); );
}, },
@@ -832,7 +989,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 23, funcId: 28,
port: port_, port: port_,
); );
}, },
@@ -859,7 +1016,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 24, funcId: 29,
port: port_, port: port_,
); );
}, },
@@ -883,7 +1040,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
SyncTask( SyncTask(
callFfi: () { callFfi: () {
final serializer = SseSerializer(generalizedFrbRustBinding); final serializer = SseSerializer(generalizedFrbRustBinding);
return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 25)!; return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 30)!;
}, },
codec: SseCodec( codec: SseCodec(
decodeSuccessData: sse_decode_String, decodeSuccessData: sse_decode_String,
@@ -913,7 +1070,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 26, funcId: 31,
port: port_, port: port_,
); );
}, },
@@ -943,7 +1100,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 27, funcId: 32,
port: port_, port: port_,
); );
}, },
@@ -970,7 +1127,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 28, funcId: 33,
port: port_, port: port_,
); );
}, },
@@ -995,7 +1152,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
callFfi: () { callFfi: () {
final serializer = SseSerializer(generalizedFrbRustBinding); final serializer = SseSerializer(generalizedFrbRustBinding);
sse_encode_String(state, serializer); sse_encode_String(state, serializer);
return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 29)!; return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 34)!;
}, },
codec: SseCodec( codec: SseCodec(
decodeSuccessData: sse_decode_unit, decodeSuccessData: sse_decode_unit,
@@ -1028,7 +1185,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 30, funcId: 35,
port: port_, port: port_,
); );
}, },
@@ -1055,7 +1212,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
callFfi: () { callFfi: () {
final serializer = SseSerializer(generalizedFrbRustBinding); final serializer = SseSerializer(generalizedFrbRustBinding);
sse_encode_bridge_audio_route(route, serializer); sse_encode_bridge_audio_route(route, serializer);
return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 31)!; return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 36)!;
}, },
codec: SseCodec( codec: SseCodec(
decodeSuccessData: sse_decode_unit, decodeSuccessData: sse_decode_unit,
@@ -1089,7 +1246,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 32, funcId: 37,
port: port_, port: port_,
); );
}, },
@@ -1124,7 +1281,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 33, funcId: 38,
port: port_, port: port_,
); );
}, },
@@ -1154,7 +1311,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 34, funcId: 39,
port: port_, port: port_,
); );
}, },
@@ -1182,7 +1339,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 35, funcId: 40,
port: port_, port: port_,
); );
}, },
@@ -1210,7 +1367,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 36, funcId: 41,
port: port_, port: port_,
); );
}, },
@@ -1240,7 +1397,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 37, funcId: 42,
port: port_, port: port_,
); );
}, },
@@ -1268,7 +1425,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
callFfi: () { callFfi: () {
final serializer = SseSerializer(generalizedFrbRustBinding); final serializer = SseSerializer(generalizedFrbRustBinding);
sse_encode_bridge_network_state(state, serializer); sse_encode_bridge_network_state(state, serializer);
return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 38)!; return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 43)!;
}, },
codec: SseCodec( codec: SseCodec(
decodeSuccessData: sse_decode_unit, decodeSuccessData: sse_decode_unit,
@@ -1294,7 +1451,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 39, funcId: 44,
port: port_, port: port_,
); );
}, },
@@ -1322,7 +1479,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 40, funcId: 45,
port: port_, port: port_,
); );
}, },
@@ -1350,7 +1507,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 41, funcId: 46,
port: port_, port: port_,
); );
}, },
@@ -1378,7 +1535,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 42, funcId: 47,
port: port_, port: port_,
); );
}, },
@@ -1410,7 +1567,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 43, funcId: 48,
port: port_, port: port_,
); );
}, },
@@ -1440,7 +1597,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 44, funcId: 49,
port: port_, port: port_,
); );
}, },
@@ -1468,7 +1625,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 45, funcId: 50,
port: port_, port: port_,
); );
}, },
@@ -1496,7 +1653,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 46, funcId: 51,
port: port_, port: port_,
); );
}, },
@@ -1523,7 +1680,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 47, funcId: 52,
port: port_, port: port_,
); );
}, },
@@ -1551,7 +1708,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 48, funcId: 53,
port: port_, port: port_,
); );
}, },
@@ -1583,7 +1740,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 49, funcId: 54,
port: port_, port: port_,
); );
}, },
@@ -1612,7 +1769,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
pdeCallFfi( pdeCallFfi(
generalizedFrbRustBinding, generalizedFrbRustBinding,
serializer, serializer,
funcId: 50, funcId: 55,
port: port_, port: port_,
); );
}, },
@@ -1683,6 +1840,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
return dco_decode_bridge_message_target(raw); return dco_decode_bridge_message_target(raw);
} }
@protected
BridgePokeStrength dco_decode_box_autoadd_bridge_poke_strength(dynamic raw) {
// Codec=Dco (DartCObject based), see doc to use other codecs
return dco_decode_bridge_poke_strength(raw);
}
@protected @protected
BridgeVoiceJoinErrorCode dco_decode_box_autoadd_bridge_voice_join_error_code( BridgeVoiceJoinErrorCode dco_decode_box_autoadd_bridge_voice_join_error_code(
dynamic raw, dynamic raw,
@@ -2007,6 +2170,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
senderName: dco_decode_String(raw[2]), senderName: dco_decode_String(raw[2]),
message: dco_decode_String(raw[3]), message: dco_decode_String(raw[3]),
target: dco_decode_box_autoadd_bridge_message_target(raw[4]), target: dco_decode_box_autoadd_bridge_message_target(raw[4]),
pokeStrength: dco_decode_opt_box_autoadd_bridge_poke_strength(raw[5]),
); );
case 11: case 11:
return BridgeEvent_ServerActivity(message: dco_decode_String(raw[1])); return BridgeEvent_ServerActivity(message: dco_decode_String(raw[1]));
@@ -2098,6 +2262,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
return BridgeNetworkState.values[raw as int]; return BridgeNetworkState.values[raw as int];
} }
@protected
BridgePokeStrength dco_decode_bridge_poke_strength(dynamic raw) {
// Codec=Dco (DartCObject based), see doc to use other codecs
return BridgePokeStrength.values[raw as int];
}
@protected @protected
BridgePttBinding dco_decode_bridge_ptt_binding(dynamic raw) { BridgePttBinding dco_decode_bridge_ptt_binding(dynamic raw) {
// Codec=Dco (DartCObject based), see doc to use other codecs // Codec=Dco (DartCObject based), see doc to use other codecs
@@ -2234,6 +2404,16 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
return raw == null ? null : dco_decode_String(raw); return raw == null ? null : dco_decode_String(raw);
} }
@protected
BridgePokeStrength? dco_decode_opt_box_autoadd_bridge_poke_strength(
dynamic raw,
) {
// Codec=Dco (DartCObject based), see doc to use other codecs
return raw == null
? null
: dco_decode_box_autoadd_bridge_poke_strength(raw);
}
@protected @protected
BridgeVoiceJoinErrorCode? BridgeVoiceJoinErrorCode?
dco_decode_opt_box_autoadd_bridge_voice_join_error_code(dynamic raw) { dco_decode_opt_box_autoadd_bridge_voice_join_error_code(dynamic raw) {
@@ -2267,6 +2447,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
return raw == null ? null : dco_decode_box_autoadd_u_64(raw); return raw == null ? null : dco_decode_box_autoadd_u_64(raw);
} }
@protected
Uint8List? dco_decode_opt_list_prim_u_8_strict(dynamic raw) {
// Codec=Dco (DartCObject based), see doc to use other codecs
return raw == null ? null : dco_decode_list_prim_u_8_strict(raw);
}
@protected @protected
PermissionStateKind dco_decode_permission_state_kind(dynamic raw) { PermissionStateKind dco_decode_permission_state_kind(dynamic raw) {
// Codec=Dco (DartCObject based), see doc to use other codecs // Codec=Dco (DartCObject based), see doc to use other codecs
@@ -2358,6 +2544,14 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
return (sse_decode_bridge_message_target(deserializer)); return (sse_decode_bridge_message_target(deserializer));
} }
@protected
BridgePokeStrength sse_decode_box_autoadd_bridge_poke_strength(
SseDeserializer deserializer,
) {
// Codec=Sse (Serialization based), see doc to use other codecs
return (sse_decode_bridge_poke_strength(deserializer));
}
@protected @protected
BridgeVoiceJoinErrorCode sse_decode_box_autoadd_bridge_voice_join_error_code( BridgeVoiceJoinErrorCode sse_decode_box_autoadd_bridge_voice_join_error_code(
SseDeserializer deserializer, SseDeserializer deserializer,
@@ -2809,11 +3003,15 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
var var_target = sse_decode_box_autoadd_bridge_message_target( var var_target = sse_decode_box_autoadd_bridge_message_target(
deserializer, deserializer,
); );
var var_pokeStrength = sse_decode_opt_box_autoadd_bridge_poke_strength(
deserializer,
);
return BridgeEvent_ChatMessage( return BridgeEvent_ChatMessage(
senderId: var_senderId, senderId: var_senderId,
senderName: var_senderName, senderName: var_senderName,
message: var_message, message: var_message,
target: var_target, target: var_target,
pokeStrength: var_pokeStrength,
); );
case 11: case 11:
var var_message = sse_decode_String(deserializer); var var_message = sse_decode_String(deserializer);
@@ -2941,6 +3139,15 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
return BridgeNetworkState.values[inner]; return BridgeNetworkState.values[inner];
} }
@protected
BridgePokeStrength sse_decode_bridge_poke_strength(
SseDeserializer deserializer,
) {
// Codec=Sse (Serialization based), see doc to use other codecs
var inner = sse_decode_i_32(deserializer);
return BridgePokeStrength.values[inner];
}
@protected @protected
BridgePttBinding sse_decode_bridge_ptt_binding(SseDeserializer deserializer) { BridgePttBinding sse_decode_bridge_ptt_binding(SseDeserializer deserializer) {
// Codec=Sse (Serialization based), see doc to use other codecs // Codec=Sse (Serialization based), see doc to use other codecs
@@ -3132,6 +3339,19 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
} }
} }
@protected
BridgePokeStrength? sse_decode_opt_box_autoadd_bridge_poke_strength(
SseDeserializer deserializer,
) {
// Codec=Sse (Serialization based), see doc to use other codecs
if (sse_decode_bool(deserializer)) {
return (sse_decode_box_autoadd_bridge_poke_strength(deserializer));
} else {
return null;
}
}
@protected @protected
BridgeVoiceJoinErrorCode? BridgeVoiceJoinErrorCode?
sse_decode_opt_box_autoadd_bridge_voice_join_error_code( sse_decode_opt_box_autoadd_bridge_voice_join_error_code(
@@ -3192,6 +3412,17 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
} }
} }
@protected
Uint8List? sse_decode_opt_list_prim_u_8_strict(SseDeserializer deserializer) {
// Codec=Sse (Serialization based), see doc to use other codecs
if (sse_decode_bool(deserializer)) {
return (sse_decode_list_prim_u_8_strict(deserializer));
} else {
return null;
}
}
@protected @protected
PermissionStateKind sse_decode_permission_state_kind( PermissionStateKind sse_decode_permission_state_kind(
SseDeserializer deserializer, SseDeserializer deserializer,
@@ -3306,6 +3537,15 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
sse_encode_bridge_message_target(self, serializer); sse_encode_bridge_message_target(self, serializer);
} }
@protected
void sse_encode_box_autoadd_bridge_poke_strength(
BridgePokeStrength self,
SseSerializer serializer,
) {
// Codec=Sse (Serialization based), see doc to use other codecs
sse_encode_bridge_poke_strength(self, serializer);
}
@protected @protected
void sse_encode_box_autoadd_bridge_voice_join_error_code( void sse_encode_box_autoadd_bridge_voice_join_error_code(
BridgeVoiceJoinErrorCode self, BridgeVoiceJoinErrorCode self,
@@ -3644,12 +3884,17 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
senderName: final senderName, senderName: final senderName,
message: final message, message: final message,
target: final target, target: final target,
pokeStrength: final pokeStrength,
): ):
sse_encode_i_32(10, serializer); sse_encode_i_32(10, serializer);
sse_encode_u_64(senderId, serializer); sse_encode_u_64(senderId, serializer);
sse_encode_String(senderName, serializer); sse_encode_String(senderName, serializer);
sse_encode_String(message, serializer); sse_encode_String(message, serializer);
sse_encode_box_autoadd_bridge_message_target(target, serializer); sse_encode_box_autoadd_bridge_message_target(target, serializer);
sse_encode_opt_box_autoadd_bridge_poke_strength(
pokeStrength,
serializer,
);
case BridgeEvent_ServerActivity(message: final message): case BridgeEvent_ServerActivity(message: final message):
sse_encode_i_32(11, serializer); sse_encode_i_32(11, serializer);
sse_encode_String(message, serializer); sse_encode_String(message, serializer);
@@ -3771,6 +4016,15 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
sse_encode_i_32(self.index, serializer); sse_encode_i_32(self.index, serializer);
} }
@protected
void sse_encode_bridge_poke_strength(
BridgePokeStrength self,
SseSerializer serializer,
) {
// Codec=Sse (Serialization based), see doc to use other codecs
sse_encode_i_32(self.index, serializer);
}
@protected @protected
void sse_encode_bridge_ptt_binding( void sse_encode_bridge_ptt_binding(
BridgePttBinding self, BridgePttBinding self,
@@ -3947,6 +4201,19 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
} }
} }
@protected
void sse_encode_opt_box_autoadd_bridge_poke_strength(
BridgePokeStrength? self,
SseSerializer serializer,
) {
// Codec=Sse (Serialization based), see doc to use other codecs
sse_encode_bool(self != null, serializer);
if (self != null) {
sse_encode_box_autoadd_bridge_poke_strength(self, serializer);
}
}
@protected @protected
void sse_encode_opt_box_autoadd_bridge_voice_join_error_code( void sse_encode_opt_box_autoadd_bridge_voice_join_error_code(
BridgeVoiceJoinErrorCode? self, BridgeVoiceJoinErrorCode? self,
@@ -4003,6 +4270,19 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
} }
} }
@protected
void sse_encode_opt_list_prim_u_8_strict(
Uint8List? self,
SseSerializer serializer,
) {
// Codec=Sse (Serialization based), see doc to use other codecs
sse_encode_bool(self != null, serializer);
if (self != null) {
sse_encode_list_prim_u_8_strict(self, serializer);
}
}
@protected @protected
void sse_encode_permission_state_kind( void sse_encode_permission_state_kind(
PermissionStateKind self, PermissionStateKind self,
@@ -46,6 +46,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
BridgeMessageTarget dco_decode_box_autoadd_bridge_message_target(dynamic raw); BridgeMessageTarget dco_decode_box_autoadd_bridge_message_target(dynamic raw);
@protected
BridgePokeStrength dco_decode_box_autoadd_bridge_poke_strength(dynamic raw);
@protected @protected
BridgeVoiceJoinErrorCode dco_decode_box_autoadd_bridge_voice_join_error_code( BridgeVoiceJoinErrorCode dco_decode_box_autoadd_bridge_voice_join_error_code(
dynamic raw, dynamic raw,
@@ -120,6 +123,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
BridgeNetworkState dco_decode_bridge_network_state(dynamic raw); BridgeNetworkState dco_decode_bridge_network_state(dynamic raw);
@protected
BridgePokeStrength dco_decode_bridge_poke_strength(dynamic raw);
@protected @protected
BridgePttBinding dco_decode_bridge_ptt_binding(dynamic raw); BridgePttBinding dco_decode_bridge_ptt_binding(dynamic raw);
@@ -174,6 +180,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
String? dco_decode_opt_String(dynamic raw); String? dco_decode_opt_String(dynamic raw);
@protected
BridgePokeStrength? dco_decode_opt_box_autoadd_bridge_poke_strength(
dynamic raw,
);
@protected @protected
BridgeVoiceJoinErrorCode? BridgeVoiceJoinErrorCode?
dco_decode_opt_box_autoadd_bridge_voice_join_error_code(dynamic raw); dco_decode_opt_box_autoadd_bridge_voice_join_error_code(dynamic raw);
@@ -190,6 +201,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
BigInt? dco_decode_opt_box_autoadd_u_64(dynamic raw); BigInt? dco_decode_opt_box_autoadd_u_64(dynamic raw);
@protected
Uint8List? dco_decode_opt_list_prim_u_8_strict(dynamic raw);
@protected @protected
PermissionStateKind dco_decode_permission_state_kind(dynamic raw); PermissionStateKind dco_decode_permission_state_kind(dynamic raw);
@@ -240,6 +254,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseDeserializer deserializer, SseDeserializer deserializer,
); );
@protected
BridgePokeStrength sse_decode_box_autoadd_bridge_poke_strength(
SseDeserializer deserializer,
);
@protected @protected
BridgeVoiceJoinErrorCode sse_decode_box_autoadd_bridge_voice_join_error_code( BridgeVoiceJoinErrorCode sse_decode_box_autoadd_bridge_voice_join_error_code(
SseDeserializer deserializer, SseDeserializer deserializer,
@@ -328,6 +347,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseDeserializer deserializer, SseDeserializer deserializer,
); );
@protected
BridgePokeStrength sse_decode_bridge_poke_strength(
SseDeserializer deserializer,
);
@protected @protected
BridgePttBinding sse_decode_bridge_ptt_binding(SseDeserializer deserializer); BridgePttBinding sse_decode_bridge_ptt_binding(SseDeserializer deserializer);
@@ -400,6 +424,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
String? sse_decode_opt_String(SseDeserializer deserializer); String? sse_decode_opt_String(SseDeserializer deserializer);
@protected
BridgePokeStrength? sse_decode_opt_box_autoadd_bridge_poke_strength(
SseDeserializer deserializer,
);
@protected @protected
BridgeVoiceJoinErrorCode? BridgeVoiceJoinErrorCode?
sse_decode_opt_box_autoadd_bridge_voice_join_error_code( sse_decode_opt_box_autoadd_bridge_voice_join_error_code(
@@ -418,6 +447,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
BigInt? sse_decode_opt_box_autoadd_u_64(SseDeserializer deserializer); BigInt? sse_decode_opt_box_autoadd_u_64(SseDeserializer deserializer);
@protected
Uint8List? sse_decode_opt_list_prim_u_8_strict(SseDeserializer deserializer);
@protected @protected
PermissionStateKind sse_decode_permission_state_kind( PermissionStateKind sse_decode_permission_state_kind(
SseDeserializer deserializer, SseDeserializer deserializer,
@@ -477,6 +509,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer, SseSerializer serializer,
); );
@protected
void sse_encode_box_autoadd_bridge_poke_strength(
BridgePokeStrength self,
SseSerializer serializer,
);
@protected @protected
void sse_encode_box_autoadd_bridge_voice_join_error_code( void sse_encode_box_autoadd_bridge_voice_join_error_code(
BridgeVoiceJoinErrorCode self, BridgeVoiceJoinErrorCode self,
@@ -588,6 +626,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer, SseSerializer serializer,
); );
@protected
void sse_encode_bridge_poke_strength(
BridgePokeStrength self,
SseSerializer serializer,
);
@protected @protected
void sse_encode_bridge_ptt_binding( void sse_encode_bridge_ptt_binding(
BridgePttBinding self, BridgePttBinding self,
@@ -681,6 +725,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
void sse_encode_opt_String(String? self, SseSerializer serializer); void sse_encode_opt_String(String? self, SseSerializer serializer);
@protected
void sse_encode_opt_box_autoadd_bridge_poke_strength(
BridgePokeStrength? self,
SseSerializer serializer,
);
@protected @protected
void sse_encode_opt_box_autoadd_bridge_voice_join_error_code( void sse_encode_opt_box_autoadd_bridge_voice_join_error_code(
BridgeVoiceJoinErrorCode? self, BridgeVoiceJoinErrorCode? self,
@@ -702,6 +752,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
void sse_encode_opt_box_autoadd_u_64(BigInt? self, SseSerializer serializer); void sse_encode_opt_box_autoadd_u_64(BigInt? self, SseSerializer serializer);
@protected
void sse_encode_opt_list_prim_u_8_strict(
Uint8List? self,
SseSerializer serializer,
);
@protected @protected
void sse_encode_permission_state_kind( void sse_encode_permission_state_kind(
PermissionStateKind self, PermissionStateKind self,
@@ -48,6 +48,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
BridgeMessageTarget dco_decode_box_autoadd_bridge_message_target(dynamic raw); BridgeMessageTarget dco_decode_box_autoadd_bridge_message_target(dynamic raw);
@protected
BridgePokeStrength dco_decode_box_autoadd_bridge_poke_strength(dynamic raw);
@protected @protected
BridgeVoiceJoinErrorCode dco_decode_box_autoadd_bridge_voice_join_error_code( BridgeVoiceJoinErrorCode dco_decode_box_autoadd_bridge_voice_join_error_code(
dynamic raw, dynamic raw,
@@ -122,6 +125,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
BridgeNetworkState dco_decode_bridge_network_state(dynamic raw); BridgeNetworkState dco_decode_bridge_network_state(dynamic raw);
@protected
BridgePokeStrength dco_decode_bridge_poke_strength(dynamic raw);
@protected @protected
BridgePttBinding dco_decode_bridge_ptt_binding(dynamic raw); BridgePttBinding dco_decode_bridge_ptt_binding(dynamic raw);
@@ -176,6 +182,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
String? dco_decode_opt_String(dynamic raw); String? dco_decode_opt_String(dynamic raw);
@protected
BridgePokeStrength? dco_decode_opt_box_autoadd_bridge_poke_strength(
dynamic raw,
);
@protected @protected
BridgeVoiceJoinErrorCode? BridgeVoiceJoinErrorCode?
dco_decode_opt_box_autoadd_bridge_voice_join_error_code(dynamic raw); dco_decode_opt_box_autoadd_bridge_voice_join_error_code(dynamic raw);
@@ -192,6 +203,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
BigInt? dco_decode_opt_box_autoadd_u_64(dynamic raw); BigInt? dco_decode_opt_box_autoadd_u_64(dynamic raw);
@protected
Uint8List? dco_decode_opt_list_prim_u_8_strict(dynamic raw);
@protected @protected
PermissionStateKind dco_decode_permission_state_kind(dynamic raw); PermissionStateKind dco_decode_permission_state_kind(dynamic raw);
@@ -242,6 +256,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseDeserializer deserializer, SseDeserializer deserializer,
); );
@protected
BridgePokeStrength sse_decode_box_autoadd_bridge_poke_strength(
SseDeserializer deserializer,
);
@protected @protected
BridgeVoiceJoinErrorCode sse_decode_box_autoadd_bridge_voice_join_error_code( BridgeVoiceJoinErrorCode sse_decode_box_autoadd_bridge_voice_join_error_code(
SseDeserializer deserializer, SseDeserializer deserializer,
@@ -330,6 +349,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseDeserializer deserializer, SseDeserializer deserializer,
); );
@protected
BridgePokeStrength sse_decode_bridge_poke_strength(
SseDeserializer deserializer,
);
@protected @protected
BridgePttBinding sse_decode_bridge_ptt_binding(SseDeserializer deserializer); BridgePttBinding sse_decode_bridge_ptt_binding(SseDeserializer deserializer);
@@ -402,6 +426,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
String? sse_decode_opt_String(SseDeserializer deserializer); String? sse_decode_opt_String(SseDeserializer deserializer);
@protected
BridgePokeStrength? sse_decode_opt_box_autoadd_bridge_poke_strength(
SseDeserializer deserializer,
);
@protected @protected
BridgeVoiceJoinErrorCode? BridgeVoiceJoinErrorCode?
sse_decode_opt_box_autoadd_bridge_voice_join_error_code( sse_decode_opt_box_autoadd_bridge_voice_join_error_code(
@@ -420,6 +449,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
BigInt? sse_decode_opt_box_autoadd_u_64(SseDeserializer deserializer); BigInt? sse_decode_opt_box_autoadd_u_64(SseDeserializer deserializer);
@protected
Uint8List? sse_decode_opt_list_prim_u_8_strict(SseDeserializer deserializer);
@protected @protected
PermissionStateKind sse_decode_permission_state_kind( PermissionStateKind sse_decode_permission_state_kind(
SseDeserializer deserializer, SseDeserializer deserializer,
@@ -479,6 +511,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer, SseSerializer serializer,
); );
@protected
void sse_encode_box_autoadd_bridge_poke_strength(
BridgePokeStrength self,
SseSerializer serializer,
);
@protected @protected
void sse_encode_box_autoadd_bridge_voice_join_error_code( void sse_encode_box_autoadd_bridge_voice_join_error_code(
BridgeVoiceJoinErrorCode self, BridgeVoiceJoinErrorCode self,
@@ -590,6 +628,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer, SseSerializer serializer,
); );
@protected
void sse_encode_bridge_poke_strength(
BridgePokeStrength self,
SseSerializer serializer,
);
@protected @protected
void sse_encode_bridge_ptt_binding( void sse_encode_bridge_ptt_binding(
BridgePttBinding self, BridgePttBinding self,
@@ -683,6 +727,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
void sse_encode_opt_String(String? self, SseSerializer serializer); void sse_encode_opt_String(String? self, SseSerializer serializer);
@protected
void sse_encode_opt_box_autoadd_bridge_poke_strength(
BridgePokeStrength? self,
SseSerializer serializer,
);
@protected @protected
void sse_encode_opt_box_autoadd_bridge_voice_join_error_code( void sse_encode_opt_box_autoadd_bridge_voice_join_error_code(
BridgeVoiceJoinErrorCode? self, BridgeVoiceJoinErrorCode? self,
@@ -704,6 +754,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected @protected
void sse_encode_opt_box_autoadd_u_64(BigInt? self, SseSerializer serializer); void sse_encode_opt_box_autoadd_u_64(BigInt? self, SseSerializer serializer);
@protected
void sse_encode_opt_list_prim_u_8_strict(
Uint8List? self,
SseSerializer serializer,
);
@protected @protected
void sse_encode_permission_state_kind( void sse_encode_permission_state_kind(
PermissionStateKind self, PermissionStateKind self,
@@ -15,6 +15,12 @@ const double _chatSidebarTileExtent = 92;
const double _chatSidebarCompactTileExtent = 76; const double _chatSidebarCompactTileExtent = 76;
const double _chatSidebarCompactHeight = 84; const double _chatSidebarCompactHeight = 84;
typedef ChatMessageSender =
Future<void> Function({
required String message,
required rust.BridgeMessageTarget target,
});
/// One chat/activity message shown in the chat hub. /// One chat/activity message shown in the chat hub.
class ChatEntry { class ChatEntry {
/// Construct a chat entry. /// Construct a chat entry.
@@ -497,7 +503,7 @@ String chatInputPlaceholder(
case rust.BridgeMessageTarget_Client(): case rust.BridgeMessageTarget_Client():
return 'Message $clientName...'; return 'Message $clientName...';
case rust.BridgeMessageTarget_Poke(): case rust.BridgeMessageTarget_Poke():
return 'Poke message...'; return 'Poke message optional...';
} }
} }
@@ -513,6 +519,16 @@ bool canSendToChatTarget(
} }
} }
bool canSendChatMessage(
rust.BridgeMessageTarget target,
BigInt? currentChannelId,
String text,
) {
if (!canSendToChatTarget(target, currentChannelId)) return false;
if (target is rust.BridgeMessageTarget_Poke) return true;
return text.trim().isNotEmpty;
}
String? chatSendBlockedReason( String? chatSendBlockedReason(
rust.BridgeMessageTarget target, rust.BridgeMessageTarget target,
BigInt? currentChannelId, BigInt? currentChannelId,
@@ -1066,6 +1082,7 @@ class ChatDetailView extends StatefulWidget {
this.messageMaxWidth, this.messageMaxWidth,
this.restoredDraft, this.restoredDraft,
this.onDraftChanged, this.onDraftChanged,
this.sendChatMessage,
}); });
/// Chat target displayed by this detail view. /// Chat target displayed by this detail view.
@@ -1101,6 +1118,9 @@ class ChatDetailView extends StatefulWidget {
/// Called with the current draft text whenever the target changes or the widget is about to be replaced. /// Called with the current draft text whenever the target changes or the widget is about to be replaced.
final ValueChanged<String>? onDraftChanged; final ValueChanged<String>? onDraftChanged;
/// Sends a chat message. Defaults to the Rust bridge send path.
final ChatMessageSender? sendChatMessage;
@override @override
State<ChatDetailView> createState() => _ChatDetailViewState(); State<ChatDetailView> createState() => _ChatDetailViewState();
} }
@@ -1168,9 +1188,12 @@ class _ChatDetailViewState extends State<ChatDetailView> {
void _send() { void _send() {
final text = _textCtl.text.trim(); final text = _textCtl.text.trim();
if (text.isEmpty || !_canSend) return; if (!canSendChatMessage(widget.target, widget.currentChannelId, text)) {
return;
}
_textCtl.clear(); _textCtl.clear();
unawaited(rust.sendChatMessage(message: text, target: widget.target)); final sendChatMessage = widget.sendChatMessage ?? rust.sendChatMessage;
unawaited(sendChatMessage(message: text, target: widget.target));
final ownId = widget.snapshot.ownClientId; final ownId = widget.snapshot.ownClientId;
setState(() { setState(() {
widget.messages.add( widget.messages.add(
@@ -1223,6 +1246,9 @@ class _ChatDetailViewState extends State<ChatDetailView> {
channelName: widget.channelName, channelName: widget.channelName,
clientName: widget.clientName, clientName: widget.clientName,
); );
final sendTooltip = widget.target is rust.BridgeMessageTarget_Poke
? 'Poke'
: 'Send';
return Column( return Column(
children: [ children: [
@@ -1332,7 +1358,7 @@ class _ChatDetailViewState extends State<ChatDetailView> {
IconButton.filled( IconButton.filled(
icon: const Icon(Icons.send), icon: const Icon(Icons.send),
onPressed: _send, onPressed: _send,
tooltip: 'Send', tooltip: sendTooltip,
), ),
], ],
), ),
@@ -0,0 +1,89 @@
import 'package:flutter/material.dart';
import '../l10n/generated/app_localizations.dart';
import '../services/poke_preferences_service.dart';
import 'voice_settings_controls.dart';
class PokeNotificationSettingsDialog extends StatelessWidget {
const PokeNotificationSettingsDialog({super.key, required this.preferences});
final PokePreferencesService preferences;
@override
Widget build(BuildContext context) {
final l10n = AppL10n.of(context);
final theme = Theme.of(context);
return AlertDialog(
title: Text(l10n.pokeSettingsTitle),
contentPadding: const EdgeInsets.fromLTRB(24, 16, 24, 0),
content: SizedBox(
width: 400,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ValueListenableBuilder<bool>(
valueListenable: preferences.pokesEnabled,
builder: (context, enabled, _) => SwitchListTile(
dense: true,
contentPadding: EdgeInsets.zero,
title: Text(l10n.pokeSettingsEnableLabel),
subtitle: Text(l10n.pokeSettingsEnableDescription),
value: enabled,
onChanged: (value) => preferences.setPokesEnabled(value),
),
),
const Divider(height: 24),
VoiceSectionHeader(l10n.pokeSettingsMutedSendersHeader),
ValueListenableBuilder<Set<BigInt>>(
valueListenable: preferences.mutedSenders,
builder: (context, mutedSenders, _) {
final senders = mutedSenders.toList()..sort();
if (senders.isEmpty) {
return Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Text(
l10n.pokeSettingsMutedSendersEmpty,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
);
}
return Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final senderId in senders)
ListTile(
dense: true,
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.notifications_off_outlined),
title: Text(
l10n.pokeSettingsMutedSenderLabel(
senderId.toString(),
),
),
trailing: TextButton(
onPressed: () => preferences.unmuteSender(senderId),
child: Text(l10n.pokeSettingsUnmuteSenderAction),
),
),
],
);
},
),
const SizedBox(height: 8),
],
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(l10n.closeAction),
),
],
);
}
}
@@ -318,6 +318,15 @@ class _VoicePttButtonState extends State<VoicePttButton> {
playVoicePttHaptic(held); playVoicePttHaptic(held);
} }
@override
void dispose() {
if (_pressed) {
_pressed = false;
widget.onHeldChanged(false);
}
super.dispose();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
@@ -629,12 +638,19 @@ class _VoiceSheetBodyState extends State<_VoiceSheetBody> {
selected: _mode == rust.BridgeTransmitMode.continuous, selected: _mode == rust.BridgeTransmitMode.continuous,
onTap: () => _setMode(rust.BridgeTransmitMode.continuous), onTap: () => _setMode(rust.BridgeTransmitMode.continuous),
), ),
_ModeRow( // Voice-activity transmit is only honoured by the engine on
label: l10n.voiceModeVoiceActivity, // hosts that ship a Chanora-owned VAD pipeline (DEC-030:
icon: Icons.graphic_eq, // Windows + Linux desktop and Android). iOS / macOS rely
selected: _mode == rust.BridgeTransmitMode.voiceActivity, // on Apple VoiceProcessingIO and have no VAD bridge, so
onTap: () => _setMode(rust.BridgeTransmitMode.voiceActivity), // hiding the row prevents the UI from advertising a
), // transmit mode the engine cannot honour.
if (voiceActivityTransmitAvailable)
_ModeRow(
label: l10n.voiceModeVoiceActivity,
icon: Icons.graphic_eq,
selected: _mode == rust.BridgeTransmitMode.voiceActivity,
onTap: () => _setMode(rust.BridgeTransmitMode.voiceActivity),
),
// 3) Release-tail slider (PTT only). // 3) Release-tail slider (PTT only).
if (isPtt) ...[ if (isPtt) ...[
@@ -128,7 +128,12 @@ class _VoiceSettingsDialogState extends State<VoiceSettingsDialog> {
VoiceSectionHeader(l10n.voiceModeLabel), VoiceSectionHeader(l10n.voiceModeLabel),
SegmentedButton<rust.BridgeTransmitMode>( SegmentedButton<rust.BridgeTransmitMode>(
style: voiceSegmentedButtonStyle(theme), style: voiceSegmentedButtonStyle(theme),
segments: transmitModeSegments, // DEC-030: hide the voice-activity segment on hosts
// that ship no Chanora-owned VAD pipeline (iOS,
// macOS, web).
segments: transmitModeSegmentsFor(
voiceActivityAvailable: voiceActivityTransmitAvailable,
),
selected: {_mode}, selected: {_mode},
onSelectionChanged: (s) => setState(() => _mode = s.first), onSelectionChanged: (s) => setState(() => _mode = s.first),
), ),
@@ -1,3 +1,6 @@
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../src/rust/api.dart' as rust; import '../src/rust/api.dart' as rust;
@@ -10,7 +13,11 @@ ButtonStyle voiceSegmentedButtonStyle(ThemeData theme) {
); );
} }
/// Transmit mode selector segments. /// Transmit mode selector segments — full set, all three modes.
///
/// This list is kept stable for legacy call sites and tests; UI
/// surfaces that must respect DEC-030 platform gating should prefer
/// [transmitModeSegmentsFor] with [voiceActivityTransmitAvailable].
const transmitModeSegments = [ const transmitModeSegments = [
ButtonSegment( ButtonSegment(
value: rust.BridgeTransmitMode.ptt, value: rust.BridgeTransmitMode.ptt,
@@ -29,6 +36,43 @@ const transmitModeSegments = [
), ),
]; ];
/// Transmit mode selector segments, optionally dropping the
/// voice-activity entry on hosts that do not ship a VAD pipeline.
///
/// Voice activity transmit is gated by [voiceActivityTransmitAvailable]
/// because the underlying VAD pipeline ships only on Windows, Linux, and
/// Android per DEC-030. Builds for unsupported platforms (iOS, macOS,
/// web) drop the VAD segment entirely so the UI never advertises a
/// transmit mode the engine cannot honour.
List<ButtonSegment<rust.BridgeTransmitMode>> transmitModeSegmentsFor({
required bool voiceActivityAvailable,
}) {
if (voiceActivityAvailable) return transmitModeSegments;
return const [
ButtonSegment(
value: rust.BridgeTransmitMode.ptt,
label: Text('PTT'),
icon: Icon(Icons.radio_button_checked, size: 14),
),
ButtonSegment(
value: rust.BridgeTransmitMode.continuous,
label: Text('Always'),
icon: Icon(Icons.podcasts, size: 14),
),
];
}
/// True when this host advertises VAD transmit per DEC-030.
///
/// The desktop Silero ONNX + WebRTC fallback ships on Windows and
/// Linux; the Android Oboe + WebRTC path covers Android; iOS uses the
/// Apple CoreML Silero VAD pipeline via `vad::apple_coreml`. macOS is
/// still gated until its VAD pipeline is confirmed.
bool get voiceActivityTransmitAvailable {
if (kIsWeb) return false;
return Platform.isWindows || Platform.isLinux || Platform.isAndroid || Platform.isIOS;
}
/// Android hardware/WebRTC selector segments. /// Android hardware/WebRTC selector segments.
const androidProcessingSegments = [ const androidProcessingSegments = [
ButtonSegment( ButtonSegment(
@@ -42,6 +42,8 @@
<string>Chanora uses Input Monitoring so push-to-talk keys work even when other apps are focused. Chanora never records what you type — only the key you bound for talking.</string> <string>Chanora uses Input Monitoring so push-to-talk keys work even when other apps are focused. Chanora never records what you type — only the key you bound for talking.</string>
<key>NSLocalNetworkUsageDescription</key> <key>NSLocalNetworkUsageDescription</key>
<string>Chanora needs local network access to connect to TeamSpeak-compatible voice servers.</string> <string>Chanora needs local network access to connect to TeamSpeak-compatible voice servers.</string>
<key>NSUserNotificationsUsageDescription</key>
<string>Chanora sends you a notification when another user pokes you.</string>
<key>NSBonjourServices</key> <key>NSBonjourServices</key>
<array> <array>
<string>_ts3._tcp</string> <string>_ts3._tcp</string>
+72 -32
View File
@@ -5,18 +5,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: _fe_analyzer_shared name: _fe_analyzer_shared
sha256: "8d7ff3948166b8ec5da0fbb5962000926b8e02f2ed9b3e51d1738905fbd4c98d" sha256: "3b19a47f6ea7c2632760777c78174f47f6aec1e05f0cd611380d4593b8af1dbc"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "93.0.0" version: "96.0.0"
analyzer: analyzer:
dependency: transitive dependency: transitive
description: description:
name: analyzer name: analyzer
sha256: de7148ed2fcec579b19f122c1800933dfa028f6d9fd38a152b04b1516cec120b sha256: "0c516bc4ad36a1a75759e54d5047cb9d15cded4459df01aa35a0b5ec7db2c2a0"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "10.0.1" version: "10.2.0"
args: args:
dependency: transitive dependency: transitive
description: description:
@@ -133,10 +133,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: code_assets name: code_assets
sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.0.0" version: "1.2.1"
collection: collection:
dependency: transitive dependency: transitive
description: description:
@@ -197,10 +197,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: dbus name: dbus
sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270 sha256: "792974a4007974fbc5c1b5433eb2330a9db3e368c3f906253af4c007d0f49a91"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.12" version: "0.7.13"
fake_async: fake_async:
dependency: transitive dependency: transitive
description: description:
@@ -262,6 +262,46 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "6.0.0" version: "6.0.0"
flutter_local_notifications:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: be38e3854d2baabcda8e16966a5fe8748cebb655bb94701494da0f052c2fc352
url: "https://pub.dev"
source: hosted
version: "22.0.0"
flutter_local_notifications_linux:
dependency: transitive
description:
name: flutter_local_notifications_linux
sha256: "9ca97e63776f29ab1b955725c09999fc2c150523269db150c39274f2a43c5a8b"
url: "https://pub.dev"
source: hosted
version: "8.0.1"
flutter_local_notifications_platform_interface:
dependency: transitive
description:
name: flutter_local_notifications_platform_interface
sha256: ff0013eae795e8dc8fad4a8992a209e64d3ba2fbd8bf5e43c36bf448f95bd814
url: "https://pub.dev"
source: hosted
version: "12.0.0"
flutter_local_notifications_web:
dependency: transitive
description:
name: flutter_local_notifications_web
sha256: "516afaf97a2d1e67a036c6617321b00d205d72f7a67b6eccf936cd565f985878"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
flutter_local_notifications_windows:
dependency: transitive
description:
name: flutter_local_notifications_windows
sha256: "5aeed973a0c1480706784fad05c5c3a911335ebb561b2274b47fe80b375201e1"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
flutter_localizations: flutter_localizations:
dependency: "direct main" dependency: "direct main"
description: flutter description: flutter
@@ -321,18 +361,18 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: haptic_kit name: haptic_kit
sha256: "39efffa513c9f8ce3cdded8a4423797f69d71c9281779b83727337f3ee1ed9b8" sha256: "457f825a3413be2651954639bed27bb2987570f75d90c4e8e1cb9be62db2e59d"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.0.0" version: "1.0.1"
hooks: hooks:
dependency: transitive dependency: transitive
description: description:
name: hooks name: hooks
sha256: "025f060e86d2d4c3c47b56e33caf7f93bf9283340f26d23424ebcfccf34f621e" sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.0.3" version: "2.0.2"
http: http:
dependency: transitive dependency: transitive
description: description:
@@ -469,14 +509,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.0" version: "2.0.0"
native_toolchain_c:
dependency: transitive
description:
name: native_toolchain_c
sha256: "6ba77bb18063eebe9de401f5e6437e95e1438af0a87a3a39084fbd37c90df572"
url: "https://pub.dev"
source: hosted
version: "0.17.6"
nm: nm:
dependency: transitive dependency: transitive
description: description:
@@ -489,10 +521,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: objective_c name: objective_c
sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" sha256: "6cb691c686fa2838c6deb34980d426145c2a5d537491cb83d463c33cdbc726ed"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "9.3.0" version: "9.4.1"
package_config: package_config:
dependency: transitive dependency: transitive
description: description:
@@ -665,10 +697,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: shared_preferences_android name: shared_preferences_android
sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 sha256: a2c49fc1fed7140cadd892d765bd47edbe4ac0b9c7e7e3c493dcb58126f99cf0
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.4.23" version: "2.4.25"
shared_preferences_foundation: shared_preferences_foundation:
dependency: transitive dependency: transitive
description: description:
@@ -794,6 +826,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.11" version: "0.7.11"
timezone:
dependency: transitive
description:
name: timezone
sha256: "784a5e34d2eb62e1326f24d6f600aaaee452eb8ca8ef2f384a59244e292d158b"
url: "https://pub.dev"
source: hosted
version: "0.11.0"
typed_data: typed_data:
dependency: transitive dependency: transitive
description: description:
@@ -814,10 +854,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: url_launcher_android name: url_launcher_android
sha256: "17bc677f0b301615530dd1d67e0a9828cafa2d0b6b6eae4cd3679b7eac4a273c" sha256: b413d49b73867ac08dd2f9890efd3cc11f2a0e577618d50843440a1fb3776c32
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "6.3.30" version: "6.3.32"
url_launcher_ios: url_launcher_ios:
dependency: transitive dependency: transitive
description: description:
@@ -926,10 +966,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: win32 name: win32
sha256: a1fc9eb9248baa05dfc12ed5b66e377b3e23f095eec078e0371622b9033810d9 sha256: ba6f4bba816c8d7e3c1580e170f3786d216951cc6b94babc3b814c08d2cb2738
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "6.2.0" version: "6.3.0"
xdg_directories: xdg_directories:
dependency: transitive dependency: transitive
description: description:
@@ -942,10 +982,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: xml name: xml
sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "6.6.1" version: "7.0.1"
yaml: yaml:
dependency: transitive dependency: transitive
description: description:
@@ -955,5 +995,5 @@ packages:
source: hosted source: hosted
version: "3.1.3" version: "3.1.3"
sdks: sdks:
dart: ">=3.11.5 <4.0.0" dart: ">=3.12.0 <4.0.0"
flutter: ">=3.38.4" flutter: ">=3.44.0"
+1
View File
@@ -75,6 +75,7 @@ dependencies:
# DEC-003 iOS 13 floor; haptic_kit supports iOS 12+). # DEC-003 iOS 13 floor; haptic_kit supports iOS 12+).
haptic_kit: ^1.0.0 haptic_kit: ^1.0.0
flutter_foreground_task: ^9.2.2 flutter_foreground_task: ^9.2.2
flutter_local_notifications: ^22.0.0
url_launcher: ^6.3.2 url_launcher: ^6.3.2
shared_preferences: ^2.5.5 shared_preferences: ^2.5.5
share_plus: ^13.1.0 share_plus: ^13.1.0
@@ -31,6 +31,18 @@ if [ ! -f "${BINARY}" ]; then
exit 1 exit 1
fi fi
# Flutter Debug builds split user code into a sibling `<App>.debug.dylib`
# alongside a tiny launcher executable; the @_cdecl symbols live in the
# dylib. Release/Profile builds put everything in the main executable.
# Prefer the dylib when both exist so the check verifies the slice that
# actually carries the symbols.
EXECUTABLE_DIR=$(dirname "${BINARY}")
EXECUTABLE_NAME=$(basename "${BINARY}")
DEBUG_DYLIB="${EXECUTABLE_DIR}/${EXECUTABLE_NAME}.debug.dylib"
if [ -f "${DEBUG_DYLIB}" ]; then
BINARY="${DEBUG_DYLIB}"
fi
REQUIRED_SYMBOLS=" REQUIRED_SYMBOLS="
_chanora_silero_vad_create _chanora_silero_vad_create
_chanora_silero_vad_destroy _chanora_silero_vad_destroy
@@ -0,0 +1,36 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:chanora_flutter/services/hard_mute_owners.dart';
void main() {
group('HardMuteOwners', () {
test('manual mute survives talk-power block and restore', () {
const owners = HardMuteOwners(manual: true);
final blocked = owners.copyWith(talkPower: true);
expect(blocked.effective, isTrue);
final restored = blocked.copyWith(talkPower: false);
expect(restored.manual, isTrue);
expect(restored.talkPower, isFalse);
expect(restored.effective, isTrue);
});
test('effective mute is the union of independent owners', () {
expect(const HardMuteOwners().effective, isFalse);
expect(const HardMuteOwners(manual: true).effective, isTrue);
expect(const HardMuteOwners(permission: true).effective, isTrue);
expect(const HardMuteOwners(talkPower: true).effective, isTrue);
});
test('bridge mute does not convert talk-power owner into manual owner', () {
const owners = HardMuteOwners(talkPower: true);
final synced = owners.withBridgeManualMute(true);
expect(synced.manual, isFalse);
expect(synced.talkPower, isTrue);
expect(synced.effective, isTrue);
});
});
}
@@ -0,0 +1,99 @@
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:chanora_flutter/services/ios_audio_session_controller.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('IosAudioSessionController', () {
const channel = MethodChannel(iosAudioSessionChannelName);
final messenger = TestDefaultBinaryMessengerBinding
.instance.defaultBinaryMessenger;
tearDown(() {
messenger.setMockMethodCallHandler(channel, null);
});
test('channel name matches Swift contract', () {
expect(iosAudioSessionChannelName, 'chanora/ios_audio_session');
});
test('activate invokes activateVoiceSession on iOS', () async {
final calls = <MethodCall>[];
messenger.setMockMethodCallHandler(channel, (call) async {
calls.add(call);
return null;
});
final controller = IosAudioSessionController(
channel: channel,
isIos: true,
);
await controller.activate();
expect(calls.map((c) => c.method), ['activateVoiceSession']);
expect(calls.single.arguments, isNull);
});
test('deactivate invokes deactivateVoiceSession on iOS', () async {
final calls = <MethodCall>[];
messenger.setMockMethodCallHandler(channel, (call) async {
calls.add(call);
return null;
});
final controller = IosAudioSessionController(
channel: channel,
isIos: true,
);
await controller.deactivate();
expect(calls.map((c) => c.method), ['deactivateVoiceSession']);
expect(calls.single.arguments, isNull);
});
test('activate is a no-op on non-iOS platforms', () async {
var invoked = false;
messenger.setMockMethodCallHandler(channel, (call) async {
invoked = true;
return null;
});
final controller = IosAudioSessionController(
channel: channel,
isIos: false,
);
await controller.activate();
await controller.deactivate();
expect(invoked, isFalse);
});
test('activate swallows PlatformException so engine keeps running',
() async {
messenger.setMockMethodCallHandler(channel, (call) async {
throw PlatformException(code: 'avaudiosession_failed');
});
final controller = IosAudioSessionController(
channel: channel,
isIos: true,
);
await expectLater(controller.activate(), completes);
await expectLater(controller.deactivate(), completes);
});
test('activate swallows MissingPluginException when channel is absent',
() async {
final controller = IosAudioSessionController(
channel: channel,
isIos: true,
);
await expectLater(controller.activate(), completes);
await expectLater(controller.deactivate(), completes);
});
});
}
@@ -0,0 +1,48 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:chanora_flutter/main.dart';
import 'package:chanora_flutter/src/rust/api.dart' as rust;
void main() {
test('active poke chat suppresses same sender notification only', () {
final sender = BigInt.from(42);
expect(
isPokeSenderActiveChat(
chatOpen: true,
inlineChatTarget: rust.BridgeMessageTarget.poke(sender),
senderId: sender,
),
isTrue,
);
expect(
isPokeSenderActiveChat(
chatOpen: true,
inlineChatTarget: rust.BridgeMessageTarget.poke(BigInt.from(7)),
senderId: sender,
),
isFalse,
);
});
test('active private chat also suppresses same sender poke notification', () {
final sender = BigInt.from(42);
expect(
isPokeSenderActiveChat(
chatOpen: true,
inlineChatTarget: rust.BridgeMessageTarget.client(sender),
senderId: sender,
),
isTrue,
);
expect(
isPokeSenderActiveChat(
chatOpen: false,
inlineChatTarget: rust.BridgeMessageTarget.client(sender),
senderId: sender,
),
isFalse,
);
});
}
@@ -0,0 +1,81 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:chanora_flutter/services/poke_notification_service.dart';
import 'package:chanora_flutter/src/rust/api.dart' as rust;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('dexterous.com/flutter/local_notifications');
late List<MethodCall> calls;
setUp(() {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
AndroidFlutterLocalNotificationsPlugin.registerWith();
calls = <MethodCall>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
calls.add(call);
return switch (call.method) {
'initialize' => true,
'requestNotificationsPermission' => true,
_ => null,
};
});
});
tearDown(() {
debugDefaultTargetPlatformOverride = null;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null);
});
test(
'show dispatches a silent poke notification with sender payload',
() async {
final service = PokeNotificationService();
await service.show(
senderName: 'Alice',
message: 'wake up',
senderId: BigInt.from(42),
strength: rust.BridgePokeStrength.strong,
);
final showCall = calls.singleWhere((call) => call.method == 'show');
final arguments = Map<Object?, Object?>.from(showCall.arguments as Map);
expect(arguments['id'], 42);
expect(arguments['title'], 'Poke from Alice');
expect(arguments['body'], 'wake up');
expect(arguments['payload'], 'poke:42');
final specifics = Map<Object?, Object?>.from(
arguments['platformSpecifics'] as Map,
);
expect(specifics['silent'], true);
expect(specifics['playSound'], false);
expect(specifics['groupKey'], 'chanora.pokes');
},
);
test('show uses fallback body for empty poke messages', () async {
final service = PokeNotificationService();
await service.show(
senderName: 'Alice',
message: ' ',
senderId: BigInt.from(42),
strength: rust.BridgePokeStrength.strong,
);
final showCall = calls.singleWhere((call) => call.method == 'show');
final arguments = Map<Object?, Object?>.from(showCall.arguments as Map);
expect(arguments['title'], 'Poke from Alice');
expect(arguments['body'], 'Alice pokes you');
expect(arguments['payload'], 'poke:42');
});
}
@@ -0,0 +1,58 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:chanora_flutter/services/poke_preferences_service.dart';
void main() {
late PokePreferencesService service;
setUp(() {
SharedPreferences.setMockInitialValues({});
service = PokePreferencesService();
});
test('loads defaults when preferences are unset', () async {
await service.load();
expect(service.pokesEnabled.value, isTrue);
expect(service.mutedSenders.value, isEmpty);
});
test('persists global enabled state', () async {
await service.load();
await service.setPokesEnabled(false);
final reloaded = PokePreferencesService();
await reloaded.load();
expect(reloaded.pokesEnabled.value, isFalse);
});
test('persists muted senders and removes them on unmute', () async {
await service.load();
final alice = BigInt.from(42);
final bob = BigInt.from(7);
await service.muteSender(alice);
await service.muteSender(bob);
await service.unmuteSender(alice);
final reloaded = PokePreferencesService();
await reloaded.load();
expect(reloaded.mutedSenders.value, {bob});
});
test('isMuted reflects in-memory changes synchronously', () async {
await service.load();
final sender = BigInt.from(99);
expect(service.isMuted(sender), isFalse);
await service.muteSender(sender);
expect(service.isMuted(sender), isTrue);
await service.unmuteSender(sender);
expect(service.isMuted(sender), isFalse);
});
}
@@ -0,0 +1,123 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:chanora_flutter/services/voice_join_ordering.dart';
void main() {
group('joinVoiceChannelWithIosAudioSession', () {
test('activates the iOS audio session before Rust voiceJoin', () async {
final calls = <String>[];
await joinVoiceChannelWithIosAudioSession(
channelId: BigInt.from(42),
password: 'secret',
activateIosAudioSession: () async {
calls.add('activateIosAudioSession');
},
deactivateIosAudioSession: () async {
calls.add('deactivateIosAudioSession');
},
voiceJoin: ({required channelId, required password}) async {
expect(channelId, BigInt.from(42));
expect(password, 'secret');
calls.add('voiceJoin');
},
);
expect(calls, ['activateIosAudioSession', 'voiceJoin']);
});
test('deactivates the iOS audio session when Rust voiceJoin fails',
() async {
final calls = <String>[];
await expectLater(
joinVoiceChannelWithIosAudioSession(
channelId: BigInt.from(42),
password: '',
activateIosAudioSession: () async {
calls.add('activateIosAudioSession');
},
deactivateIosAudioSession: () async {
calls.add('deactivateIosAudioSession');
},
voiceJoin: ({required channelId, required password}) async {
calls.add('voiceJoin');
throw StateError('join rejected');
},
),
throwsStateError,
);
expect(calls, [
'activateIosAudioSession',
'voiceJoin',
'deactivateIosAudioSession',
]);
});
test(
'keeps the iOS audio session active when voiceJoin throws but the '
'error is recognised as already-in-channel (treated as success); '
'still rethrows so the caller runs its success-on-already-joined branch',
() async {
final calls = <String>[];
await expectLater(
joinVoiceChannelWithIosAudioSession(
channelId: BigInt.from(42),
password: '',
activateIosAudioSession: () async {
calls.add('activateIosAudioSession');
},
deactivateIosAudioSession: () async {
calls.add('deactivateIosAudioSession');
},
voiceJoin: ({required channelId, required password}) async {
calls.add('voiceJoin');
throw _FakeAlreadyInChannel();
},
isJoinSuccess: (error) => error is _FakeAlreadyInChannel,
),
throwsA(isA<_FakeAlreadyInChannel>()),
);
expect(calls, ['activateIosAudioSession', 'voiceJoin']);
},
);
test(
'deactivates the iOS audio session when isJoinSuccess returns false '
'for a non-success error',
() async {
final calls = <String>[];
await expectLater(
joinVoiceChannelWithIosAudioSession(
channelId: BigInt.from(42),
password: '',
activateIosAudioSession: () async {
calls.add('activateIosAudioSession');
},
deactivateIosAudioSession: () async {
calls.add('deactivateIosAudioSession');
},
voiceJoin: ({required channelId, required password}) async {
calls.add('voiceJoin');
throw StateError('join rejected');
},
isJoinSuccess: (error) => error is _FakeAlreadyInChannel,
),
throwsStateError,
);
expect(calls, [
'activateIosAudioSession',
'voiceJoin',
'deactivateIosAudioSession',
]);
},
);
});
}
class _FakeAlreadyInChannel implements Exception {}
@@ -455,7 +455,7 @@ void main() {
channelName: '', channelName: '',
clientName: 'Alpha', clientName: 'Alpha',
), ),
'Poke message...', 'Poke message optional...',
); );
}); });
@@ -737,6 +737,179 @@ void main() {
refresh.dispose(); refresh.dispose();
}); });
test('evaluates target-aware chat message send policy', () {
final clientTarget = rust.BridgeMessageTarget.client(BigInt.from(2));
final pokeTarget = rust.BridgeMessageTarget.poke(BigInt.from(2));
expect(canSendChatMessage(pokeTarget, null, ''), isTrue);
expect(canSendChatMessage(pokeTarget, null, ' '), isTrue);
expect(canSendChatMessage(pokeTarget, null, 'wake up'), isTrue);
expect(
canSendChatMessage(const rust.BridgeMessageTarget.server(), null, ''),
isFalse,
);
expect(
canSendChatMessage(
const rust.BridgeMessageTarget.channel(),
BigInt.from(10),
'',
),
isFalse,
);
expect(canSendChatMessage(clientTarget, null, ''), isFalse);
expect(
canSendChatMessage(
const rust.BridgeMessageTarget.channel(),
null,
'hello',
),
isFalse,
);
expect(
canSendChatMessage(
const rust.BridgeMessageTarget.channel(),
BigInt.from(10),
'hello',
),
isTrue,
);
});
testWidgets('poke detail sends an empty poke when the composer is empty', (
tester,
) async {
String? sentMessage;
rust.BridgeMessageTarget? sentTarget;
final messages = <ChatEntry>[];
final target = rust.BridgeMessageTarget.poke(BigInt.from(2));
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppL10n.localizationsDelegates,
supportedLocales: AppL10n.supportedLocales,
home: Scaffold(
body: ChatDetailView(
messages: messages,
snapshot: snapshot(
channels: const [],
clients: [
client(id: BigInt.one, name: 'Me', channelId: BigInt.zero),
],
),
target: target,
clientName: 'Alpha',
currentChannelId: null,
channelName: '',
sendChatMessage: ({required message, required target}) async {
sentMessage = message;
sentTarget = target;
},
),
),
),
);
expect(find.byTooltip('Poke'), findsOneWidget);
expect(find.byTooltip('Send'), findsNothing);
await tester.tap(find.byTooltip('Poke'));
await tester.pump();
expect(sentMessage, '');
expect(sentTarget, target);
expect(messages, hasLength(1));
expect(messages.single.isPoke, isTrue);
expect(messages.single.message, '');
expect(find.textContaining('You poked "Alpha"'), findsOneWidget);
expect(find.byType(CircleAvatar), findsNothing);
});
testWidgets('poke detail sends typed optional poke message', (tester) async {
String? sentMessage;
rust.BridgeMessageTarget? sentTarget;
final messages = <ChatEntry>[];
final target = rust.BridgeMessageTarget.poke(BigInt.from(2));
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppL10n.localizationsDelegates,
supportedLocales: AppL10n.supportedLocales,
home: Scaffold(
body: ChatDetailView(
messages: messages,
snapshot: snapshot(
channels: const [],
clients: [
client(id: BigInt.one, name: 'Me', channelId: BigInt.zero),
],
),
target: target,
clientName: 'Alpha',
currentChannelId: null,
channelName: '',
sendChatMessage: ({required message, required target}) async {
sentMessage = message;
sentTarget = target;
},
),
),
),
);
await tester.enterText(find.byType(TextField), 'wake up');
await tester.tap(find.byTooltip('Poke'));
await tester.pump();
expect(sentMessage, 'wake up');
expect(sentTarget, target);
expect(messages.single.message, 'wake up');
expect(
find.textContaining('You poked "Alpha" with message: wake up'),
findsOneWidget,
);
});
testWidgets('channel detail blocks empty sends with a joined channel', (
tester,
) async {
var sendCount = 0;
final messages = <ChatEntry>[];
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppL10n.localizationsDelegates,
supportedLocales: AppL10n.supportedLocales,
home: Scaffold(
body: ChatDetailView(
messages: messages,
snapshot: snapshot(
channels: [channel(BigInt.from(10), 'Lobby')],
clients: [
client(id: BigInt.one, name: 'Me', channelId: BigInt.from(10)),
],
),
target: const rust.BridgeMessageTarget.channel(),
clientName: '',
currentChannelId: BigInt.from(10),
channelName: 'Lobby',
sendChatMessage: ({required message, required target}) async {
sendCount++;
},
),
),
),
);
expect(find.byTooltip('Send'), findsOneWidget);
await tester.tap(find.byTooltip('Send'));
await tester.pump();
expect(sendCount, 0);
expect(messages, isEmpty);
});
test('blocks channel chat when no voice channel is joined', () { test('blocks channel chat when no voice channel is joined', () {
expect( expect(
canSendToChatTarget(const rust.BridgeMessageTarget.channel(), null), canSendToChatTarget(const rust.BridgeMessageTarget.channel(), null),
@@ -0,0 +1,37 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:chanora_flutter/l10n/generated/app_localizations.dart';
import 'package:chanora_flutter/services/poke_preferences_service.dart';
import 'package:chanora_flutter/widgets/poke_notification_settings.dart';
void main() {
testWidgets('toggles poke notifications and unmutes senders', (tester) async {
SharedPreferences.setMockInitialValues({});
final preferences = PokePreferencesService();
await preferences.load();
await preferences.muteSender(BigInt.from(42));
addTearDown(preferences.dispose);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppL10n.localizationsDelegates,
supportedLocales: AppL10n.supportedLocales,
home: PokeNotificationSettingsDialog(preferences: preferences),
),
);
expect(find.text('Poke notifications'), findsOneWidget);
expect(find.text('Client ID 42'), findsOneWidget);
await tester.tap(find.byType(Switch));
await tester.pumpAndSettle();
expect(preferences.pokesEnabled.value, isFalse);
await tester.tap(find.text('Unmute'));
await tester.pumpAndSettle();
expect(preferences.isMuted(BigInt.from(42)), isFalse);
expect(find.text('No muted poke senders.'), findsOneWidget);
});
}
@@ -0,0 +1,38 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:chanora_flutter/l10n/generated/app_localizations.dart';
import 'package:chanora_flutter/widgets/voice_compact.dart';
void main() {
testWidgets('touch PTT releases when disposed while held', (tester) async {
final heldChanges = <bool>[];
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppL10n.localizationsDelegates,
supportedLocales: AppL10n.supportedLocales,
home: Scaffold(
body: VoicePttButton(
active: false,
onHeldChanged: heldChanges.add,
),
),
),
);
final center = tester.getCenter(find.byType(VoicePttButton));
final gesture = await tester.startGesture(center);
await tester.pump();
expect(heldChanges, [true]);
await tester.pumpWidget(const MaterialApp(home: Scaffold()));
expect(heldChanges, [true, false]);
await gesture.cancel();
expect(heldChanges, [true, false]);
});
}
@@ -13,6 +13,24 @@ void main() {
]); ]);
}); });
test('gated transmit mode segments drop VAD when unsupported', () {
expect(
transmitModeSegmentsFor(voiceActivityAvailable: false).map((s) => s.value),
[rust.BridgeTransmitMode.ptt, rust.BridgeTransmitMode.continuous],
);
});
test('gated transmit mode segments include VAD when supported', () {
expect(
transmitModeSegmentsFor(voiceActivityAvailable: true).map((s) => s.value),
[
rust.BridgeTransmitMode.ptt,
rust.BridgeTransmitMode.continuous,
rust.BridgeTransmitMode.voiceActivity,
],
);
});
test('shared Android processing segments expose hardware and WebRTC', () { test('shared Android processing segments expose hardware and WebRTC', () {
expect(androidProcessingSegments.map((s) => s.value), [true, false]); expect(androidProcessingSegments.map((s) => s.value), [true, false]);
}); });
@@ -9,6 +9,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
) )
list(APPEND FLUTTER_FFI_PLUGIN_LIST list(APPEND FLUTTER_FFI_PLUGIN_LIST
flutter_local_notifications_windows
jni jni
) )
+2 -1
View File
@@ -10,6 +10,7 @@ repository.workspace = true
publish.workspace = true publish.workspace = true
[dependencies] [dependencies]
chanora_cache = { path = "../../crates/chanora_cache" }
chanora_protocol = { path = "../../crates/chanora_protocol" } chanora_protocol = { path = "../../crates/chanora_protocol" }
chanora_state = { path = "../../crates/chanora_state" } chanora_state = { path = "../../crates/chanora_state" }
chanora_audio = { path = "../../crates/chanora_audio" } chanora_audio = { path = "../../crates/chanora_audio" }
@@ -18,7 +19,7 @@ chanora_diagnostics = { path = "../../crates/chanora_diagnostics" }
chanora_prefetch = { path = "../../crates/chanora_prefetch" } chanora_prefetch = { path = "../../crates/chanora_prefetch" }
thiserror.workspace = true thiserror.workspace = true
tracing.workspace = true tracing.workspace = true
tokio = { version = "1", features = ["sync", "rt", "macros"] } tokio = { version = "1", features = ["sync", "rt", "macros", "time"] }
[dev-dependencies] [dev-dependencies]
# Used by integration tests to inspect the bookmark DB row layout # Used by integration tests to inspect the bookmark DB row layout
+287
View File
@@ -0,0 +1,287 @@
use chanora_audio::{AudioRoute, PttBackendDescriptor};
use chanora_protocol::{MessageTarget, PokeStrength};
/// Privacy-safe snapshot of the active PTT capability.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PttDescriptorSnapshot {
/// Stable capability level name.
pub level: String,
/// Stable backend identifier.
pub backend_id: String,
/// Coarse bound input class; empty when no binding is active.
pub bound_input_class: String,
}
impl From<PttBackendDescriptor> for PttDescriptorSnapshot {
fn from(desc: PttBackendDescriptor) -> Self {
Self {
level: desc.level.as_str().to_string(),
backend_id: desc.backend_id.to_string(),
bound_input_class: desc.bound_input_class.unwrap_or("").to_string(),
}
}
}
/// Persisted PTT binding state exposed to callers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PersistedPttBinding {
/// Stable input category string (`""`, `"keyboard"`, or
/// `"mouse-side-button"`).
pub input_class: String,
/// Display-only key label; empty when no binding is active.
pub key_label: String,
}
impl PersistedPttBinding {
pub(crate) fn empty() -> Self {
Self {
input_class: String::new(),
key_label: String::new(),
}
}
}
/// High-level lifecycle event surfaced to subscribers.
///
/// This is the minimal set needed for A.6 (reconnect banner). The
/// full event catalogue lands in A.4.
#[derive(Debug, Clone)]
pub enum SessionEvent {
/// Initial connect succeeded, or reconnect attempt succeeded.
Connected {
/// Server name reported in the snapshot.
server_name: String,
},
/// Connection lost; the supervisor will retry.
Lost {
/// Reason classification from the protocol layer.
reason: String,
},
/// Supervisor is sleeping before its next reconnect attempt.
Reconnecting {
/// 1-based attempt counter for the current outage.
attempt: u32,
/// Seconds the supervisor will sleep before this attempt.
delay_secs: u32,
},
/// Supervisor gave up after `attempt` failed retries (or the
/// user explicitly disconnected mid-outage).
Disconnected {
/// Reason classification from the protocol layer.
reason: String,
},
/// Audio engine started (e.g. after a successful reconnect with
/// reattachment).
AudioStarted,
/// Audio engine stopped (e.g. before a reconnect cycle, or by
/// explicit user action).
AudioStopped,
/// Detected desktop Push-to-Talk capability (gen2 v0.9.3 /
/// DEC-023..028). Published when the audio engine starts or
/// when the active backend transitions (for example macOS
/// permission state change). Carries only the privacy-safe
/// descriptor — capability level, backend identifier, bound
/// input class — per SRS-202 / DEC-027.
PttCapability {
/// Stable level name from `PttCapabilityLevel::as_str()`.
level: String,
/// Stable backend identifier (e.g. `"focused"`).
backend_id: String,
/// Coarse bound input class (e.g. `"keyboard"`); empty when
/// no binding is active.
bound_input_class: String,
},
/// Voice subsystem state snapshot (SDD-094). Emitted on
/// `voice_join` / `voice_leave`, transmit-mode changes,
/// hard-mute toggles, and release-tail edits.
VoiceState {
/// True when the user has joined a voice channel via
/// `voice_join` and the audio engine is running.
in_channel: bool,
/// Active transmit mode encoded as
/// [`chanora_audio::TransmitMode::as_u8`].
transmit_mode: u8,
/// True when the hard-mute clamp is engaged.
mute: bool,
/// Current release-tail in milliseconds (0..=500).
release_tail_ms: u32,
/// Last confirmed authoritative channel id from the
/// `channel_join` reducer projection.
current_channel_id: Option<u64>,
/// Non-authoritative pending target channel id from the
/// reducer projection.
pending_target_channel_id: Option<u64>,
/// Whether the reducer currently allows a new join intent.
can_join: bool,
/// Whether the reducer currently allows leave intent.
can_leave: bool,
/// Join projection synchronization state.
join_sync_state: VoiceJoinSyncState,
/// Last stable sanitized join error code, if any.
join_error_code: Option<VoiceJoinErrorCode>,
},
/// iOS audio-session interruption state (SDD-101). Emitted when
/// interruption begins and when it ends (with the platform hint
/// indicating whether audio should resume).
InterruptionState {
/// True when interruption began, false when interruption ended.
began: bool,
/// Platform-provided resume hint. For begin events this is false.
should_resume: bool,
},
/// A text message was received from the server.
ChatMessage {
/// Client id of the sender.
sender_id: u64,
/// Nickname of the sender.
sender_name: String,
/// Message content.
message: String,
/// Target scope (server/channel/private/poke).
target: MessageTarget,
/// Poke notification strength, present only for poke messages.
poke_strength: Option<PokeStrength>,
},
/// Human-readable TeamSpeak-style server activity.
ServerActivity {
/// Activity line text.
message: String,
},
/// Audio route changed (speaker/earpiece/BT/wired headset).
AudioRouteChanged {
/// New audio output route.
route: AudioRoute,
},
/// A client moved to a different channel.
ClientMoved {
/// Unique client identifier.
client_id: u64,
/// Destination channel.
new_channel_id: u64,
},
/// A new client connected.
ClientJoined {
/// Unique client identifier.
client_id: u64,
/// Channel the client joined.
channel_id: u64,
/// Display nickname.
name: String,
/// Microphone muted state.
input_muted: bool,
/// Speaker muted state.
output_muted: bool,
/// Whether this is a server query (bot) client.
is_server_query: bool,
/// Client's talk power value.
talk_power: i32,
/// Whether the server granted temporary talk power.
talk_power_granted: bool,
},
/// A client disconnected.
ClientLeft {
/// Unique client identifier.
client_id: u64,
/// Display nickname at time of disconnect.
name: String,
},
/// Client properties changed.
ClientUpdated {
/// Unique client identifier.
client_id: u64,
/// Microphone muted state.
input_muted: bool,
/// Speaker muted state.
output_muted: bool,
/// Whether this is a server query (bot) client.
is_server_query: bool,
/// Client's talk power value.
talk_power: i32,
/// Whether the server granted temporary talk power.
talk_power_granted: bool,
},
/// A new channel appeared.
ChannelAdded {
/// Unique channel identifier.
id: u64,
/// Parent channel ID.
parent: u64,
/// Channel name.
name: String,
/// Predecessor channel ID within the same parent (TeamSpeak
/// linked-list ordering hint). Zero means first child.
order: i64,
/// Whether the channel requires a password.
has_password: bool,
/// Talk power required to speak, or `None` when unrestricted.
needed_talk_power: Option<i32>,
},
/// A channel was deleted.
ChannelRemoved {
/// Channel identifier.
id: u64,
},
/// Channel properties changed.
ChannelUpdated {
/// Unique channel identifier.
id: u64,
/// Channel name.
name: String,
/// Whether the channel requires a password.
has_password: bool,
/// Talk power required to speak, or `None` when unrestricted.
needed_talk_power: Option<i32>,
},
}
/// Bridge-safe mirror of channel-join projection sync state.
#[derive(Debug, Clone, Copy)]
pub enum VoiceJoinSyncState {
/// Reducer is ready to accept channel actions.
Ready,
/// Reducer is synchronizing against an initial snapshot.
SynchronizingInitialSnapshot,
/// Reducer is synchronizing after reconnect.
SynchronizingReconnect,
}
/// Bridge-safe mirror of stable channel-join error codes.
#[derive(Debug, Clone, Copy)]
pub enum VoiceJoinErrorCode {
/// Duplicate same-target join intent was coalesced.
DuplicateSameTargetCoalesced,
/// A different target was requested while one is already pending.
JoinAlreadyPendingDifferentTarget,
/// Join denied by server policy/permission.
JoinDenied,
/// Join failed due to protocol-level error.
JoinProtocolFailure,
/// Join failed due to transport/network error.
JoinNetworkFailure,
/// Join timed out awaiting confirmation.
JoinTimeout,
/// Pending join was superseded by user leave.
JoinSupersededByLeave,
/// Stale join outcome was ignored.
JoinStaleOutcomeIgnored,
/// Authoritative membership reconciled to different channel.
JoinReconciledDifferentChannel,
/// Join command was rejected before send acceptance.
JoinCommandRejectedBeforeSend,
/// Join intent rejected while reducer synchronizing.
JoinCannotStartWhileSynchronizing,
}
/// Coarse OS-reported network state. Populated by the Flutter side
/// via `connectivity_plus`; on platforms where no signal is wired
/// we stay at `Unknown` forever and the supervisor falls back to
/// pure watchdog/backoff behaviour.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkState {
/// No signal seen yet — treat as ambiguous; don't change behaviour.
Unknown,
/// OS reports at least one network with internet capability.
Online,
/// OS reports no networks available.
Offline,
}
+344
View File
@@ -0,0 +1,344 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use chanora_cache::{BlobCache, BlobCacheError, PREFIX_AVATAR, PREFIX_ICON};
use chanora_protocol::{ProtocolClient, ProtocolError};
use tokio::sync::{Mutex, Semaphore, oneshot};
use tracing::warn;
const MAX_CONCURRENT_DOWNLOADS: usize = 2;
const NEGATIVE_CACHE_TTL: Duration = Duration::from_secs(5 * 60);
type InFlightWaiters = Vec<oneshot::Sender<Result<Option<Vec<u8>>, FileTransferError>>>;
/// Errors raised while resolving protocol-owned file assets.
#[derive(Debug, thiserror::Error)]
pub enum FileTransferError {
/// No live protocol client is available for a download.
#[error("not connected")]
NotConnected,
/// The protocol layer failed while downloading the asset.
#[error("protocol error: {0}")]
Protocol(#[from] ProtocolError),
/// The blob cache failed while reading or writing the asset.
#[error("cache error: {0}")]
Cache(#[from] BlobCacheError),
}
impl Clone for FileTransferError {
fn clone(&self) -> Self {
match self {
Self::NotConnected => Self::NotConnected,
Self::Protocol(error) => Self::Protocol(clone_protocol_error(error)),
Self::Cache(error) => Self::Cache(clone_blob_cache_error(error)),
}
}
}
pub struct FileTransferService {
cache: BlobCache,
protocol: Arc<Mutex<Option<ProtocolClient>>>,
semaphore: Arc<Semaphore>,
in_flight: Arc<Mutex<HashMap<String, InFlightWaiters>>>,
negative_cache: Arc<Mutex<HashMap<String, Instant>>>,
}
impl FileTransferService {
pub fn new(cache: BlobCache, protocol: Arc<Mutex<Option<ProtocolClient>>>) -> Self {
Self {
cache,
protocol,
semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_DOWNLOADS)),
in_flight: Arc::new(Mutex::new(HashMap::new())),
negative_cache: Arc::new(Mutex::new(HashMap::new())),
}
}
pub async fn set_protocol(&self, client: Option<ProtocolClient>) {
*self.protocol.lock().await = client;
}
pub async fn get_avatar(
&self,
avatar_hash: &str,
client_uid: &str,
) -> Result<Option<Vec<u8>>, FileTransferError> {
if let Some(bytes) = self.cache.get(PREFIX_AVATAR, avatar_hash).await? {
return Ok(Some(bytes));
}
if self.is_negative_cache_hit(avatar_hash).await {
return Ok(None);
}
let rx = {
let mut in_flight = self.in_flight.lock().await;
if let Some(waiters) = in_flight.get_mut(avatar_hash) {
let (tx, rx) = oneshot::channel();
waiters.push(tx);
Some(rx)
} else {
in_flight.insert(avatar_hash.to_string(), Vec::new());
None
}
};
if let Some(rx) = rx {
return rx.await.unwrap_or_else(|_| {
Err(FileTransferError::Protocol(ProtocolError::Lost(
"coalesced avatar download waiter dropped".to_string(),
)))
});
}
let _permit = self
.semaphore
.acquire()
.await
.expect("file transfer semaphore should stay open");
let result = self.do_download_avatar(avatar_hash, client_uid).await;
self.finish_in_flight(avatar_hash, &result).await;
result
}
pub async fn get_icon(&self, icon_id: u64) -> Result<Option<Vec<u8>>, FileTransferError> {
let icon_key = icon_id.to_string();
let negative_key = format!("ic_{icon_id}");
let in_flight_key = format!("icon_{icon_id}");
if let Some(bytes) = self.cache.get(PREFIX_ICON, &icon_key).await? {
return Ok(Some(bytes));
}
if self.is_negative_cache_hit(&negative_key).await {
return Ok(None);
}
let rx = {
let mut in_flight = self.in_flight.lock().await;
if let Some(waiters) = in_flight.get_mut(&in_flight_key) {
let (tx, rx) = oneshot::channel();
waiters.push(tx);
Some(rx)
} else {
in_flight.insert(in_flight_key.clone(), Vec::new());
None
}
};
if let Some(rx) = rx {
return rx.await.unwrap_or_else(|_| {
Err(FileTransferError::Protocol(ProtocolError::Lost(
"coalesced icon download waiter dropped".to_string(),
)))
});
}
let _permit = self
.semaphore
.acquire()
.await
.expect("file transfer semaphore should stay open");
let result = self.do_download_icon(icon_id).await;
self.finish_in_flight(&in_flight_key, &result).await;
result
}
pub async fn clear_cache(&self) -> Result<(), FileTransferError> {
self.cache.clear().await?;
self.negative_cache.lock().await.clear();
Ok(())
}
pub async fn cache_size(&self) -> Result<u64, FileTransferError> {
Ok(self.cache.total_size().await?)
}
async fn do_download_avatar(
&self,
avatar_hash: &str,
client_uid: &str,
) -> Result<Option<Vec<u8>>, FileTransferError> {
if let Some(bytes) = self.cache.get(PREFIX_AVATAR, avatar_hash).await? {
return Ok(Some(bytes));
}
if self.is_negative_cache_hit(avatar_hash).await {
return Ok(None);
}
let protocol = self.protocol.lock().await;
let client = protocol.as_ref().ok_or(FileTransferError::NotConnected)?;
match client.download_avatar(client_uid).await {
Ok(bytes) => {
self.cache.put(PREFIX_AVATAR, avatar_hash, &bytes).await?;
self.negative_cache.lock().await.remove(avatar_hash);
Ok(Some(bytes))
}
Err(ProtocolError::ServerRejected { .. }) => {
self.negative_cache
.lock()
.await
.insert(avatar_hash.to_string(), Instant::now() + NEGATIVE_CACHE_TTL);
Ok(None)
}
Err(error) => Err(FileTransferError::Protocol(error)),
}
}
async fn do_download_icon(&self, icon_id: u64) -> Result<Option<Vec<u8>>, FileTransferError> {
let icon_key = icon_id.to_string();
let negative_key = format!("ic_{icon_id}");
if let Some(bytes) = self.cache.get(PREFIX_ICON, &icon_key).await? {
return Ok(Some(bytes));
}
if self.is_negative_cache_hit(&negative_key).await {
return Ok(None);
}
let protocol = self.protocol.lock().await;
let client = protocol.as_ref().ok_or(FileTransferError::NotConnected)?;
match client.download_icon(icon_id).await {
Ok(bytes) => {
self.cache.put(PREFIX_ICON, &icon_key, &bytes).await?;
self.negative_cache.lock().await.remove(&negative_key);
Ok(Some(bytes))
}
Err(ProtocolError::ServerRejected { .. }) => {
self.negative_cache
.lock()
.await
.insert(negative_key, Instant::now() + NEGATIVE_CACHE_TTL);
Ok(None)
}
Err(error) => Err(FileTransferError::Protocol(error)),
}
}
async fn finish_in_flight(
&self,
avatar_hash: &str,
result: &Result<Option<Vec<u8>>, FileTransferError>,
) {
let waiters = self.in_flight.lock().await.remove(avatar_hash).unwrap_or_default();
for waiter in waiters {
if waiter.send(result.clone()).is_err() {
warn!(target: "chanora_core", avatar_hash, "avatar download waiter dropped");
}
}
}
async fn is_negative_cache_hit(&self, avatar_hash: &str) -> bool {
let now = Instant::now();
let mut negative_cache = self.negative_cache.lock().await;
match negative_cache.get(avatar_hash).copied() {
Some(expires_at) if expires_at > now => true,
Some(_) => {
negative_cache.remove(avatar_hash);
false
}
None => false,
}
}
}
fn clone_protocol_error(error: &ProtocolError) -> ProtocolError {
match error {
ProtocolError::Invalid(message) => ProtocolError::Invalid(message.clone()),
ProtocolError::DnsFailed { host, reason } => ProtocolError::DnsFailed {
host: host.clone(),
reason: reason.clone(),
},
ProtocolError::Connect(message) => ProtocolError::Connect(message.clone()),
ProtocolError::DisconnectedEarly(message) => {
ProtocolError::DisconnectedEarly(message.clone())
}
ProtocolError::Lost(message) => ProtocolError::Lost(message.clone()),
ProtocolError::Identity(message) => ProtocolError::Identity(message.clone()),
ProtocolError::Timeout => ProtocolError::Timeout,
ProtocolError::ServerRejected { code, message } => ProtocolError::ServerRejected {
code: *code,
message: message.clone(),
},
ProtocolError::Backend(message) => ProtocolError::Backend(message.clone()),
ProtocolError::FileTransfer(message) => ProtocolError::FileTransfer(message.clone()),
}
}
fn clone_blob_cache_error(error: &BlobCacheError) -> BlobCacheError {
match error {
BlobCacheError::Io(message) => BlobCacheError::Io(message.clone()),
BlobCacheError::InvalidKey(message) => BlobCacheError::InvalidKey(message.clone()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_cache_dir(name: &str) -> std::path::PathBuf {
let mut path = std::env::temp_dir();
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
path.push(format!("chanora-core-file-transfer-{name}-{nanos}"));
path
}
#[tokio::test]
async fn returns_cached_avatar_without_connection() {
let cache_dir = test_cache_dir("cache-hit");
let cache = BlobCache::new(&cache_dir, 1024).unwrap();
cache.put(PREFIX_AVATAR, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", b"avatar")
.await
.unwrap();
let service = FileTransferService::new(cache, Arc::new(Mutex::new(None)));
let avatar = service
.get_avatar("a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", "client")
.await
.unwrap();
assert_eq!(avatar, Some(b"avatar".to_vec()));
let _ = std::fs::remove_dir_all(cache_dir);
}
#[tokio::test]
async fn negative_cache_short_circuits_not_connected() {
let cache_dir = test_cache_dir("negative-cache");
let cache = BlobCache::new(&cache_dir, 1024).unwrap();
let service = FileTransferService::new(cache, Arc::new(Mutex::new(None)));
service
.negative_cache
.lock()
.await
.insert("a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6".to_string(), Instant::now() + NEGATIVE_CACHE_TTL);
let avatar = service
.get_avatar("a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", "client")
.await
.unwrap();
assert_eq!(avatar, None);
let _ = std::fs::remove_dir_all(cache_dir);
}
#[tokio::test]
async fn returns_cached_icon_without_connection() {
let cache_dir = test_cache_dir("icon-cache-hit");
let cache = BlobCache::new(&cache_dir, 1024).unwrap();
cache.put(PREFIX_ICON, "12345", b"icon").await.unwrap();
let service = FileTransferService::new(cache, Arc::new(Mutex::new(None)));
let icon = service.get_icon(12345).await.unwrap();
assert_eq!(icon, Some(b"icon".to_vec()));
let _ = std::fs::remove_dir_all(cache_dir);
}
}
+341 -383
View File
@@ -52,6 +52,9 @@ use chanora_state::channel_join::{
ConnectionEpoch, JoinFailureKind, ConnectionEpoch, JoinFailureKind,
}; };
mod events;
mod file_transfer;
mod network_diagnostics;
pub mod ptt; pub mod ptt;
pub use chanora_audio::{ pub use chanora_audio::{
@@ -66,49 +69,15 @@ pub use chanora_diagnostics::{
}; };
pub use chanora_protocol::{ pub use chanora_protocol::{
ChannelInfo, ChatMessage, ClientInfo, ClientProfile, ConnectConfig, DisconnectReason, ChannelInfo, ChatMessage, ClientInfo, ClientProfile, ConnectConfig, DisconnectReason,
MessageTarget, ProtocolError, ServerActivity, ServerSnapshot, MessageTarget, PokeStrength, ProtocolError, ServerActivity, ServerSnapshot,
}; };
pub use chanora_storage::{Bookmark, BookmarkRepository, IdentityFileStore}; pub use chanora_storage::{Bookmark, BookmarkRepository, IdentityFileStore};
pub use events::{
/// Privacy-safe snapshot of the active PTT capability. NetworkState, PersistedPttBinding, PttDescriptorSnapshot, SessionEvent, VoiceJoinErrorCode,
#[derive(Debug, Clone, PartialEq, Eq)] VoiceJoinSyncState,
pub struct PttDescriptorSnapshot { };
/// Stable capability level name. pub use file_transfer::FileTransferError;
pub level: String, use network_diagnostics::NetworkDiagnostics;
/// Stable backend identifier.
pub backend_id: String,
/// Coarse bound input class; empty when no binding is active.
pub bound_input_class: String,
}
impl From<PttBackendDescriptor> for PttDescriptorSnapshot {
fn from(desc: PttBackendDescriptor) -> Self {
Self {
level: desc.level.as_str().to_string(),
backend_id: desc.backend_id.to_string(),
bound_input_class: desc.bound_input_class.unwrap_or("").to_string(),
}
}
}
/// Persisted PTT binding state exposed to callers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PersistedPttBinding {
/// Stable input category string (`""`, `"keyboard"`, or
/// `"mouse-side-button"`).
pub input_class: String,
/// Display-only key label; empty when no binding is active.
pub key_label: String,
}
impl PersistedPttBinding {
fn empty() -> Self {
Self {
input_class: String::new(),
key_label: String::new(),
}
}
}
/// Errors that can arise during top-level orchestration. /// Errors that can arise during top-level orchestration.
#[derive(Debug, Error)] #[derive(Debug, Error)]
@@ -125,6 +94,12 @@ pub enum CoreError {
/// Storage error. /// Storage error.
#[error("storage: {0}")] #[error("storage: {0}")]
Storage(#[from] chanora_storage::StorageError), Storage(#[from] chanora_storage::StorageError),
/// Blob-cache failure.
#[error("cache: {0}")]
Cache(#[from] chanora_cache::BlobCacheError),
/// File-transfer failure.
#[error("file transfer: {0}")]
FileTransfer(#[from] FileTransferError),
/// Diagnostics error. /// Diagnostics error.
#[error("diagnostics: {0}")] #[error("diagnostics: {0}")]
Diagnostics(#[from] chanora_diagnostics::DiagnosticsError), Diagnostics(#[from] chanora_diagnostics::DiagnosticsError),
@@ -147,291 +122,11 @@ pub enum CoreError {
Ptt(#[from] ptt::PttControllerError), Ptt(#[from] ptt::PttControllerError),
} }
/// High-level lifecycle event surfaced to subscribers.
///
/// This is the minimal set needed for A.6 (reconnect banner). The
/// full event catalogue lands in A.4.
#[derive(Debug, Clone)]
pub enum SessionEvent {
/// Initial connect succeeded, or reconnect attempt succeeded.
Connected {
/// Server name reported in the snapshot.
server_name: String,
},
/// Connection lost; the supervisor will retry.
Lost {
/// Reason classification from the protocol layer.
reason: String,
},
/// Supervisor is sleeping before its next reconnect attempt.
Reconnecting {
/// 1-based attempt counter for the current outage.
attempt: u32,
/// Seconds the supervisor will sleep before this attempt.
delay_secs: u32,
},
/// Supervisor gave up after `attempt` failed retries (or the
/// user explicitly disconnected mid-outage).
Disconnected {
/// Reason classification from the protocol layer.
reason: String,
},
/// Audio engine started (e.g. after a successful reconnect with
/// reattachment).
AudioStarted,
/// Audio engine stopped (e.g. before a reconnect cycle, or by
/// explicit user action).
AudioStopped,
/// Detected desktop Push-to-Talk capability (gen2 v0.9.3 /
/// DEC-023..028). Published when the audio engine starts or
/// when the active backend transitions (for example macOS
/// permission state change). Carries only the privacy-safe
/// descriptor — capability level, backend identifier, bound
/// input class — per SRS-202 / DEC-027.
PttCapability {
/// Stable level name from `PttCapabilityLevel::as_str()`.
level: String,
/// Stable backend identifier (e.g. `"focused"`).
backend_id: String,
/// Coarse bound input class (e.g. `"keyboard"`); empty when
/// no binding is active.
bound_input_class: String,
},
/// Voice subsystem state snapshot (SDD-094). Emitted on
/// `voice_join` / `voice_leave`, transmit-mode changes,
/// hard-mute toggles, and release-tail edits.
VoiceState {
/// True when the user has joined a voice channel via
/// `voice_join` and the audio engine is running.
in_channel: bool,
/// Active transmit mode encoded as
/// [`chanora_audio::TransmitMode::as_u8`].
transmit_mode: u8,
/// True when the hard-mute clamp is engaged.
mute: bool,
/// Current release-tail in milliseconds (0..=500).
release_tail_ms: u32,
/// Last confirmed authoritative channel id from the
/// `channel_join` reducer projection.
current_channel_id: Option<u64>,
/// Non-authoritative pending target channel id from the
/// reducer projection.
pending_target_channel_id: Option<u64>,
/// Whether the reducer currently allows a new join intent.
can_join: bool,
/// Whether the reducer currently allows leave intent.
can_leave: bool,
/// Join projection synchronization state.
join_sync_state: VoiceJoinSyncState,
/// Last stable sanitized join error code, if any.
join_error_code: Option<VoiceJoinErrorCode>,
},
/// iOS audio-session interruption state (SDD-101). Emitted when
/// interruption begins and when it ends (with the platform hint
/// indicating whether audio should resume).
InterruptionState {
/// True when interruption began, false when interruption ended.
began: bool,
/// Platform-provided resume hint. For begin events this is false.
should_resume: bool,
},
/// A text message was received from the server.
ChatMessage {
/// Client id of the sender.
sender_id: u64,
/// Nickname of the sender.
sender_name: String,
/// Message content.
message: String,
/// Target scope (server/channel/private/poke).
target: MessageTarget,
},
/// Human-readable TeamSpeak-style server activity.
ServerActivity {
/// Activity line text.
message: String,
},
/// Audio route changed (speaker/earpiece/BT/wired headset).
AudioRouteChanged {
/// New audio output route.
route: AudioRoute,
},
/// A client moved to a different channel.
ClientMoved {
/// Unique client identifier.
client_id: u64,
/// Destination channel.
new_channel_id: u64,
},
/// A new client connected.
ClientJoined {
/// Unique client identifier.
client_id: u64,
/// Channel the client joined.
channel_id: u64,
/// Display nickname.
name: String,
/// Microphone muted state.
input_muted: bool,
/// Speaker muted state.
output_muted: bool,
/// Whether this is a server query (bot) client.
is_server_query: bool,
/// Client's talk power value.
talk_power: i32,
/// Whether the server granted temporary talk power.
talk_power_granted: bool,
},
/// A client disconnected.
ClientLeft {
/// Unique client identifier.
client_id: u64,
/// Display nickname at time of disconnect.
name: String,
},
/// Client properties changed.
ClientUpdated {
/// Unique client identifier.
client_id: u64,
/// Microphone muted state.
input_muted: bool,
/// Speaker muted state.
output_muted: bool,
/// Whether this is a server query (bot) client.
is_server_query: bool,
/// Client's talk power value.
talk_power: i32,
/// Whether the server granted temporary talk power.
talk_power_granted: bool,
},
/// A new channel appeared.
ChannelAdded {
/// Unique channel identifier.
id: u64,
/// Parent channel ID.
parent: u64,
/// Channel name.
name: String,
/// Predecessor channel ID within the same parent (TeamSpeak
/// linked-list ordering hint). Zero means first child.
order: i64,
/// Whether the channel requires a password.
has_password: bool,
/// Talk power required to speak, or `None` when unrestricted.
needed_talk_power: Option<i32>,
},
/// A channel was deleted.
ChannelRemoved {
/// Channel identifier.
id: u64,
},
/// Channel properties changed.
ChannelUpdated {
/// Unique channel identifier.
id: u64,
/// Channel name.
name: String,
/// Whether the channel requires a password.
has_password: bool,
/// Talk power required to speak, or `None` when unrestricted.
needed_talk_power: Option<i32>,
},
}
/// Bridge-safe mirror of channel-join projection sync state.
#[derive(Debug, Clone, Copy)]
pub enum VoiceJoinSyncState {
/// Reducer is ready to accept channel actions.
Ready,
/// Reducer is synchronizing against an initial snapshot.
SynchronizingInitialSnapshot,
/// Reducer is synchronizing after reconnect.
SynchronizingReconnect,
}
/// Bridge-safe mirror of stable channel-join error codes.
#[derive(Debug, Clone, Copy)]
pub enum VoiceJoinErrorCode {
/// Duplicate same-target join intent was coalesced.
DuplicateSameTargetCoalesced,
/// A different target was requested while one is already pending.
JoinAlreadyPendingDifferentTarget,
/// Join denied by server policy/permission.
JoinDenied,
/// Join failed due to protocol-level error.
JoinProtocolFailure,
/// Join failed due to transport/network error.
JoinNetworkFailure,
/// Join timed out awaiting confirmation.
JoinTimeout,
/// Pending join was superseded by user leave.
JoinSupersededByLeave,
/// Stale join outcome was ignored.
JoinStaleOutcomeIgnored,
/// Authoritative membership reconciled to different channel.
JoinReconciledDifferentChannel,
/// Join command was rejected before send acceptance.
JoinCommandRejectedBeforeSend,
/// Join intent rejected while reducer synchronizing.
JoinCannotStartWhileSynchronizing,
}
/// Coarse OS-reported network state. Populated by the Flutter side
/// via `connectivity_plus`; on platforms where no signal is wired
/// we stay at `Unknown` forever and the supervisor falls back to
/// pure watchdog/backoff behaviour.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkState {
/// No signal seen yet — treat as ambiguous; don't change behaviour.
Unknown,
/// OS reports at least one network with internet capability.
Online,
/// OS reports no networks available.
Offline,
}
/// Channel capacity for the broadcast events. Generous because /// Channel capacity for the broadcast events. Generous because
/// reconnect cycles emit several events per attempt; if subscribers /// reconnect cycles emit several events per attempt; if subscribers
/// fall behind we'd rather skip than block the supervisor. /// fall behind we'd rather skip than block the supervisor.
const EVENT_CHANNEL_CAPACITY: usize = 64; const EVENT_CHANNEL_CAPACITY: usize = 64;
/// Network diagnostics snapshot collected across connection lifetimes.
#[derive(Debug, Clone, Default)]
struct NetworkDiagnostics {
/// Total count of connects (including the initial one).
connect_count: u64,
/// Count of disconnects (graceful + loss).
disconnect_count: u64,
/// Recent loss reasons (last 8, ring buffer).
loss_reasons: Vec<String>,
}
impl NetworkDiagnostics {
fn record_connect(&mut self) {
self.connect_count = self.connect_count.saturating_add(1);
}
fn record_loss(&mut self, reason: &str) {
self.disconnect_count = self.disconnect_count.saturating_add(1);
if self.loss_reasons.len() >= 8 {
self.loss_reasons.remove(0);
}
self.loss_reasons.push(reason.to_string());
}
fn summary(&self) -> String {
let mut s = format!(
"connects: {}\ndisconnects: {}\n",
self.connect_count, self.disconnect_count
);
if !self.loss_reasons.is_empty() {
s.push_str(&format!(
"loss_reasons: [{}]\n",
self.loss_reasons.join(", ")
));
}
s
}
}
struct SupervisorInner { struct SupervisorInner {
/// Optional cached AudioEngineConfig — set when start_audio is /// Optional cached AudioEngineConfig — set when start_audio is
/// first called, used to re-create the engine after a reconnect. /// first called, used to re-create the engine after a reconnect.
@@ -443,7 +138,6 @@ struct SupervisorInner {
} }
struct ConnectedState { struct ConnectedState {
protocol: chanora_protocol::ProtocolClient,
audio: Option<chanora_audio::AudioEngine>, audio: Option<chanora_audio::AudioEngine>,
/// Active PTT controller (SDD-088). Owns the platform input /// Active PTT controller (SDD-088). Owns the platform input
/// backend, the active binding, and the capability watch /// backend, the active binding, and the capability watch
@@ -477,12 +171,20 @@ struct ConnectedState {
local_output_muted: bool, local_output_muted: bool,
} }
async fn take_disconnect_state<T>(inner: &Arc<Mutex<Option<T>>>) -> Option<T> {
inner.lock().await.take()
}
fn normalize_channel_password(password: Option<String>) -> Option<String> { fn normalize_channel_password(password: Option<String>) -> Option<String> {
password password
.map(|p| p.trim().to_string()) .map(|p| p.trim().to_string())
.filter(|p| !p.is_empty()) .filter(|p| !p.is_empty())
} }
fn should_dispatch_text_message(message: &str, target: &MessageTarget) -> bool {
!message.trim().is_empty() || matches!(target, MessageTarget::Poke(_))
}
/// The top-level Chanora session. Owns at most one active server /// The top-level Chanora session. Owns at most one active server
/// connection (DEC-006). /// connection (DEC-006).
#[derive(Clone)] #[derive(Clone)]
@@ -502,6 +204,8 @@ pub struct ChanoraSession {
/// extension). Lives alongside the identity file. Wired by /// extension). Lives alongside the identity file. Wired by
/// [`Self::init_storage`]. /// [`Self::init_storage`].
bookmark_store: Arc<Mutex<Option<BookmarkRepository>>>, bookmark_store: Arc<Mutex<Option<BookmarkRepository>>>,
protocol: Arc<Mutex<Option<chanora_protocol::ProtocolClient>>>,
file_transfer: Arc<Mutex<Option<Arc<file_transfer::FileTransferService>>>>,
/// Invisible server-address prefetch cache. Warmed by Flutter typing /// Invisible server-address prefetch cache. Warmed by Flutter typing
/// but validated by Rust before Connect can reuse it. /// but validated by Rust before Connect can reuse it.
server_prefetch: ServerPrefetcher, server_prefetch: ServerPrefetcher,
@@ -557,6 +261,8 @@ impl ChanoraSession {
network_tx, network_tx,
identity_store: Arc::new(Mutex::new(None)), identity_store: Arc::new(Mutex::new(None)),
bookmark_store: Arc::new(Mutex::new(None)), bookmark_store: Arc::new(Mutex::new(None)),
protocol: Arc::new(Mutex::new(None)),
file_transfer: Arc::new(Mutex::new(None)),
server_prefetch: ServerPrefetcher::new(), server_prefetch: ServerPrefetcher::new(),
voice_selector: selector, voice_selector: selector,
release_tail, release_tail,
@@ -578,6 +284,17 @@ impl ChanoraSession {
ConnectionEpoch(epoch) ConnectionEpoch(epoch)
} }
async fn store_protocol(&self, client: Option<chanora_protocol::ProtocolClient>) {
// Always update the shared Arc. The FileTransferService holds
// the same Arc, so it sees the new client automatically — no
// separate set_protocol call needed.
*self.protocol.lock().await = client;
}
async fn take_protocol(&self) -> Option<chanora_protocol::ProtocolClient> {
self.protocol.lock().await.take()
}
/// Wire a directory-backed identity store. Called by the bridge /// Wire a directory-backed identity store. Called by the bridge
/// during `bridge_init` once Flutter has resolved the platform /// during `bridge_init` once Flutter has resolved the platform
/// app-private storage directory. Subsequent [`Self::connect`] /// app-private storage directory. Subsequent [`Self::connect`]
@@ -642,6 +359,65 @@ impl ChanoraSession {
Ok(()) Ok(())
} }
/// Configure the blob cache root.
pub async fn init_cache(&self, dir: &str) -> Result<(), CoreError> {
let cache = chanora_cache::BlobCache::new(dir, 100 * 1024 * 1024)?;
cache.evict().await?;
let service = Arc::new(file_transfer::FileTransferService::new(
cache,
self.protocol.clone(),
));
let mut guard = self.file_transfer.lock().await;
*guard = Some(service);
Ok(())
}
/// Resolve avatar bytes.
pub async fn get_avatar(
&self,
avatar_hash: &str,
client_uid: &str,
) -> Result<Option<Vec<u8>>, CoreError> {
let service = { self.file_transfer.lock().await.clone() };
if let Some(service) = service {
return Ok(service.get_avatar(avatar_hash, client_uid).await?);
}
let protocol = self.protocol.lock().await;
let client = protocol.as_ref().ok_or(CoreError::NotConnected)?;
Ok(Some(client.download_avatar(client_uid).await?))
}
/// Resolve icon bytes.
pub async fn get_icon(&self, icon_id: u64) -> Result<Option<Vec<u8>>, CoreError> {
let service = { self.file_transfer.lock().await.clone() };
if let Some(service) = service {
return Ok(service.get_icon(icon_id).await?);
}
let protocol = self.protocol.lock().await;
let client = protocol.as_ref().ok_or(CoreError::NotConnected)?;
Ok(Some(client.download_icon(icon_id).await?))
}
/// Purge cached protocol-owned assets.
pub async fn clear_cache(&self) -> Result<(), CoreError> {
let service = { self.file_transfer.lock().await.clone() };
if let Some(service) = service {
service.clear_cache().await?;
}
Ok(())
}
/// Report the configured blob-cache size.
pub async fn cache_size(&self) -> Result<u64, CoreError> {
let service = { self.file_transfer.lock().await.clone() };
match service {
Some(service) => Ok(service.cache_size().await?),
None => Ok(0),
}
}
/// List persisted bookmarks. Returns an empty list if the store /// List persisted bookmarks. Returns an empty list if the store
/// has not been wired or has no entries. /// has not been wired or has no entries.
pub async fn list_bookmarks(&self) -> Result<Vec<Bookmark>, CoreError> { pub async fn list_bookmarks(&self) -> Result<Vec<Bookmark>, CoreError> {
@@ -819,6 +595,7 @@ impl ChanoraSession {
let supervisor = tokio::spawn(supervisor_loop(SupervisorContext { let supervisor = tokio::spawn(supervisor_loop(SupervisorContext {
state_arc: self.inner.clone(), state_arc: self.inner.clone(),
protocol: self.protocol.clone(),
events_tx: self.events_tx.clone(), events_tx: self.events_tx.clone(),
initial_cfg: cfg.clone(), initial_cfg: cfg.clone(),
initial_lost_rx: lost_rx, initial_lost_rx: lost_rx,
@@ -873,9 +650,9 @@ impl ChanoraSession {
} }
spawn_event_forwarders(&client, &self.events_tx); spawn_event_forwarders(&client, &self.events_tx);
self.store_protocol(Some(client)).await;
*guard = Some(ConnectedState { *guard = Some(ConnectedState {
protocol: client,
audio: None, audio: None,
ptt_controller: None, ptt_controller: None,
cancel_tx: Some(cancel_tx), cancel_tx: Some(cancel_tx),
@@ -936,9 +713,13 @@ impl ChanoraSession {
/// Return a fresh snapshot of the current server state. /// Return a fresh snapshot of the current server state.
pub async fn snapshot(&self) -> Result<ServerSnapshot, CoreError> { pub async fn snapshot(&self) -> Result<ServerSnapshot, CoreError> {
let snap = {
let protocol = self.protocol.lock().await;
let client = protocol.as_ref().ok_or(CoreError::NotConnected)?;
client.snapshot().await?
};
let mut guard = self.inner.lock().await; let mut guard = self.inner.lock().await;
let state = guard.as_mut().ok_or(CoreError::NotConnected)?; let state = guard.as_mut().ok_or(CoreError::NotConnected)?;
let snap = state.protocol.snapshot().await?;
let current_channel = self let current_channel = self
.find_own_in(&snap) .find_own_in(&snap)
.await .await
@@ -966,9 +747,9 @@ impl ChanoraSession {
/// Fetch richer profile and live connection details for one online client. /// Fetch richer profile and live connection details for one online client.
pub async fn client_profile(&self, client_id: u64) -> Result<ClientProfile, CoreError> { pub async fn client_profile(&self, client_id: u64) -> Result<ClientProfile, CoreError> {
let guard = self.inner.lock().await; let protocol = self.protocol.lock().await;
let state = guard.as_ref().ok_or(CoreError::NotConnected)?; let client = protocol.as_ref().ok_or(CoreError::NotConnected)?;
Ok(state.protocol.client_profile(client_id).await?) Ok(client.client_profile(client_id).await?)
} }
/// True if a connection is currently active. /// True if a connection is currently active.
@@ -982,12 +763,12 @@ impl ChanoraSession {
message: String, message: String,
target: MessageTarget, target: MessageTarget,
) -> Result<(), CoreError> { ) -> Result<(), CoreError> {
if message.trim().is_empty() { if !should_dispatch_text_message(&message, &target) {
return Ok(()); return Ok(());
} }
let guard = self.inner.lock().await; let protocol = self.protocol.lock().await;
let state = guard.as_ref().ok_or(CoreError::NotConnected)?; let client = protocol.as_ref().ok_or(CoreError::NotConnected)?;
state.protocol.send_text_message(message, target).await?; client.send_text_message(message, target).await?;
Ok(()) Ok(())
} }
@@ -1046,11 +827,16 @@ impl ChanoraSession {
// session permanently unable to restart audio without a // session permanently unable to restart audio without a
// reconnect (the user saw "voice_in already taken" on the // reconnect (the user saw "voice_in already taken" on the
// second channel switch). // second channel switch).
let voice_out = state.protocol.voice_out(); let (voice_out, voice_in) = {
let voice_in = state let protocol = self.protocol.lock().await;
.protocol let client = protocol.as_ref().ok_or(CoreError::NotConnected)?;
.take_voice_in() (
.ok_or(CoreError::Invariant("voice_in already taken"))?; client.voice_out(),
client
.take_voice_in()
.ok_or(CoreError::Invariant("voice_in already taken"))?,
)
};
let gate = AudioTransmitGate::new(cfg.ptt_initial); let gate = AudioTransmitGate::new(cfg.ptt_initial);
cfg.voice_activity_selector = Some(self.voice_selector.clone()); cfg.voice_activity_selector = Some(self.voice_selector.clone());
let new_engine = match chanora_audio::AudioEngine::start_with_gate( let new_engine = match chanora_audio::AudioEngine::start_with_gate(
@@ -1281,10 +1067,11 @@ impl ChanoraSession {
let password_to_send = requested_password let password_to_send = requested_password
.clone() .clone()
.or_else(|| state.channel_passwords.get(&channel_id).cloned()); .or_else(|| state.channel_passwords.get(&channel_id).cloned());
state {
.protocol let protocol = self.protocol.lock().await;
.move_to_channel(channel_id, password_to_send) let client = protocol.as_ref().ok_or(CoreError::NotConnected)?;
.await?; client.move_to_channel(channel_id, password_to_send).await?;
}
if let Some(pw) = requested_password { if let Some(pw) = requested_password {
state.channel_passwords.insert(channel_id, pw); state.channel_passwords.insert(channel_id, pw);
} }
@@ -1309,7 +1096,11 @@ impl ChanoraSession {
if let Some(muted) = output { if let Some(muted) = output {
state.local_output_muted = muted; state.local_output_muted = muted;
} }
state.protocol.set_muted(input, output).await?; {
let protocol = self.protocol.lock().await;
let client = protocol.as_ref().ok_or(CoreError::NotConnected)?;
client.set_muted(input, output).await?;
}
if let Some(muted) = output { if let Some(muted) = output {
if let Some(audio) = state.audio.as_ref() { if let Some(audio) = state.audio.as_ref() {
audio.set_output_muted(muted); audio.set_output_muted(muted);
@@ -1421,11 +1212,19 @@ impl ChanoraSession {
/// Configure the preferred Silero ONNX VAD model path on platforms /// Configure the preferred Silero ONNX VAD model path on platforms
/// that ship the ONNX detector. /// that ship the ONNX detector.
/// ///
/// This does not require an active connection. Running non-iOS /// Set the Silero VAD model path on supported platforms.
/// audio backends can observe the model-path epoch and reload on ///
/// the next capture frame when Silero is selected. /// This does not require an active connection. On desktop, the audio
/// engine immediately reloads the Silero ONNX worker if one is active
/// or if the model file is now available at the new path.
pub async fn set_vad_model_path(&self, path: String) -> Result<(), CoreError> { pub async fn set_vad_model_path(&self, path: String) -> Result<(), CoreError> {
chanora_audio::vad::set_silero_model_path(&path)?; chanora_audio::vad::set_silero_model_path(&path)?;
let guard = self.inner.lock().await;
if let Some(state) = guard.as_ref() {
if let Some(audio) = state.audio.as_ref() {
audio.reload_audio_processing_config()?;
}
}
Ok(()) Ok(())
} }
@@ -1624,11 +1423,12 @@ impl ChanoraSession {
let password_to_send = requested_password let password_to_send = requested_password
.clone() .clone()
.or_else(|| state.channel_passwords.get(&channel_id).cloned()); .or_else(|| state.channel_passwords.get(&channel_id).cloned());
if let Err(e) = state let move_result = {
.protocol let protocol = self.protocol.lock().await;
.queue_move_to_channel(channel_id, password_to_send) let client = protocol.as_ref().ok_or(CoreError::NotConnected)?;
.await client.queue_move_to_channel(channel_id, password_to_send).await
{ };
if let Err(e) = move_result {
// TS3 error 0x0302 = `channel_already_in`: we're already // TS3 error 0x0302 = `channel_already_in`: we're already
// in the target channel, so this is a no-op success. // in the target channel, so this is a no-op success.
// Rolling `in_channel` back to false would break PTT // Rolling `in_channel` back to false would break PTT
@@ -1878,8 +1678,7 @@ impl ChanoraSession {
/// Disconnect from the server. No-op if not connected. /// Disconnect from the server. No-op if not connected.
pub async fn disconnect(&self) -> Result<(), CoreError> { pub async fn disconnect(&self) -> Result<(), CoreError> {
let mut guard = self.inner.lock().await; if let Some(mut state) = take_disconnect_state(&self.inner).await {
if let Some(mut state) = guard.take() {
// Signal the supervisor to exit (cancels any backoff sleep). // Signal the supervisor to exit (cancels any backoff sleep).
if let Some(tx) = state.cancel_tx.take() { if let Some(tx) = state.cancel_tx.take() {
let _ = tx.send(()); let _ = tx.send(());
@@ -1891,11 +1690,13 @@ impl ChanoraSession {
audio.stop(); audio.stop();
let _ = self.events_tx.send(SessionEvent::AudioStopped); let _ = self.events_tx.send(SessionEvent::AudioStopped);
} }
state.protocol.disconnect().await; if let Some(protocol) = self.take_protocol().await {
protocol.disconnect().await;
}
// Wait for the supervisor to wind down so we don't race // Wait for the supervisor to wind down so we don't race
// a redial against the explicit disconnect. // a redial against the explicit disconnect.
if let Some(handle) = state.supervisor.take() { if let Some(handle) = state.supervisor.take() {
let _ = handle.await; await_supervisor_shutdown(handle, SUPERVISOR_SHUTDOWN_TIMEOUT).await;
} }
let _ = self.events_tx.send(SessionEvent::Disconnected { let _ = self.events_tx.send(SessionEvent::Disconnected {
reason: "user requested".to_string(), reason: "user requested".to_string(),
@@ -1934,9 +1735,26 @@ const WATCHDOG_PROBE_TIMEOUT: Duration = Duration::from_secs(4);
/// Number of consecutive watchdog failures before the supervisor /// Number of consecutive watchdog failures before the supervisor
/// declares the connection lost. /// declares the connection lost.
const WATCHDOG_MAX_MISSES: u32 = 3; const WATCHDOG_MAX_MISSES: u32 = 3;
const SUPERVISOR_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(1);
async fn await_supervisor_shutdown(mut handle: JoinHandle<()>, timeout_duration: Duration) {
if tokio::time::timeout(timeout_duration, &mut handle)
.await
.is_err()
{
warn!(
target: "chanora_core",
timeout_ms = timeout_duration.as_millis() as u64,
"supervisor did not stop before shutdown timeout"
);
handle.abort();
let _ = handle.await;
}
}
struct SupervisorContext { struct SupervisorContext {
state_arc: Arc<Mutex<Option<ConnectedState>>>, state_arc: Arc<Mutex<Option<ConnectedState>>>,
protocol: Arc<Mutex<Option<chanora_protocol::ProtocolClient>>>,
events_tx: broadcast::Sender<SessionEvent>, events_tx: broadcast::Sender<SessionEvent>,
initial_cfg: ConnectConfig, initial_cfg: ConnectConfig,
initial_lost_rx: oneshot::Receiver<chanora_protocol::DisconnectReason>, initial_lost_rx: oneshot::Receiver<chanora_protocol::DisconnectReason>,
@@ -1968,6 +1786,7 @@ fn spawn_event_forwarders(
sender_name: msg.sender_name, sender_name: msg.sender_name,
message: msg.message, message: msg.message,
target: msg.target, target: msg.target,
poke_strength: msg.poke_strength,
}); });
} }
}); });
@@ -1989,27 +1808,77 @@ fn spawn_event_forwarders(
let mut rx = delta_rx; let mut rx = delta_rx;
while let Some(delta) = rx.recv().await { while let Some(delta) = rx.recv().await {
let event = match delta { let event = match delta {
ProtocolDelta::ClientMoved { client_id, new_channel_id } => { ProtocolDelta::ClientMoved {
SessionEvent::ClientMoved { client_id, new_channel_id } client_id,
} new_channel_id,
ProtocolDelta::ClientJoined { client_id, channel_id, name, input_muted, output_muted, is_server_query, talk_power, talk_power_granted } => { } => SessionEvent::ClientMoved {
SessionEvent::ClientJoined { client_id, channel_id, name, input_muted, output_muted, is_server_query, talk_power, talk_power_granted } client_id,
} new_channel_id,
},
ProtocolDelta::ClientJoined {
client_id,
channel_id,
name,
input_muted,
output_muted,
is_server_query,
talk_power,
talk_power_granted,
} => SessionEvent::ClientJoined {
client_id,
channel_id,
name,
input_muted,
output_muted,
is_server_query,
talk_power,
talk_power_granted,
},
ProtocolDelta::ClientLeft { client_id, name } => { ProtocolDelta::ClientLeft { client_id, name } => {
SessionEvent::ClientLeft { client_id, name } SessionEvent::ClientLeft { client_id, name }
} }
ProtocolDelta::ClientUpdated { client_id, input_muted, output_muted, is_server_query, talk_power, talk_power_granted } => { ProtocolDelta::ClientUpdated {
SessionEvent::ClientUpdated { client_id, input_muted, output_muted, is_server_query, talk_power, talk_power_granted } client_id,
} input_muted,
ProtocolDelta::ChannelAdded { id, parent, name, order, has_password, needed_talk_power } => { output_muted,
SessionEvent::ChannelAdded { id, parent, name, order, has_password, needed_talk_power } is_server_query,
} talk_power,
ProtocolDelta::ChannelRemoved { id } => { talk_power_granted,
SessionEvent::ChannelRemoved { id } } => SessionEvent::ClientUpdated {
} client_id,
ProtocolDelta::ChannelUpdated { id, name, has_password, needed_talk_power } => { input_muted,
SessionEvent::ChannelUpdated { id, name, has_password, needed_talk_power } output_muted,
} is_server_query,
talk_power,
talk_power_granted,
},
ProtocolDelta::ChannelAdded {
id,
parent,
name,
order,
has_password,
needed_talk_power,
} => SessionEvent::ChannelAdded {
id,
parent,
name,
order,
has_password,
needed_talk_power,
},
ProtocolDelta::ChannelRemoved { id } => SessionEvent::ChannelRemoved { id },
ProtocolDelta::ChannelUpdated {
id,
name,
has_password,
needed_talk_power,
} => SessionEvent::ChannelUpdated {
id,
name,
has_password,
needed_talk_power,
},
}; };
let _ = ev_tx.send(event); let _ = ev_tx.send(event);
} }
@@ -2020,6 +1889,7 @@ fn spawn_event_forwarders(
async fn supervisor_loop(ctx: SupervisorContext) { async fn supervisor_loop(ctx: SupervisorContext) {
let SupervisorContext { let SupervisorContext {
state_arc, state_arc,
protocol,
events_tx, events_tx,
initial_cfg, initial_cfg,
initial_lost_rx, initial_lost_rx,
@@ -2289,20 +2159,21 @@ async fn supervisor_loop(ctx: SupervisorContext) {
// Reattach into the session state. // Reattach into the session state.
let restart_audio = { let restart_audio = {
let guard = state_arc.lock().await;
if guard.is_none() {
// Session was disposed mid-reconnect.
return;
}
drop(guard);
let old = protocol.lock().await.replace(new_client);
drop(old);
let mut guard = state_arc.lock().await; let mut guard = state_arc.lock().await;
let state = match guard.as_mut() { let state = match guard.as_mut() {
Some(s) => s, Some(s) => s,
None => { None => {
// Session was disposed mid-reconnect.
return; return;
} }
}; };
// Replace the dead protocol client with the new one.
// The old client's background task either already
// exited (loss notifier fired) or will exit when
// its request channel drops (watchdog path).
let old = std::mem::replace(&mut state.protocol, new_client);
drop(old);
let _ = channel_join::reduce( let _ = channel_join::reduce(
&mut state.join_state, &mut state.join_state,
@@ -2332,9 +2203,9 @@ async fn supervisor_loop(ctx: SupervisorContext) {
}); });
{ {
let guard = state_arc.lock().await; let protocol = protocol.lock().await;
if let Some(state) = guard.as_ref() { if let Some(client) = protocol.as_ref() {
spawn_event_forwarders(&state.protocol, &events_tx); spawn_event_forwarders(client, &events_tx);
} }
} }
@@ -2346,8 +2217,15 @@ async fn supervisor_loop(ctx: SupervisorContext) {
}; };
let mut guard = state_arc.lock().await; let mut guard = state_arc.lock().await;
if let Some(state) = guard.as_mut() { if let Some(state) = guard.as_mut() {
let voice_out = state.protocol.voice_out(); let (voice_out, voice_in) = {
if let Some(voice_in) = state.protocol.take_voice_in() { let protocol = protocol.lock().await;
let client = match protocol.as_ref() {
Some(client) => client,
None => return,
};
(client.voice_out(), client.take_voice_in())
};
if let Some(voice_in) = voice_in {
let gate = chanora_audio::AudioTransmitGate::new( let gate = chanora_audio::AudioTransmitGate::new(
audio_cfg.ptt_initial, audio_cfg.ptt_initial,
); );
@@ -2633,6 +2511,54 @@ mod tests {
s.disconnect().await.unwrap(); s.disconnect().await.unwrap();
} }
#[tokio::test]
async fn disconnect_state_take_releases_inner_lock_before_teardown() {
let inner = Arc::new(Mutex::new(Some(())));
let state = super::take_disconnect_state(&inner).await;
assert_eq!(state, Some(()));
assert!(inner.try_lock().is_ok());
}
#[tokio::test]
async fn supervisor_join_returns_after_shutdown_timeout() {
let handle = tokio::spawn(async {
std::future::pending::<()>().await;
});
let start = std::time::Instant::now();
super::await_supervisor_shutdown(handle, Duration::from_millis(10)).await;
assert!(start.elapsed() < Duration::from_millis(100));
}
#[tokio::test]
async fn supervisor_shutdown_timeout_aborts_pending_task() {
struct DropNotice(Option<tokio::sync::oneshot::Sender<()>>);
impl Drop for DropNotice {
fn drop(&mut self) {
if let Some(tx) = self.0.take() {
let _ = tx.send(());
}
}
}
let (dropped_tx, dropped_rx) = tokio::sync::oneshot::channel();
let handle = tokio::spawn(async move {
let _notice = DropNotice(Some(dropped_tx));
std::future::pending::<()>().await;
});
super::await_supervisor_shutdown(handle, Duration::from_millis(10)).await;
tokio::time::timeout(Duration::from_millis(100), dropped_rx)
.await
.expect("pending supervisor task should be aborted")
.expect("drop notice should be delivered");
}
#[test] #[test]
fn signature_detects_in_channel_move() { fn signature_detects_in_channel_move() {
use chanora_protocol::{ChannelInfo, ClientInfo}; use chanora_protocol::{ChannelInfo, ClientInfo};
@@ -2730,6 +2656,38 @@ mod tests {
); );
} }
#[test]
fn empty_poke_messages_are_dispatchable() {
assert!(super::should_dispatch_text_message(
"",
&MessageTarget::Poke(42)
));
assert!(super::should_dispatch_text_message(
" \t ",
&MessageTarget::Poke(42)
));
}
#[test]
fn empty_non_poke_messages_remain_suppressed() {
assert!(!super::should_dispatch_text_message(
"",
&MessageTarget::Server
));
assert!(!super::should_dispatch_text_message(
" ",
&MessageTarget::Channel
));
assert!(!super::should_dispatch_text_message(
"",
&MessageTarget::Client(42)
));
assert!(super::should_dispatch_text_message(
"hello",
&MessageTarget::Channel
));
}
#[tokio::test] #[tokio::test]
async fn empty_address_is_rejected() { async fn empty_address_is_rejected() {
let s = ChanoraSession::new(); let s = ChanoraSession::new();
@@ -0,0 +1,72 @@
use std::collections::VecDeque;
/// Network diagnostics snapshot collected across connection lifetimes.
#[derive(Debug, Clone, Default)]
pub(crate) struct NetworkDiagnostics {
/// Total count of connects (including the initial one).
connect_count: u64,
/// Count of disconnects (graceful + loss).
disconnect_count: u64,
/// Recent loss reasons (last 8, ring buffer).
loss_reasons: VecDeque<String>,
}
impl NetworkDiagnostics {
pub(crate) fn record_connect(&mut self) {
self.connect_count = self.connect_count.saturating_add(1);
}
pub(crate) fn record_loss(&mut self, reason: &str) {
self.disconnect_count = self.disconnect_count.saturating_add(1);
if self.loss_reasons.len() >= 8 {
self.loss_reasons.pop_front();
}
self.loss_reasons.push_back(reason.to_string());
}
pub(crate) fn summary(&self) -> String {
let mut s = format!(
"connects: {}\ndisconnects: {}\n",
self.connect_count, self.disconnect_count
);
if !self.loss_reasons.is_empty() {
s.push_str(&format!(
"loss_reasons: [{}]\n",
self.loss_reasons
.iter()
.map(String::as_str)
.collect::<Vec<_>>()
.join(", ")
));
}
s
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn network_diagnostics_keeps_last_eight_loss_reasons() {
let mut diagnostics = NetworkDiagnostics::default();
for i in 0..10 {
diagnostics.record_loss(&format!("loss-{i}"));
}
assert_eq!(diagnostics.disconnect_count, 10);
assert_eq!(diagnostics.loss_reasons.len(), 8);
assert_eq!(
diagnostics.loss_reasons.front().map(String::as_str),
Some("loss-2")
);
assert_eq!(
diagnostics.loss_reasons.back().map(String::as_str),
Some("loss-9")
);
assert!(diagnostics.summary().contains(
"loss_reasons: [loss-2, loss-3, loss-4, loss-5, loss-6, loss-7, loss-8, loss-9]"
));
}
}
+50
View File
@@ -0,0 +1,50 @@
use std::env;
use std::path::PathBuf;
use std::process;
use std::time::{SystemTime, UNIX_EPOCH};
#[tokio::test]
async fn get_avatar_returns_cached_bytes_without_connection() {
let tmp = mktemp("chanora_core_avatar_cache_test");
let session = chanora_core::ChanoraSession::new();
session.init_cache(tmp.to_str().unwrap()).await.unwrap();
let cache = chanora_cache::BlobCache::new(&tmp, 100 * 1024 * 1024).unwrap();
let hash = "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6";
cache
.put(chanora_cache::PREFIX_AVATAR, hash, b"avatar-bytes")
.await
.unwrap();
let bytes = session
.get_avatar(hash, "client-uid")
.await
.unwrap()
.unwrap();
assert_eq!(bytes, b"avatar-bytes");
let _ = std::fs::remove_dir_all(&tmp);
}
#[tokio::test]
async fn get_avatar_without_cache_or_connection_returns_not_connected() {
let session = chanora_core::ChanoraSession::new();
let err = session
.get_avatar("a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", "client-uid")
.await
.unwrap_err();
assert!(matches!(err, chanora_core::CoreError::NotConnected));
}
fn mktemp(label: &str) -> PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let p = env::temp_dir()
.join(label)
.join(format!("{}-{nanos}", process::id()));
std::fs::create_dir_all(&p).unwrap();
p
}
+1 -1
View File
@@ -51,7 +51,7 @@ coreaudio-rs = "0.14"
# on the main queue to avoid the VPIO RPC timeout on iOS simulator. # on the main queue to avoid the VPIO RPC timeout on iOS simulator.
dispatch2 = "0.3" dispatch2 = "0.3"
[target.'cfg(not(target_os = "ios"))'.dependencies] [target.'cfg(not(any(target_os = "ios", target_os = "macos", target_os = "android")))'.dependencies]
ort = { version = "2.0.0-rc.12", default-features = false, features = ["load-dynamic", "ndarray", "api-24"] } ort = { version = "2.0.0-rc.12", default-features = false, features = ["load-dynamic", "ndarray", "api-24"] }
[target.'cfg(target_os = "android")'.dependencies] [target.'cfg(target_os = "android")'.dependencies]
@@ -0,0 +1,124 @@
use std::sync::Arc;
use crossbeam::queue::ArrayQueue;
/// Fixed-capacity PCM handoff from the Android render producer task to
/// the Oboe output callback.
pub(crate) struct AndroidRenderRing {
frames: Arc<ArrayQueue<[f32; 2]>>,
}
impl AndroidRenderRing {
pub(crate) fn new(capacity: usize) -> Self {
Self {
frames: Arc::new(ArrayQueue::new((capacity / 2).max(1))),
}
}
pub(crate) fn producer(&self) -> AndroidRenderRingProducer {
AndroidRenderRingProducer {
frames: Arc::clone(&self.frames),
}
}
pub(crate) fn consumer(&self) -> AndroidRenderRingConsumer {
AndroidRenderRingConsumer {
frames: Arc::clone(&self.frames),
}
}
}
pub(crate) struct AndroidRenderRingProducer {
frames: Arc<ArrayQueue<[f32; 2]>>,
}
impl AndroidRenderRingProducer {
pub(crate) fn push_frame_lossy(&self, samples: &[f32]) {
for frame in samples.chunks_exact(2) {
let stereo_frame = [frame[0], frame[1]];
if self.frames.push(stereo_frame).is_err() {
let _ = self.frames.pop();
let _ = self.frames.push(stereo_frame);
}
}
}
}
pub(crate) struct AndroidRenderRingConsumer {
frames: Arc<ArrayQueue<[f32; 2]>>,
}
impl AndroidRenderRingConsumer {
#[cfg(test)]
pub(crate) fn drain_into_zero_filling(&self, out: &mut [f32]) {
let mut chunks = out.chunks_exact_mut(2);
for frame_out in &mut chunks {
let frame = self.frames.pop().unwrap_or([0.0, 0.0]);
frame_out.copy_from_slice(&frame);
}
for sample in chunks.into_remainder() {
*sample = 0.0;
}
}
pub(crate) fn drain_stereo_into_zero_filling(&self, out: &mut [(f32, f32)]) {
for frame_out in out {
let frame = self.frames.pop().unwrap_or([0.0, 0.0]);
*frame_out = (frame[0], frame[1]);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn producer_drops_oldest_samples_when_ring_is_full() {
let ring = AndroidRenderRing::new(4);
let producer = ring.producer();
let consumer = ring.consumer();
producer.push_frame_lossy(&[1.0, 2.0, 3.0, 4.0]);
producer.push_frame_lossy(&[5.0, 6.0]);
let mut out = [0.0; 4];
consumer.drain_into_zero_filling(&mut out);
assert_eq!(out, [3.0, 4.0, 5.0, 6.0]);
}
#[test]
fn overflow_after_partial_consumer_drain_preserves_stereo_pairing() {
let ring = AndroidRenderRing::new(4);
let producer = ring.producer();
let consumer = ring.consumer();
producer.push_frame_lossy(&[1.0, 10.0, 2.0, 20.0]);
let mut odd_out = [9.0];
consumer.drain_into_zero_filling(&mut odd_out);
assert_eq!(odd_out, [0.0]);
producer.push_frame_lossy(&[3.0, 30.0]);
let mut out = [0.0; 4];
consumer.drain_into_zero_filling(&mut out);
assert_eq!(out, [2.0, 20.0, 3.0, 30.0]);
}
#[test]
fn consumer_zero_fills_tail_on_underrun() {
let ring = AndroidRenderRing::new(4);
let producer = ring.producer();
let consumer = ring.consumer();
producer.push_frame_lossy(&[0.25, -0.25]);
let mut out = [9.0; 4];
consumer.drain_into_zero_filling(&mut out);
assert_eq!(out, [0.25, -0.25, 0.0, 0.0]);
}
}
+305 -298
View File
@@ -53,7 +53,6 @@ use crate::mobile_voice_backend::{
BackendEventTx, EffectEngagement, EffectEngine, InputPresetChoice, MobileVoiceAudioBackend, BackendEventTx, EffectEngagement, EffectEngine, InputPresetChoice, MobileVoiceAudioBackend,
SharingModeChoice, VoiceAudioParams, SharingModeChoice, VoiceAudioParams,
}; };
use chanora_protocol::OutPacket;
use tsclientlib::audio::AudioHandler; use tsclientlib::audio::AudioHandler;
use crate::{engine::SessionAudioId, AudioError}; use crate::{engine::SessionAudioId, AudioError};
@@ -86,40 +85,11 @@ use crate::processor::AudioProcessor;
const RENDER_REF_SLOTS: usize = 4; const RENDER_REF_SLOTS: usize = 4;
const RENDER_REF_SAMPLES: usize = crate::frame::FRAME_10MS_SAMPLES; const RENDER_REF_SAMPLES: usize = crate::frame::FRAME_10MS_SAMPLES;
const ANDROID_RENDER_PULL_SAMPLES: usize = crate::frame::FRAME_20MS_SAMPLES * 2;
const ANDROID_RENDER_RING_CAPACITY: usize = ANDROID_RENDER_PULL_SAMPLES * 5;
struct RenderReferenceBuffer { type RenderReferenceBuffer =
buf: Box<[[f32; RENDER_REF_SAMPLES]; RENDER_REF_SLOTS]>, crate::render_reference::RenderReferenceBuffer<RENDER_REF_SAMPLES, RENDER_REF_SLOTS>;
write_idx: std::sync::atomic::AtomicUsize,
}
impl RenderReferenceBuffer {
fn new() -> Arc<Self> {
Arc::new(Self {
buf: Box::new([[0.0_f32; RENDER_REF_SAMPLES]; RENDER_REF_SLOTS]),
write_idx: std::sync::atomic::AtomicUsize::new(0),
})
}
fn write(&self, frame: &[f32; RENDER_REF_SAMPLES]) {
let idx = self.write_idx.load(Ordering::Relaxed);
unsafe {
let slot = &self.buf[idx] as *const [f32; RENDER_REF_SAMPLES]
as *mut [f32; RENDER_REF_SAMPLES];
(*slot).copy_from_slice(frame);
}
self.write_idx
.store((idx + 1) % RENDER_REF_SLOTS, Ordering::Relaxed);
}
fn read_latest(&self) -> [f32; RENDER_REF_SAMPLES] {
let wi = self.write_idx.load(Ordering::Relaxed);
let ri = (wi + RENDER_REF_SLOTS - 1) % RENDER_REF_SLOTS;
self.buf[ri]
}
}
unsafe impl Send for RenderReferenceBuffer {}
unsafe impl Sync for RenderReferenceBuffer {}
// --- Capture state for Oboe input callback (SDD-111 / SDD-120) ---- // --- Capture state for Oboe input callback (SDD-111 / SDD-120) ----
// //
@@ -138,9 +108,8 @@ struct AndroidCaptureState {
encoder: OpusEncoder, encoder: OpusEncoder,
pcm_accum: Vec<i16>, pcm_accum: Vec<i16>,
opus_out: [u8; crate::opus_voice::MAX_OPUS_FRAME], opus_out: [u8; crate::opus_voice::MAX_OPUS_FRAME],
voice_out_tx: mpsc::Sender<OutPacket>, voice_out_tx: crate::opus_voice::EncodedVoiceFrameSender,
transmit_active: Arc<AtomicBool>, transmit_active: Arc<AtomicBool>,
frames_sent: Arc<AtomicU32>,
mic_gain: f32, mic_gain: f32,
voice_activity_selector: Option<Arc<crate::TransmitModeSelector>>, voice_activity_selector: Option<Arc<crate::TransmitModeSelector>>,
vad_detector: crate::vad::WebRtcFallbackVad, vad_detector: crate::vad::WebRtcFallbackVad,
@@ -164,7 +133,7 @@ struct AndroidCaptureState {
impl AndroidCaptureState { impl AndroidCaptureState {
fn new( fn new(
voice_out_tx: mpsc::Sender<OutPacket>, voice_out_tx: mpsc::Sender<chanora_protocol::OutPacket>,
transmit_active: Arc<AtomicBool>, transmit_active: Arc<AtomicBool>,
frames_sent: Arc<AtomicU32>, frames_sent: Arc<AtomicU32>,
mic_gain: f32, mic_gain: f32,
@@ -188,9 +157,12 @@ impl AndroidCaptureState {
encoder, encoder,
pcm_accum: Vec::with_capacity(crate::frame::FRAME_20MS_SAMPLES * 2), pcm_accum: Vec::with_capacity(crate::frame::FRAME_20MS_SAMPLES * 2),
opus_out: [0u8; crate::opus_voice::MAX_OPUS_FRAME], opus_out: [0u8; crate::opus_voice::MAX_OPUS_FRAME],
voice_out_tx, voice_out_tx: crate::opus_voice::start_out_packet_worker(
voice_out_tx,
frames_sent.clone(),
"android",
)?,
transmit_active, transmit_active,
frames_sent,
mic_gain, mic_gain,
voice_activity_selector, voice_activity_selector,
vad_detector: crate::vad::WebRtcFallbackVad::default(), vad_detector: crate::vad::WebRtcFallbackVad::default(),
@@ -221,8 +193,10 @@ impl AndroidCaptureState {
self.audio_processing_stats self.audio_processing_stats
.record_callback_frames(samples.len() as u64); .record_callback_frames(samples.len() as u64);
if self.input_sample_rate_hz != crate::frame::SAMPLE_RATE_HZ { if self.input_sample_rate_hz != crate::frame::SAMPLE_RATE_HZ {
let resampled = self.resample_capture_to_48k(samples); self.resample_capture_to_48k(samples);
let resampled = std::mem::take(&mut self.resample_scratch);
self.ingest_48k_i16(&resampled); self.ingest_48k_i16(&resampled);
self.resample_scratch = resampled;
return; return;
} }
self.ingest_48k_i16(samples); self.ingest_48k_i16(samples);
@@ -241,6 +215,7 @@ impl AndroidCaptureState {
if self.pending_10ms_len == crate::frame::FRAME_10MS_SAMPLES { if self.pending_10ms_len == crate::frame::FRAME_10MS_SAMPLES {
let frame = self.pending_10ms; let frame = self.pending_10ms;
self.process_10ms_capture_frame(&frame); self.process_10ms_capture_frame(&frame);
self.encode_complete_20ms_frames();
self.pending_10ms_len = 0; self.pending_10ms_len = 0;
} }
} }
@@ -250,6 +225,10 @@ impl AndroidCaptureState {
return; return;
} }
self.encode_complete_20ms_frames();
}
fn encode_complete_20ms_frames(&mut self) {
while self.pcm_accum.len() >= crate::frame::FRAME_20MS_SAMPLES { while self.pcm_accum.len() >= crate::frame::FRAME_20MS_SAMPLES {
let mut frame = [0i16; crate::frame::FRAME_20MS_SAMPLES]; let mut frame = [0i16; crate::frame::FRAME_20MS_SAMPLES];
frame.copy_from_slice(&self.pcm_accum[..crate::frame::FRAME_20MS_SAMPLES]); frame.copy_from_slice(&self.pcm_accum[..crate::frame::FRAME_20MS_SAMPLES]);
@@ -258,7 +237,6 @@ impl AndroidCaptureState {
Ok(len) => { Ok(len) => {
crate::opus_voice::send_voip_frame( crate::opus_voice::send_voip_frame(
&self.voice_out_tx, &self.voice_out_tx,
&self.frames_sent,
&self.opus_out, &self.opus_out,
len, len,
|| { || {
@@ -286,35 +264,18 @@ impl AndroidCaptureState {
} }
} }
fn resample_capture_to_48k(&mut self, samples: &[i16]) -> Vec<i16> { fn resample_capture_to_48k(&mut self, samples: &[i16]) -> usize {
if samples.is_empty() { let result = crate::capture_resampler::resample_capture_to_48k(
return Vec::new(); samples,
self.input_sample_rate_hz,
&mut self.resample_pos,
&mut self.resample_last,
&mut self.resample_scratch,
);
if result.dropped {
self.audio_processing_stats.increment_callback_xrun();
} }
self.resample_scratch.clear(); result.output_len
let ratio = self.input_sample_rate_hz as f64 / crate::frame::SAMPLE_RATE_HZ as f64;
let mut pos = self.resample_pos;
while pos < samples.len() as f64 {
let i = pos.floor() as isize;
let frac = pos - i as f64;
let a = if i <= 0 {
self.resample_last as f64
} else {
samples[(i - 1) as usize] as f64
};
let b = if i < samples.len() as isize {
samples[i as usize] as f64
} else {
a
};
let value = (a + frac * (b - a))
.round()
.clamp(i16::MIN as f64, i16::MAX as f64) as i16;
self.resample_scratch.push(value);
pos += ratio;
}
self.resample_pos = pos - samples.len() as f64;
self.resample_last = *samples.last().unwrap_or(&self.resample_last);
self.resample_scratch.clone()
} }
fn set_input_sample_rate_hz(&mut self, sample_rate_hz: u32) { fn set_input_sample_rate_hz(&mut self, sample_rate_hz: u32) {
@@ -393,15 +354,9 @@ impl AndroidCaptureState {
self.fallback_warned_backend = None; self.fallback_warned_backend = None;
match vad_backend { match vad_backend {
crate::VadBackend::SileroOnnx => { crate::VadBackend::SileroOnnx => {
let path = crate::vad::silero_model_bundle_path(); self.silero_vad_worker = None;
self.silero_vad_worker = self.mark_vad_fallback_active(crate::VadBackend::SileroOnnx);
crate::vad::silero_onnx::SileroOnnxVadWorker::try_new(&path); self.audio_processing_stats.set_vad_fallback_active(true);
if self.silero_vad_worker.is_none() {
warn!(
target: "chanora_audio",
"android: Silero VAD model not found at {path}; falling back to WebRTC VAD"
);
}
} }
_ => { _ => {
self.silero_vad_worker = None; self.silero_vad_worker = None;
@@ -444,7 +399,10 @@ impl AndroidCaptureState {
} else { } else {
used_fallback_vad = true; used_fallback_vad = true;
self.mark_vad_fallback_active(vad_backend); self.mark_vad_fallback_active(vad_backend);
crate::vad::VoiceActivityDetector::process_10ms(&mut self.vad_detector, &frame) crate::vad::VoiceActivityDetector::process_10ms(
&mut self.vad_detector,
&frame,
)
} }
} else { } else {
crate::vad::VoiceActivityDetector::process_10ms(&mut self.vad_detector, &frame) crate::vad::VoiceActivityDetector::process_10ms(&mut self.vad_detector, &frame)
@@ -472,21 +430,19 @@ impl AndroidCaptureState {
return; return;
} }
let gain = self.mic_gain; if crate::capture_accumulator::append_processed_i16_bounded(
if (gain - 1.0).abs() < f32::EPSILON { &mut self.pcm_accum,
self.pcm_accum &frame,
.extend(frame.iter().copied().map(crate::frame::f32_to_i16)); self.mic_gain,
} else { ) {
self.pcm_accum.extend(frame.iter().copied().map(|s| { self.audio_processing_stats.increment_callback_xrun();
let scaled = (crate::frame::f32_to_i16(s) as f32) * gain;
scaled.clamp(i16::MIN as f32, i16::MAX as f32) as i16
}));
} }
} }
} }
struct InputCallback { struct InputCallback {
state: Arc<Mutex<AndroidCaptureState>>, state: Arc<Mutex<AndroidCaptureState>>,
audio_processing_stats: Arc<crate::SharedAudioProcessingStats>,
event_tx: BackendEventTx, event_tx: BackendEventTx,
} }
@@ -498,9 +454,13 @@ impl AudioInputCallback for InputCallback {
_stream: &mut dyn AudioInputStreamSafe, _stream: &mut dyn AudioInputStreamSafe,
frames: &[i16], frames: &[i16],
) -> DataCallbackResult { ) -> DataCallbackResult {
let _ = catch_unwind(AssertUnwindSafe(|| { let _ = catch_unwind(AssertUnwindSafe(|| match self.state.try_lock() {
if let Ok(mut s) = self.state.lock() { Ok(mut s) => s.ingest_i16(frames),
s.ingest_i16(frames); Err(std::sync::TryLockError::WouldBlock) => {
self.audio_processing_stats.increment_callback_xrun();
}
Err(std::sync::TryLockError::Poisoned(e)) => {
warn!(target: "chanora_audio", "android: capture state poisoned: {e}");
} }
})); }));
DataCallbackResult::Continue DataCallbackResult::Continue
@@ -522,8 +482,7 @@ impl AudioInputCallback for InputCallback {
// writes stereo f32 directly to the Oboe output buffer. // writes stereo f32 directly to the Oboe output buffer.
struct OutputCallback { struct OutputCallback {
handler: AudioHandler<SessionAudioId>, pcm_consumer: crate::android_render_ring::AndroidRenderRingConsumer,
event_consumer: crate::audio_event_queue::AudioEventConsumer,
output_gain: Arc<AtomicU32>, output_gain: Arc<AtomicU32>,
output_muted: Arc<AtomicBool>, output_muted: Arc<AtomicBool>,
event_tx: BackendEventTx, event_tx: BackendEventTx,
@@ -542,47 +501,39 @@ impl AudioOutputCallback for OutputCallback {
frames: &mut [(f32, f32)], frames: &mut [(f32, f32)],
) -> DataCallbackResult { ) -> DataCallbackResult {
let _ = catch_unwind(AssertUnwindSafe(|| { let _ = catch_unwind(AssertUnwindSafe(|| {
let buf: &mut [f32] = self.pcm_consumer.drain_stereo_into_zero_filling(frames);
bytemuck::cast_slice_mut::<(f32, f32), f32>(frames);
for s in buf.iter_mut() {
*s = 0.0;
}
for cmd in self.event_consumer.drain_controls() {
match cmd {
AudioCommand::SetVolume(id, vol) => {
if let Some(q) = self.handler.get_mut_queues().get_mut(&id) {
q.volume = vol;
}
}
AudioCommand::RemoveClient(id) => {
self.handler.get_mut_queues().remove(&id);
}
}
}
for pkt in self.event_consumer.drain_packets(50) {
if let Err(e) = self.handler.handle_packet(pkt.client_id, pkt.data) {
debug!(target: "chanora_audio", error = %e, "decode failed");
}
}
let _ = self.handler.fill_buffer(buf);
let gain = f32::from_bits(self.output_gain.load(Ordering::Relaxed)); let gain = f32::from_bits(self.output_gain.load(Ordering::Relaxed));
let muted = self.output_muted.load(Ordering::Relaxed); let muted = self.output_muted.load(Ordering::Relaxed);
if muted { if muted {
for s in buf.iter_mut() { for frame in frames.iter_mut() {
*s = 0.0; *frame = (0.0, 0.0);
} }
} else if gain != 1.0 { } else if gain != 1.0 {
for s in buf.iter_mut() { for (left, right) in frames.iter_mut() {
*s *= gain; *left *= gain;
*right *= gain;
} }
} }
let mut sum_squares = 0.0_f32;
for (left, right) in frames.iter() {
sum_squares += left * left + right * right;
}
let sample_count = frames.len() * 2;
let dbfs = if sample_count == 0 {
-120.0
} else {
let rms = (sum_squares / sample_count as f32).sqrt();
if rms <= 0.000_001 {
-120.0
} else {
20.0 * rms.log10()
}
};
self.audio_processing_stats self.audio_processing_stats
.update_render(crate::frame::dbfs(buf), frames.len() as u32); .update_render(dbfs, frames.len() as u32);
for chunk in buf.chunks_exact(2) { for (left, right) in frames.iter() {
self.pending_render_ref[self.pending_render_ref_len] = (chunk[0] + chunk[1]) * 0.5; self.pending_render_ref[self.pending_render_ref_len] = (left + right) * 0.5;
self.pending_render_ref_len += 1; self.pending_render_ref_len += 1;
if self.pending_render_ref_len == crate::frame::FRAME_10MS_SAMPLES { if self.pending_render_ref_len == crate::frame::FRAME_10MS_SAMPLES {
self.render_reference.write(&self.pending_render_ref); self.render_reference.write(&self.pending_render_ref);
@@ -614,6 +565,7 @@ impl AudioOutputCallback for OutputCallback {
pub struct AndroidVoiceUnit { pub struct AndroidVoiceUnit {
input: Option<AudioStreamAsync<OboeInput, InputCallback>>, input: Option<AudioStreamAsync<OboeInput, InputCallback>>,
output: Option<AudioStreamAsync<OboeOutput, OutputCallback>>, output: Option<AudioStreamAsync<OboeOutput, OutputCallback>>,
render_producer_shutdown: Arc<AtomicBool>,
// Recorded achieved values (SDD-112). // Recorded achieved values (SDD-112).
input_perf: AchievedPerformanceMode, input_perf: AchievedPerformanceMode,
@@ -635,11 +587,13 @@ pub struct AndroidVoiceUnit {
#[derive(Default)] #[derive(Default)]
struct HardwareEffectHandles { struct HardwareEffectHandles {
aec: Option<jni::objects::GlobalRef>, aec: Option<AndroidGlobalObject>,
ns: Option<jni::objects::GlobalRef>, ns: Option<AndroidGlobalObject>,
agc: Option<jni::objects::GlobalRef>, agc: Option<AndroidGlobalObject>,
} }
type AndroidGlobalObject = jni::refs::Global<jni::objects::JObject<'static>>;
impl AndroidVoiceUnit { impl AndroidVoiceUnit {
/// Open the input + output streams (SDD-111 + SDD-112) and, /// Open the input + output streams (SDD-111 + SDD-112) and,
/// once a session id is available, attach SDD-113 hardware /// once a session id is available, attach SDD-113 hardware
@@ -706,6 +660,7 @@ impl AndroidVoiceUnit {
let input_cb = InputCallback { let input_cb = InputCallback {
state: capture_state.clone(), state: capture_state.clone(),
audio_processing_stats: audio_processing_stats.clone(),
event_tx: event_tx.clone(), event_tx: event_tx.clone(),
}; };
let input_builder = input_builder.set_callback(input_cb); let input_builder = input_builder.set_callback(input_cb);
@@ -722,7 +677,12 @@ impl AndroidVoiceUnit {
error = ?e, error = ?e,
"android: primary input stream open failed; entering fallback ladder" "android: primary input stream open failed; entering fallback ladder"
); );
match Self::open_input_fallback(cfg, &event_tx, capture_state.clone()) { match Self::open_input_fallback(
cfg,
&event_tx,
capture_state.clone(),
audio_processing_stats.clone(),
) {
Ok(s) => Some(s), Ok(s) => Some(s),
Err(fallback_err) => { Err(fallback_err) => {
warn!( warn!(
@@ -789,9 +749,10 @@ impl AndroidVoiceUnit {
let render_ref_for_output = render_ref_buf.clone(); let render_ref_for_output = render_ref_buf.clone();
let event_queue = params.event_producer.queue(); let event_queue = params.event_producer.queue();
let render_ring =
crate::android_render_ring::AndroidRenderRing::new(ANDROID_RENDER_RING_CAPACITY);
let output_cb = OutputCallback { let output_cb = OutputCallback {
handler: params.handler, pcm_consumer: render_ring.consumer(),
event_consumer: AudioEventQueue::consumer(&event_queue),
output_gain: params.output_gain.clone(), output_gain: params.output_gain.clone(),
output_muted: params.output_muted.clone(), output_muted: params.output_muted.clone(),
event_tx: event_tx.clone(), event_tx: event_tx.clone(),
@@ -813,8 +774,7 @@ impl AndroidVoiceUnit {
Self::open_output_fallback( Self::open_output_fallback(
cfg, cfg,
&event_tx, &event_tx,
AudioHandler::new(), render_ring.consumer(),
AudioEventQueue::consumer(&event_queue),
params.output_gain.clone(), params.output_gain.clone(),
params.output_muted.clone(), params.output_muted.clone(),
audio_processing_stats.clone(), audio_processing_stats.clone(),
@@ -822,6 +782,11 @@ impl AndroidVoiceUnit {
)? )?
} }
}; };
let render_producer_shutdown = Self::spawn_render_producer(
params.handler,
AudioEventQueue::consumer(&event_queue),
render_ring.producer(),
);
let output_frames_per_burst = output_stream.get_frames_per_burst(); let output_frames_per_burst = output_stream.get_frames_per_burst();
if output_frames_per_burst > 0 { if output_frames_per_burst > 0 {
@@ -978,6 +943,7 @@ impl AndroidVoiceUnit {
Ok(Self { Ok(Self {
input: input_stream, input: input_stream,
output: Some(output_stream), output: Some(output_stream),
render_producer_shutdown,
input_perf, input_perf,
input_share, input_share,
output_perf, output_perf,
@@ -995,6 +961,7 @@ impl AndroidVoiceUnit {
cfg: &AndroidVoiceStreamConfig, cfg: &AndroidVoiceStreamConfig,
event_tx: &BackendEventTx, event_tx: &BackendEventTx,
capture_state: Arc<Mutex<AndroidCaptureState>>, capture_state: Arc<Mutex<AndroidCaptureState>>,
audio_processing_stats: Arc<crate::SharedAudioProcessingStats>,
) -> Result<AudioStreamAsync<OboeInput, InputCallback>, BackendError> { ) -> Result<AudioStreamAsync<OboeInput, InputCallback>, BackendError> {
// SDD-112 items 6 & 7: explore (preset × sharing) independently // SDD-112 items 6 & 7: explore (preset × sharing) independently
// via the pure helpers in `mobile_voice_backend`. Primary // via the pure helpers in `mobile_voice_backend`. Primary
@@ -1031,6 +998,7 @@ impl AndroidVoiceUnit {
}; };
let cb = InputCallback { let cb = InputCallback {
state: capture_state.clone(), state: capture_state.clone(),
audio_processing_stats: audio_processing_stats.clone(),
event_tx: event_tx.clone(), event_tx: event_tx.clone(),
}; };
let builder = AudioStreamBuilder::default() let builder = AudioStreamBuilder::default()
@@ -1066,16 +1034,14 @@ impl AndroidVoiceUnit {
fn open_output_fallback( fn open_output_fallback(
cfg: &AndroidVoiceStreamConfig, cfg: &AndroidVoiceStreamConfig,
event_tx: &BackendEventTx, event_tx: &BackendEventTx,
handler: AudioHandler<SessionAudioId>, pcm_consumer: crate::android_render_ring::AndroidRenderRingConsumer,
event_consumer: crate::audio_event_queue::AudioEventConsumer,
output_gain: Arc<AtomicU32>, output_gain: Arc<AtomicU32>,
output_muted: Arc<AtomicBool>, output_muted: Arc<AtomicBool>,
audio_processing_stats: Arc<crate::SharedAudioProcessingStats>, audio_processing_stats: Arc<crate::SharedAudioProcessingStats>,
render_reference: Arc<RenderReferenceBuffer>, render_reference: Arc<RenderReferenceBuffer>,
) -> Result<AudioStreamAsync<OboeOutput, OutputCallback>, BackendError> { ) -> Result<AudioStreamAsync<OboeOutput, OutputCallback>, BackendError> {
let cb = OutputCallback { let cb = OutputCallback {
handler, pcm_consumer,
event_consumer,
output_gain, output_gain,
output_muted, output_muted,
event_tx: event_tx.clone(), event_tx: event_tx.clone(),
@@ -1100,6 +1066,50 @@ impl AndroidVoiceUnit {
.map_err(|e| BackendError::OpenFailed(format!("output fallback: {e:?}"))) .map_err(|e| BackendError::OpenFailed(format!("output fallback: {e:?}")))
} }
fn spawn_render_producer(
mut handler: AudioHandler<SessionAudioId>,
event_consumer: crate::audio_event_queue::AudioEventConsumer,
pcm_producer: crate::android_render_ring::AndroidRenderRingProducer,
) -> Arc<AtomicBool> {
let shutdown = Arc::new(AtomicBool::new(false));
let shutdown_for_task = shutdown.clone();
tokio::spawn(async move {
let mut pull_scratch = vec![0.0_f32; ANDROID_RENDER_PULL_SAMPLES];
let mut interval = tokio::time::interval(std::time::Duration::from_millis(20));
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
interval.tick().await;
if shutdown_for_task.load(Ordering::Relaxed) {
break;
}
for cmd in event_consumer.drain_controls() {
match cmd {
AudioCommand::SetVolume(id, vol) => {
if let Some(q) = handler.get_mut_queues().get_mut(&id) {
q.volume = vol;
}
}
AudioCommand::RemoveClient(id) => {
handler.get_mut_queues().remove(&id);
}
}
}
for pkt in event_consumer.drain_packets(50) {
if let Err(e) = handler.handle_packet(pkt.client_id, pkt.data) {
debug!(target: "chanora_audio", error = %e, "decode failed");
}
}
pull_scratch.fill(0.0);
let _ = handler.fill_buffer(&mut pull_scratch);
pcm_producer.push_frame_lossy(&pull_scratch);
}
});
shutdown
}
/// Clone of the event sender, for JNI focus / SCO listeners /// Clone of the event sender, for JNI focus / SCO listeners
/// registered on the engine's behalf. /// registered on the engine's behalf.
pub fn event_sender(&self) -> BackendEventTx { pub fn event_sender(&self) -> BackendEventTx {
@@ -1151,6 +1161,7 @@ impl MobileVoiceAudioBackend for AndroidVoiceUnit {
fn close(&mut self) -> Result<(), BackendError> { fn close(&mut self) -> Result<(), BackendError> {
// SDD-115 reverse order: release hardware effects FIRST, // SDD-115 reverse order: release hardware effects FIRST,
// then close streams. // then close streams.
self.render_producer_shutdown.store(true, Ordering::Relaxed);
release_hardware_effects(&mut self.hw_effects); release_hardware_effects(&mut self.hw_effects);
self.stop().ok(); self.stop().ok();
// Dropping the Option drops the underlying AudioStreamAsync // Dropping the Option drops the underlying AudioStreamAsync
@@ -1208,6 +1219,7 @@ impl Drop for AndroidVoiceUnit {
// Wrap in catch_unwind so a panic during Drop cannot unwind // Wrap in catch_unwind so a panic during Drop cannot unwind
// into the JVM (SDD-115 callback safety). // into the JVM (SDD-115 callback safety).
let _ = catch_unwind(AssertUnwindSafe(|| { let _ = catch_unwind(AssertUnwindSafe(|| {
self.render_producer_shutdown.store(true, Ordering::Relaxed);
release_hardware_effects(&mut self.hw_effects); release_hardware_effects(&mut self.hw_effects);
// SDD-116: clear the diagnostics slot on Drop too. // SDD-116: clear the diagnostics slot on Drop too.
clear_android_audio_diagnostics(); clear_android_audio_diagnostics();
@@ -1287,62 +1299,71 @@ fn attach_hardware_effects_inner(
session_id: AudioSessionId, session_id: AudioSessionId,
effects: &crate::AudioEffects, effects: &crate::AudioEffects,
) -> HardwareEffectHandles { ) -> HardwareEffectHandles {
with_android_env("hardware effects", |env| {
let mut handles = HardwareEffectHandles::default();
if effects.aec {
handles.aec = create_effect(
env,
"android/media/audiofx/AcousticEchoCanceler",
session_id,
"AEC",
);
}
if effects.noise_suppression {
handles.ns = create_effect(
env,
"android/media/audiofx/NoiseSuppressor",
session_id,
"NS",
);
}
if effects.agc {
handles.agc = create_effect(
env,
"android/media/audiofx/AutomaticGainControl",
session_id,
"AGC",
);
}
handles
})
.unwrap_or_default()
}
fn with_android_env<R>(
operation: &str,
op: impl for<'local> FnOnce(&mut jni::Env<'local>) -> R,
) -> Option<R> {
let ctx = ndk_context::android_context(); let ctx = ndk_context::android_context();
if ctx.vm().is_null() { if ctx.vm().is_null() {
warn!( warn!(
target: "chanora_audio", target: "chanora_audio",
"android: ndk_context vm null; cannot bind hardware effects (software fallback engages)" operation,
"android: ndk_context vm null; JNI call skipped"
); );
return HardwareEffectHandles::default(); return None;
} }
let jvm = match unsafe { jni::JavaVM::from_raw(ctx.vm() as *mut _) } {
Ok(v) => v,
Err(e) => {
warn!(target: "chanora_audio", error = %e, "android: JavaVM::from_raw failed; effects not bound");
return HardwareEffectHandles::default();
}
};
let mut env = match jvm.attach_current_thread() {
Ok(e) => e,
Err(e) => {
warn!(target: "chanora_audio", error = %e, "android: attach_current_thread failed; effects not bound");
return HardwareEffectHandles::default();
}
};
let mut handles = HardwareEffectHandles::default(); let jvm = unsafe { jni::JavaVM::from_raw(ctx.vm() as *mut _) };
if effects.aec { match jvm.attach_current_thread(|env| Ok::<R, jni::errors::Error>(op(env))) {
handles.aec = create_effect( Ok(value) => Some(value),
&mut env, Err(e) => {
"android/media/audiofx/AcousticEchoCanceler", warn!(target: "chanora_audio", error = %e, operation, "android: attach_current_thread failed");
session_id, None
"AEC", }
);
} }
if effects.noise_suppression {
handles.ns = create_effect(
&mut env,
"android/media/audiofx/NoiseSuppressor",
session_id,
"NS",
);
}
if effects.agc {
handles.agc = create_effect(
&mut env,
"android/media/audiofx/AutomaticGainControl",
session_id,
"AGC",
);
}
handles
} }
/// SDD-113 item 3: probe the static `isAvailable()` on each effect /// SDD-113 item 3: probe the static `isAvailable()` on each effect
/// class before calling `create(int)`. Returns `false` on any JNI /// class before calling `create(int)`. Returns `false` on any JNI
/// failure so the caller engages the software fallback. /// failure so the caller engages the software fallback.
fn effect_is_available(env: &mut jni::JNIEnv, class: &jni::objects::JClass, label: &str) -> bool { fn effect_is_available(env: &mut jni::Env<'_>, class: &jni::objects::JClass, label: &str) -> bool {
match env.call_static_method(class, "isAvailable", "()Z", &[]) { match env.call_static_method(
class,
jni::jni_str!("isAvailable"),
jni::jni_sig!("()Z"),
&[],
) {
Ok(v) => match v.z() { Ok(v) => match v.z() {
Ok(b) => b, Ok(b) => b,
Err(e) => { Err(e) => {
@@ -1360,14 +1381,14 @@ fn effect_is_available(env: &mut jni::JNIEnv, class: &jni::objects::JClass, labe
} }
fn create_effect( fn create_effect(
env: &mut jni::JNIEnv, env: &mut jni::Env<'_>,
fqcn: &str, fqcn: &str,
session_id: AudioSessionId, session_id: AudioSessionId,
label: &str, label: &str,
) -> Option<jni::objects::GlobalRef> { ) -> Option<AndroidGlobalObject> {
use jni::objects::JValue; use jni::objects::JValue;
// Class.create(int) -> ClassInstance|null // Class.create(int) -> ClassInstance|null
let class = match env.find_class(fqcn) { let class = match env.find_class(jni::strings::JNIString::new(fqcn)) {
Ok(c) => c, Ok(c) => c,
Err(e) => { Err(e) => {
warn!(target: "chanora_audio", error = %e, effect = label, "android: find_class failed; effect not bound — software fallback engages"); warn!(target: "chanora_audio", error = %e, effect = label, "android: find_class failed; effect not bound — software fallback engages");
@@ -1383,10 +1404,18 @@ fn create_effect(
); );
return None; return None;
} }
let create_sig = match jni::signature::RuntimeMethodSignature::from_str(format!("(I)L{fqcn};"))
{
Ok(sig) => sig,
Err(e) => {
warn!(target: "chanora_audio", error = %e, effect = label, "android: create() signature parse failed");
return None;
}
};
let inst = match env.call_static_method( let inst = match env.call_static_method(
&class, &class,
"create", jni::jni_str!("create"),
&format!("(I)L{fqcn};"), create_sig.method_signature(),
&[JValue::Int(session_id)], &[JValue::Int(session_id)],
) { ) {
Ok(v) => match v.l() { Ok(v) => match v.l() {
@@ -1411,8 +1440,8 @@ fn create_effect(
// setEnabled(true) -> int (success code) // setEnabled(true) -> int (success code)
if let Err(e) = env.call_method( if let Err(e) = env.call_method(
&inst, &inst,
"setEnabled", jni::jni_str!("setEnabled"),
"(Z)I", jni::jni_sig!("(Z)I"),
&[JValue::Bool(jni::sys::JNI_TRUE)], &[JValue::Bool(jni::sys::JNI_TRUE)],
) { ) {
let _ = env.exception_clear(); let _ = env.exception_clear();
@@ -1448,34 +1477,28 @@ fn release_hardware_effects_inner(handles: &mut HardwareEffectHandles) {
if aec.is_none() && ns.is_none() && agc.is_none() { if aec.is_none() && ns.is_none() && agc.is_none() {
return; return;
} }
let ctx = ndk_context::android_context(); let _ = with_android_env("release hardware effects", |env| {
if ctx.vm().is_null() { for (effect, label) in [(aec, "AEC"), (ns, "NS"), (agc, "AGC")] {
return; if let Some(g) = effect {
} let _ = env.call_method(
// SAFETY: vm is non-null and owned for process lifetime via JNI_OnLoad. g.as_obj(),
let jvm = match unsafe { jni::JavaVM::from_raw(ctx.vm() as *mut _) } { jni::jni_str!("setEnabled"),
Ok(v) => v, jni::jni_sig!("(Z)I"),
Err(_) => return, &[jni::objects::JValue::Bool(jni::sys::JNI_FALSE)],
}; );
let mut env = match jvm.attach_current_thread() { env.exception_clear();
Ok(e) => e, let _ = env.call_method(
Err(_) => return, g.as_obj(),
}; jni::jni_str!("release"),
for (effect, label) in [(aec, "AEC"), (ns, "NS"), (agc, "AGC")] { jni::jni_sig!("()V"),
if let Some(g) = effect { &[],
let _ = env.call_method( );
g.as_obj(), env.exception_clear();
"setEnabled", drop(g);
"(Z)I", info!(target: "chanora_audio", effect = label, "android: hardware effect released");
&[jni::objects::JValue::Bool(jni::sys::JNI_FALSE)], }
);
let _ = env.exception_clear();
let _ = env.call_method(g.as_obj(), "release", "()V", &[]);
let _ = env.exception_clear();
drop(g);
info!(target: "chanora_audio", effect = label, "android: hardware effect released");
} }
} });
} }
// --- Process-global BackendEvent sender for JNI callbacks -------- // --- Process-global BackendEvent sender for JNI callbacks --------
@@ -1550,7 +1573,7 @@ pub fn chanora_android_stop_voice_service() -> bool {
fn call_voice_service_static(method: &str) -> bool { fn call_voice_service_static(method: &str) -> bool {
use jni::objects::{JObject, JValue}; use jni::objects::{JObject, JValue};
let ctx = ndk_context::android_context(); let ctx = ndk_context::android_context();
if ctx.vm().is_null() || ctx.context().is_null() { if ctx.context().is_null() {
warn!( warn!(
target: "chanora_audio", target: "chanora_audio",
method, method,
@@ -1558,54 +1581,41 @@ fn call_voice_service_static(method: &str) -> bool {
); );
return false; return false;
} }
// SAFETY: vm/context populated by chanora_bridge::android_init at
// JNI_OnLoad + initChanoraContext; both pointers are valid for with_android_env("voice foreground service", |env| {
// the process lifetime. // SAFETY: ndk_context::context() is the application Context
let jvm = match unsafe { jni::JavaVM::from_raw(ctx.vm() as *mut _) } { // jobject; valid global ref for process lifetime.
Ok(v) => v, let context_obj = unsafe { JObject::from_raw(env, ctx.context() as jni::sys::jobject) };
Err(e) => { let class = match load_app_class(env, &context_obj, ANDROID_VOICE_FG_SERVICE_FQCN) {
warn!(target: "chanora_audio", error = %e, method, "android: JavaVM::from_raw failed"); Some(c) => c,
return false; None => return false,
};
match env.call_static_method(
&class,
jni::strings::JNIString::new(method),
jni::jni_sig!("(Landroid/content/Context;)V"),
&[JValue::Object(&context_obj)],
) {
Ok(_) => {
info!(target: "chanora_audio", method, "android: voice foreground service call dispatched");
true
}
Err(e) => {
env.exception_clear();
warn!(target: "chanora_audio", error = %e, method, "android: foreground service static call failed");
false
}
} }
}; })
let mut env = match jvm.attach_current_thread() { .unwrap_or(false)
Ok(e) => e,
Err(e) => {
warn!(target: "chanora_audio", error = %e, method, "android: attach_current_thread failed");
return false;
}
};
// SAFETY: ndk_context::context() is the application Context
// jobject; valid global ref for process lifetime.
let context_obj = unsafe { JObject::from_raw(ctx.context() as jni::sys::jobject) };
let class = match load_app_class(&mut env, &context_obj, ANDROID_VOICE_FG_SERVICE_FQCN) {
Some(c) => c,
None => return false,
};
match env.call_static_method(
&class,
method,
"(Landroid/content/Context;)V",
&[JValue::Object(&context_obj)],
) {
Ok(_) => {
info!(target: "chanora_audio", method, "android: voice foreground service call dispatched");
true
}
Err(e) => {
let _ = env.exception_clear();
warn!(target: "chanora_audio", error = %e, method, "android: foreground service static call failed");
false
}
}
} }
fn load_app_class<'local>( fn load_app_class<'local>(
env: &mut jni::JNIEnv<'local>, env: &mut jni::Env<'local>,
context_obj: &jni::objects::JObject<'local>, context_obj: &jni::objects::JObject<'local>,
slash_name: &str, slash_name: &str,
) -> Option<jni::objects::JClass<'local>> { ) -> Option<jni::objects::JClass<'local>> {
match env.find_class(slash_name) { match env.find_class(jni::strings::JNIString::new(slash_name)) {
Ok(c) => return Some(c), Ok(c) => return Some(c),
Err(e) => { Err(e) => {
let _ = env.exception_clear(); let _ = env.exception_clear();
@@ -1616,8 +1626,8 @@ fn load_app_class<'local>(
let loader = match env let loader = match env
.call_method( .call_method(
context_obj, context_obj,
"getClassLoader", jni::jni_str!("getClassLoader"),
"()Ljava/lang/ClassLoader;", jni::jni_sig!("()Ljava/lang/ClassLoader;"),
&[], &[],
) )
.and_then(|v| v.l()) .and_then(|v| v.l())
@@ -1642,13 +1652,20 @@ fn load_app_class<'local>(
match env match env
.call_method( .call_method(
&loader, &loader,
"loadClass", jni::jni_str!("loadClass"),
"(Ljava/lang/String;)Ljava/lang/Class;", jni::jni_sig!("(Ljava/lang/String;)Ljava/lang/Class;"),
&[jni::objects::JValue::Object(&class_name_obj)], &[jni::objects::JValue::Object(&class_name_obj)],
) )
.and_then(|v| v.l()) .and_then(|v| v.l())
{ {
Ok(class_obj) => Some(jni::objects::JClass::from(class_obj)), Ok(class_obj) => match env.cast_local::<jni::objects::JClass>(class_obj) {
Ok(class) => Some(class),
Err(e) => {
env.exception_clear();
warn!(target: "chanora_audio", error = %e, class = %dotted_name, "android: ClassLoader.loadClass returned non-Class object");
None
}
},
Err(e) => { Err(e) => {
let _ = env.exception_clear(); let _ = env.exception_clear();
warn!(target: "chanora_audio", error = %e, class = %dotted_name, "android: ClassLoader.loadClass failed"); warn!(target: "chanora_audio", error = %e, class = %dotted_name, "android: ClassLoader.loadClass failed");
@@ -1679,7 +1696,7 @@ fn load_app_class<'local>(
pub extern "system" fn Java_app_chanora_chanora_1flutter_AndroidAudioFocusController_publishFocusChange< pub extern "system" fn Java_app_chanora_chanora_1flutter_AndroidAudioFocusController_publishFocusChange<
'local, 'local,
>( >(
_env: jni::JNIEnv<'local>, _env: jni::EnvUnowned<'local>,
_class: jni::objects::JClass<'local>, _class: jni::objects::JClass<'local>,
state: jni::sys::jint, state: jni::sys::jint,
) { ) {
@@ -1717,7 +1734,7 @@ pub extern "system" fn Java_app_chanora_chanora_1flutter_AndroidAudioFocusContro
pub extern "system" fn Java_app_chanora_chanora_1flutter_AndroidBluetoothScoController_publishScoStateChange< pub extern "system" fn Java_app_chanora_chanora_1flutter_AndroidBluetoothScoController_publishScoStateChange<
'local, 'local,
>( >(
_env: jni::JNIEnv<'local>, _env: jni::EnvUnowned<'local>,
_class: jni::objects::JClass<'local>, _class: jni::objects::JClass<'local>,
state: jni::sys::jint, state: jni::sys::jint,
) { ) {
@@ -1766,7 +1783,7 @@ pub fn chanora_android_stop_bluetooth_sco() -> bool {
fn call_static_void_context(fqcn: &str, method: &str) -> bool { fn call_static_void_context(fqcn: &str, method: &str) -> bool {
use jni::objects::{JObject, JValue}; use jni::objects::{JObject, JValue};
let ctx = ndk_context::android_context(); let ctx = ndk_context::android_context();
if ctx.vm().is_null() || ctx.context().is_null() { if ctx.context().is_null() {
warn!( warn!(
target: "chanora_audio", target: "chanora_audio",
class = fqcn, class = fqcn,
@@ -1775,39 +1792,29 @@ fn call_static_void_context(fqcn: &str, method: &str) -> bool {
); );
return false; return false;
} }
let jvm = match unsafe { jni::JavaVM::from_raw(ctx.vm() as *mut _) } {
Ok(v) => v, with_android_env("static context call", |env| {
Err(e) => { let context_obj = unsafe { JObject::from_raw(env, ctx.context() as jni::sys::jobject) };
warn!(target: "chanora_audio", error = %e, class = fqcn, method, "android: JavaVM::from_raw failed"); let class = match load_app_class(env, &context_obj, fqcn) {
return false; Some(c) => c,
None => return false,
};
match env.call_static_method(
&class,
jni::strings::JNIString::new(method),
jni::jni_sig!("(Landroid/content/Context;)V"),
&[JValue::Object(&context_obj)],
) {
Ok(_) => {
info!(target: "chanora_audio", class = fqcn, method, "android: dispatched");
true
}
Err(e) => {
env.exception_clear();
warn!(target: "chanora_audio", error = %e, class = fqcn, method, "android: static call failed");
false
}
} }
}; })
let mut env = match jvm.attach_current_thread() { .unwrap_or(false)
Ok(e) => e,
Err(e) => {
warn!(target: "chanora_audio", error = %e, class = fqcn, method, "android: attach_current_thread failed");
return false;
}
};
let context_obj = unsafe { JObject::from_raw(ctx.context() as jni::sys::jobject) };
let class = match load_app_class(&mut env, &context_obj, fqcn) {
Some(c) => c,
None => return false,
};
match env.call_static_method(
&class,
method,
"(Landroid/content/Context;)V",
&[JValue::Object(&context_obj)],
) {
Ok(_) => {
info!(target: "chanora_audio", class = fqcn, method, "android: dispatched");
true
}
Err(e) => {
let _ = env.exception_clear();
warn!(target: "chanora_audio", error = %e, class = fqcn, method, "android: static call failed");
false
}
}
} }
+11 -51
View File
@@ -56,10 +56,8 @@ impl AudioRoute {
/// iOS voice-processing mode. /// iOS voice-processing mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IosVoiceProcessingMode { pub enum IosVoiceProcessingMode {
/// Shipping default: Apple VoiceProcessingIO owns AEC/NS/AGC. /// Apple VoiceProcessingIO owns AEC/NS/AGC.
PlatformVoiceProcessing, PlatformVoiceProcessing,
/// Experimental raw capture-processing path.
SonoraExperimental,
} }
/// Processing backend selected by policy/config. /// Processing backend selected by policy/config.
@@ -195,28 +193,20 @@ impl AudioProcessingConfig {
"bluetooth_a2dp is output-only and cannot transmit duplex voice".to_string(), "bluetooth_a2dp is output-only and cannot transmit duplex voice".to_string(),
)); ));
} }
if self.ios_mode == IosVoiceProcessingMode::PlatformVoiceProcessing if self.processing_backend == AudioBackend::Sonora
&& (self.processing_backend == AudioBackend::Sonora || self.processing_backend == AudioBackend::WebrtcApm
|| self.processing_backend == AudioBackend::WebrtcApm || self.aec == EffectOwner::Sonora
|| self.aec == EffectOwner::Sonora || self.aec == EffectOwner::WebrtcApm
|| self.aec == EffectOwner::WebrtcApm || self.ns == EffectOwner::Sonora
|| self.ns == EffectOwner::Sonora || self.ns == EffectOwner::WebrtcApm
|| self.ns == EffectOwner::WebrtcApm || self.agc == EffectOwner::Sonora
|| self.agc == EffectOwner::Sonora || self.agc == EffectOwner::WebrtcApm
|| self.agc == EffectOwner::WebrtcApm)
{ {
return Err(AudioError::InvalidAudioProcessingConfig( return Err(AudioError::InvalidAudioProcessingConfig(
"software audio processing cannot be enabled with iOS VoiceProcessingIO" "software audio processing cannot be enabled with iOS VoiceProcessingIO"
.to_string(), .to_string(),
)); ));
} }
if self.ios_mode == IosVoiceProcessingMode::SonoraExperimental
&& self.processing_backend != AudioBackend::WebrtcApm
{
return Err(AudioError::InvalidAudioProcessingConfig(
"ios raw processing mode requires the WebRTC APM backend".to_string(),
));
}
Ok(()) Ok(())
} }
@@ -262,34 +252,6 @@ mod tests {
assert!(config.validate_for_ios().is_err()); assert!(config.validate_for_ios().is_err());
} }
#[test]
fn raw_processing_allows_full_webrtc_apm_chain() {
let config = AudioProcessingConfig {
ios_mode: IosVoiceProcessingMode::SonoraExperimental,
processing_backend: AudioBackend::WebrtcApm,
aec: EffectOwner::WebrtcApm,
ns: EffectOwner::WebrtcApm,
agc: EffectOwner::WebrtcApm,
..AudioProcessingConfig::default()
};
assert!(config.validate_for_ios().is_ok());
}
#[test]
fn raw_processing_rejects_non_webrtc_apm_backend() {
let config = AudioProcessingConfig {
ios_mode: IosVoiceProcessingMode::SonoraExperimental,
processing_backend: AudioBackend::PlatformVoiceProcessing,
aec: EffectOwner::WebrtcApm,
ns: EffectOwner::WebrtcApm,
agc: EffectOwner::WebrtcApm,
..AudioProcessingConfig::default()
};
assert!(config.validate_for_ios().is_err());
}
#[test] #[test]
fn disable_failed_vad_backend_demotes_to_webrtc() { fn disable_failed_vad_backend_demotes_to_webrtc() {
let mut config = AudioProcessingConfig { let mut config = AudioProcessingConfig {
@@ -404,10 +366,8 @@ impl Default for SharedAudioProcessingStats {
} }
impl SharedAudioProcessingStats { impl SharedAudioProcessingStats {
/// Store the raw input dBFS level (desktop capture path). /// Store the raw input dBFS level for capture paths that do not
/// Mobile platforms use [`Self::update_capture`] instead, which /// update the full processing/VAD snapshot on this callback.
/// also records VAD state; this lighter method is for the cpal
/// capture path that has no VAD pipeline.
pub fn set_input_dbfs(&self, dbfs: f32) { pub fn set_input_dbfs(&self, dbfs: f32) {
self.input_dbfs.store(dbfs.to_bits(), Ordering::Relaxed); self.input_dbfs.store(dbfs.to_bits(), Ordering::Relaxed);
} }
@@ -0,0 +1,118 @@
pub(crate) fn append_processed_i16_bounded(
pcm_accum: &mut Vec<i16>,
frame: &[f32],
gain: f32,
) -> bool {
if (gain - 1.0).abs() < f32::EPSILON {
for src in frame.iter().copied() {
if pcm_accum.len() == pcm_accum.capacity() {
return true;
}
pcm_accum.push(crate::frame::f32_to_i16(src));
}
} else {
for src in frame.iter().copied() {
if pcm_accum.len() == pcm_accum.capacity() {
return true;
}
let scaled = (crate::frame::f32_to_i16(src) as f32) * gain;
pcm_accum.push(scaled.clamp(i16::MIN as f32, i16::MAX as f32) as i16);
}
}
false
}
pub(crate) fn append_i16_bounded(pcm_accum: &mut Vec<i16>, frame: &[i16]) -> bool {
for src in frame.iter().copied() {
if pcm_accum.len() == pcm_accum.capacity() {
return true;
}
pcm_accum.push(src);
}
false
}
#[cfg(test)]
mod tests {
use super::{append_i16_bounded, append_processed_i16_bounded};
#[test]
fn append_processed_i16_bounded_does_not_grow_when_full() {
let frame = [0.25_f32; crate::frame::FRAME_10MS_SAMPLES];
let mut accum = Vec::with_capacity(crate::frame::FRAME_10MS_SAMPLES / 2);
let warmed_capacity = accum.capacity();
let warmed_ptr = accum.as_ptr();
let dropped = append_processed_i16_bounded(&mut accum, &frame, 1.0);
assert!(dropped);
assert_eq!(accum.len(), warmed_capacity);
assert_eq!(accum.capacity(), warmed_capacity);
assert_eq!(accum.as_ptr(), warmed_ptr);
}
#[test]
fn append_processed_i16_bounded_preserves_expected_10ms_append() {
let frame = [0.25_f32; crate::frame::FRAME_10MS_SAMPLES];
let mut accum = Vec::with_capacity(crate::frame::FRAME_20MS_SAMPLES * 2);
let warmed_capacity = accum.capacity();
let warmed_ptr = accum.as_ptr();
let dropped = append_processed_i16_bounded(&mut accum, &frame, 1.0);
assert!(!dropped);
assert_eq!(accum.len(), crate::frame::FRAME_10MS_SAMPLES);
assert_eq!(accum.capacity(), warmed_capacity);
assert_eq!(accum.as_ptr(), warmed_ptr);
}
#[test]
fn append_i16_bounded_does_not_grow_when_preroll_exceeds_capacity() {
let frame = [7_i16; crate::frame::FRAME_10MS_SAMPLES];
let mut accum = Vec::with_capacity(crate::frame::FRAME_10MS_SAMPLES / 2);
let warmed_capacity = accum.capacity();
let warmed_ptr = accum.as_ptr();
let dropped = append_i16_bounded(&mut accum, &frame);
assert!(dropped);
assert_eq!(accum.len(), warmed_capacity);
assert_eq!(accum.capacity(), warmed_capacity);
assert_eq!(accum.as_ptr(), warmed_ptr);
}
#[test]
fn append_i16_bounded_preserves_expected_10ms_append() {
let frame = [7_i16; crate::frame::FRAME_10MS_SAMPLES];
let mut accum = Vec::with_capacity(crate::frame::FRAME_20MS_SAMPLES * 2);
let warmed_capacity = accum.capacity();
let warmed_ptr = accum.as_ptr();
let dropped = append_i16_bounded(&mut accum, &frame);
assert!(!dropped);
assert_eq!(accum.len(), crate::frame::FRAME_10MS_SAMPLES);
assert_eq!(accum.capacity(), warmed_capacity);
assert_eq!(accum.as_ptr(), warmed_ptr);
}
#[test]
fn append_i16_bounded_preserves_full_vad_preroll_window() {
let frame = [7_i16; crate::frame::FRAME_10MS_SAMPLES];
let mut accum = Vec::with_capacity(crate::frame::FRAME_10MS_SAMPLES * 16);
let warmed_capacity = accum.capacity();
let warmed_ptr = accum.as_ptr();
for _ in 0..16 {
assert!(!append_i16_bounded(&mut accum, &frame));
}
assert_eq!(accum.len(), crate::frame::FRAME_10MS_SAMPLES * 16);
assert_eq!(accum.capacity(), warmed_capacity);
assert_eq!(accum.as_ptr(), warmed_ptr);
assert!(append_i16_bounded(&mut accum, &frame));
assert_eq!(accum.len(), warmed_capacity);
assert_eq!(accum.capacity(), warmed_capacity);
assert_eq!(accum.as_ptr(), warmed_ptr);
}
}
@@ -0,0 +1,105 @@
pub(crate) struct CaptureResampleResult {
pub(crate) output_len: usize,
pub(crate) dropped: bool,
}
pub(crate) fn resample_capture_to_48k(
samples: &[i16],
input_sample_rate_hz: u32,
resample_pos: &mut f64,
resample_last: &mut i16,
scratch: &mut Vec<i16>,
) -> CaptureResampleResult {
scratch.clear();
if samples.is_empty() {
return CaptureResampleResult {
output_len: 0,
dropped: false,
};
}
let ratio = input_sample_rate_hz.max(1) as f64 / crate::frame::SAMPLE_RATE_HZ as f64;
let mut pos = *resample_pos;
let mut dropped = false;
while pos < samples.len() as f64 {
let i = pos.floor() as isize;
let frac = pos - i as f64;
let a = if i <= 0 {
*resample_last as f64
} else {
samples[(i - 1) as usize] as f64
};
let b = if i < samples.len() as isize {
samples[i as usize] as f64
} else {
a
};
let value = (a + frac * (b - a))
.round()
.clamp(i16::MIN as f64, i16::MAX as f64) as i16;
if scratch.len() < scratch.capacity() {
scratch.push(value);
} else {
dropped = true;
}
pos += ratio;
}
*resample_pos = pos - samples.len() as f64;
*resample_last = *samples.last().unwrap_or(resample_last);
CaptureResampleResult {
output_len: scratch.len(),
dropped,
}
}
#[cfg(test)]
mod android_voice_unit_resampler_tests {
use super::resample_capture_to_48k;
#[test]
fn android_voice_unit_resampler_reuses_scratch_without_capacity_growth() {
let samples: Vec<i16> = (0..882).map(|i| i as i16).collect();
let mut pos = 0.0;
let mut last = 0_i16;
let mut scratch = Vec::with_capacity(960);
let first = resample_capture_to_48k(&samples, 44_100, &mut pos, &mut last, &mut scratch);
let first_len = first.output_len;
assert_eq!(first_len, 960);
assert!(!first.dropped);
assert_eq!(scratch.len(), first_len);
let warmed_capacity = scratch.capacity();
let warmed_ptr = scratch.as_ptr();
for _ in 0..8 {
let result =
resample_capture_to_48k(&samples, 44_100, &mut pos, &mut last, &mut scratch);
let len = result.output_len;
assert_eq!(len, scratch.len());
assert!(len >= 959 && len <= 960);
assert!(!result.dropped);
assert_eq!(scratch.capacity(), warmed_capacity);
assert_eq!(scratch.as_ptr(), warmed_ptr);
}
}
#[test]
fn android_voice_unit_resampler_truncates_oversized_burst_without_capacity_growth() {
let samples: Vec<i16> = (0..4_800).map(|i| i as i16).collect();
let mut pos = 0.0;
let mut last = 0_i16;
let mut scratch = Vec::with_capacity(960);
let warmed_capacity = scratch.capacity();
let warmed_ptr = scratch.as_ptr();
let result = resample_capture_to_48k(&samples, 48_000, &mut pos, &mut last, &mut scratch);
assert_eq!(result.output_len, warmed_capacity);
assert!(result.dropped);
assert_eq!(scratch.len(), warmed_capacity);
assert_eq!(scratch.capacity(), warmed_capacity);
assert_eq!(scratch.as_ptr(), warmed_ptr);
assert_eq!(pos, 0.0);
assert_eq!(last, *samples.last().unwrap());
}
}
File diff suppressed because it is too large Load Diff
-558
View File
@@ -1,558 +0,0 @@
//! Optional raw iOS RemoteIO path for the WebRTC APM experimental mode.
//!
//! Provides an alternative to `ios_voice_unit.rs` for the
//! `SonoraExperimental` processing mode. Instead of
//! `kAudioUnitSubType_VoiceProcessingIO` (which owns AEC/NS/AGC), it
//! opens `kAudioUnitSubType_RemoteIO` with voice processing explicitly
//! disabled so WebRTC APM can own the full signal path.
//!
//! ## Hard invariants enforced here
//!
//! * INV_009: Rust AEC only active when platform AEC is disabled.
//! * INV_010: VoiceProcessingIO and WebRTC APM AEC are mutually exclusive.
//! * INV_011: Software AEC backend receives both capture and render-reference.
//! * INV_012: Render reference is copied from decoded/mixed remote PCM
//! before playout.
//!
//! ## Fallback
//!
//! If RemoteIO construction fails, the caller falls back to `IosVoiceUnit`
//! (VPIO) and logs the error.
//!
//! ## Status
//!
//! Experimental / disabled by default. Only activated when the user
//! explicitly selects `SonoraExperimental` mode via the bridge API.
//!
//! ## Platform
//!
//! `kAudioUnitSubType_RemoteIO` is only available in the iOS SDK.
//! This module is gated to `target_os = "ios"`.
#[cfg(target_os = "ios")]
pub use inner::IosRawUnit;
#[cfg(target_os = "ios")]
mod inner {
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use audiopus::coder::Encoder as OpusEncoder;
use coreaudio::audio_unit::audio_format::LinearPcmFlags;
use coreaudio::audio_unit::render_callback::{self, data};
use coreaudio::audio_unit::IOType;
use coreaudio::audio_unit::{AudioUnit, Element, SampleFormat, Scope, StreamFormat};
use tokio::sync::mpsc;
use tracing::{info, warn};
use crate::mobile_voice_backend::VoiceAudioParams;
use crate::processor::AudioProcessor;
use crate::AudioError;
use chanora_protocol::OutPacket;
const SAMPLE_RATE_HZ: f64 = 48_000.0;
// ------------------------------------------------------------------ //
// Render-reference ring buffer //
// ------------------------------------------------------------------ //
/// 4-slot ring buffer shared between the render callback (writer) and
/// the capture callback (reader for Sonora AEC3). Capacity: 4 × 10 ms
/// = 40 ms of headroom.
///
/// If the capture callback runs before the render callback has written
/// a frame it reads zeros (silence reference), which is safe — Sonora
/// AEC3 simply skips cancellation for that frame.
struct RenderReferenceBuffer {
buf: Box<[[f32; 480]; 4]>,
write_idx: std::sync::atomic::AtomicUsize,
}
impl RenderReferenceBuffer {
fn new() -> Arc<Self> {
Arc::new(Self {
buf: Box::new([[0.0; 480]; 4]),
write_idx: std::sync::atomic::AtomicUsize::new(0),
})
}
/// Write one 10 ms render-reference frame. Realtime-safe.
fn write(&self, frame: &[f32; 480]) {
let idx = self.write_idx.load(Ordering::Relaxed);
// SAFETY: only one writer (render callback); torn reads
// are bounded to one frame of AEC degradation.
unsafe {
let slot = &self.buf[idx] as *const [f32; 480] as *mut [f32; 480];
(*slot).copy_from_slice(frame);
}
self.write_idx.store((idx + 1) % 4, Ordering::Relaxed);
}
/// Read the most recently completed render-reference frame.
fn read_latest(&self) -> [f32; 480] {
let wi = self.write_idx.load(Ordering::Relaxed);
let ri = (wi + 3) % 4;
self.buf[ri]
}
}
// SAFETY: accessed from two audio callback threads; data races are
// bounded to one frame of AEC quality degradation.
unsafe impl Send for RenderReferenceBuffer {}
unsafe impl Sync for RenderReferenceBuffer {}
// ------------------------------------------------------------------ //
// Capture pipeline state //
// ------------------------------------------------------------------ //
struct RawCaptureState {
encoder: OpusEncoder,
pcm_accum: Vec<i16>,
opus_out: [u8; crate::opus_voice::MAX_OPUS_FRAME],
voice_out_tx: mpsc::Sender<OutPacket>,
transmit_active: Arc<AtomicBool>,
output_muted: Arc<AtomicBool>,
frames_sent: Arc<AtomicU32>,
mic_gain: f32,
voice_activity_selector: Option<Arc<crate::TransmitModeSelector>>,
vad_detector: crate::vad::WebRtcFallbackVad,
silero_coreml_worker: Option<crate::vad::apple_coreml::AppleCoreMlVadWorker>,
current_vad_backend: crate::VadBackend,
capture_frame_seq: u64,
vad_state: crate::voice_activity::VoiceActivityStateMachine,
/// Processing config — retained for route-change reloads.
audio_processing_config: Arc<Mutex<crate::AudioProcessingConfig>>,
webrtc_apm_processor: crate::processor::WebRtcApmProcessor,
audio_processing_stats: Arc<crate::SharedAudioProcessingStats>,
render_reference: Arc<RenderReferenceBuffer>,
pending_10ms: [i16; crate::frame::FRAME_10MS_SAMPLES],
pending_10ms_len: usize,
fallback_warned_backend: Option<crate::VadBackend>,
wav_recorder: Option<Arc<crate::debug_wav::WavDebugRecorder>>,
}
impl RawCaptureState {
fn new(
params: &VoiceAudioParams,
render_reference: Arc<RenderReferenceBuffer>,
) -> Result<Self, AudioError> {
let encoder = crate::opus_voice::new_voip_encoder("ios raw")?;
let webrtc_apm_config = params
.audio_processing_config
.lock()
.map(|cfg| crate::processor::webrtc_apm::WebRtcApmConfig::from_audio_config(&cfg))
.unwrap_or_default();
Ok(Self {
encoder,
pcm_accum: Vec::with_capacity(crate::frame::FRAME_20MS_SAMPLES * 2),
opus_out: [0u8; crate::opus_voice::MAX_OPUS_FRAME],
voice_out_tx: params.voice_out_tx.clone(),
transmit_active: params.transmit_active.clone(),
output_muted: params.output_muted.clone(),
frames_sent: params.frames_sent.clone(),
mic_gain: params.mic_gain,
voice_activity_selector: params.voice_activity_selector.clone(),
vad_detector: crate::vad::WebRtcFallbackVad::default(),
silero_coreml_worker: None,
current_vad_backend: crate::VadBackend::WebrtcVad,
capture_frame_seq: 0,
vad_state: crate::voice_activity::VoiceActivityStateMachine::default(),
audio_processing_config: params.audio_processing_config.clone(),
webrtc_apm_processor: crate::processor::WebRtcApmProcessor::with_config(
webrtc_apm_config,
)?,
audio_processing_stats: params.audio_processing_stats.clone(),
render_reference,
pending_10ms: [0_i16; crate::frame::FRAME_10MS_SAMPLES],
pending_10ms_len: 0,
fallback_warned_backend: None,
wav_recorder: None,
})
}
fn mark_vad_fallback_active(&mut self, failed_backend: crate::VadBackend) {
if self.fallback_warned_backend != Some(failed_backend) {
self.fallback_warned_backend = Some(failed_backend);
if self.capture_frame_seq < 128 {
tracing::info!(
target: "chanora_audio",
backend = failed_backend.as_str(),
seq = self.capture_frame_seq,
"VAD backend warming up; using WebRTC fallback"
);
} else {
tracing::warn!(
target: "chanora_audio",
backend = failed_backend.as_str(),
"VAD backend unavailable; using WebRTC fallback for runtime detection"
);
}
}
}
fn ingest_i16(&mut self, samples: &[i16]) {
// Accumulate into 10 ms frames for VAD / Sonora processing.
let mut offset = 0;
while offset < samples.len() {
let remaining = crate::frame::FRAME_10MS_SAMPLES - self.pending_10ms_len;
let take = remaining.min(samples.len() - offset);
self.pending_10ms[self.pending_10ms_len..self.pending_10ms_len + take]
.copy_from_slice(&samples[offset..offset + take]);
self.pending_10ms_len += take;
offset += take;
if self.pending_10ms_len == crate::frame::FRAME_10MS_SAMPLES {
let frame = self.pending_10ms;
self.process_10ms_capture_frame(&frame);
self.pending_10ms_len = 0;
}
}
if !self.transmit_active.load(Ordering::Relaxed) {
self.pcm_accum.clear();
return;
}
// Encode complete 20 ms Opus frames.
while self.pcm_accum.len() >= crate::frame::FRAME_20MS_SAMPLES {
let mut frame = [0i16; crate::frame::FRAME_20MS_SAMPLES];
frame.copy_from_slice(&self.pcm_accum[..crate::frame::FRAME_20MS_SAMPLES]);
self.pcm_accum.drain(..crate::frame::FRAME_20MS_SAMPLES);
match self.encoder.encode(&frame, &mut self.opus_out[..]) {
Ok(len) => {
crate::opus_voice::send_voip_frame(
&self.voice_out_tx,
&self.frames_sent,
&self.opus_out,
len,
|| {
warn!(
target: "chanora_audio",
"ios raw: voice_out queue full; dropping frame"
);
},
|| {},
);
}
Err(e) => {
tracing::error!(target: "chanora_audio",
error = %e, "ios raw opus encode failed");
}
}
}
}
fn process_10ms_capture_frame(
&mut self,
samples: &[i16; crate::frame::FRAME_10MS_SAMPLES],
) {
let mut frame = [0.0_f32; crate::frame::FRAME_10MS_SAMPLES];
for (dst, src) in frame.iter_mut().zip(samples.iter().copied()) {
*dst = crate::frame::i16_to_f32(src);
}
let input_dbfs = crate::frame::dbfs(&frame);
// WAV tap: raw mic (before processing).
if let Some(ref rec) = self.wav_recorder {
rec.push_raw_mic(&frame);
}
// Feed render reference to WebRTC APM before capture so AEC can adapt.
let render_ref = self.render_reference.read_latest();
self.webrtc_apm_processor.process_render(&render_ref);
self.webrtc_apm_processor.process_capture(&mut frame);
// WAV tap: processed mic (after WebRTC APM).
if let Some(ref rec) = self.wav_recorder {
rec.push_processed_mic(&frame);
}
let voice_activity_mode = self
.voice_activity_selector
.as_ref()
.map(|selector| selector.mode() == crate::TransmitMode::VoiceActivity)
.unwrap_or(false);
if !voice_activity_mode {
self.silero_coreml_worker = None;
self.current_vad_backend = crate::VadBackend::Disabled;
self.fallback_warned_backend = None;
self.audio_processing_stats.set_vad_fallback_active(false);
}
let (vad_backend, vad_hangover) = self
.audio_processing_config
.try_lock()
.map(|cfg| (cfg.vad_backend, cfg.vad_hangover_ms))
.unwrap_or((
crate::VadBackend::WebrtcVad,
crate::voice_activity::VAD_HANGOVER_MS,
));
if voice_activity_mode {
self.vad_state.configure(
crate::voice_activity::VAD_OPEN_AFTER_MS,
vad_hangover,
crate::voice_activity::VAD_MIN_TX_MS,
);
}
if voice_activity_mode && vad_backend != self.current_vad_backend {
self.current_vad_backend = vad_backend;
self.fallback_warned_backend = None;
if vad_backend == crate::VadBackend::SileroOnnx {
self.silero_coreml_worker =
crate::vad::apple_coreml::AppleCoreMlVadWorker::try_new();
if self.silero_coreml_worker.is_none() {
self.mark_vad_fallback_active(crate::VadBackend::SileroOnnx);
self.audio_processing_stats.set_vad_fallback_active(true);
} else {
self.audio_processing_stats.set_vad_fallback_active(false);
}
} else {
self.silero_coreml_worker = None;
self.audio_processing_stats.set_vad_fallback_active(false);
}
self.vad_state.reset();
}
let (vad_probability, active) = if voice_activity_mode {
self.capture_frame_seq = self.capture_frame_seq.wrapping_add(1);
let capture_seq = self.capture_frame_seq;
let mut used_fallback_vad = false;
let vad = if vad_backend == crate::VadBackend::Disabled {
crate::vad::VadOutput {
probability: 1.0,
speech: true,
}
} else if vad_backend == crate::VadBackend::SileroOnnx {
if let Some(worker) = self.silero_coreml_worker.as_ref() {
let enqueued = worker.try_send(capture_seq, &frame);
if !worker.is_stale(capture_seq) {
let p = worker.latest_probability();
crate::vad::VadOutput {
probability: p,
speech: p >= 0.5,
}
} else if enqueued {
crate::vad::VadOutput {
probability: 0.0,
speech: false,
}
} else {
used_fallback_vad = true;
self.mark_vad_fallback_active(vad_backend);
crate::vad::VoiceActivityDetector::process_10ms(
&mut self.vad_detector,
&frame,
)
}
} else {
used_fallback_vad = true;
self.mark_vad_fallback_active(vad_backend);
crate::vad::VoiceActivityDetector::process_10ms(
&mut self.vad_detector,
&frame,
)
}
} else {
crate::vad::VoiceActivityDetector::process_10ms(&mut self.vad_detector, &frame)
};
self.audio_processing_stats
.set_vad_fallback_active(used_fallback_vad);
(vad.probability, self.vad_state.update(vad.speech))
} else {
(0.0, false)
};
if let Some(sel) = &self.voice_activity_selector {
sel.set_voice_activity_open(voice_activity_mode && active);
}
self.audio_processing_stats.update_capture(
input_dbfs,
crate::frame::dbfs(&frame),
vad_probability,
voice_activity_mode && active,
self.transmit_active.load(Ordering::Relaxed),
);
if !self.transmit_active.load(Ordering::Relaxed) {
return;
}
let gain = self.mic_gain;
if (gain - 1.0).abs() < f32::EPSILON {
self.pcm_accum
.extend(frame.iter().copied().map(crate::frame::f32_to_i16));
} else {
self.pcm_accum.extend(frame.iter().copied().map(|s| {
let scaled = crate::frame::f32_to_i16(s) as f32 * gain;
scaled.clamp(i16::MIN as f32, i16::MAX as f32) as i16
}));
}
}
}
// ------------------------------------------------------------------ //
// IosRawUnit //
// ------------------------------------------------------------------ //
/// Raw iOS RemoteIO audio unit for the Sonora experimental path.
pub struct IosRawUnit {
unit: AudioUnit,
}
impl IosRawUnit {
/// Open a RemoteIO AudioUnit, install render + input callbacks, start.
pub(crate) fn start(params: VoiceAudioParams) -> Result<Self, AudioError> {
// INV_010: reject if config requests VPIO (that's IosVoiceUnit's job).
{
let cfg = params.audio_processing_config.lock().unwrap();
if cfg.ios_mode == crate::IosVoiceProcessingMode::PlatformVoiceProcessing {
return Err(AudioError::InvalidAudioProcessingConfig(
"IosRawUnit requires raw WebRTC APM mode".to_string(),
));
}
}
let mut unit = AudioUnit::new_uninitialized(IOType::RemoteIO)
.map_err(|e| AudioError::Backend(format!("remoteio new: {e}")))?;
// Enable input on bus 1.
const ENABLE_IO: u32 = 2003;
let enable: u32 = 1;
unit.set_property(ENABLE_IO, Scope::Input, Element::Input, Some(&enable))
.map_err(|e| AudioError::Backend(format!("remoteio enable input: {e}")))?;
// 48 kHz Int16 mono on both buses.
let fmt = StreamFormat {
sample_rate: SAMPLE_RATE_HZ,
sample_format: SampleFormat::I16,
flags: LinearPcmFlags::IS_SIGNED_INTEGER | LinearPcmFlags::IS_PACKED,
channels: 1,
};
unit.set_stream_format(fmt, Scope::Input, Element::Output)
.map_err(|e| AudioError::StreamConfig(format!("remoteio fmt output: {e}")))?;
unit.set_stream_format(fmt, Scope::Output, Element::Input)
.map_err(|e| AudioError::StreamConfig(format!("remoteio fmt input: {e}")))?;
// Shared render-reference buffer (INV_011 / INV_012).
let render_ref_buf = RenderReferenceBuffer::new();
let render_ref_for_capture = render_ref_buf.clone();
let mut capture_state = RawCaptureState::new(&params, render_ref_for_capture)?;
unit.set_input_callback(move |args: render_callback::Args<data::Interleaved<i16>>| {
capture_state.ingest_i16(args.data.buffer);
Ok(())
})
.map_err(|e| AudioError::Backend(format!("remoteio input cb: {e}")))?;
let mut scratch: Vec<f32> = Vec::with_capacity(2048);
let handler = params.handler.clone();
let output_gain = params.output_gain.clone();
let output_muted = params.output_muted.clone();
let stats_render = params.audio_processing_stats.clone();
unit.set_render_callback(move |args: render_callback::Args<data::Interleaved<i16>>| {
let out = args.data.buffer;
let n = out.len();
let stereo_n = n * 2;
if scratch.len() < stereo_n {
scratch.resize(stereo_n, 0.0);
}
scratch[..stereo_n].fill(0.0);
match handler.try_lock() {
Ok(mut h) => {
let _ = h.fill_buffer(&mut scratch[..stereo_n]);
}
Err(std::sync::TryLockError::WouldBlock) => {
stats_render.increment_callback_xrun();
}
Err(std::sync::TryLockError::Poisoned(e)) => {
warn!(target: "chanora_audio",
"AudioHandler poisoned (raw render): {e}");
}
}
// INV_012: copy render reference BEFORE playout.
let mono_n = n.min(480);
let mut ref_frame = [0.0_f32; 480];
crate::voice_render::downmix_stereo_f32_to_mono_f32(
&scratch[..stereo_n],
&mut ref_frame[..mono_n],
);
render_ref_buf.write(&ref_frame);
let gain = f32::from_bits(output_gain.load(Ordering::Relaxed));
let muted = output_muted.load(Ordering::Relaxed);
let mix_stats = crate::voice_render::downmix_stereo_f32_to_mono_i16(
&scratch[..stereo_n],
out,
gain,
muted,
);
if mix_stats.clipped_samples > 0 {
stats_render.add_clipped_samples(mix_stats.clipped_samples);
}
stats_render.update_render(crate::frame::dbfs(&scratch[..stereo_n]), n as u32);
Ok(())
})
.map_err(|e| AudioError::Backend(format!("remoteio render cb: {e}")))?;
unit.initialize()
.map_err(|e| AudioError::Backend(format!("remoteio init: {e}")))?;
unit.start()
.map_err(|e| AudioError::Backend(format!("remoteio start: {e}")))?;
info!(
target: "chanora_audio",
sample_rate_hz = SAMPLE_RATE_HZ,
"ios RemoteIO (Sonora experimental) started"
);
Ok(Self { unit })
}
/// Restart the unit after a route change (stop → uninit → init → start).
pub fn restart(&mut self) -> Result<(), AudioError> {
self.unit
.stop()
.map_err(|e| AudioError::Backend(format!("remoteio restart stop: {e}")))?;
self.unit
.uninitialize()
.map_err(|e| AudioError::Backend(format!("remoteio restart uninit: {e}")))?;
self.unit
.initialize()
.map_err(|e| AudioError::Backend(format!("remoteio restart init: {e}")))?;
self.unit
.start()
.map_err(|e| AudioError::Backend(format!("remoteio restart start: {e}")))?;
info!(target: "chanora_audio", "ios RemoteIO restarted");
Ok(())
}
/// Pause the unit during an AVAudioSession interruption.
pub fn pause(&mut self) -> Result<(), AudioError> {
self.unit
.stop()
.map_err(|e| AudioError::Backend(format!("remoteio pause: {e}")))
}
/// Resume the unit after an interruption ends.
pub fn resume(&mut self) -> Result<(), AudioError> {
self.unit
.start()
.map_err(|e| AudioError::Backend(format!("remoteio resume: {e}")))
}
}
impl Drop for IosRawUnit {
fn drop(&mut self) {
if let Err(e) = self.unit.stop() {
warn!(target: "chanora_audio", error = %e,
"ios RemoteIO stop on drop failed");
} else {
info!(target: "chanora_audio", "ios RemoteIO stopped");
}
}
}
}
+159 -220
View File
@@ -66,7 +66,7 @@
//! * AVAudioSession category / mode configuration — Swift owns the //! * AVAudioSession category / mode configuration — Swift owns the
//! session (it must be set up before Flutter loads). //! session (it must be set up before Flutter loads).
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use audiopus::coder::Encoder as OpusEncoder; use audiopus::coder::Encoder as OpusEncoder;
@@ -75,12 +75,10 @@ use coreaudio::audio_unit::render_callback::{self, data};
use coreaudio::audio_unit::IOType; use coreaudio::audio_unit::IOType;
use coreaudio::audio_unit::{AudioUnit, Element, SampleFormat, Scope, StreamFormat}; use coreaudio::audio_unit::{AudioUnit, Element, SampleFormat, Scope, StreamFormat};
use crossbeam::queue::ArrayQueue; use crossbeam::queue::ArrayQueue;
use tokio::sync::mpsc;
use tracing::{debug, error, info, warn}; use tracing::{debug, error, info, warn};
use crate::mobile_voice_backend::VoiceAudioParams; use crate::mobile_voice_backend::VoiceAudioParams;
use crate::AudioError; use crate::AudioError;
use chanora_protocol::OutPacket;
/// Sample rate every layer above us assumes. Matches the Opus /// Sample rate every layer above us assumes. Matches the Opus
/// encoder rate, the `tsclientlib::AudioHandler` mix rate, and the /// encoder rate, the `tsclientlib::AudioHandler` mix rate, and the
@@ -105,6 +103,15 @@ const INPUT_BUS: Element = Element::Input;
/// when the VAD gate opens (VAD_004 / pre_roll_ms=160). /// when the VAD gate opens (VAD_004 / pre_roll_ms=160).
const PRE_ROLL_FRAMES: usize = 16; const PRE_ROLL_FRAMES: usize = 16;
/// Enough room for the 160 ms VAD pre-roll plus a few jitter frames, without
/// growing inside the input callback.
const CAPTURE_ACCUM_CAPACITY_SAMPLES: usize = crate::frame::FRAME_10MS_SAMPLES * 20;
/// Fixed iOS render scratch capacity. Larger callback requests are truncated
/// to this capacity and the remaining output is silence.
#[cfg_attr(not(target_os = "ios"), allow(dead_code))]
const IOS_RENDER_SCRATCH_FRAMES: usize = 4096;
/// Capture pipeline state owned by the VPIO input callback. The /// Capture pipeline state owned by the VPIO input callback. The
/// AudioUnit hands us 48 kHz signed-int16 mono PCM directly (no /// AudioUnit hands us 48 kHz signed-int16 mono PCM directly (no
/// downmix or resample needed — VPIO's hardware-side mix-down /// downmix or resample needed — VPIO's hardware-side mix-down
@@ -132,10 +139,9 @@ struct IosCaptureState {
/// jitter without reallocating. /// jitter without reallocating.
pcm_accum: Vec<i16>, pcm_accum: Vec<i16>,
opus_out: [u8; crate::opus_voice::MAX_OPUS_FRAME], opus_out: [u8; crate::opus_voice::MAX_OPUS_FRAME],
voice_out_tx: mpsc::Sender<OutPacket>, voice_out_tx: crate::opus_voice::EncodedVoiceFrameSender,
transmit_active: Arc<AtomicBool>, transmit_active: Arc<AtomicBool>,
output_muted: Arc<AtomicBool>, output_muted: Arc<AtomicBool>,
frames_sent: Arc<AtomicU32>,
mic_gain: f32, mic_gain: f32,
voice_activity_selector: Option<Arc<crate::TransmitModeSelector>>, voice_activity_selector: Option<Arc<crate::TransmitModeSelector>>,
vad_detector: crate::vad::WebRtcFallbackVad, vad_detector: crate::vad::WebRtcFallbackVad,
@@ -154,7 +160,6 @@ struct IosCaptureState {
pre_roll_count: usize, pre_roll_count: usize,
pre_roll_flushed: bool, pre_roll_flushed: bool,
capture_frame_seq: u64, capture_frame_seq: u64,
wav_recorder: Arc<Mutex<Option<Arc<crate::debug_wav::WavDebugRecorder>>>>,
} }
impl IosCaptureState { impl IosCaptureState {
@@ -162,20 +167,20 @@ impl IosCaptureState {
/// Encoder configuration is the same as cpal-side /// Encoder configuration is the same as cpal-side
/// `try_open_capture` (engine.rs) so audio quality is platform- /// `try_open_capture` (engine.rs) so audio quality is platform-
/// neutral. /// neutral.
fn new( fn new(params: &VoiceAudioParams) -> Result<Self, AudioError> {
params: &VoiceAudioParams,
wav_recorder: Arc<Mutex<Option<Arc<crate::debug_wav::WavDebugRecorder>>>>,
) -> Result<Self, AudioError> {
let encoder = crate::opus_voice::new_voip_encoder("ios VPIO")?; let encoder = crate::opus_voice::new_voip_encoder("ios VPIO")?;
Ok(Self { Ok(Self {
encoder, encoder,
pcm_accum: Vec::with_capacity(crate::frame::FRAME_20MS_SAMPLES * 2), pcm_accum: Vec::with_capacity(CAPTURE_ACCUM_CAPACITY_SAMPLES),
opus_out: [0u8; crate::opus_voice::MAX_OPUS_FRAME], opus_out: [0u8; crate::opus_voice::MAX_OPUS_FRAME],
voice_out_tx: params.voice_out_tx.clone(), voice_out_tx: crate::opus_voice::start_out_packet_worker(
params.voice_out_tx.clone(),
params.frames_sent.clone(),
"ios-vpio",
)?,
transmit_active: params.transmit_active.clone(), transmit_active: params.transmit_active.clone(),
output_muted: params.output_muted.clone(), output_muted: params.output_muted.clone(),
frames_sent: params.frames_sent.clone(),
mic_gain: params.mic_gain, mic_gain: params.mic_gain,
voice_activity_selector: params.voice_activity_selector.clone(), voice_activity_selector: params.voice_activity_selector.clone(),
vad_detector: crate::vad::WebRtcFallbackVad::default(), vad_detector: crate::vad::WebRtcFallbackVad::default(),
@@ -193,7 +198,6 @@ impl IosCaptureState {
pre_roll_count: 0, pre_roll_count: 0,
pre_roll_flushed: false, pre_roll_flushed: false,
capture_frame_seq: 0, capture_frame_seq: 0,
wav_recorder,
}) })
} }
@@ -267,7 +271,6 @@ impl IosCaptureState {
Ok(len) => { Ok(len) => {
crate::opus_voice::send_voip_frame( crate::opus_voice::send_voip_frame(
&self.voice_out_tx, &self.voice_out_tx,
&self.frames_sent,
&self.opus_out, &self.opus_out,
len, len,
|| { || {
@@ -298,25 +301,9 @@ impl IosCaptureState {
} }
let input_dbfs = crate::frame::dbfs(&frame); let input_dbfs = crate::frame::dbfs(&frame);
// WAV tap: raw mic (before processing, DIAG_002).
if let Ok(guard) = self.wav_recorder.try_lock() {
if let Some(rec) = guard.as_ref() {
rec.push_raw_mic(&frame);
}
}
// Read config once per frame (try_lock: non-blocking, falls back to // Read config once per frame (try_lock: non-blocking, falls back to
// last-known values if the lock is contended — safe to miss one frame). // last-known values if the lock is contended — safe to miss one frame).
let ( let (run_ns, run_agc, run_hpf, vad_backend, vad_hangover, debug_wav_dump_enabled) = self
run_ns,
run_agc,
run_hpf,
vad_backend,
vad_hangover,
debug_wav_dump_enabled,
route,
processing_backend,
) = self
.audio_processing_config .audio_processing_config
.try_lock() .try_lock()
.map(|cfg| { .map(|cfg| {
@@ -332,8 +319,6 @@ impl IosCaptureState {
cfg.vad_backend, cfg.vad_backend,
cfg.vad_hangover_ms, cfg.vad_hangover_ms,
cfg.debug_wav_dump_enabled, cfg.debug_wav_dump_enabled,
cfg.route,
cfg.processing_backend,
) )
}) })
.unwrap_or(( .unwrap_or((
@@ -343,10 +328,13 @@ impl IosCaptureState {
crate::VadBackend::WebrtcVad, crate::VadBackend::WebrtcVad,
crate::voice_activity::VAD_HANGOVER_MS, crate::voice_activity::VAD_HANGOVER_MS,
false, false,
crate::AudioRoute::Unknown,
crate::AudioBackend::PlatformVoiceProcessing,
)); ));
// VPIO realtime callbacks cannot use WavDebugRecorder today: its push
// path allocates per frame. Debug WAV capture is intentionally disabled
// here until the recorder can hand off preallocated frames.
let _ = debug_wav_dump_enabled;
let voice_activity_mode = self let voice_activity_mode = self
.voice_activity_selector .voice_activity_selector
.as_ref() .as_ref()
@@ -359,32 +347,13 @@ impl IosCaptureState {
self.audio_processing_stats.set_vad_fallback_active(false); self.audio_processing_stats.set_vad_fallback_active(false);
} }
// Switch VAD backend only while VoiceActivity mode is active.
if let Ok(mut recorder_guard) = self.wav_recorder.try_lock() {
if debug_wav_dump_enabled {
if recorder_guard.is_none() {
*recorder_guard = Some(crate::debug_wav::WavDebugRecorder::start(
route,
processing_backend,
));
}
} else if let Some(recorder) = recorder_guard.take() {
recorder.stop();
}
}
if voice_activity_mode && vad_backend != self.current_vad_backend { if voice_activity_mode && vad_backend != self.current_vad_backend {
self.current_vad_backend = vad_backend; self.current_vad_backend = vad_backend;
self.fallback_warned_backend = None; self.fallback_warned_backend = None;
if vad_backend == crate::VadBackend::SileroOnnx { if vad_backend == crate::VadBackend::SileroOnnx {
self.silero_coreml_worker = self.silero_coreml_worker = None;
crate::vad::apple_coreml::AppleCoreMlVadWorker::try_new(); self.mark_vad_fallback_active(crate::VadBackend::SileroOnnx);
if self.silero_coreml_worker.is_none() { self.audio_processing_stats.set_vad_fallback_active(true);
self.mark_vad_fallback_active(crate::VadBackend::SileroOnnx);
self.audio_processing_stats.set_vad_fallback_active(true);
} else {
self.audio_processing_stats.set_vad_fallback_active(false);
}
} else { } else {
self.silero_coreml_worker = None; self.silero_coreml_worker = None;
self.audio_processing_stats.set_vad_fallback_active(false); self.audio_processing_stats.set_vad_fallback_active(false);
@@ -461,7 +430,10 @@ impl IosCaptureState {
} else { } else {
used_fallback_vad = true; used_fallback_vad = true;
self.mark_vad_fallback_active(crate::VadBackend::SileroOnnx); self.mark_vad_fallback_active(crate::VadBackend::SileroOnnx);
crate::vad::VoiceActivityDetector::process_10ms(&mut self.vad_detector, &frame) crate::vad::VoiceActivityDetector::process_10ms(
&mut self.vad_detector,
&frame,
)
} }
} else { } else {
crate::vad::VoiceActivityDetector::process_10ms(&mut self.vad_detector, &frame) crate::vad::VoiceActivityDetector::process_10ms(&mut self.vad_detector, &frame)
@@ -484,13 +456,6 @@ impl IosCaptureState {
transmit_active, transmit_active,
); );
// WAV tap: processed mic (after Rust DSP, DIAG_002).
if let Ok(guard) = self.wav_recorder.try_lock() {
if let Some(rec) = guard.as_ref() {
rec.push_processed_mic(&frame);
}
}
// Convert to i16 for accumulation. // Convert to i16 for accumulation.
let mut pcm_frame = [0_i16; crate::frame::FRAME_10MS_SAMPLES]; let mut pcm_frame = [0_i16; crate::frame::FRAME_10MS_SAMPLES];
if (self.mic_gain - 1.0).abs() < f32::EPSILON { if (self.mic_gain - 1.0).abs() < f32::EPSILON {
@@ -528,7 +493,13 @@ impl IosCaptureState {
let pre_roll_to_emit = self.pre_roll_count.saturating_sub(1); let pre_roll_to_emit = self.pre_roll_count.saturating_sub(1);
for i in 0..pre_roll_to_emit { for i in 0..pre_roll_to_emit {
let idx = (oldest + i) % PRE_ROLL_FRAMES; let idx = (oldest + i) % PRE_ROLL_FRAMES;
self.pcm_accum.extend_from_slice(&self.pre_roll_buf[idx]); if crate::capture_accumulator::append_i16_bounded(
&mut self.pcm_accum,
&self.pre_roll_buf[idx],
) {
self.audio_processing_stats.increment_callback_xrun();
break;
}
} }
} else if !transmit_active { } else if !transmit_active {
// Gate closed — reset the flush flag so pre-roll fires again // Gate closed — reset the flush flag so pre-roll fires again
@@ -540,7 +511,9 @@ impl IosCaptureState {
return; return;
} }
self.pcm_accum.extend_from_slice(&pcm_frame); if crate::capture_accumulator::append_i16_bounded(&mut self.pcm_accum, &pcm_frame) {
self.audio_processing_stats.increment_callback_xrun();
}
} }
} }
@@ -694,9 +667,7 @@ impl IosVoiceUnit {
Element::Output, Element::Output,
Some(&ducking_config), Some(&ducking_config),
) { ) {
tracing::debug!( tracing::debug!("vpio set OtherAudioDuckingConfiguration failed (older OS?): {e}");
"vpio set OtherAudioDuckingConfiguration failed (older OS?): {e}"
);
} }
// Note: we keep VPIO's voice processing chain ENABLED // Note: we keep VPIO's voice processing chain ENABLED
@@ -748,18 +719,7 @@ impl IosVoiceUnit {
// scratch are owned by the closure — no Mutex needed // scratch are owned by the closure — no Mutex needed
// because the input callback is the sole writer/reader on // because the input callback is the sole writer/reader on
// the audio thread. // the audio thread.
let wav_recorder = Arc::new(Mutex::new({ let mut capture_state = IosCaptureState::new(&params)?;
let cfg = params.audio_processing_config.lock().unwrap().clone();
if cfg.debug_wav_dump_enabled {
Some(crate::debug_wav::WavDebugRecorder::start(
cfg.route,
cfg.processing_backend,
))
} else {
None
}
}));
let mut capture_state = IosCaptureState::new(&params, wav_recorder.clone())?;
unit.set_input_callback(move |args: render_callback::Args<data::Interleaved<i16>>| { unit.set_input_callback(move |args: render_callback::Args<data::Interleaved<i16>>| {
// VPIO with our pinned stream format delivers // VPIO with our pinned stream format delivers
@@ -879,11 +839,8 @@ impl IosVoiceUnit {
tokio::spawn(async move { tokio::spawn(async move {
let mut pull_scratch: Vec<f32> = vec![0.0; PULL_SAMPLES]; let mut pull_scratch: Vec<f32> = vec![0.0; PULL_SAMPLES];
let mut interval = let mut interval = tokio::time::interval(std::time::Duration::from_millis(20));
tokio::time::interval(std::time::Duration::from_millis(20)); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
interval.set_missed_tick_behavior(
tokio::time::MissedTickBehavior::Delay,
);
loop { loop {
interval.tick().await; interval.tick().await;
if producer_shutdown_for_task.load(Ordering::Relaxed) { if producer_shutdown_for_task.load(Ordering::Relaxed) {
@@ -909,16 +866,16 @@ impl IosVoiceUnit {
unit.set_render_callback(move |args: render_callback::Args<data::Interleaved<i16>>| { unit.set_render_callback(move |args: render_callback::Args<data::Interleaved<i16>>| {
let render_callback::Args { let render_callback::Args {
data, data, num_frames, ..
num_frames,
..
} = args; } = args;
let out: &mut [i16] = data.buffer; let out: &mut [i16] = data.buffer;
let out_channels = data.channels; let out_channels = data.channels;
let needed = num_frames * out_channels; let needed = num_frames * out_channels;
if pcm_ring_consumer.len() < PREBUFFER_SAMPLES { if pcm_ring_consumer.len() < PREBUFFER_SAMPLES {
for sample in &mut out[..needed] { *sample = 0; } for sample in &mut out[..needed] {
*sample = 0;
}
return Ok(()); return Ok(());
} }
@@ -939,10 +896,8 @@ impl IosVoiceUnit {
let mono = (l_lim + r_lim) * 0.5; let mono = (l_lim + r_lim) * 0.5;
out[base] = (mono.clamp(-1.0, 1.0) * i16::MAX as f32) as i16; out[base] = (mono.clamp(-1.0, 1.0) * i16::MAX as f32) as i16;
} else { } else {
out[base] = out[base] = (l_lim.clamp(-1.0, 1.0) * i16::MAX as f32) as i16;
(l_lim.clamp(-1.0, 1.0) * i16::MAX as f32) as i16; out[base + 1] = (r_lim.clamp(-1.0, 1.0) * i16::MAX as f32) as i16;
out[base + 1] =
(r_lim.clamp(-1.0, 1.0) * i16::MAX as f32) as i16;
} }
written_frames += 1; written_frames += 1;
} }
@@ -951,17 +906,18 @@ impl IosVoiceUnit {
let remaining = num_frames - written_frames; let remaining = num_frames - written_frames;
for f in 0..remaining { for f in 0..remaining {
let base = (written_frames + f) * out_channels; let base = (written_frames + f) * out_channels;
for c in 0..out_channels { out[base + c] = 0; } for c in 0..out_channels {
out[base + c] = 0;
}
} }
} }
let gain = f32::from_bits( let gain = f32::from_bits(output_gain_for_render.load(Ordering::Relaxed));
output_gain_for_render.load(Ordering::Relaxed), let muted = output_muted_for_render.load(Ordering::Relaxed);
);
let muted =
output_muted_for_render.load(Ordering::Relaxed);
if muted { if muted {
for sample in &mut out[..needed] { *sample = 0; } for sample in &mut out[..needed] {
*sample = 0;
}
} else if gain != 1.0 { } else if gain != 1.0 {
for sample in &mut out[..needed] { for sample in &mut out[..needed] {
*sample = (((*sample as f32) * gain) *sample = (((*sample as f32) * gain)
@@ -972,9 +928,7 @@ impl IosVoiceUnit {
Ok(()) Ok(())
}) })
.map_err(|e| AudioError::Backend(format!( .map_err(|e| AudioError::Backend(format!("audio unit set render callback: {e}")))?;
"audio unit set render callback: {e}"
)))?;
} }
// iOS path: direct fill_buffer in callback. iOS VPIO // iOS path: direct fill_buffer in callback. iOS VPIO
@@ -984,127 +938,112 @@ impl IosVoiceUnit {
// producer-task path above. // producer-task path above.
#[cfg(target_os = "ios")] #[cfg(target_os = "ios")]
{ {
let mut scratch_stereo: Vec<f32> = vec![0.0; 4096 * 2]; let mut scratch_stereo: Vec<f32> = vec![0.0; IOS_RENDER_SCRATCH_FRAMES * 2];
let handler_for_render = params.handler.clone(); let handler_for_render = params.handler.clone();
let output_gain_for_render = params.output_gain.clone(); let output_gain_for_render = params.output_gain.clone();
let output_muted_for_render = params.output_muted.clone(); let output_muted_for_render = params.output_muted.clone();
let audio_processing_stats_for_render = params.audio_processing_stats.clone(); let audio_processing_stats_for_render = params.audio_processing_stats.clone();
// Level meter decimation: the render callback fires ~93 // Level meter decimation: the render callback fires ~93
// times/sec, but the bridge consumer reads at ~30 Hz. // times/sec, but the bridge consumer reads at ~30 Hz.
let mut render_level_decimation: u32 = 0; let mut render_level_decimation: u32 = 0;
unit.set_render_callback(move |args: render_callback::Args<data::Interleaved<i16>>| { // Debug WAV render-reference capture is intentionally unavailable
let render_callback::Args { // on iOS VPIO callbacks until WavDebugRecorder supports a
data, // preallocated handoff; its current push path allocates per frame.
num_frames, // Diagnostic counters sampled every 100 callbacks.
.. let mut cb_count: u64 = 0;
} = args; let mut last_num_frames: usize = 0;
let out: &mut [i16] = data.buffer; let mut num_frames_changes: u64 = 0;
let out_channels = data.channels; let mut callbacks_with_audio: u64 = 0;
// AudioHandler produces 48 kHz stereo f32 (= num_frames * 2 floats). let mut callbacks_with_silence: u64 = 0;
let needed = num_frames * 2; unit.set_render_callback(move |args: render_callback::Args<data::Interleaved<i16>>| {
if scratch_stereo.len() < needed { let render_callback::Args {
scratch_stereo.resize(needed, 0.0); data, num_frames, ..
} } = args;
// Zero the live slice. AudioHandler::fill_buffer is let out: &mut [i16] = data.buffer;
// additive (does NOT clear); residual values from let out_channels = data.channels;
// earlier callbacks (when scratch was bigger) would let process_frames = num_frames.min(IOS_RENDER_SCRATCH_FRAMES);
// leak through otherwise. if process_frames < num_frames {
scratch_stereo[..needed].fill(0.0);
match handler_for_render.try_lock() {
Ok(mut h) => {
let _ = h.fill_buffer(&mut scratch_stereo[..needed]);
}
Err(std::sync::TryLockError::WouldBlock) => {
audio_processing_stats_for_render.increment_callback_xrun(); audio_processing_stats_for_render.increment_callback_xrun();
// scratch_stereo is already zeroed above.
} }
Err(std::sync::TryLockError::Poisoned(e)) => { // AudioHandler produces 48 kHz stereo f32 (= frames * 2 floats).
// Never panic on the realtime IO thread. let needed = process_frames * 2;
warn!(target: "chanora_audio", "AudioHandler mutex poisoned: {e}"); // Zero the live slice. AudioHandler::fill_buffer is
} // additive (does NOT clear); residual values from
} // earlier callbacks (when scratch was bigger) would
// Peak limiter — multi-client mixes can sum past 0 dBFS; // leak through otherwise.
// without this the downmix helper would hard-clip to i16::MAX. scratch_stereo[..needed].fill(0.0);
crate::voice_render::limit_peak_inplace(&mut scratch_stereo[..needed], 0.99); match handler_for_render.try_lock() {
let gain = f32::from_bits(output_gain_for_render.load(Ordering::Relaxed)); Ok(mut h) => {
let muted = output_muted_for_render.load(Ordering::Relaxed); let _ = h.fill_buffer(&mut scratch_stereo[..needed]);
let mix_stats = crate::voice_render::downmix_stereo_f32_to_interleaved_i16(
&scratch_stereo[..needed],
out,
out_channels,
gain,
muted,
);
if mix_stats.clipped_samples > 0 {
audio_processing_stats_for_render.add_clipped_samples(mix_stats.clipped_samples);
}
render_level_decimation = render_level_decimation.wrapping_add(1);
if render_level_decimation % 3 == 0 {
audio_processing_stats_for_render.update_render(
crate::frame::dbfs(&scratch_stereo[..needed]),
num_frames as u32,
);
}
if let Ok(guard) = wav_recorder_for_render.try_lock() {
if let Some(rec) = guard.as_ref() {
if !render_recorder_active {
render_ref_len = 0;
render_ref_accum.fill(0.0);
render_recorder_active = true;
} }
let mut idx = 0; Err(std::sync::TryLockError::WouldBlock) => {
while idx + 1 < needed { audio_processing_stats_for_render.increment_callback_xrun();
let mono = (scratch_stereo[idx] + scratch_stereo[idx + 1]) * 0.5; // scratch_stereo is already zeroed above.
render_ref_accum[render_ref_len] = mono; }
render_ref_len += 1; Err(std::sync::TryLockError::Poisoned(e)) => {
idx += 2; // Never panic on the realtime IO thread.
if render_ref_len == crate::frame::FRAME_10MS_SAMPLES { warn!(target: "chanora_audio", "AudioHandler mutex poisoned: {e}");
rec.push_render_reference(&render_ref_accum);
render_ref_len = 0;
}
} }
} else {
render_recorder_active = false;
} }
} else { // Peak limiter — multi-client mixes can sum past 0 dBFS;
render_recorder_active = false; // without this the downmix helper would hard-clip to i16::MAX.
} crate::voice_render::limit_peak_inplace(&mut scratch_stereo[..needed], 0.99);
// Track audio-vs-silence for the diagnostic. let gain = f32::from_bits(output_gain_for_render.load(Ordering::Relaxed));
if mix_stats.peak_i16 > 0 { let muted = output_muted_for_render.load(Ordering::Relaxed);
callbacks_with_audio = callbacks_with_audio.wrapping_add(1); let mix_stats = crate::voice_render::downmix_stereo_f32_to_interleaved_i16(
} else { &scratch_stereo[..needed],
callbacks_with_silence = callbacks_with_silence.wrapping_add(1); out,
// Muted output writes intentional silence (peak_i16 == 0 by out_channels,
// design), not a starved render path. Gate on !muted to avoid
// counting deliberate silence as an output underrun.
if !muted {
audio_processing_stats_for_render.increment_output_underrun();
}
}
// Diagnostic sampling.
if last_num_frames != 0 && last_num_frames != num_frames {
num_frames_changes = num_frames_changes.wrapping_add(1);
}
last_num_frames = num_frames;
cb_count = cb_count.wrapping_add(1);
if cb_count.is_multiple_of(100) {
debug!(
target: "chanora_audio",
cb = cb_count,
num_frames,
frames_changes = num_frames_changes,
callbacks_with_audio,
callbacks_with_silence,
peak_out_i16 = mix_stats.peak_i16,
gain, gain,
"ios audio unit render callback diagnostic sample (direct fill_buffer)" muted,
); );
} if mix_stats.clipped_samples > 0 {
Ok(()) audio_processing_stats_for_render
}) .add_clipped_samples(mix_stats.clipped_samples);
.map_err(|e| AudioError::Backend(format!("audio unit set render callback: {e}")))?; }
render_level_decimation = render_level_decimation.wrapping_add(1);
if render_level_decimation % 3 == 0 {
audio_processing_stats_for_render.update_render(
crate::frame::dbfs(&scratch_stereo[..needed]),
num_frames as u32,
);
}
// Track audio-vs-silence for the diagnostic.
if mix_stats.peak_i16 > 0 {
callbacks_with_audio = callbacks_with_audio.wrapping_add(1);
} else {
callbacks_with_silence = callbacks_with_silence.wrapping_add(1);
// Muted output writes intentional silence (peak_i16 == 0 by
// design), not a starved render path. Gate on !muted to avoid
// counting deliberate silence as an output underrun.
if !muted {
audio_processing_stats_for_render.increment_output_underrun();
}
}
// Diagnostic sampling.
if last_num_frames != 0 && last_num_frames != num_frames {
num_frames_changes = num_frames_changes.wrapping_add(1);
}
last_num_frames = num_frames;
cb_count = cb_count.wrapping_add(1);
if cb_count.is_multiple_of(100) {
debug!(
target: "chanora_audio",
cb = cb_count,
num_frames,
frames_changes = num_frames_changes,
callbacks_with_audio,
callbacks_with_silence,
peak_out_i16 = mix_stats.peak_i16,
gain,
"ios audio unit render callback diagnostic sample (direct fill_buffer)"
);
}
Ok(())
})
.map_err(|e| AudioError::Backend(format!("audio unit set render callback: {e}")))?;
} // end #[cfg(target_os = "ios")] block } // end #[cfg(target_os = "ios")] block
// Finalise the unit — allocates internal buffers per the // Finalise the unit — allocates internal buffers per the
+13 -4
View File
@@ -28,10 +28,17 @@
#![warn(missing_docs)] #![warn(missing_docs)]
#[cfg(any(target_os = "android", test))]
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
mod android_render_ring;
#[cfg(any(target_os = "android", test))] #[cfg(any(target_os = "android", test))]
#[cfg_attr(not(target_os = "android"), allow(dead_code))] #[cfg_attr(not(target_os = "android"), allow(dead_code))]
mod audio_event_queue; mod audio_event_queue;
pub mod audio_processing; pub mod audio_processing;
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
mod capture_accumulator;
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
mod capture_resampler;
pub mod debug_wav; pub mod debug_wav;
mod engine; mod engine;
pub mod frame; pub mod frame;
@@ -42,6 +49,11 @@ pub mod processor;
pub mod ptt; pub mod ptt;
pub mod ptt_backends; pub mod ptt_backends;
pub mod release_tail; pub mod release_tail;
#[cfg_attr(
not(any(target_os = "android", target_os = "ios", test)),
allow(dead_code)
)]
pub(crate) mod render_reference;
pub mod route_policy; pub mod route_policy;
pub mod transmit_mode; pub mod transmit_mode;
pub mod transmit_selector; pub mod transmit_selector;
@@ -53,10 +65,7 @@ pub(crate) mod voice_render;
mod sdl_output; mod sdl_output;
#[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg(any(target_os = "ios", target_os = "macos"))]
mod ios_voice_unit; mod ios_voice_unit;
#[cfg(target_os = "ios")]
pub mod ios_raw_unit;
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
pub mod android_voice_unit; pub mod android_voice_unit;
+198 -15
View File
@@ -3,15 +3,18 @@ use audiopus::{
Application as OpusApp, Bitrate as OpusBitrate, Channels as OpusChannels, Application as OpusApp, Bitrate as OpusBitrate, Channels as OpusChannels,
SampleRate as OpusSampleRate, SampleRate as OpusSampleRate,
}; };
use std::sync::atomic::{AtomicU32, Ordering}; use crossbeam::queue::ArrayQueue;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::Arc;
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tracing::{info, warn}; use tracing::{debug, info, warn};
use chanora_protocol::{AudioData, CodecType, OutAudio, OutPacket}; use chanora_protocol::{AudioData, CodecType, OutAudio, OutPacket};
use crate::AudioError; use crate::AudioError;
pub(crate) const MAX_OPUS_FRAME: usize = 1275; pub(crate) const MAX_OPUS_FRAME: usize = 1275;
const VOICE_FRAME_QUEUE_CAPACITY: usize = 64;
const VOIP_BITRATE_BPS: i32 = 32_000; const VOIP_BITRATE_BPS: i32 = 32_000;
const VOIP_COMPLEXITY: u8 = 10; const VOIP_COMPLEXITY: u8 = 10;
@@ -54,10 +57,129 @@ pub(crate) fn tune_voip_encoder(encoder: &mut OpusEncoder, context: &str) {
); );
} }
pub(crate) struct EncodedVoiceFrame {
data: [u8; MAX_OPUS_FRAME],
len: usize,
}
pub(crate) struct EncodedVoiceFrameSender {
queue: Arc<ArrayQueue<EncodedVoiceFrame>>,
open: Arc<AtomicBool>,
}
enum EncodedVoiceFrameSendError {
Full,
Closed,
}
impl EncodedVoiceFrameSender {
fn new(capacity: usize) -> Self {
Self {
queue: Arc::new(ArrayQueue::new(capacity)),
open: Arc::new(AtomicBool::new(true)),
}
}
fn worker_queue(&self) -> Arc<ArrayQueue<EncodedVoiceFrame>> {
Arc::clone(&self.queue)
}
fn worker_open_flag(&self) -> Arc<AtomicBool> {
Arc::clone(&self.open)
}
fn push(&self, frame: EncodedVoiceFrame) -> Result<(), EncodedVoiceFrameSendError> {
if !self.open.load(Ordering::Relaxed) {
return Err(EncodedVoiceFrameSendError::Closed);
}
self.queue
.push(frame)
.map_err(|_| EncodedVoiceFrameSendError::Full)
}
}
pub(crate) fn start_out_packet_worker(
voice_out_tx: mpsc::Sender<OutPacket>,
frames_sent: Arc<AtomicU32>,
context: &'static str,
) -> Result<EncodedVoiceFrameSender, AudioError> {
start_out_packet_worker_with_spawner(voice_out_tx, frames_sent, context, |name, worker| {
std::thread::Builder::new()
.name(name)
.spawn(worker)
.map(|_| ())
})
}
fn start_out_packet_worker_with_spawner<S>(
voice_out_tx: mpsc::Sender<OutPacket>,
frames_sent: Arc<AtomicU32>,
context: &'static str,
spawn: S,
) -> Result<EncodedVoiceFrameSender, AudioError>
where
S: FnOnce(String, Box<dyn FnOnce() + Send + 'static>) -> std::io::Result<()>,
{
let tx = EncodedVoiceFrameSender::new(VOICE_FRAME_QUEUE_CAPACITY);
let rx = tx.worker_queue();
let worker_open = tx.worker_open_flag();
spawn(
format!("chanora-{context}-voice-packets"),
Box::new(move || {
loop {
let Some(frame) = rx.pop() else {
if Arc::strong_count(&rx) == 1 {
break;
}
std::thread::sleep(std::time::Duration::from_millis(1));
continue;
};
let packet = OutAudio::new(&AudioData::C2S {
id: 0,
codec: CodecType::OpusVoice,
data: frame.as_slice(),
});
match voice_out_tx.try_send(packet) {
Ok(()) => {
frames_sent.fetch_add(1, Ordering::Relaxed);
}
Err(mpsc::error::TrySendError::Full(_)) => {
warn!(target: "chanora_audio", context = %context, "voice_out queue full; dropping frame");
}
Err(mpsc::error::TrySendError::Closed(_)) => {
debug!(target: "chanora_audio", context = %context, "voice_out closed; voice packet worker stopping");
worker_open.store(false, Ordering::Relaxed);
break;
}
}
}
}),
)
.map_err(|e| {
tx.open.store(false, Ordering::Relaxed);
AudioError::Backend(format!("voice packet worker spawn ({context}): {e}"))
})?;
Ok(tx)
}
impl EncodedVoiceFrame {
fn try_from_opus(opus_out: &[u8], len: usize) -> Option<Self> {
if len > opus_out.len() || len > MAX_OPUS_FRAME {
return None;
}
let mut data = [0u8; MAX_OPUS_FRAME];
data[..len].copy_from_slice(&opus_out[..len]);
Some(Self { data, len })
}
fn as_slice(&self) -> &[u8] {
&self.data[..self.len]
}
}
/// Encode-scope send helper for a freshly encoded Opus voice frame. /// Encode-scope send helper for a freshly encoded Opus voice frame.
pub(crate) fn send_voip_frame<F, G>( pub(crate) fn send_voip_frame<F, G>(
voice_out_tx: &mpsc::Sender<OutPacket>, voice_out_tx: &EncodedVoiceFrameSender,
frames_sent: &AtomicU32,
opus_out: &[u8], opus_out: &[u8],
len: usize, len: usize,
on_full: F, on_full: F,
@@ -66,16 +188,77 @@ pub(crate) fn send_voip_frame<F, G>(
F: FnOnce(), F: FnOnce(),
G: FnOnce(), G: FnOnce(),
{ {
let packet = OutAudio::new(&AudioData::C2S { let Some(frame) = EncodedVoiceFrame::try_from_opus(opus_out, len) else {
id: 0, on_full();
codec: CodecType::OpusVoice, return;
data: &opus_out[..len], };
}); match voice_out_tx.push(frame) {
match voice_out_tx.try_send(packet) { Ok(()) => {}
Ok(()) => { Err(EncodedVoiceFrameSendError::Full) => on_full(),
frames_sent.fetch_add(1, Ordering::Relaxed); Err(EncodedVoiceFrameSendError::Closed) => on_closed(),
} }
Err(mpsc::error::TrySendError::Full(_)) => on_full(), }
Err(mpsc::error::TrySendError::Closed(_)) => on_closed(),
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encoded_voice_frame_copies_into_fixed_storage() {
let source = [7u8; MAX_OPUS_FRAME];
let frame = EncodedVoiceFrame::try_from_opus(&source, MAX_OPUS_FRAME).unwrap();
assert_eq!(frame.as_slice().len(), MAX_OPUS_FRAME);
assert!(frame.as_slice().iter().all(|byte| *byte == 7));
}
#[test]
fn encoded_voice_frame_rejects_lengths_beyond_fixed_storage() {
let source = [0u8; MAX_OPUS_FRAME];
assert!(EncodedVoiceFrame::try_from_opus(&source, MAX_OPUS_FRAME + 1).is_none());
}
#[test]
fn encoded_voice_frame_sender_reports_full_without_blocking() {
let sender = EncodedVoiceFrameSender::new(1);
let source = [3u8; MAX_OPUS_FRAME];
let first = EncodedVoiceFrame::try_from_opus(&source, 4).unwrap();
let second = EncodedVoiceFrame::try_from_opus(&source, 4).unwrap();
assert!(sender.push(first).is_ok());
assert!(sender.push(second).is_err());
}
#[test]
fn encoded_voice_frame_sender_reports_closed_without_queueing() {
let sender = EncodedVoiceFrameSender::new(1);
sender.open.store(false, Ordering::Relaxed);
let source = [3u8; MAX_OPUS_FRAME];
let frame = EncodedVoiceFrame::try_from_opus(&source, 4).unwrap();
assert!(matches!(
sender.push(frame),
Err(EncodedVoiceFrameSendError::Closed)
));
assert_eq!(sender.queue.len(), 0);
}
#[test]
fn encoded_voice_frame_sender_reports_spawn_failure() {
let (voice_out_tx, _voice_out_rx) = mpsc::channel(1);
let frames_sent = Arc::new(AtomicU32::new(0));
let result = start_out_packet_worker_with_spawner(
voice_out_tx,
frames_sent,
"test",
|_name, _worker| Err(std::io::Error::other("spawn failed")),
);
assert!(
matches!(result, Err(AudioError::Backend(message)) if message.contains("spawn failed"))
);
} }
} }
+28 -11
View File
@@ -22,6 +22,7 @@
use core::fmt; use core::fmt;
use crate::ptt::{AudioTransmitGate, PttBackendDescriptor}; use crate::ptt::{AudioTransmitGate, PttBackendDescriptor};
use thiserror::Error;
mod focused; mod focused;
@@ -108,35 +109,51 @@ impl fmt::Display for PttInputClass {
} }
/// Errors raised by a desktop PTT backend. /// Errors raised by a desktop PTT backend.
#[derive(Debug)] #[derive(Debug, Error)]
pub enum PttBackendError { pub enum PttBackendError {
/// The OS rejected the backend initialisation (e.g. Raw Input /// The OS rejected the backend initialisation (e.g. Raw Input
/// registration failed, event tap creation failed). /// registration failed, event tap creation failed).
#[error("init failed: {0}")]
Init(String), Init(String),
/// The user-granted permission required for global capture is /// The user-granted permission required for global capture is
/// not granted (typically macOS Input Monitoring / Accessibility). /// not granted (typically macOS Input Monitoring / Accessibility).
#[error("permission denied")]
PermissionDenied, PermissionDenied,
/// The display server or compositor does not expose the /// The display server or compositor does not expose the
/// expected interface (typically a non-tested Linux compositor). /// expected interface (typically a non-tested Linux compositor).
#[error("unsupported environment")]
UnsupportedEnvironment, UnsupportedEnvironment,
/// Caller submitted a binding whose `platform_key` cannot be /// Caller submitted a binding whose `platform_key` cannot be
/// parsed in the active OS. /// parsed in the active OS.
#[error("invalid binding: {0}")]
InvalidBinding(String), InvalidBinding(String),
} }
impl fmt::Display for PttBackendError { #[cfg(test)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { mod tests {
match self { use super::*;
Self::Init(s) => write!(f, "init failed: {s}"),
Self::PermissionDenied => f.write_str("permission denied"), #[test]
Self::UnsupportedEnvironment => f.write_str("unsupported environment"), fn ptt_backend_error_display_strings_stay_stable() {
Self::InvalidBinding(s) => write!(f, "invalid binding: {s}"), assert_eq!(
} PttBackendError::Init("rawinput".into()).to_string(),
"init failed: rawinput"
);
assert_eq!(
PttBackendError::PermissionDenied.to_string(),
"permission denied"
);
assert_eq!(
PttBackendError::UnsupportedEnvironment.to_string(),
"unsupported environment"
);
assert_eq!(
PttBackendError::InvalidBinding("bad key".into()).to_string(),
"invalid binding: bad key"
);
} }
} }
impl std::error::Error for PttBackendError {}
/// Cross-platform desktop PTT backend (SDD-081). /// Cross-platform desktop PTT backend (SDD-081).
/// ///
/// All implementations call exactly the audio transmit gate's /// All implementations call exactly the audio transmit gate's
@@ -26,7 +26,7 @@ use std::thread;
use tracing::{info, warn}; use tracing::{info, warn};
use windows::core::{w, PCWSTR}; use windows::core::{w, PCWSTR};
use windows::Win32::Foundation::{HMODULE, HWND, LPARAM, LRESULT, WPARAM}; use windows::Win32::Foundation::{HINSTANCE, HMODULE, HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::System::LibraryLoader::GetModuleHandleW; use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::Input::{ use windows::Win32::UI::Input::{
GetRawInputData, RegisterRawInputDevices, HRAWINPUT, RAWINPUT, RAWINPUTDEVICE, RAWINPUTHEADER, GetRawInputData, RegisterRawInputDevices, HRAWINPUT, RAWINPUT, RAWINPUTDEVICE, RAWINPUTHEADER,
@@ -35,7 +35,7 @@ use windows::Win32::UI::Input::{
use windows::Win32::UI::WindowsAndMessaging::{ use windows::Win32::UI::WindowsAndMessaging::{
CallNextHookEx, CreateWindowExW, DefWindowProcW, DispatchMessageW, GetMessageW, CallNextHookEx, CreateWindowExW, DefWindowProcW, DispatchMessageW, GetMessageW,
PostThreadMessageW, RegisterClassExW, SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx, PostThreadMessageW, RegisterClassExW, SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx,
HC_ACTION, HHOOK, HOOKPROC, KBDLLHOOKSTRUCT, MSG, MSLLHOOKSTRUCT, WH_KEYBOARD_LL, WH_MOUSE_LL, HC_ACTION, HOOKPROC, KBDLLHOOKSTRUCT, MSG, MSLLHOOKSTRUCT, WH_KEYBOARD_LL, WH_MOUSE_LL,
WINDOW_EX_STYLE, WINDOW_STYLE, WM_INPUT, WM_KEYDOWN, WM_KEYUP, WM_QUIT, WM_SYSKEYDOWN, WINDOW_EX_STYLE, WINDOW_STYLE, WM_INPUT, WM_KEYDOWN, WM_KEYUP, WM_QUIT, WM_SYSKEYDOWN,
WM_SYSKEYUP, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, XBUTTON1, XBUTTON2, WM_SYSKEYUP, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, XBUTTON1, XBUTTON2,
}; };
@@ -423,7 +423,7 @@ unsafe fn run_raw_input_loop(
// class. // class.
let _atom = RegisterClassExW(&wc); let _atom = RegisterClassExW(&wc);
let hwnd = unsafe { let hwnd = match unsafe {
CreateWindowExW( CreateWindowExW(
WINDOW_EX_STYLE(0), WINDOW_EX_STYLE(0),
class_name, class_name,
@@ -433,13 +433,23 @@ unsafe fn run_raw_input_loop(
0, 0,
0, 0,
0, 0,
HWND(HWND_MESSAGE_PTR), Some(HWND(HWND_MESSAGE_PTR as *mut core::ffi::c_void)),
None, None,
h_instance, Some(HINSTANCE(h_instance.0)),
None, None,
) )
} {
Ok(h) => h,
Err(_) => {
warn!(
target: "chanora_audio",
"windows ptt: CreateWindowExW(HWND_MESSAGE) returned null"
);
report!(false);
return false;
}
}; };
if hwnd.0 == 0 { if hwnd.0.is_null() {
warn!( warn!(
target: "chanora_audio", target: "chanora_audio",
"windows ptt: CreateWindowExW(HWND_MESSAGE) returned null" "windows ptt: CreateWindowExW(HWND_MESSAGE) returned null"
@@ -517,13 +527,13 @@ unsafe fn run_raw_input_loop(
usUsagePage: 0x01, usUsagePage: 0x01,
usUsage: 0x06, usUsage: 0x06,
dwFlags: RIDEV_REMOVE, dwFlags: RIDEV_REMOVE,
hwndTarget: HWND(0), hwndTarget: HWND(std::ptr::null_mut()),
}, },
RAWINPUTDEVICE { RAWINPUTDEVICE {
usUsagePage: 0x01, usUsagePage: 0x01,
usUsage: 0x02, usUsage: 0x02,
dwFlags: RIDEV_REMOVE, dwFlags: RIDEV_REMOVE,
hwndTarget: HWND(0), hwndTarget: HWND(std::ptr::null_mut()),
}, },
]; ];
let _ = RegisterRawInputDevices(&undo, std::mem::size_of::<RAWINPUTDEVICE>() as u32); let _ = RegisterRawInputDevices(&undo, std::mem::size_of::<RAWINPUTDEVICE>() as u32);
@@ -544,7 +554,7 @@ unsafe extern "system" fn raw_input_wnd_proc(
} }
unsafe fn handle_wm_input(lparam: LPARAM) { unsafe fn handle_wm_input(lparam: LPARAM) {
let h_raw = HRAWINPUT(lparam.0); let h_raw = HRAWINPUT(lparam.0 as *mut core::ffi::c_void);
let mut size: u32 = 0; let mut size: u32 = 0;
let header_sz = std::mem::size_of::<RAWINPUTHEADER>() as u32; let header_sz = std::mem::size_of::<RAWINPUTHEADER>() as u32;
// First call: query buffer size. // First call: query buffer size.
@@ -841,31 +851,33 @@ unsafe fn run_hook_loop(
let kbd_proc: HOOKPROC = Some(kbd_hook_proc); let kbd_proc: HOOKPROC = Some(kbd_hook_proc);
let mouse_proc: HOOKPROC = Some(mouse_hook_proc); let mouse_proc: HOOKPROC = Some(mouse_hook_proc);
let kbd_hook = match SetWindowsHookExW(WH_KEYBOARD_LL, kbd_proc, h_instance, 0) { let kbd_hook =
Ok(h) => h, match SetWindowsHookExW(WH_KEYBOARD_LL, kbd_proc, Some(HINSTANCE(h_instance.0)), 0) {
Err(e) => { Ok(h) => h,
warn!( Err(e) => {
target: "chanora_audio", warn!(
error = %e, target: "chanora_audio",
"windows ptt: SetWindowsHookExW(WH_KEYBOARD_LL) failed" error = %e,
); "windows ptt: SetWindowsHookExW(WH_KEYBOARD_LL) failed"
report!(false); );
return false; report!(false);
} return false;
}; }
let mouse_hook = match SetWindowsHookExW(WH_MOUSE_LL, mouse_proc, h_instance, 0) { };
Ok(h) => h, let mouse_hook =
Err(e) => { match SetWindowsHookExW(WH_MOUSE_LL, mouse_proc, Some(HINSTANCE(h_instance.0)), 0) {
warn!( Ok(h) => h,
target: "chanora_audio", Err(e) => {
error = %e, warn!(
"windows ptt: SetWindowsHookExW(WH_MOUSE_LL) failed" target: "chanora_audio",
); error = %e,
let _ = UnhookWindowsHookEx(kbd_hook); "windows ptt: SetWindowsHookExW(WH_MOUSE_LL) failed"
report!(false); );
return false; let _ = UnhookWindowsHookEx(kbd_hook);
} report!(false);
}; return false;
}
};
info!( info!(
target: "chanora_audio", target: "chanora_audio",
@@ -908,7 +920,7 @@ unsafe extern "system" fn kbd_hook_proc(code: i32, wparam: WPARAM, lparam: LPARA
} }
}); });
} }
CallNextHookEx(HHOOK(0), code, wparam, lparam) CallNextHookEx(None, code, wparam, lparam)
} }
/// Pure-logic dispatcher for a low-level keyboard hook event (L0 /// Pure-logic dispatcher for a low-level keyboard hook event (L0
@@ -943,7 +955,7 @@ unsafe extern "system" fn mouse_hook_proc(code: i32, wparam: WPARAM, lparam: LPA
} }
}); });
} }
CallNextHookEx(HHOOK(0), code, wparam, lparam) CallNextHookEx(None, code, wparam, lparam)
} }
/// Pure-logic dispatcher for a low-level mouse hook event (L0 /// Pure-logic dispatcher for a low-level mouse hook event (L0
@@ -0,0 +1,241 @@
use std::array;
use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use std::sync::Arc;
const NO_LATEST_SLOT: usize = usize::MAX;
struct Slot<const SAMPLES: usize> {
version: AtomicUsize,
samples: [AtomicU32; SAMPLES],
#[cfg(test)]
bump_after_first_sample_read: std::sync::atomic::AtomicBool,
}
impl<const SAMPLES: usize> Slot<SAMPLES> {
fn new() -> Self {
Self {
version: AtomicUsize::new(0),
samples: array::from_fn(|_| AtomicU32::new(0.0_f32.to_bits())),
#[cfg(test)]
bump_after_first_sample_read: std::sync::atomic::AtomicBool::new(false),
}
}
}
pub(crate) struct RenderReferenceFrameAccumulator<const SAMPLES: usize> {
pending: [f32; SAMPLES],
pending_len: usize,
}
impl<const SAMPLES: usize> RenderReferenceFrameAccumulator<SAMPLES> {
pub(crate) fn new() -> Self {
assert!(
SAMPLES > 0,
"RenderReferenceFrameAccumulator requires at least one sample"
);
Self {
pending: [0.0; SAMPLES],
pending_len: 0,
}
}
pub(crate) fn push_mono_samples(
&mut self,
mut samples: &[f32],
mut publish: impl FnMut(&[f32; SAMPLES]),
) {
while !samples.is_empty() {
let needed = SAMPLES - self.pending_len;
let take = needed.min(samples.len());
self.pending[self.pending_len..self.pending_len + take]
.copy_from_slice(&samples[..take]);
self.pending_len += take;
samples = &samples[take..];
if self.pending_len == SAMPLES {
publish(&self.pending);
self.pending_len = 0;
}
}
}
#[cfg(test)]
fn pending_len(&self) -> usize {
self.pending_len
}
}
pub(crate) struct RenderReferenceBuffer<const SAMPLES: usize, const SLOTS: usize> {
slots: Box<[Slot<SAMPLES>; SLOTS]>,
write_idx: AtomicUsize,
latest_slot: AtomicUsize,
}
impl<const SAMPLES: usize, const SLOTS: usize> RenderReferenceBuffer<SAMPLES, SLOTS> {
pub(crate) fn new() -> Arc<Self> {
assert!(
SLOTS > 0,
"RenderReferenceBuffer requires at least one slot"
);
Arc::new(Self {
slots: Box::new(array::from_fn(|_| Slot::new())),
write_idx: AtomicUsize::new(0),
latest_slot: AtomicUsize::new(NO_LATEST_SLOT),
})
}
pub(crate) fn write(&self, frame: &[f32; SAMPLES]) {
let idx = self.write_idx.load(Ordering::Relaxed) % SLOTS;
let slot = &self.slots[idx];
// The acquire half keeps payload stores after the odd in-progress marker.
let version = slot.version.fetch_add(1, Ordering::AcqRel);
debug_assert_eq!(version & 1, 0, "single writer should only enter even slots");
for (sample, value) in slot.samples.iter().zip(frame.iter().copied()) {
sample.store(value.to_bits(), Ordering::Relaxed);
}
slot.version
.store(version.wrapping_add(2) & !1, Ordering::Release);
self.latest_slot.store(idx, Ordering::Release);
self.write_idx.store((idx + 1) % SLOTS, Ordering::Relaxed);
}
pub(crate) fn read_latest(&self) -> [f32; SAMPLES] {
let mut out = [0.0_f32; SAMPLES];
self.read_latest_into(&mut out);
out
}
pub(crate) fn read_latest_into(&self, out: &mut [f32; SAMPLES]) {
let idx = self.latest_slot.load(Ordering::Acquire);
if idx == NO_LATEST_SLOT {
out.fill(0.0);
return;
}
let slot = &self.slots[idx];
let before = slot.version.load(Ordering::Acquire);
if before & 1 == 1 {
out.fill(0.0);
return;
}
#[cfg(not(test))]
for (dst, sample) in out.iter_mut().zip(slot.samples.iter()) {
*dst = f32::from_bits(sample.load(Ordering::Relaxed));
}
#[cfg(test)]
for (idx, (dst, sample)) in out.iter_mut().zip(slot.samples.iter()).enumerate() {
*dst = f32::from_bits(sample.load(Ordering::Relaxed));
if idx == 0
&& slot
.bump_after_first_sample_read
.swap(false, Ordering::Relaxed)
{
slot.version.fetch_add(2, Ordering::Release);
}
}
let after = slot.version.load(Ordering::Acquire);
if before != after || after & 1 == 1 {
out.fill(0.0);
}
}
#[cfg(test)]
fn mark_latest_slot_in_progress_for_test(&self) {
let idx = self.latest_slot.load(Ordering::Acquire);
assert_ne!(idx, NO_LATEST_SLOT);
self.slots[idx].version.fetch_or(1, Ordering::Release);
}
#[cfg(test)]
fn bump_latest_slot_version_after_first_sample_for_test(&self) {
let idx = self.latest_slot.load(Ordering::Acquire);
assert_ne!(idx, NO_LATEST_SLOT);
self.slots[idx]
.bump_after_first_sample_read
.store(true, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use super::{RenderReferenceBuffer, RenderReferenceFrameAccumulator};
#[test]
fn render_reference_reads_zero_before_first_publish() {
let buffer = RenderReferenceBuffer::<4, 2>::new();
assert_eq!(buffer.read_latest(), [0.0; 4]);
}
#[test]
fn render_reference_reader_gets_latest_complete_frame() {
let buffer = RenderReferenceBuffer::<4, 3>::new();
buffer.write(&[1.0, 2.0, 3.0, 4.0]);
buffer.write(&[5.0, 6.0, 7.0, 8.0]);
assert_eq!(buffer.read_latest(), [5.0, 6.0, 7.0, 8.0]);
}
#[test]
fn render_reference_writes_wrap_without_returning_stale_frame() {
let buffer = RenderReferenceBuffer::<2, 2>::new();
buffer.write(&[1.0, 2.0]);
buffer.write(&[3.0, 4.0]);
buffer.write(&[5.0, 6.0]);
assert_eq!(buffer.read_latest(), [5.0, 6.0]);
}
#[test]
fn render_reference_accumulator_publishes_only_complete_frames() {
let mut accum = RenderReferenceFrameAccumulator::<4>::new();
let mut frames = Vec::new();
accum.push_mono_samples(&[1.0, 2.0], |frame| frames.push(*frame));
assert!(frames.is_empty());
assert_eq!(accum.pending_len(), 2);
accum.push_mono_samples(&[3.0, 4.0, 5.0, 6.0, 7.0], |frame| frames.push(*frame));
assert_eq!(frames, vec![[1.0, 2.0, 3.0, 4.0]]);
assert_eq!(accum.pending_len(), 3);
accum.push_mono_samples(&[8.0], |frame| frames.push(*frame));
assert_eq!(frames, vec![[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]]);
assert_eq!(accum.pending_len(), 0);
}
#[test]
fn render_reference_reader_rejects_in_progress_slot() {
let buffer = RenderReferenceBuffer::<2, 1>::new();
buffer.write(&[1.0, 2.0]);
buffer.mark_latest_slot_in_progress_for_test();
assert_eq!(buffer.read_latest(), [0.0, 0.0]);
}
#[test]
fn render_reference_reader_rejects_stale_slot_changed_during_read() {
let buffer = RenderReferenceBuffer::<2, 1>::new();
buffer.write(&[1.0, 2.0]);
buffer.bump_latest_slot_version_after_first_sample_for_test();
assert_eq!(buffer.read_latest(), [0.0, 0.0]);
}
#[test]
#[should_panic(expected = "RenderReferenceBuffer requires at least one slot")]
fn render_reference_rejects_zero_slots() {
let _ = RenderReferenceBuffer::<2, 0>::new();
}
}
+26 -2
View File
@@ -8,7 +8,7 @@
#[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg(any(target_os = "ios", target_os = "macos"))]
pub mod apple_coreml; pub mod apple_coreml;
pub mod resampler; pub mod resampler;
#[cfg(not(target_os = "ios"))] #[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "android")))]
pub mod silero_onnx; pub mod silero_onnx;
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
@@ -18,7 +18,7 @@ use crate::frame::{f32_to_i16, i16_to_f32};
use crate::AudioError; use crate::AudioError;
use resampler::{Downsampler48to16, INPUT_FRAME_10MS}; use resampler::{Downsampler48to16, INPUT_FRAME_10MS};
#[cfg(not(target_os = "ios"))] #[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "android")))]
pub use silero_onnx::SileroOnnxVad; pub use silero_onnx::SileroOnnxVad;
/// Voice activity detector output for one 10 ms frame. /// Voice activity detector output for one 10 ms frame.
@@ -111,6 +111,9 @@ pub fn process_i16_10ms(detector: &mut dyn VoiceActivityDetector, samples: &[i16
static SILERO_MODEL_PATH_OVERRIDE: OnceLock<RwLock<Option<String>>> = OnceLock::new(); static SILERO_MODEL_PATH_OVERRIDE: OnceLock<RwLock<Option<String>>> = OnceLock::new();
static SILERO_MODEL_EPOCH: AtomicU64 = AtomicU64::new(0); static SILERO_MODEL_EPOCH: AtomicU64 = AtomicU64::new(0);
#[cfg(test)]
pub(crate) static SILERO_MODEL_PATH_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn silero_model_path_override() -> &'static RwLock<Option<String>> { fn silero_model_path_override() -> &'static RwLock<Option<String>> {
SILERO_MODEL_PATH_OVERRIDE.get_or_init(|| RwLock::new(None)) SILERO_MODEL_PATH_OVERRIDE.get_or_init(|| RwLock::new(None))
} }
@@ -145,6 +148,19 @@ pub fn silero_model_epoch() -> u64 {
SILERO_MODEL_EPOCH.load(Ordering::Relaxed) SILERO_MODEL_EPOCH.load(Ordering::Relaxed)
} }
#[cfg(test)]
pub(crate) fn clear_silero_model_path_for_test() {
set_silero_model_path_for_test(None);
}
#[cfg(test)]
pub(crate) fn set_silero_model_path_for_test(path: Option<String>) {
if let Ok(mut guard) = silero_model_path_override().write() {
*guard = path;
SILERO_MODEL_EPOCH.fetch_add(1, Ordering::Relaxed);
}
}
/// Return the expected path of the Silero VAD v6 ONNX model on /// Return the expected path of the Silero VAD v6 ONNX model on
/// supported platforms. /// supported platforms.
/// The model is shipped as a Flutter asset and copied to the app's /// The model is shipped as a Flutter asset and copied to the app's
@@ -234,13 +250,20 @@ mod tests {
#[test] #[test]
fn set_silero_model_path_rejects_missing_file() { fn set_silero_model_path_rejects_missing_file() {
let _guard = SILERO_MODEL_PATH_TEST_LOCK.lock().unwrap();
clear_silero_model_path_for_test();
let result = set_silero_model_path("/definitely/not/a/silero_vad.onnx"); let result = set_silero_model_path("/definitely/not/a/silero_vad.onnx");
assert!(result.is_err()); assert!(result.is_err());
clear_silero_model_path_for_test();
} }
#[test] #[test]
fn set_silero_model_path_updates_override_and_epoch() { fn set_silero_model_path_updates_override_and_epoch() {
let _guard = SILERO_MODEL_PATH_TEST_LOCK.lock().unwrap();
clear_silero_model_path_for_test();
let path = let path =
std::env::temp_dir().join(format!("chanora_test_silero_{}.onnx", std::process::id())); std::env::temp_dir().join(format!("chanora_test_silero_{}.onnx", std::process::id()));
std::fs::write(&path, b"test").unwrap(); std::fs::write(&path, b"test").unwrap();
@@ -250,6 +273,7 @@ mod tests {
assert!(silero_model_epoch() > before); assert!(silero_model_epoch() > before);
assert_eq!(silero_model_bundle_path(), path.to_string_lossy()); assert_eq!(silero_model_bundle_path(), path.to_string_lossy());
clear_silero_model_path_for_test();
let _ = std::fs::remove_file(path); let _ = std::fs::remove_file(path);
} }
} }
+33 -1
View File
@@ -361,6 +361,31 @@ impl SileroOnnxVadWorker {
}) })
} }
#[cfg(test)]
pub(crate) fn stale_test_worker() -> Self {
let (tx, rx) = std::sync::mpsc::sync_channel::<SileroFrameMessage>(64);
let alive = Arc::new(AtomicBool::new(true));
let alive_for_thread = alive.clone();
let handle = std::thread::Builder::new()
.name("chanora-silero-vad-stale-test".to_string())
.spawn(move || {
while alive_for_thread.load(Ordering::Relaxed) {
match rx.recv_timeout(std::time::Duration::from_millis(10)) {
Ok(_) | Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
}
}
})
.ok();
Self {
tx: Some(tx),
latest_probability: Arc::new(AtomicU32::new(0.0_f32.to_bits())),
latest_processed_seq: Arc::new(AtomicU64::new(u64::MAX)),
alive,
handle,
}
}
/// Best-effort enqueue of a 10 ms frame for background inference. /// Best-effort enqueue of a 10 ms frame for background inference.
pub fn try_send(&self, seq: u64, frame: &[f32; super::resampler::INPUT_FRAME_10MS]) -> bool { pub fn try_send(&self, seq: u64, frame: &[f32; super::resampler::INPUT_FRAME_10MS]) -> bool {
let Some(tx) = &self.tx else { let Some(tx) = &self.tx else {
@@ -393,8 +418,15 @@ impl SileroOnnxVadWorker {
impl Drop for SileroOnnxVadWorker { impl Drop for SileroOnnxVadWorker {
fn drop(&mut self) { fn drop(&mut self) {
self.alive.store(false, Ordering::Relaxed); self.alive.store(false, Ordering::Relaxed);
// Drop the sender first so the worker thread's rx.recv() returns
// Err and the loop exits promptly.
let _ = self.tx.take(); let _ = self.tx.take();
let _ = self.handle.take(); // Join the thread instead of detaching. The channel close
// unblocks rx.recv() so the join is bounded; it waits at most
// until the current in-flight inference completes.
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
} }
} }
+5 -47
View File
@@ -1,4 +1,5 @@
/// Diagnostics returned by render downmix helpers. /// Diagnostics returned by render downmix helpers.
#[cfg(any(target_os = "ios", test))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct RenderDownmixStats { pub(crate) struct RenderDownmixStats {
/// Peak absolute sample magnitude after i16 conversion. /// Peak absolute sample magnitude after i16 conversion.
@@ -7,47 +8,7 @@ pub(crate) struct RenderDownmixStats {
pub clipped_samples: u64, pub clipped_samples: u64,
} }
/// Downmix interleaved stereo f32 samples into mono i16 samples.
///
/// The helper is allocation-free and safe for realtime render callbacks.
/// If the stereo source is shorter than expected, the remainder of `out`
/// is filled with silence.
#[cfg(any(target_os = "ios", test))] #[cfg(any(target_os = "ios", test))]
pub(crate) fn downmix_stereo_f32_to_mono_i16(
stereo: &[f32],
out: &mut [i16],
gain: f32,
muted: bool,
) -> RenderDownmixStats {
if muted {
out.fill(0);
return RenderDownmixStats::default();
}
let available_frames = stereo.len() / 2;
if available_frames < out.len() {
out.fill(0);
}
let mut peak = 0_u16;
let mut clipped_samples = 0_u64;
for (dst, lr) in out.iter_mut().zip(stereo.chunks_exact(2)) {
let mono = (lr[0] + lr[1]) * 0.5 * gain;
let clamped = mono.clamp(-1.0, 1.0);
if (mono - clamped).abs() > f32::EPSILON {
clipped_samples = clipped_samples.saturating_add(1);
}
let sample = (clamped * i16::MAX as f32) as i16;
*dst = sample;
peak = peak.max(sample.unsigned_abs());
}
RenderDownmixStats {
peak_i16: peak.min(i16::MAX as u16) as i16,
clipped_samples,
}
}
pub(crate) fn downmix_stereo_f32_to_interleaved_i16( pub(crate) fn downmix_stereo_f32_to_interleaved_i16(
stereo: &[f32], stereo: &[f32],
out: &mut [i16], out: &mut [i16],
@@ -122,10 +83,7 @@ pub(crate) fn limit_peak_inplace(samples: &mut [f32], threshold: f32) -> f32 {
if threshold <= 0.0 || !threshold.is_finite() { if threshold <= 0.0 || !threshold.is_finite() {
return 1.0; return 1.0;
} }
let peak = samples let peak = samples.iter().map(|s| s.abs()).fold(0.0_f32, f32::max);
.iter()
.map(|s| s.abs())
.fold(0.0_f32, f32::max);
if peak <= threshold { if peak <= threshold {
return 1.0; return 1.0;
} }
@@ -145,7 +103,7 @@ mod tests {
let stereo = [1.0_f32, 1.0, 0.25, -0.25, -2.0, -2.0]; let stereo = [1.0_f32, 1.0, 0.25, -0.25, -2.0, -2.0];
let mut out = [0_i16; 3]; let mut out = [0_i16; 3];
let stats = downmix_stereo_f32_to_mono_i16(&stereo, &mut out, 2.0, false); let stats = downmix_stereo_f32_to_interleaved_i16(&stereo, &mut out, 1, 2.0, false);
assert_eq!(out[0], i16::MAX); assert_eq!(out[0], i16::MAX);
assert_eq!(out[1], 0); assert_eq!(out[1], 0);
@@ -159,7 +117,7 @@ mod tests {
let stereo = [1.0_f32, 1.0, -1.0, -1.0]; let stereo = [1.0_f32, 1.0, -1.0, -1.0];
let mut out = [123_i16; 2]; let mut out = [123_i16; 2];
let stats = downmix_stereo_f32_to_mono_i16(&stereo, &mut out, 1.0, true); let stats = downmix_stereo_f32_to_interleaved_i16(&stereo, &mut out, 1, 1.0, true);
assert_eq!(out, [0, 0]); assert_eq!(out, [0, 0]);
assert_eq!(stats, RenderDownmixStats::default()); assert_eq!(stats, RenderDownmixStats::default());
@@ -234,7 +192,7 @@ mod tests {
let mut scratch = [1.0_f32, 1.0, -0.5, -0.5, 0.8, 0.8]; let mut scratch = [1.0_f32, 1.0, -0.5, -0.5, 0.8, 0.8];
limit_peak_inplace(&mut scratch, 0.95); limit_peak_inplace(&mut scratch, 0.95);
let mut out = [0_i16; 3]; let mut out = [0_i16; 3];
let stats = downmix_stereo_f32_to_mono_i16(&scratch, &mut out, 1.0, false); let stats = downmix_stereo_f32_to_interleaved_i16(&scratch, &mut out, 1, 1.0, false);
assert_eq!(stats.clipped_samples, 0); assert_eq!(stats.clipped_samples, 0);
assert!(stats.peak_i16 < i16::MAX); assert!(stats.peak_i16 < i16::MAX);
} }
+2 -2
View File
@@ -196,8 +196,8 @@ fn windows_exercise() {
// start/stop lifecycle through the public trait surface so // start/stop lifecycle through the public trait surface so
// any info!/warn! the factory or the backend's `start` path // any info!/warn! the factory or the backend's `start` path
// emits is captured by the layer. // emits is captured by the layer.
use chanora_audio::ptt_backends::{select_ptt_backend, PttBinding, PttInputClass}; use chanora_audio::ptt_backends::{PttBinding, PttInputClass};
use chanora_audio::AudioTransmitGate; use chanora_audio::{select_ptt_backend, AudioTransmitGate};
let mut backend = select_ptt_backend(); let mut backend = select_ptt_backend();
let gate = AudioTransmitGate::new(false); let gate = AudioTransmitGate::new(false);
+146 -41
View File
@@ -1062,10 +1062,8 @@ pub enum BridgeAudioRoute {
/// Bridge iOS voice-processing mode. /// Bridge iOS voice-processing mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BridgeIosVoiceProcessingMode { pub enum BridgeIosVoiceProcessingMode {
/// Shipping VPIO path. /// Apple VoiceProcessingIO path.
PlatformVoiceProcessing, PlatformVoiceProcessing,
/// Experimental Sonora path.
SonoraExperimental,
} }
/// Bridge processing backend. /// Bridge processing backend.
@@ -1223,7 +1221,6 @@ impl From<BridgeIosVoiceProcessingMode> for chanora_core::IosVoiceProcessingMode
fn from(mode: BridgeIosVoiceProcessingMode) -> Self { fn from(mode: BridgeIosVoiceProcessingMode) -> Self {
match mode { match mode {
BridgeIosVoiceProcessingMode::PlatformVoiceProcessing => Self::PlatformVoiceProcessing, BridgeIosVoiceProcessingMode::PlatformVoiceProcessing => Self::PlatformVoiceProcessing,
BridgeIosVoiceProcessingMode::SonoraExperimental => Self::SonoraExperimental,
} }
} }
} }
@@ -1234,7 +1231,6 @@ impl From<chanora_core::IosVoiceProcessingMode> for BridgeIosVoiceProcessingMode
chanora_core::IosVoiceProcessingMode::PlatformVoiceProcessing => { chanora_core::IosVoiceProcessingMode::PlatformVoiceProcessing => {
Self::PlatformVoiceProcessing Self::PlatformVoiceProcessing
} }
chanora_core::IosVoiceProcessingMode::SonoraExperimental => Self::SonoraExperimental,
} }
} }
} }
@@ -1469,6 +1465,54 @@ pub async fn init_storage(dir: String) -> Result<(), BridgeError> {
Ok(()) Ok(())
} }
/// Configure the bridge blob cache root.
pub async fn init_cache(dir: String) -> Result<(), BridgeError> {
runtime()
.spawn(async move { session().init_cache(&dir).await })
.await
.map_err(|e| task_join_error("init_cache", e))??;
Ok(())
}
/// Resolve avatar bytes through the bridge.
pub async fn download_avatar(
avatar_hash: String,
client_uid: String,
) -> Result<Option<Vec<u8>>, BridgeError> {
runtime()
.spawn(async move { session().get_avatar(&avatar_hash, &client_uid).await })
.await
.map_err(|e| task_join_error("download_avatar", e))?
.map_err(BridgeError::from)
}
/// Resolve icon bytes through the bridge.
pub async fn download_icon(icon_id: u64) -> Result<Option<Vec<u8>>, BridgeError> {
runtime()
.spawn(async move { session().get_icon(icon_id).await })
.await
.map_err(|e| task_join_error("download_icon", e))?
.map_err(BridgeError::from)
}
/// Purge cached protocol-owned assets.
pub async fn clear_file_cache() -> Result<(), BridgeError> {
runtime()
.spawn(async move { session().clear_cache().await })
.await
.map_err(|e| task_join_error("clear_file_cache", e))??;
Ok(())
}
/// Report the configured file-cache size.
pub async fn file_cache_size() -> Result<u64, BridgeError> {
runtime()
.spawn(async move { session().cache_size().await })
.await
.map_err(|e| task_join_error("file_cache_size", e))?
.map_err(BridgeError::from)
}
/// Bookmark DTO mirroring [`chanora_core::Bookmark`]. /// Bookmark DTO mirroring [`chanora_core::Bookmark`].
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct BridgeBookmark { pub struct BridgeBookmark {
@@ -1695,6 +1739,8 @@ pub enum BridgeEvent {
message: String, message: String,
/// Target scope (server/channel/private/poke). /// Target scope (server/channel/private/poke).
target: BridgeMessageTarget, target: BridgeMessageTarget,
/// Poke notification strength, present only for poke messages.
poke_strength: Option<BridgePokeStrength>,
}, },
/// Human-readable server activity surfaced from protocol bookkeeping events. /// Human-readable server activity surfaced from protocol bookkeeping events.
ServerActivity { ServerActivity {
@@ -1812,6 +1858,27 @@ impl From<chanora_core::MessageTarget> for BridgeMessageTarget {
} }
} }
/// Bridge poke notification strength.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BridgePokeStrength {
/// Poke should be surfaced at full strength.
Strong,
/// Poke is rate-limited but below overflow severity.
Suppressed,
/// Poke remains suppressed after repeated suppressed pokes.
SuppressedOverflow,
}
impl From<chanora_core::PokeStrength> for BridgePokeStrength {
fn from(strength: chanora_core::PokeStrength) -> Self {
match strength {
chanora_core::PokeStrength::Strong => Self::Strong,
chanora_core::PokeStrength::Suppressed => Self::Suppressed,
chanora_core::PokeStrength::SuppressedOverflow => Self::SuppressedOverflow,
}
}
}
/// Bridge mirror of core join projection sync state. /// Bridge mirror of core join projection sync state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BridgeVoiceJoinSyncState { pub enum BridgeVoiceJoinSyncState {
@@ -1958,11 +2025,13 @@ impl From<chanora_core::SessionEvent> for BridgeEvent {
sender_name, sender_name,
message, message,
target, target,
poke_strength,
} => BridgeEvent::ChatMessage { } => BridgeEvent::ChatMessage {
sender_id, sender_id,
sender_name, sender_name,
message, message,
target: target.into(), target: target.into(),
poke_strength: poke_strength.map(Into::into),
}, },
chanora_core::SessionEvent::ServerActivity { message } => { chanora_core::SessionEvent::ServerActivity { message } => {
BridgeEvent::ServerActivity { message } BridgeEvent::ServerActivity { message }
@@ -1972,27 +2041,77 @@ impl From<chanora_core::SessionEvent> for BridgeEvent {
route: route.into(), route: route.into(),
} }
} }
chanora_core::SessionEvent::ClientMoved { client_id, new_channel_id } => { chanora_core::SessionEvent::ClientMoved {
BridgeEvent::ClientMoved { client_id, new_channel_id } client_id,
} new_channel_id,
chanora_core::SessionEvent::ClientJoined { client_id, channel_id, name, input_muted, output_muted, is_server_query, talk_power, talk_power_granted } => { } => BridgeEvent::ClientMoved {
BridgeEvent::ClientJoined { client_id, channel_id, name, input_muted, output_muted, is_server_query, talk_power, talk_power_granted } client_id,
} new_channel_id,
},
chanora_core::SessionEvent::ClientJoined {
client_id,
channel_id,
name,
input_muted,
output_muted,
is_server_query,
talk_power,
talk_power_granted,
} => BridgeEvent::ClientJoined {
client_id,
channel_id,
name,
input_muted,
output_muted,
is_server_query,
talk_power,
talk_power_granted,
},
chanora_core::SessionEvent::ClientLeft { client_id, name } => { chanora_core::SessionEvent::ClientLeft { client_id, name } => {
BridgeEvent::ClientLeft { client_id, name } BridgeEvent::ClientLeft { client_id, name }
} }
chanora_core::SessionEvent::ClientUpdated { client_id, input_muted, output_muted, is_server_query, talk_power, talk_power_granted } => { chanora_core::SessionEvent::ClientUpdated {
BridgeEvent::ClientUpdated { client_id, input_muted, output_muted, is_server_query, talk_power, talk_power_granted } client_id,
} input_muted,
chanora_core::SessionEvent::ChannelAdded { id, parent, name, order, has_password, needed_talk_power } => { output_muted,
BridgeEvent::ChannelAdded { id, parent, name, order, has_password, needed_talk_power } is_server_query,
} talk_power,
chanora_core::SessionEvent::ChannelRemoved { id } => { talk_power_granted,
BridgeEvent::ChannelRemoved { id } } => BridgeEvent::ClientUpdated {
} client_id,
chanora_core::SessionEvent::ChannelUpdated { id, name, has_password, needed_talk_power } => { input_muted,
BridgeEvent::ChannelUpdated { id, name, has_password, needed_talk_power } output_muted,
} is_server_query,
talk_power,
talk_power_granted,
},
chanora_core::SessionEvent::ChannelAdded {
id,
parent,
name,
order,
has_password,
needed_talk_power,
} => BridgeEvent::ChannelAdded {
id,
parent,
name,
order,
has_password,
needed_talk_power,
},
chanora_core::SessionEvent::ChannelRemoved { id } => BridgeEvent::ChannelRemoved { id },
chanora_core::SessionEvent::ChannelUpdated {
id,
name,
has_password,
needed_talk_power,
} => BridgeEvent::ChannelUpdated {
id,
name,
has_password,
needed_talk_power,
},
} }
} }
} }
@@ -2286,25 +2405,11 @@ pub async fn set_ios_voice_processing_mode(
let config = BridgeAudioProcessingConfig { let config = BridgeAudioProcessingConfig {
route: BridgeAudioRoute::Speaker, route: BridgeAudioRoute::Speaker,
ios_mode: mode, ios_mode: mode,
processing_backend: match mode { processing_backend: BridgeAudioBackend::PlatformVoiceProcessing,
BridgeIosVoiceProcessingMode::PlatformVoiceProcessing => {
BridgeAudioBackend::PlatformVoiceProcessing
}
BridgeIosVoiceProcessingMode::SonoraExperimental => BridgeAudioBackend::WebrtcApm,
},
vad_backend: BridgeVadBackend::SileroOnnx, vad_backend: BridgeVadBackend::SileroOnnx,
aec: match mode { aec: BridgeEffectOwner::Platform,
BridgeIosVoiceProcessingMode::PlatformVoiceProcessing => BridgeEffectOwner::Platform, ns: BridgeEffectOwner::Platform,
BridgeIosVoiceProcessingMode::SonoraExperimental => BridgeEffectOwner::WebrtcApm, agc: BridgeEffectOwner::Platform,
},
ns: match mode {
BridgeIosVoiceProcessingMode::PlatformVoiceProcessing => BridgeEffectOwner::Platform,
BridgeIosVoiceProcessingMode::SonoraExperimental => BridgeEffectOwner::WebrtcApm,
},
agc: match mode {
BridgeIosVoiceProcessingMode::PlatformVoiceProcessing => BridgeEffectOwner::Platform,
BridgeIosVoiceProcessingMode::SonoraExperimental => BridgeEffectOwner::WebrtcApm,
},
hpf_enabled: true, hpf_enabled: true,
limiter_enabled: true, limiter_enabled: true,
vad_hangover_ms: 500, vad_hangover_ms: 500,
+333 -50
View File
@@ -38,7 +38,7 @@ flutter_rust_bridge::frb_generated_boilerplate!(
default_rust_auto_opaque = RustAutoOpaqueMoi, default_rust_auto_opaque = RustAutoOpaqueMoi,
); );
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.12.0"; pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.12.0";
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -20394775; pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 635684021;
// Section: executor // Section: executor
@@ -186,6 +186,41 @@ fn wire__crate__api__bridge_init_impl(
}, },
) )
} }
fn wire__crate__api__clear_file_cache_impl(
port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
rust_vec_len_: i32,
data_len_: i32,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
flutter_rust_bridge::for_generated::TaskInfo {
debug_name: "clear_file_cache",
port: Some(port_),
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
},
move || {
let message = unsafe {
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
ptr_,
rust_vec_len_,
data_len_,
)
};
let mut deserializer =
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
deserializer.end();
move |context| async move {
transform_result_sse::<_, crate::BridgeError>(
(move || async move {
let output_ok = crate::api::clear_file_cache().await?;
Ok(output_ok)
})()
.await,
)
}
},
)
}
fn wire__crate__api__client_profile_impl( fn wire__crate__api__client_profile_impl(
port_: flutter_rust_bridge::for_generated::MessagePort, port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
@@ -332,6 +367,80 @@ fn wire__crate__api__disconnect_impl(
}, },
) )
} }
fn wire__crate__api__download_avatar_impl(
port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
rust_vec_len_: i32,
data_len_: i32,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
flutter_rust_bridge::for_generated::TaskInfo {
debug_name: "download_avatar",
port: Some(port_),
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
},
move || {
let message = unsafe {
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
ptr_,
rust_vec_len_,
data_len_,
)
};
let mut deserializer =
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
let api_avatar_hash = <String>::sse_decode(&mut deserializer);
let api_client_uid = <String>::sse_decode(&mut deserializer);
deserializer.end();
move |context| async move {
transform_result_sse::<_, crate::BridgeError>(
(move || async move {
let output_ok =
crate::api::download_avatar(api_avatar_hash, api_client_uid).await?;
Ok(output_ok)
})()
.await,
)
}
},
)
}
fn wire__crate__api__download_icon_impl(
port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
rust_vec_len_: i32,
data_len_: i32,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
flutter_rust_bridge::for_generated::TaskInfo {
debug_name: "download_icon",
port: Some(port_),
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
},
move || {
let message = unsafe {
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
ptr_,
rust_vec_len_,
data_len_,
)
};
let mut deserializer =
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
let api_icon_id = <u64>::sse_decode(&mut deserializer);
deserializer.end();
move |context| async move {
transform_result_sse::<_, crate::BridgeError>(
(move || async move {
let output_ok = crate::api::download_icon(api_icon_id).await?;
Ok(output_ok)
})()
.await,
)
}
},
)
}
fn wire__crate__api__enable_audio_debug_wav_dump_impl( fn wire__crate__api__enable_audio_debug_wav_dump_impl(
port_: flutter_rust_bridge::for_generated::MessagePort, port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
@@ -434,6 +543,41 @@ fn wire__crate__api__export_diagnostics_impl(
}, },
) )
} }
fn wire__crate__api__file_cache_size_impl(
port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
rust_vec_len_: i32,
data_len_: i32,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
flutter_rust_bridge::for_generated::TaskInfo {
debug_name: "file_cache_size",
port: Some(port_),
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
},
move || {
let message = unsafe {
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
ptr_,
rust_vec_len_,
data_len_,
)
};
let mut deserializer =
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
deserializer.end();
move |context| async move {
transform_result_sse::<_, crate::BridgeError>(
(move || async move {
let output_ok = crate::api::file_cache_size().await?;
Ok(output_ok)
})()
.await,
)
}
},
)
}
fn wire__crate__api__get_audio_processing_config_impl( fn wire__crate__api__get_audio_processing_config_impl(
port_: flutter_rust_bridge::for_generated::MessagePort, port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
@@ -702,6 +846,42 @@ fn wire__crate__api__handle_route_change_impl(
}, },
) )
} }
fn wire__crate__api__init_cache_impl(
port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
rust_vec_len_: i32,
data_len_: i32,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
flutter_rust_bridge::for_generated::TaskInfo {
debug_name: "init_cache",
port: Some(port_),
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
},
move || {
let message = unsafe {
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
ptr_,
rust_vec_len_,
data_len_,
)
};
let mut deserializer =
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
let api_dir = <String>::sse_decode(&mut deserializer);
deserializer.end();
move |context| async move {
transform_result_sse::<_, crate::BridgeError>(
(move || async move {
let output_ok = crate::api::init_cache(api_dir).await?;
Ok(output_ok)
})()
.await,
)
}
},
)
}
fn wire__crate__api__init_storage_impl( fn wire__crate__api__init_storage_impl(
port_: flutter_rust_bridge::for_generated::MessagePort, port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
@@ -2292,11 +2472,14 @@ impl SseDecode for crate::api::BridgeEvent {
let mut var_senderName = <String>::sse_decode(deserializer); let mut var_senderName = <String>::sse_decode(deserializer);
let mut var_message = <String>::sse_decode(deserializer); let mut var_message = <String>::sse_decode(deserializer);
let mut var_target = <crate::api::BridgeMessageTarget>::sse_decode(deserializer); let mut var_target = <crate::api::BridgeMessageTarget>::sse_decode(deserializer);
let mut var_pokeStrength =
<Option<crate::api::BridgePokeStrength>>::sse_decode(deserializer);
return crate::api::BridgeEvent::ChatMessage { return crate::api::BridgeEvent::ChatMessage {
sender_id: var_senderId, sender_id: var_senderId,
sender_name: var_senderName, sender_name: var_senderName,
message: var_message, message: var_message,
target: var_target, target: var_target,
poke_strength: var_pokeStrength,
}; };
} }
11 => { 11 => {
@@ -2406,7 +2589,6 @@ impl SseDecode for crate::api::BridgeIosVoiceProcessingMode {
let mut inner = <i32>::sse_decode(deserializer); let mut inner = <i32>::sse_decode(deserializer);
return match inner { return match inner {
0 => crate::api::BridgeIosVoiceProcessingMode::PlatformVoiceProcessing, 0 => crate::api::BridgeIosVoiceProcessingMode::PlatformVoiceProcessing,
1 => crate::api::BridgeIosVoiceProcessingMode::SonoraExperimental,
_ => unreachable!( _ => unreachable!(
"Invalid variant for BridgeIosVoiceProcessingMode: {}", "Invalid variant for BridgeIosVoiceProcessingMode: {}",
inner inner
@@ -2454,6 +2636,19 @@ impl SseDecode for crate::api::BridgeNetworkState {
} }
} }
impl SseDecode for crate::api::BridgePokeStrength {
// Codec=Sse (Serialization based), see doc to use other codecs
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
let mut inner = <i32>::sse_decode(deserializer);
return match inner {
0 => crate::api::BridgePokeStrength::Strong,
1 => crate::api::BridgePokeStrength::Suppressed,
2 => crate::api::BridgePokeStrength::SuppressedOverflow,
_ => unreachable!("Invalid variant for BridgePokeStrength: {}", inner),
};
}
}
impl SseDecode for crate::api::BridgePttBinding { impl SseDecode for crate::api::BridgePttBinding {
// Codec=Sse (Serialization based), see doc to use other codecs // Codec=Sse (Serialization based), see doc to use other codecs
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
@@ -2680,6 +2875,17 @@ impl SseDecode for Option<String> {
} }
} }
impl SseDecode for Option<crate::api::BridgePokeStrength> {
// Codec=Sse (Serialization based), see doc to use other codecs
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
if (<bool>::sse_decode(deserializer)) {
return Some(<crate::api::BridgePokeStrength>::sse_decode(deserializer));
} else {
return None;
}
}
}
impl SseDecode for Option<crate::api::BridgeVoiceJoinErrorCode> { impl SseDecode for Option<crate::api::BridgeVoiceJoinErrorCode> {
// Codec=Sse (Serialization based), see doc to use other codecs // Codec=Sse (Serialization based), see doc to use other codecs
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
@@ -2737,6 +2943,17 @@ impl SseDecode for Option<u64> {
} }
} }
impl SseDecode for Option<Vec<u8>> {
// Codec=Sse (Serialization based), see doc to use other codecs
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
if (<bool>::sse_decode(deserializer)) {
return Some(<Vec<u8>>::sse_decode(deserializer));
} else {
return None;
}
}
}
impl SseDecode for crate::api::PermissionStateKind { impl SseDecode for crate::api::PermissionStateKind {
// Codec=Sse (Serialization based), see doc to use other codecs // Codec=Sse (Serialization based), see doc to use other codecs
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
@@ -2790,45 +3007,50 @@ fn pde_ffi_dispatcher_primary_impl(
2 => wire__crate__api__audio_processing_stats_impl(port, ptr, rust_vec_len, data_len), 2 => wire__crate__api__audio_processing_stats_impl(port, ptr, rust_vec_len, data_len),
3 => wire__crate__api__audio_stats_impl(port, ptr, rust_vec_len, data_len), 3 => wire__crate__api__audio_stats_impl(port, ptr, rust_vec_len, data_len),
4 => wire__crate__api__bridge_init_impl(port, ptr, rust_vec_len, data_len), 4 => wire__crate__api__bridge_init_impl(port, ptr, rust_vec_len, data_len),
5 => wire__crate__api__client_profile_impl(port, ptr, rust_vec_len, data_len), 5 => wire__crate__api__clear_file_cache_impl(port, ptr, rust_vec_len, data_len),
6 => wire__crate__api__connect_impl(port, ptr, rust_vec_len, data_len), 6 => wire__crate__api__client_profile_impl(port, ptr, rust_vec_len, data_len),
7 => wire__crate__api__delete_bookmark_impl(port, ptr, rust_vec_len, data_len), 7 => wire__crate__api__connect_impl(port, ptr, rust_vec_len, data_len),
8 => wire__crate__api__disconnect_impl(port, ptr, rust_vec_len, data_len), 8 => wire__crate__api__delete_bookmark_impl(port, ptr, rust_vec_len, data_len),
9 => wire__crate__api__enable_audio_debug_wav_dump_impl(port, ptr, rust_vec_len, data_len), 9 => wire__crate__api__disconnect_impl(port, ptr, rust_vec_len, data_len),
10 => wire__crate__api__events_stream_impl(port, ptr, rust_vec_len, data_len), 10 => wire__crate__api__download_avatar_impl(port, ptr, rust_vec_len, data_len),
12 => wire__crate__api__get_audio_processing_config_impl(port, ptr, rust_vec_len, data_len), 11 => wire__crate__api__download_icon_impl(port, ptr, rust_vec_len, data_len),
13 => wire__crate__api__get_ptt_binding_impl(port, ptr, rust_vec_len, data_len), 12 => wire__crate__api__enable_audio_debug_wav_dump_impl(port, ptr, rust_vec_len, data_len),
14 => wire__crate__api__get_release_tail_ms_impl(port, ptr, rust_vec_len, data_len), 13 => wire__crate__api__events_stream_impl(port, ptr, rust_vec_len, data_len),
15 => wire__crate__api__get_transmit_mode_impl(port, ptr, rust_vec_len, data_len), 15 => wire__crate__api__file_cache_size_impl(port, ptr, rust_vec_len, data_len),
20 => wire__crate__api__init_storage_impl(port, ptr, rust_vec_len, data_len), 16 => wire__crate__api__get_audio_processing_config_impl(port, ptr, rust_vec_len, data_len),
21 => wire__crate__api__input_level_stream_impl(port, ptr, rust_vec_len, data_len), 17 => wire__crate__api__get_ptt_binding_impl(port, ptr, rust_vec_len, data_len),
22 => wire__crate__api__is_connected_impl(port, ptr, rust_vec_len, data_len), 18 => wire__crate__api__get_release_tail_ms_impl(port, ptr, rust_vec_len, data_len),
23 => wire__crate__api__list_audio_devices_impl(port, ptr, rust_vec_len, data_len), 19 => wire__crate__api__get_transmit_mode_impl(port, ptr, rust_vec_len, data_len),
24 => wire__crate__api__list_bookmarks_impl(port, ptr, rust_vec_len, data_len), 24 => wire__crate__api__init_cache_impl(port, ptr, rust_vec_len, data_len),
26 => wire__crate__api__move_to_channel_impl(port, ptr, rust_vec_len, data_len), 25 => wire__crate__api__init_storage_impl(port, ptr, rust_vec_len, data_len),
27 => wire__crate__api__prefetch_server_impl(port, ptr, rust_vec_len, data_len), 26 => wire__crate__api__input_level_stream_impl(port, ptr, rust_vec_len, data_len),
28 => wire__crate__api__ptt_descriptor_impl(port, ptr, rust_vec_len, data_len), 27 => wire__crate__api__is_connected_impl(port, ptr, rust_vec_len, data_len),
30 => wire__crate__api__send_chat_message_impl(port, ptr, rust_vec_len, data_len), 28 => wire__crate__api__list_audio_devices_impl(port, ptr, rust_vec_len, data_len),
32 => wire__crate__api__set_audio_processing_config_impl(port, ptr, rust_vec_len, data_len), 29 => wire__crate__api__list_bookmarks_impl(port, ptr, rust_vec_len, data_len),
33 => wire__crate__api__set_client_volume_impl(port, ptr, rust_vec_len, data_len), 31 => wire__crate__api__move_to_channel_impl(port, ptr, rust_vec_len, data_len),
34 => wire__crate__api__set_hard_mute_impl(port, ptr, rust_vec_len, data_len), 32 => wire__crate__api__prefetch_server_impl(port, ptr, rust_vec_len, data_len),
35 => wire__crate__api__set_input_device_impl(port, ptr, rust_vec_len, data_len), 33 => wire__crate__api__ptt_descriptor_impl(port, ptr, rust_vec_len, data_len),
36 => wire__crate__api__set_input_muted_impl(port, ptr, rust_vec_len, data_len), 35 => wire__crate__api__send_chat_message_impl(port, ptr, rust_vec_len, data_len),
37 => { 37 => wire__crate__api__set_audio_processing_config_impl(port, ptr, rust_vec_len, data_len),
38 => wire__crate__api__set_client_volume_impl(port, ptr, rust_vec_len, data_len),
39 => wire__crate__api__set_hard_mute_impl(port, ptr, rust_vec_len, data_len),
40 => wire__crate__api__set_input_device_impl(port, ptr, rust_vec_len, data_len),
41 => wire__crate__api__set_input_muted_impl(port, ptr, rust_vec_len, data_len),
42 => {
wire__crate__api__set_ios_voice_processing_mode_impl(port, ptr, rust_vec_len, data_len) wire__crate__api__set_ios_voice_processing_mode_impl(port, ptr, rust_vec_len, data_len)
} }
39 => wire__crate__api__set_output_device_impl(port, ptr, rust_vec_len, data_len), 44 => wire__crate__api__set_output_device_impl(port, ptr, rust_vec_len, data_len),
40 => wire__crate__api__set_output_gain_impl(port, ptr, rust_vec_len, data_len), 45 => wire__crate__api__set_output_gain_impl(port, ptr, rust_vec_len, data_len),
41 => wire__crate__api__set_output_muted_impl(port, ptr, rust_vec_len, data_len), 46 => wire__crate__api__set_output_muted_impl(port, ptr, rust_vec_len, data_len),
42 => wire__crate__api__set_ptt_impl(port, ptr, rust_vec_len, data_len), 47 => wire__crate__api__set_ptt_impl(port, ptr, rust_vec_len, data_len),
43 => wire__crate__api__set_ptt_binding_impl(port, ptr, rust_vec_len, data_len), 48 => wire__crate__api__set_ptt_binding_impl(port, ptr, rust_vec_len, data_len),
44 => wire__crate__api__set_release_tail_ms_impl(port, ptr, rust_vec_len, data_len), 49 => wire__crate__api__set_release_tail_ms_impl(port, ptr, rust_vec_len, data_len),
45 => wire__crate__api__set_transmit_mode_impl(port, ptr, rust_vec_len, data_len), 50 => wire__crate__api__set_transmit_mode_impl(port, ptr, rust_vec_len, data_len),
46 => wire__crate__api__set_vad_model_path_impl(port, ptr, rust_vec_len, data_len), 51 => wire__crate__api__set_vad_model_path_impl(port, ptr, rust_vec_len, data_len),
47 => wire__crate__api__snapshot_impl(port, ptr, rust_vec_len, data_len), 52 => wire__crate__api__snapshot_impl(port, ptr, rust_vec_len, data_len),
48 => wire__crate__api__update_bookmark_impl(port, ptr, rust_vec_len, data_len), 53 => wire__crate__api__update_bookmark_impl(port, ptr, rust_vec_len, data_len),
49 => wire__crate__api__voice_join_impl(port, ptr, rust_vec_len, data_len), 54 => wire__crate__api__voice_join_impl(port, ptr, rust_vec_len, data_len),
50 => wire__crate__api__voice_leave_impl(port, ptr, rust_vec_len, data_len), 55 => wire__crate__api__voice_leave_impl(port, ptr, rust_vec_len, data_len),
_ => unreachable!(), _ => unreachable!(),
} }
} }
@@ -2841,19 +3063,19 @@ fn pde_ffi_dispatcher_sync_impl(
) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse {
// Codec=Pde (Serialization + dispatch), see doc to use other codecs // Codec=Pde (Serialization + dispatch), see doc to use other codecs
match func_id { match func_id {
11 => wire__crate__api__export_diagnostics_impl(ptr, rust_vec_len, data_len), 14 => wire__crate__api__export_diagnostics_impl(ptr, rust_vec_len, data_len),
16 => wire__crate__api__handle_interruption_began_impl(ptr, rust_vec_len, data_len), 20 => wire__crate__api__handle_interruption_began_impl(ptr, rust_vec_len, data_len),
17 => wire__crate__api__handle_interruption_ended_impl(ptr, rust_vec_len, data_len), 21 => wire__crate__api__handle_interruption_ended_impl(ptr, rust_vec_len, data_len),
18 => wire__crate__api__handle_media_services_reset_with_route_impl( 22 => wire__crate__api__handle_media_services_reset_with_route_impl(
ptr, ptr,
rust_vec_len, rust_vec_len,
data_len, data_len,
), ),
19 => wire__crate__api__handle_route_change_impl(ptr, rust_vec_len, data_len), 23 => wire__crate__api__handle_route_change_impl(ptr, rust_vec_len, data_len),
25 => wire__crate__api__log_file_path_str_impl(ptr, rust_vec_len, data_len), 30 => wire__crate__api__log_file_path_str_impl(ptr, rust_vec_len, data_len),
29 => wire__crate__api__record_lifecycle_event_impl(ptr, rust_vec_len, data_len), 34 => wire__crate__api__record_lifecycle_event_impl(ptr, rust_vec_len, data_len),
31 => wire__crate__api__set_audio_output_route_impl(ptr, rust_vec_len, data_len), 36 => wire__crate__api__set_audio_output_route_impl(ptr, rust_vec_len, data_len),
38 => wire__crate__api__set_network_state_impl(ptr, rust_vec_len, data_len), 43 => wire__crate__api__set_network_state_impl(ptr, rust_vec_len, data_len),
_ => unreachable!(), _ => unreachable!(),
} }
} }
@@ -3299,12 +3521,14 @@ impl flutter_rust_bridge::IntoDart for crate::api::BridgeEvent {
sender_name, sender_name,
message, message,
target, target,
poke_strength,
} => [ } => [
10.into_dart(), 10.into_dart(),
sender_id.into_into_dart().into_dart(), sender_id.into_into_dart().into_dart(),
sender_name.into_into_dart().into_dart(), sender_name.into_into_dart().into_dart(),
message.into_into_dart().into_dart(), message.into_into_dart().into_dart(),
target.into_into_dart().into_dart(), target.into_into_dart().into_dart(),
poke_strength.into_into_dart().into_dart(),
] ]
.into_dart(), .into_dart(),
crate::api::BridgeEvent::ServerActivity { message } => { crate::api::BridgeEvent::ServerActivity { message } => {
@@ -3416,7 +3640,6 @@ impl flutter_rust_bridge::IntoDart for crate::api::BridgeIosVoiceProcessingMode
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
match self { match self {
Self::PlatformVoiceProcessing => 0.into_dart(), Self::PlatformVoiceProcessing => 0.into_dart(),
Self::SonoraExperimental => 1.into_dart(),
_ => unreachable!(), _ => unreachable!(),
} }
} }
@@ -3484,6 +3707,28 @@ impl flutter_rust_bridge::IntoIntoDart<crate::api::BridgeNetworkState>
} }
} }
// Codec=Dco (DartCObject based), see doc to use other codecs // Codec=Dco (DartCObject based), see doc to use other codecs
impl flutter_rust_bridge::IntoDart for crate::api::BridgePokeStrength {
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
match self {
Self::Strong => 0.into_dart(),
Self::Suppressed => 1.into_dart(),
Self::SuppressedOverflow => 2.into_dart(),
_ => unreachable!(),
}
}
}
impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive
for crate::api::BridgePokeStrength
{
}
impl flutter_rust_bridge::IntoIntoDart<crate::api::BridgePokeStrength>
for crate::api::BridgePokeStrength
{
fn into_into_dart(self) -> crate::api::BridgePokeStrength {
self
}
}
// Codec=Dco (DartCObject based), see doc to use other codecs
impl flutter_rust_bridge::IntoDart for crate::api::BridgePttBinding { impl flutter_rust_bridge::IntoDart for crate::api::BridgePttBinding {
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
[ [
@@ -4053,12 +4298,14 @@ impl SseEncode for crate::api::BridgeEvent {
sender_name, sender_name,
message, message,
target, target,
poke_strength,
} => { } => {
<i32>::sse_encode(10, serializer); <i32>::sse_encode(10, serializer);
<u64>::sse_encode(sender_id, serializer); <u64>::sse_encode(sender_id, serializer);
<String>::sse_encode(sender_name, serializer); <String>::sse_encode(sender_name, serializer);
<String>::sse_encode(message, serializer); <String>::sse_encode(message, serializer);
<crate::api::BridgeMessageTarget>::sse_encode(target, serializer); <crate::api::BridgeMessageTarget>::sse_encode(target, serializer);
<Option<crate::api::BridgePokeStrength>>::sse_encode(poke_strength, serializer);
} }
crate::api::BridgeEvent::ServerActivity { message } => { crate::api::BridgeEvent::ServerActivity { message } => {
<i32>::sse_encode(11, serializer); <i32>::sse_encode(11, serializer);
@@ -4162,7 +4409,6 @@ impl SseEncode for crate::api::BridgeIosVoiceProcessingMode {
<i32>::sse_encode( <i32>::sse_encode(
match self { match self {
crate::api::BridgeIosVoiceProcessingMode::PlatformVoiceProcessing => 0, crate::api::BridgeIosVoiceProcessingMode::PlatformVoiceProcessing => 0,
crate::api::BridgeIosVoiceProcessingMode::SonoraExperimental => 1,
_ => { _ => {
unimplemented!(""); unimplemented!("");
} }
@@ -4214,6 +4460,23 @@ impl SseEncode for crate::api::BridgeNetworkState {
} }
} }
impl SseEncode for crate::api::BridgePokeStrength {
// Codec=Sse (Serialization based), see doc to use other codecs
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
<i32>::sse_encode(
match self {
crate::api::BridgePokeStrength::Strong => 0,
crate::api::BridgePokeStrength::Suppressed => 1,
crate::api::BridgePokeStrength::SuppressedOverflow => 2,
_ => {
unimplemented!("");
}
},
serializer,
);
}
}
impl SseEncode for crate::api::BridgePttBinding { impl SseEncode for crate::api::BridgePttBinding {
// Codec=Sse (Serialization based), see doc to use other codecs // Codec=Sse (Serialization based), see doc to use other codecs
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
@@ -4429,6 +4692,16 @@ impl SseEncode for Option<String> {
} }
} }
impl SseEncode for Option<crate::api::BridgePokeStrength> {
// Codec=Sse (Serialization based), see doc to use other codecs
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
<bool>::sse_encode(self.is_some(), serializer);
if let Some(value) = self {
<crate::api::BridgePokeStrength>::sse_encode(value, serializer);
}
}
}
impl SseEncode for Option<crate::api::BridgeVoiceJoinErrorCode> { impl SseEncode for Option<crate::api::BridgeVoiceJoinErrorCode> {
// Codec=Sse (Serialization based), see doc to use other codecs // Codec=Sse (Serialization based), see doc to use other codecs
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
@@ -4479,6 +4752,16 @@ impl SseEncode for Option<u64> {
} }
} }
impl SseEncode for Option<Vec<u8>> {
// Codec=Sse (Serialization based), see doc to use other codecs
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
<bool>::sse_encode(self.is_some(), serializer);
if let Some(value) = self {
<Vec<u8>>::sse_encode(value, serializer);
}
}
}
impl SseEncode for crate::api::PermissionStateKind { impl SseEncode for crate::api::PermissionStateKind {
// Codec=Sse (Serialization based), see doc to use other codecs // Codec=Sse (Serialization based), see doc to use other codecs
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
+4
View File
@@ -110,9 +110,13 @@ impl From<chanora_core::CoreError> for BridgeError {
code, code,
message, message,
}) => BridgeError::ServerRejected { code, message }, }) => BridgeError::ServerRejected { code, message },
chanora_core::CoreError::Protocol(chanora_core::ProtocolError::FileTransfer(p)) => {
BridgeError::Connection(format!("file transfer: {p}"))
}
chanora_core::CoreError::Protocol(p) => BridgeError::Connection(format!("{p}")), chanora_core::CoreError::Protocol(p) => BridgeError::Connection(format!("{p}")),
chanora_core::CoreError::Audio(a) => BridgeError::Connection(format!("audio: {a}")), chanora_core::CoreError::Audio(a) => BridgeError::Connection(format!("audio: {a}")),
chanora_core::CoreError::Storage(s) => BridgeError::Connection(format!("storage: {s}")), chanora_core::CoreError::Storage(s) => BridgeError::Connection(format!("storage: {s}")),
chanora_core::CoreError::Cache(c) => BridgeError::Connection(format!("cache: {c}")),
other => BridgeError::Unmapped(format!("{other}")), other => BridgeError::Unmapped(format!("{other}")),
} }
} }
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "chanora_cache"
description = "Chanora disposable content-addressed blob cache for avatars and icons"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
authors.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
cacache = "13"
thiserror.workspace = true
tokio = { version = "1", features = ["fs", "rt"] }
tracing.workspace = true
[dev-dependencies]
tempfile = "3"
tokio = { version = "1", features = ["rt", "macros", "time"] }
+359
View File
@@ -0,0 +1,359 @@
//! Disposable content-addressed blob cache for avatar and icon files.
//!
//! Wraps [`cacache`] for production-tested crash safety and integrity
//! verification. The on-disk layout is managed by cacache (content-v2,
//! index-v2). Chanora maps protocol keys (`av_<md5>`, `ic_<crc32>`) to
//! cacache string keys.
//!
//! This crate is intentionally separate from `chanora_storage`:
//! storage owns persistent identity/bookmark data; cache owns
//! reconstructible, disposable blob data with different durability
//! and backup semantics.
#![forbid(unsafe_code)]
#![warn(missing_docs)]
use std::path::{Path, PathBuf};
/// Errors raised by the blob cache.
#[derive(Debug, thiserror::Error)]
pub enum BlobCacheError {
/// Filesystem I/O error.
#[error("io: {0}")]
Io(String),
/// Key validation error.
#[error("invalid key: {0}")]
InvalidKey(String),
}
/// Content-addressed blob cache backed by cacache.
pub struct BlobCache {
cache_dir: PathBuf,
/// Maximum total cache size in bytes. 0 = no limit.
max_bytes: u64,
}
/// Avatar blob prefix.
pub const PREFIX_AVATAR: &str = "av_";
/// Icon blob prefix.
pub const PREFIX_ICON: &str = "ic_";
impl BlobCache {
/// Create or open a [`BlobCache`] rooted at `cache_dir/chanora/`.
///
/// Creates the cacache directory. `max_bytes` sets the eviction
/// threshold; 0 means no automatic eviction.
pub fn new(cache_dir: impl AsRef<Path>, max_bytes: u64) -> Result<Self, BlobCacheError> {
let cache_dir = cache_dir.as_ref().join("chanora").join("blobs");
// cacache creates the directory on first write, but we create
// it eagerly so total_size() works before any writes.
std::fs::create_dir_all(&cache_dir)
.map_err(|e| BlobCacheError::Io(format!("mkdir cache: {e}")))?;
Ok(Self {
cache_dir,
max_bytes,
})
}
/// Store a blob. `prefix` is [`PREFIX_AVATAR`] or [`PREFIX_ICON`].
/// `key` is the content hash (MD5 hex for avatars, unsigned
/// decimal CRC32 for icons).
///
/// Cacache handles dedup and integrity internally.
pub async fn put(
&self,
prefix: &str,
key: &str,
data: &[u8],
) -> Result<(), BlobCacheError> {
validate_key(prefix, key)?;
let cache_key = format!("{prefix}{key}");
cacache::write(&self.cache_dir, &cache_key, data)
.await
.map_err(|e| BlobCacheError::Io(format!("cacache write: {e}")))?;
Ok(())
}
/// Read a blob. Returns `None` if not cached.
///
/// Cacache verifies SSRI integrity on every read.
pub async fn get(&self, prefix: &str, key: &str) -> Result<Option<Vec<u8>>, BlobCacheError> {
validate_key(prefix, key)?;
let cache_key = format!("{prefix}{key}");
match cacache::read(&self.cache_dir, &cache_key).await {
Ok(data) => Ok(Some(data)),
Err(cacache::Error::EntryNotFound(_, _)) => Ok(None),
Err(e) => {
// Integrity failure or I/O error — remove corrupt entry.
tracing::warn!(
target: "chanora_cache",
key = %cache_key,
error = %e,
"cache read failed; removing entry"
);
let _ = cacache::remove(&self.cache_dir, &cache_key).await;
Ok(None)
}
}
}
/// Delete a specific blob.
pub async fn remove(&self, prefix: &str, key: &str) -> Result<(), BlobCacheError> {
validate_key(prefix, key)?;
let cache_key = format!("{prefix}{key}");
cacache::remove(&self.cache_dir, &cache_key)
.await
.map_err(|e| BlobCacheError::Io(format!("cacache remove: {e}")))?;
Ok(())
}
/// Delete all blobs.
pub async fn clear(&self) -> Result<(), BlobCacheError> {
let path = self.cache_dir.clone();
tokio::task::spawn_blocking(move || {
if path.exists() {
std::fs::remove_dir_all(&path)
.map_err(|e| BlobCacheError::Io(format!("clear cache: {e}")))?;
std::fs::create_dir_all(&path)
.map_err(|e| BlobCacheError::Io(format!("recreate cache dir: {e}")))?;
}
Ok(())
})
.await
.map_err(|e| BlobCacheError::Io(format!("clear task: {e}")))?
}
/// Return total bytes used by all blobs.
///
/// Walks cacache entries and sums sizes.
pub async fn total_size(&self) -> Result<u64, BlobCacheError> {
let cache_dir = self.cache_dir.clone();
tokio::task::spawn_blocking(move || {
let mut total: u64 = 0;
for entry in cacache::list_sync(&cache_dir) {
match entry {
Ok(meta) => total += meta.size as u64,
Err(e) => {
tracing::warn!(
target: "chanora_cache",
error = %e,
"skipping bad entry during size scan"
);
}
}
}
Ok(total)
})
.await
.map_err(|e| BlobCacheError::Io(format!("total_size task: {e}")))?
}
/// Evict oldest entries by timestamp until total size is under
/// `max_bytes`. Call on startup or periodically. No-op if
/// `max_bytes` is 0.
pub async fn evict(&self) -> Result<(), BlobCacheError> {
if self.max_bytes == 0 {
return Ok(());
}
let cache_dir = self.cache_dir.clone();
let max_bytes = self.max_bytes;
tokio::task::spawn_blocking(move || {
let mut entries: Vec<(String, usize, u128)> = Vec::new();
for entry in cacache::list_sync(&cache_dir) {
match entry {
Ok(meta) => {
entries.push((meta.key, meta.size, meta.time));
}
Err(e) => {
tracing::warn!(
target: "chanora_cache",
error = %e,
"skipping bad entry during eviction scan"
);
}
}
}
let total: usize = entries.iter().map(|(_, s, _)| *s).sum();
if total as u64 <= max_bytes {
return Ok(());
}
entries.sort_by_key(|(_, _, t)| *t);
let mut freed: usize = 0;
let target = total - max_bytes as usize;
for (key, size, _) in entries {
if freed >= target {
break;
}
let _ = cacache::remove_sync(&cache_dir, &key);
freed += size;
}
tracing::info!(
target: "chanora_cache",
freed_bytes = freed,
"evicted oldest blobs"
);
Ok(())
})
.await
.map_err(|e| BlobCacheError::Io(format!("evict task: {e}")))?
}
}
/// Validate key format to prevent malformed entries.
fn validate_key(prefix: &str, key: &str) -> Result<(), BlobCacheError> {
if !matches!(prefix, PREFIX_AVATAR | PREFIX_ICON) {
return Err(BlobCacheError::InvalidKey(format!("bad prefix: {prefix}")));
}
match prefix {
PREFIX_AVATAR => {
// MD5 hex = exactly 32 hex chars.
if key.len() != 32 || !key.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(BlobCacheError::InvalidKey(format!(
"avatar key must be 32 hex chars, got: {key}"
)));
}
}
PREFIX_ICON => {
// Unsigned CRC32 = decimal digits.
if key.is_empty() || !key.chars().all(|c| c.is_ascii_digit()) {
return Err(BlobCacheError::InvalidKey(format!(
"icon key must be decimal digits, got: {key}"
)));
}
}
_ => unreachable!(),
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn tempdir() -> tempfile::TempDir {
tempfile::Builder::new()
.prefix("chanora_cache_test_")
.tempdir()
.unwrap()
}
#[tokio::test]
async fn put_get_roundtrip() {
let tmp = tempdir();
let cache = BlobCache::new(&tmp, 0).unwrap();
assert!(cache
.get(PREFIX_AVATAR, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6")
.await
.unwrap()
.is_none());
cache
.put(PREFIX_AVATAR, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", b"avatar-bytes")
.await
.unwrap();
let data = cache
.get(PREFIX_AVATAR, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6")
.await
.unwrap();
assert_eq!(data.as_deref(), Some(b"avatar-bytes".as_slice()));
}
#[tokio::test]
async fn get_missing_returns_none() {
let tmp = tempdir();
let cache = BlobCache::new(&tmp, 0).unwrap();
assert!(cache
.get(PREFIX_AVATAR, "00000000000000000000000000000000")
.await
.unwrap()
.is_none());
}
#[tokio::test]
async fn clear_removes_all() {
let tmp = tempdir();
let cache = BlobCache::new(&tmp, 0).unwrap();
cache
.put(PREFIX_AVATAR, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", b"data")
.await
.unwrap();
cache.put(PREFIX_ICON, "12345", b"icon").await.unwrap();
cache.clear().await.unwrap();
assert_eq!(cache.total_size().await.unwrap(), 0);
}
#[tokio::test]
async fn total_size_accounts_for_all_entries() {
let tmp = tempdir();
let cache = BlobCache::new(&tmp, 0).unwrap();
cache
.put(PREFIX_AVATAR, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", b"12345")
.await
.unwrap();
cache.put(PREFIX_ICON, "99999", b"12").await.unwrap();
assert_eq!(cache.total_size().await.unwrap(), 5 + 2);
}
#[tokio::test]
async fn invalid_key_rejected() {
let tmp = tempdir();
let cache = BlobCache::new(&tmp, 0).unwrap();
// Too short for MD5.
assert!(cache.put(PREFIX_AVATAR, "abc", b"data").await.is_err());
// Non-hex in MD5.
assert!(cache
.put(PREFIX_AVATAR, "g".repeat(32).as_str(), b"data")
.await
.is_err());
// Non-digit in icon key.
assert!(cache.put(PREFIX_ICON, "12a45", b"data").await.is_err());
// Bad prefix.
assert!(cache.put("xx_", "abc", b"data").await.is_err());
}
#[tokio::test]
async fn evict_deletes_oldest_until_under_cap() {
let tmp = tempdir();
// 10 byte cap.
let cache = BlobCache::new(&tmp, 10).unwrap();
cache
.put(
PREFIX_AVATAR,
"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6",
b"12345678",
)
.await
.unwrap(); // 8 bytes
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
cache
.put(PREFIX_ICON, "11111", b"12345")
.await
.unwrap(); // 5 bytes → total 13, over cap
cache.evict().await.unwrap();
// Oldest (avatar) should be evicted.
assert!(cache
.get(PREFIX_AVATAR, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6")
.await
.unwrap()
.is_none());
assert!(cache.get(PREFIX_ICON, "11111").await.unwrap().is_some());
}
#[tokio::test]
async fn remove_deletes_entry() {
let tmp = tempdir();
let cache = BlobCache::new(&tmp, 0).unwrap();
cache
.put(PREFIX_AVATAR, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6", b"data")
.await
.unwrap();
cache
.remove(PREFIX_AVATAR, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6")
.await
.unwrap();
assert!(cache
.get(PREFIX_AVATAR, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6")
.await
.unwrap()
.is_none());
}
}
+19 -7
View File
@@ -36,7 +36,7 @@
#![forbid(unsafe_code)] #![forbid(unsafe_code)]
#![warn(missing_docs)] #![warn(missing_docs)]
use std::collections::HashSet; use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use thiserror::Error; use thiserror::Error;
@@ -712,7 +712,7 @@ impl DiagnosticExport {
/// diagnostic export and state-sync replay verification. /// diagnostic export and state-sync replay verification.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ProtocolEventRecorder { pub struct ProtocolEventRecorder {
events: Vec<String>, events: VecDeque<String>,
capacity: usize, capacity: usize,
} }
@@ -720,17 +720,20 @@ impl ProtocolEventRecorder {
/// Create a recorder with the given ring-buffer capacity. /// Create a recorder with the given ring-buffer capacity.
pub fn new(capacity: usize) -> Self { pub fn new(capacity: usize) -> Self {
Self { Self {
events: Vec::with_capacity(capacity), events: VecDeque::with_capacity(capacity),
capacity, capacity,
} }
} }
fn push(&mut self, ts: &str, kind: &str, detail: &str) { fn push(&mut self, ts: &str, kind: &str, detail: &str) {
if self.capacity == 0 {
return;
}
let s = format!("[{ts}] {kind}: {detail}"); let s = format!("[{ts}] {kind}: {detail}");
if self.events.len() >= self.capacity { if self.events.len() >= self.capacity {
self.events.remove(0); self.events.pop_front();
} }
self.events.push(s); self.events.push_back(s);
} }
/// Record a successful connection. /// Record a successful connection.
@@ -777,12 +780,12 @@ impl ProtocolEventRecorder {
/// Drain all recorded events and reset the buffer. /// Drain all recorded events and reset the buffer.
pub fn drain(&mut self) -> Vec<String> { pub fn drain(&mut self) -> Vec<String> {
std::mem::take(&mut self.events) self.events.drain(..).collect()
} }
/// Snapshot all recorded events without clearing the buffer. /// Snapshot all recorded events without clearing the buffer.
pub fn snapshot(&self) -> Vec<String> { pub fn snapshot(&self) -> Vec<String> {
self.events.clone() self.events.iter().cloned().collect()
} }
} }
@@ -1103,4 +1106,13 @@ mod tests {
assert_eq!(first, second); assert_eq!(first, second);
assert_eq!(drained, first); assert_eq!(drained, first);
} }
#[test]
fn protocol_event_zero_capacity_drops_events() {
let mut recorder = ProtocolEventRecorder::new(0);
recorder.record_connected("Server");
assert!(recorder.snapshot().is_empty());
assert!(recorder.drain().is_empty());
}
} }
+318 -42
View File
@@ -24,6 +24,7 @@ use base64::prelude::*;
use chanora_resolver::ChanoraResolver; use chanora_resolver::ChanoraResolver;
use futures::prelude::*; use futures::prelude::*;
use std::collections::HashMap; use std::collections::HashMap;
use tokio::io::AsyncReadExt;
use tokio::sync::{mpsc, oneshot}; use tokio::sync::{mpsc, oneshot};
use tracing::{info, warn}; use tracing::{info, warn};
@@ -32,7 +33,8 @@ use tsclientlib::messages::s2c::{InClientDbInfoPart, InMessage};
use tsclientlib::prelude::*; use tsclientlib::prelude::*;
use tsclientlib::{ use tsclientlib::{
ChannelId as TsChannelId, ClientId as TsClientId, Connection, ConnectionStats, ChannelId as TsChannelId, ClientId as TsClientId, Connection, ConnectionStats,
DisconnectOptions, Identity, MessageHandle, OutCommandExt, StreamItem, Version, DisconnectOptions, FileDownloadResult, FiletransferHandle, Identity, MessageHandle,
OutCommandExt, StreamItem, Version,
}; };
use tsproto_packets::packets::{Direction, Flags, InAudioBuf, OutCommand, OutPacket, PacketType}; use tsproto_packets::packets::{Direction, Flags, InAudioBuf, OutCommand, OutPacket, PacketType};
use tsproto_types::ClientType; use tsproto_types::ClientType;
@@ -41,11 +43,15 @@ use crate::dto::{
ChannelId, ChannelInfo, ChatMessage, ClientId, ClientInfo, ClientProfile, MessageTarget, ChannelId, ChannelInfo, ChatMessage, ClientId, ClientInfo, ClientProfile, MessageTarget,
ProtocolDelta, ServerActivity, ServerSnapshot, ProtocolDelta, ServerActivity, ServerSnapshot,
}; };
use crate::poke_limiter::PokeLimiter;
use crate::ProtocolError; use crate::ProtocolError;
const SPEAKING_ACTIVITY_WINDOW: Duration = Duration::from_millis(750); const SPEAKING_ACTIVITY_WINDOW: Duration = Duration::from_millis(750);
const INBOUND_VOICE_SEND_TIMEOUT: Duration = Duration::from_millis(40); const INBOUND_VOICE_SEND_TIMEOUT: Duration = Duration::from_millis(40);
const PROFILE_REFRESH_RESULT_TIMEOUT: Duration = Duration::from_secs(3); const PROFILE_REFRESH_RESULT_TIMEOUT: Duration = Duration::from_secs(3);
const OUTBOUND_VOICE_PACKETS_PER_TICK: usize = 8;
const DISCONNECT_REPLY_TIMEOUT: Duration = Duration::from_secs(1);
const DISCONNECT_EVENT_DRAIN_TIMEOUT: Duration = Duration::from_millis(500);
type PendingMoves = HashMap< type PendingMoves = HashMap<
MessageHandle, MessageHandle,
@@ -56,6 +62,9 @@ type PendingMoves = HashMap<
), ),
>; >;
type PendingDownloads =
HashMap<FiletransferHandle, oneshot::Sender<Result<Vec<u8>, ProtocolError>>>;
struct EventChannels { struct EventChannels {
voice_in: mpsc::Sender<InboundVoice>, voice_in: mpsc::Sender<InboundVoice>,
chat: mpsc::Sender<ChatMessage>, chat: mpsc::Sender<ChatMessage>,
@@ -84,6 +93,30 @@ async fn send_with_timeout<T: Send>(
} }
} }
fn drain_voice_packets_for_tick<T, E>(
voice_out_rx: &mut mpsc::Receiver<T>,
max_packets: usize,
mut send: impl FnMut(T) -> Result<(), E>,
) -> usize {
let mut drained = 0;
for _ in 0..max_packets {
let packet = match voice_out_rx.try_recv() {
Ok(packet) => packet,
Err(_) => break,
};
let _ = send(packet);
drained += 1;
}
drained
}
async fn bounded_drain_stream<S>(stream: S, timeout_duration: Duration)
where
S: futures::Stream,
{
let _ = tokio::time::timeout(timeout_duration, stream.for_each(|_| future::ready(()))).await;
}
/// Pick the TeamSpeak `client_version`/platform/signature triple /// Pick the TeamSpeak `client_version`/platform/signature triple
/// (sourced from `ReSpeak/tsdeclarations/Versions.csv`, baked into /// (sourced from `ReSpeak/tsdeclarations/Versions.csv`, baked into
/// `tsproto-types` at vendor-time) that best matches the *runtime* /// `tsproto-types` at vendor-time) that best matches the *runtime*
@@ -179,6 +212,10 @@ enum Request {
client_id: u64, client_id: u64,
reply: oneshot::Sender<Result<ClientProfile, ProtocolError>>, reply: oneshot::Sender<Result<ClientProfile, ProtocolError>>,
}, },
DownloadFile {
path: String,
reply: oneshot::Sender<Result<Vec<u8>, ProtocolError>>,
},
} }
/// Why a [`ProtocolClient`] task ended. Distinguishes a user-driven /// Why a [`ProtocolClient`] task ended. Distinguishes a user-driven
@@ -338,11 +375,44 @@ impl ProtocolClient {
.map_err(|_| ProtocolError::Lost("client_profile reply dropped".to_string()))? .map_err(|_| ProtocolError::Lost("client_profile reply dropped".to_string()))?
} }
async fn download_file(&self, path: String) -> Result<Vec<u8>, ProtocolError> {
let (tx, rx) = oneshot::channel();
self.tx
.send(Request::DownloadFile { path, reply: tx })
.await
.map_err(|_| ProtocolError::Lost("connection task is gone".to_string()))?;
rx.await
.map_err(|_| ProtocolError::Lost("download_file reply dropped".to_string()))?
}
/// Download the current avatar bytes for a TeamSpeak client UID.
pub async fn download_avatar(&self, client_uid: &str) -> Result<Vec<u8>, ProtocolError> {
self.download_file(avatar_download_path(client_uid)).await
}
/// Download the current channel/server icon bytes for an icon id.
pub async fn download_icon(&self, icon_id: u64) -> Result<Vec<u8>, ProtocolError> {
self.download_file(icon_download_path(icon_id)).await
}
/// Disconnect cleanly. Blocks until the task exits. /// Disconnect cleanly. Blocks until the task exits.
pub async fn disconnect(self) { pub async fn disconnect(self) {
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
if self.tx.send(Request::Disconnect(tx)).await.is_ok() { let request_path = async {
let _ = rx.await; if self.tx.send(Request::Disconnect(tx)).await.is_ok() {
let _ = rx.await;
}
};
if tokio::time::timeout(DISCONNECT_REPLY_TIMEOUT, request_path)
.await
.is_err()
{
warn!(
target: "chanora_protocol",
timeout_ms = DISCONNECT_REPLY_TIMEOUT.as_millis() as u64,
"disconnect request did not complete before timeout"
);
} }
} }
@@ -672,16 +742,20 @@ async fn connection_task(
// deadline so a server that never replies doesn't leak the // deadline so a server that never replies doesn't leak the
// reply channel — at most 3 s of pending state per move. // reply channel — at most 3 s of pending state per move.
let mut pending_moves: PendingMoves = HashMap::new(); let mut pending_moves: PendingMoves = HashMap::new();
let mut pending_downloads: PendingDownloads = HashMap::new();
let mut voice_activity: HashMap<u64, Instant> = HashMap::new(); let mut voice_activity: HashMap<u64, Instant> = HashMap::new();
let mut poke_limiter = PokeLimiter::new();
// Main loop: pump events, service requests, forward voice. // Main loop: pump events, service requests, forward voice.
loop { loop {
// 1. Drain any outbound voice packets first — they're time-sensitive. // 1. Send a bounded batch of outbound voice packets first — they're
while let Ok(pkt) = voice_out_rx.try_recv() { // time-sensitive, but control requests must still make progress.
drain_voice_packets_for_tick(&mut voice_out_rx, OUTBOUND_VOICE_PACKETS_PER_TICK, |pkt| {
if let Err(e) = con.send_audio(pkt) { if let Err(e) = con.send_audio(pkt) {
warn!(target: "chanora_protocol", error = %e, "send_audio failed"); warn!(target: "chanora_protocol", error = %e, "send_audio failed");
} }
} Ok::<(), ()>(())
});
// 2. Advance event stream by at most one event with a small timeout. // 2. Advance event stream by at most one event with a small timeout.
let pump = async { let pump = async {
@@ -689,21 +763,26 @@ async fn connection_task(
tokio::time::timeout(Duration::from_millis(20), ev_stream.next()).await tokio::time::timeout(Duration::from_millis(20), ev_stream.next()).await
}; };
match pump.await { match pump.await {
Ok(Some(Ok(item))) => { Ok(Some(Ok(item))) => match item {
match item { StreamItem::Audio(buf) => {
StreamItem::Audio(buf) => { handle_audio_stream_item(&channels.voice_in, &mut voice_activity, buf).await;
handle_audio_stream_item(&channels.voice_in, &mut voice_activity, buf).await;
}
other => handle_non_audio_stream_item(
&con,
other,
&channels.chat,
&channels.activity,
&channels.delta,
&mut pending_moves,
),
} }
} StreamItem::FileDownload(handle, result) => {
handle_download_stream_item(&mut pending_downloads, handle, result).await;
}
StreamItem::FiletransferFailed(handle, error) => {
handle_download_failure(&mut pending_downloads, handle, error);
}
other => handle_non_audio_stream_item(
&con,
other,
&channels.chat,
&channels.activity,
&channels.delta,
&mut pending_moves,
&mut poke_limiter,
),
},
Ok(Some(Err(e))) => { Ok(Some(Err(e))) => {
warn!(target: "chanora_protocol", error = %e, "event error"); warn!(target: "chanora_protocol", error = %e, "event error");
// Some errors are transient; treat persistent ones // Some errors are transient; treat persistent ones
@@ -800,14 +879,28 @@ async fn connection_task(
client_id, client_id,
&channels, &channels,
&mut pending_moves, &mut pending_moves,
&mut pending_downloads,
&mut voice_activity, &mut voice_activity,
&mut poke_limiter,
) )
.await; .await;
let _ = reply.send(r); let _ = reply.send(r);
} }
Ok(Request::DownloadFile { path, reply }) => {
match con.download_file(TsChannelId(0), &path, None, None) {
Ok(handle) => {
pending_downloads.insert(handle, reply);
}
Err(e) => {
let _ = reply.send(Err(ProtocolError::FileTransfer(format!(
"start download {path}: {e}"
))));
}
}
}
Ok(Request::Disconnect(reply)) => { Ok(Request::Disconnect(reply)) => {
let _ = con.disconnect(DisconnectOptions::new()); let _ = con.disconnect(DisconnectOptions::new());
con.events().for_each(|_| future::ready(())).await; bounded_drain_stream(con.events(), DISCONNECT_EVENT_DRAIN_TIMEOUT).await;
let _ = reply.send(()); let _ = reply.send(());
info!(target: "chanora_protocol", "clean disconnect"); info!(target: "chanora_protocol", "clean disconnect");
exit!(DisconnectReason::UserRequested); exit!(DisconnectReason::UserRequested);
@@ -815,7 +908,7 @@ async fn connection_task(
Err(mpsc::error::TryRecvError::Empty) => {} Err(mpsc::error::TryRecvError::Empty) => {}
Err(mpsc::error::TryRecvError::Disconnected) => { Err(mpsc::error::TryRecvError::Disconnected) => {
let _ = con.disconnect(DisconnectOptions::new()); let _ = con.disconnect(DisconnectOptions::new());
con.events().for_each(|_| future::ready(())).await; bounded_drain_stream(con.events(), DISCONNECT_EVENT_DRAIN_TIMEOUT).await;
info!(target: "chanora_protocol", "handle dropped; implicit disconnect"); info!(target: "chanora_protocol", "handle dropped; implicit disconnect");
exit!(DisconnectReason::UserRequested); exit!(DisconnectReason::UserRequested);
} }
@@ -863,6 +956,7 @@ fn handle_non_audio_stream_item(
activity_tx: &mpsc::Sender<ServerActivity>, activity_tx: &mpsc::Sender<ServerActivity>,
delta_tx: &mpsc::Sender<ProtocolDelta>, delta_tx: &mpsc::Sender<ProtocolDelta>,
pending_moves: &mut PendingMoves, pending_moves: &mut PendingMoves,
poke_limiter: &mut PokeLimiter,
) { ) {
match item { match item {
StreamItem::BookEvents(events) => { StreamItem::BookEvents(events) => {
@@ -924,17 +1018,25 @@ fn handle_non_audio_stream_item(
message, message,
} = ev } = ev
{ {
let mapped = match target { let (mapped, poke_strength) = match target {
tsclientlib::MessageTarget::Server => MessageTarget::Server, tsclientlib::MessageTarget::Server => (MessageTarget::Server, None),
tsclientlib::MessageTarget::Channel => MessageTarget::Channel, tsclientlib::MessageTarget::Channel => (MessageTarget::Channel, None),
tsclientlib::MessageTarget::Client(id) => MessageTarget::Client(id.0 as u64), tsclientlib::MessageTarget::Client(id) => {
tsclientlib::MessageTarget::Poke(id) => MessageTarget::Poke(id.0 as u64), (MessageTarget::Client(id.0 as u64), None)
}
tsclientlib::MessageTarget::Poke(id) => {
let own_client_id =
con.get_state().ok().map(|state| state.own_client.0 as u64);
let strength = poke_limiter.record(invoker.id.0 as u64, own_client_id);
(MessageTarget::Poke(id.0 as u64), Some(strength))
}
}; };
let _ = chat_tx.try_send(ChatMessage { let _ = chat_tx.try_send(ChatMessage {
sender_id: ClientId(invoker.id.0 as u64), sender_id: ClientId(invoker.id.0 as u64),
sender_name: sanitize(&invoker.name), sender_name: sanitize(&invoker.name),
message: sanitize(&message), message: sanitize(&message),
target: mapped, target: mapped,
poke_strength,
}); });
} }
} }
@@ -971,6 +1073,47 @@ fn handle_non_audio_stream_item(
} }
} }
async fn handle_download_stream_item(
pending_downloads: &mut PendingDownloads,
handle: FiletransferHandle,
result: FileDownloadResult,
) {
if let Some(reply) = pending_downloads.remove(&handle) {
let _ = reply.send(read_download_bytes(result).await);
}
}
fn handle_download_failure(
pending_downloads: &mut PendingDownloads,
handle: FiletransferHandle,
error: tsclientlib::Error,
) {
if let Some(reply) = pending_downloads.remove(&handle) {
let _ = reply.send(Err(ProtocolError::FileTransfer(error.to_string())));
}
}
const MAX_DOWNLOAD_SIZE: u64 = 10 * 1024 * 1024;
async fn read_download_bytes(result: FileDownloadResult) -> Result<Vec<u8>, ProtocolError> {
if result.size > MAX_DOWNLOAD_SIZE {
return Err(ProtocolError::FileTransfer(format!(
"download too large: {} bytes (max {})",
result.size, MAX_DOWNLOAD_SIZE
)));
}
let size = usize::try_from(result.size).map_err(|_| {
ProtocolError::FileTransfer(format!("download too large to buffer: {} bytes", result.size))
})?;
let mut stream = result.stream;
let mut bytes = vec![0_u8; size];
stream
.read_exact(&mut bytes)
.await
.map_err(|e| ProtocolError::FileTransfer(e.to_string()))?;
Ok(bytes)
}
async fn resolve_server_socket(address: &str) -> Result<SocketAddr, ProtocolError> { async fn resolve_server_socket(address: &str) -> Result<SocketAddr, ProtocolError> {
let resolver = ChanoraResolver::new().map_err(|err| ProtocolError::DnsFailed { let resolver = ChanoraResolver::new().map_err(|err| ProtocolError::DnsFailed {
host: address.to_string(), host: address.to_string(),
@@ -1121,11 +1264,21 @@ async fn fetch_client_profile(
client_id: u64, client_id: u64,
channels: &EventChannels, channels: &EventChannels,
pending_moves: &mut PendingMoves, pending_moves: &mut PendingMoves,
pending_downloads: &mut PendingDownloads,
voice_activity: &mut HashMap<u64, Instant>, voice_activity: &mut HashMap<u64, Instant>,
poke_limiter: &mut PokeLimiter,
) -> Result<ClientProfile, ProtocolError> { ) -> Result<ClientProfile, ProtocolError> {
let target_id = TsClientId(client_id as u16); let target_id = TsClientId(client_id as u16);
let (database_id, uid_b64, has_optional, has_connection, is_own, needs_server_groups, needs_channel_groups) = { let (
database_id,
uid_b64,
has_optional,
has_connection,
is_own,
needs_server_groups,
needs_channel_groups,
) = {
let state = con let state = con
.get_state() .get_state()
.map_err(|e| ProtocolError::Backend(format!("get_state: {e}")))?; .map_err(|e| ProtocolError::Backend(format!("get_state: {e}")))?;
@@ -1158,7 +1311,9 @@ async fn fetch_client_profile(
build_command("servergrouplist", &[], &[]), build_command("servergrouplist", &[], &[]),
channels, channels,
pending_moves, pending_moves,
pending_downloads,
voice_activity, voice_activity,
poke_limiter,
) )
.await; .await;
} }
@@ -1168,7 +1323,9 @@ async fn fetch_client_profile(
build_command("channelgrouplist", &[], &[]), build_command("channelgrouplist", &[], &[]),
channels, channels,
pending_moves, pending_moves,
pending_downloads,
voice_activity, voice_activity,
poke_limiter,
) )
.await; .await;
} }
@@ -1182,7 +1339,9 @@ async fn fetch_client_profile(
), ),
channels, channels,
pending_moves, pending_moves,
pending_downloads,
voice_activity, voice_activity,
poke_limiter,
) )
.await .await
{ {
@@ -1200,7 +1359,9 @@ async fn fetch_client_profile(
build_command("getconnectioninfo", &[("clid", client_id.to_string())], &[]), build_command("getconnectioninfo", &[("clid", client_id.to_string())], &[]),
channels, channels,
pending_moves, pending_moves,
pending_downloads,
voice_activity, voice_activity,
poke_limiter,
) )
.await .await
{ {
@@ -1219,7 +1380,9 @@ async fn fetch_client_profile(
database_id, database_id,
channels, channels,
pending_moves, pending_moves,
pending_downloads,
voice_activity, voice_activity,
poke_limiter,
) )
.await .await
.ok() .ok()
@@ -1289,10 +1452,18 @@ async fn fetch_client_profile(
.or_else(|| db_info.as_ref().map(|info| info.created.unix_timestamp())), .or_else(|| db_info.as_ref().map(|info| info.created.unix_timestamp())),
last_connected_unix_seconds: optional last_connected_unix_seconds: optional
.map(|info| info.last_connected.unix_timestamp()) .map(|info| info.last_connected.unix_timestamp())
.or_else(|| db_info.as_ref().map(|info| info.last_connected.unix_timestamp())), .or_else(|| {
db_info
.as_ref()
.map(|info| info.last_connected.unix_timestamp())
}),
connections_total: optional connections_total: optional
.map(|info| u64::from(info.connections_total)) .map(|info| u64::from(info.connections_total))
.or_else(|| db_info.as_ref().map(|info| u64::from(info.connections_total))), .or_else(|| {
db_info
.as_ref()
.map(|info| u64::from(info.connections_total))
}),
online_seconds: connection online_seconds: connection
.and_then(|info| info.connected_time.map(|duration| duration.whole_seconds())), .and_then(|info| info.connected_time.map(|duration| duration.whole_seconds())),
idle_milliseconds: connection.map(|info| duration_millis(info.idle_time)), idle_milliseconds: connection.map(|info| duration_millis(info.idle_time)),
@@ -1325,14 +1496,10 @@ async fn fetch_client_profile(
.or_else(|| db_info.as_ref().map(|info| info.bytes_uploaded_total)), .or_else(|| db_info.as_ref().map(|info| info.bytes_uploaded_total)),
packet_loss_client_to_server_total: net_stats packet_loss_client_to_server_total: net_stats
.map(|s| s.get_packetloss()) .map(|s| s.get_packetloss())
.or_else(|| { .or_else(|| connection.map(|info| info.client_to_server_packetloss_total)),
connection.map(|info| info.client_to_server_packetloss_total)
}),
packet_loss_server_to_client_total: net_stats packet_loss_server_to_client_total: net_stats
.map(|s| s.get_packetloss_s2c_total()) .map(|s| s.get_packetloss_s2c_total())
.or_else(|| { .or_else(|| connection.and_then(|info| info.server_to_client_packetloss_total)),
connection.and_then(|info| info.server_to_client_packetloss_total)
}),
}) })
} }
@@ -1377,7 +1544,9 @@ async fn request_messages(
command: OutCommand, command: OutCommand,
channels: &EventChannels, channels: &EventChannels,
pending_moves: &mut PendingMoves, pending_moves: &mut PendingMoves,
pending_downloads: &mut PendingDownloads,
voice_activity: &mut HashMap<u64, Instant>, voice_activity: &mut HashMap<u64, Instant>,
poke_limiter: &mut PokeLimiter,
) -> Result<Vec<InMessage>, ProtocolError> { ) -> Result<Vec<InMessage>, ProtocolError> {
let handle = command let handle = command
.send_with_result(con) .send_with_result(con)
@@ -1413,6 +1582,12 @@ async fn request_messages(
StreamItem::Audio(buf) => { StreamItem::Audio(buf) => {
handle_audio_stream_item(&channels.voice_in, voice_activity, buf).await; handle_audio_stream_item(&channels.voice_in, voice_activity, buf).await;
} }
StreamItem::FileDownload(handle, result) => {
handle_download_stream_item(pending_downloads, handle, result).await;
}
StreamItem::FiletransferFailed(handle, error) => {
handle_download_failure(pending_downloads, handle, error);
}
other => handle_non_audio_stream_item( other => handle_non_audio_stream_item(
con, con,
other, other,
@@ -1420,6 +1595,7 @@ async fn request_messages(
&channels.activity, &channels.activity,
&channels.delta, &channels.delta,
pending_moves, pending_moves,
poke_limiter,
), ),
} }
} }
@@ -1430,14 +1606,18 @@ async fn request_client_db_info(
dbid: tsclientlib::ClientDbId, dbid: tsclientlib::ClientDbId,
channels: &EventChannels, channels: &EventChannels,
pending_moves: &mut PendingMoves, pending_moves: &mut PendingMoves,
pending_downloads: &mut PendingDownloads,
voice_activity: &mut HashMap<u64, Instant>, voice_activity: &mut HashMap<u64, Instant>,
poke_limiter: &mut PokeLimiter,
) -> Result<InClientDbInfoPart, ProtocolError> { ) -> Result<InClientDbInfoPart, ProtocolError> {
let messages = request_messages( let messages = request_messages(
con, con,
build_command("clientdbinfo", &[("cldbid", dbid.0.to_string())], &[]), build_command("clientdbinfo", &[("cldbid", dbid.0.to_string())], &[]),
channels, channels,
pending_moves, pending_moves,
pending_downloads,
voice_activity, voice_activity,
poke_limiter,
) )
.await?; .await?;
for message in messages { for message in messages {
@@ -1493,6 +1673,14 @@ fn uid_to_avatar_path(uid_b64: &str) -> String {
rendered rendered
} }
fn avatar_download_path(client_uid: &str) -> String {
format!("/avatar_{}", uid_to_avatar_path(client_uid))
}
fn icon_download_path(icon_id: u64) -> String {
format!("/icon_{icon_id}")
}
fn find_client_by_id<'a>( fn find_client_by_id<'a>(
clients: impl IntoIterator<Item = &'a Client>, clients: impl IntoIterator<Item = &'a Client>,
client_id: u64, client_id: u64,
@@ -1876,10 +2064,13 @@ const _: () = {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{ use super::{
client_profile_refresh_plan, is_server_query_client_type, send_with_timeout, avatar_download_path, bounded_drain_stream, client_profile_refresh_plan,
server_socket_from_config, sort_channels_tree_by, std_duration_millis, drain_voice_packets_for_tick, icon_download_path, is_server_query_client_type,
ConnectConfig, SendTimeoutError, send_with_timeout, server_socket_from_config, sort_channels_tree_by,
std_duration_millis, ConnectConfig, ProtocolClient, Request, SendTimeoutError,
DISCONNECT_REPLY_TIMEOUT,
}; };
use futures::stream;
use std::time::Duration; use std::time::Duration;
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tsproto_types::ClientType; use tsproto_types::ClientType;
@@ -1975,6 +2166,16 @@ mod tests {
assert!(plan.needs_channel_groups); assert!(plan.needs_channel_groups);
} }
#[test]
fn avatar_download_path_uses_uid_hex_encoding() {
assert_eq!(avatar_download_path("AQID"), "/avatar_abacad");
}
#[test]
fn icon_download_path_uses_unsigned_icon_id() {
assert_eq!(icon_download_path(42), "/icon_42");
}
#[test] #[test]
fn channel_sort_linked_list_under_one_parent() { fn channel_sort_linked_list_under_one_parent() {
// Server emits four root-level channels in arbitrary HashMap // Server emits four root-level channels in arbitrary HashMap
@@ -2122,6 +2323,83 @@ mod tests {
assert_eq!(result, Err(SendTimeoutError::Timeout(2))); assert_eq!(result, Err(SendTimeoutError::Timeout(2)));
} }
#[tokio::test]
async fn disconnect_request_send_is_bounded_when_request_channel_is_full() {
let (tx, _rx) = mpsc::channel(1);
let (reply_tx, _reply_rx) = tokio::sync::oneshot::channel();
tx.send(Request::Snapshot(reply_tx))
.await
.expect("seed first request");
let (disconnect_tx, _disconnect_rx) = tokio::sync::oneshot::channel();
let result = send_with_timeout(
&tx,
Request::Disconnect(disconnect_tx),
Duration::from_millis(10),
)
.await;
assert!(matches!(result, Err(SendTimeoutError::Timeout(_))));
}
#[tokio::test]
async fn protocol_client_disconnect_returns_when_request_channel_is_full() {
let (tx, _rx) = mpsc::channel(1);
let (snapshot_tx, _snapshot_rx) = tokio::sync::oneshot::channel();
tx.send(Request::Snapshot(snapshot_tx))
.await
.expect("seed first request");
let (voice_out_tx, _voice_out_rx) = mpsc::channel(1);
let (_voice_in_tx, voice_in_rx) = mpsc::channel(1);
let (_lost_tx, lost_rx) = tokio::sync::oneshot::channel();
let (_chat_tx, chat_rx) = mpsc::channel(1);
let (_activity_tx, activity_rx) = mpsc::channel(1);
let (_delta_tx, delta_rx) = mpsc::channel(1);
let client = ProtocolClient {
tx,
voice_out_tx,
voice_in_rx: std::sync::Mutex::new(Some(voice_in_rx)),
lost_rx: std::sync::Mutex::new(Some(lost_rx)),
chat_rx: std::sync::Mutex::new(Some(chat_rx)),
activity_rx: std::sync::Mutex::new(Some(activity_rx)),
delta_rx: std::sync::Mutex::new(Some(delta_rx)),
};
tokio::time::timeout(
DISCONNECT_REPLY_TIMEOUT + Duration::from_millis(100),
client.disconnect(),
)
.await
.expect("disconnect should not wait indefinitely for request channel capacity");
}
#[tokio::test]
async fn voice_drain_stops_at_per_tick_budget() {
let (tx, mut rx) = mpsc::channel(8);
for value in 0_u8..5 {
tx.send(value).await.expect("seed voice packet");
}
let mut sent = Vec::new();
let drained = drain_voice_packets_for_tick(&mut rx, 2, |value| {
sent.push(value);
Ok::<(), ()>(())
});
assert_eq!(drained, 2);
assert_eq!(sent, vec![0, 1]);
assert_eq!(rx.len(), 3);
}
#[tokio::test]
async fn disconnect_stream_drain_returns_after_timeout() {
let start = tokio::time::Instant::now();
bounded_drain_stream(stream::pending::<()>(), Duration::from_millis(10)).await;
assert!(start.elapsed() < Duration::from_millis(100));
}
} }
fn forward_delta( fn forward_delta(
@@ -2204,9 +2482,7 @@ fn forward_delta(
old: PropertyValue::Channel(channel), old: PropertyValue::Channel(channel),
.. ..
} => { } => {
let _ = delta_tx.try_send(ProtocolDelta::ChannelRemoved { let _ = delta_tx.try_send(ProtocolDelta::ChannelRemoved { id: channel.id.0 });
id: channel.id.0,
});
} }
Event::PropertyChanged { Event::PropertyChanged {
id: PropertyId::Channel(channel_id), id: PropertyId::Channel(channel_id),
+4
View File
@@ -3,6 +3,8 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
pub use crate::poke_limiter::PokeStrength;
/// Opaque server-side channel identifier. Internal representation is /// Opaque server-side channel identifier. Internal representation is
/// the upstream u64 but callers must treat it as opaque. /// the upstream u64 but callers must treat it as opaque.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -54,6 +56,8 @@ pub struct ChatMessage {
pub message: String, pub message: String,
/// Target scope of this message. /// Target scope of this message.
pub target: MessageTarget, pub target: MessageTarget,
/// Strength classification for poke notifications.
pub poke_strength: Option<PokeStrength>,
} }
/// A server-activity notification derived from TeamSpeak bookkeeping events. /// A server-activity notification derived from TeamSpeak bookkeeping events.
+7 -1
View File
@@ -35,12 +35,14 @@
mod adapter; mod adapter;
mod dto; mod dto;
pub mod poke_limiter;
pub use adapter::{ConnectConfig, DisconnectReason, InboundVoice, ProtocolClient, SnapshotProbe}; pub use adapter::{ConnectConfig, DisconnectReason, InboundVoice, ProtocolClient, SnapshotProbe};
pub use dto::{ pub use dto::{
ChannelId, ChannelInfo, ChatMessage, ClientId, ClientInfo, ClientProfile, MessageTarget, ChannelId, ChannelInfo, ChatMessage, ClientId, ClientInfo, ClientProfile, MessageTarget,
ProtocolDelta, ServerActivity, ServerSnapshot, PokeStrength, ProtocolDelta, ServerActivity, ServerSnapshot,
}; };
pub use poke_limiter::PokeLimiter;
// Re-export the upstream voice types so chanora_audio can build outbound // Re-export the upstream voice types so chanora_audio can build outbound
// voice packets without taking a direct dependency on tsclientlib / // voice packets without taking a direct dependency on tsclientlib /
@@ -113,4 +115,8 @@ pub enum ProtocolError {
/// should never see this; if they do, it is a mapping bug here. /// should never see this; if they do, it is a mapping bug here.
#[error("protocol backend: {0}")] #[error("protocol backend: {0}")]
Backend(String), Backend(String),
/// A file transfer failed while downloading protocol-owned assets.
#[error("file transfer failed: {0}")]
FileTransfer(String),
} }
+174
View File
@@ -0,0 +1,174 @@
//! Per-connection poke strength classification.
use std::collections::HashMap;
use std::time::{Duration, Instant};
/// Notification strength assigned to an inbound poke.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PokeStrength {
/// Poke should be surfaced at full strength.
Strong,
/// Poke is rate-limited but below overflow severity.
Suppressed,
/// Poke remains suppressed after repeated suppressed pokes.
SuppressedOverflow,
}
/// Per-connection poke limiter.
#[derive(Debug)]
pub struct PokeLimiter {
window: Duration,
entries: HashMap<u64, PokeEntry>,
}
#[derive(Debug)]
struct PokeEntry {
tokens: u8,
last_refill: Instant,
suppressed_in_window: u8,
}
impl PokeLimiter {
const CAPACITY: u8 = 2;
const OVERFLOW_THRESHOLD: u8 = 3;
/// Create a limiter using the default five-minute refill interval.
pub fn new() -> Self {
Self {
window: Duration::from_secs(5 * 60),
entries: HashMap::new(),
}
}
/// Record a poke at the current instant.
pub fn record(&mut self, sender_id: u64, own_client_id: Option<u64>) -> PokeStrength {
self.record_at(sender_id, own_client_id, Instant::now())
}
/// Record a poke at an injected instant.
pub fn record_at(
&mut self,
sender_id: u64,
own_client_id: Option<u64>,
now: Instant,
) -> PokeStrength {
if own_client_id == Some(sender_id) {
return PokeStrength::Suppressed;
}
let entry = self.entries.entry(sender_id).or_insert(PokeEntry {
tokens: Self::CAPACITY,
last_refill: now,
suppressed_in_window: 0,
});
if now.duration_since(entry.last_refill) >= self.window {
entry.tokens = Self::CAPACITY;
entry.last_refill = now;
entry.suppressed_in_window = 0;
}
if entry.tokens > 0 {
entry.tokens -= 1;
return PokeStrength::Strong;
}
entry.suppressed_in_window = entry.suppressed_in_window.saturating_add(1);
if entry.suppressed_in_window >= Self::OVERFLOW_THRESHOLD {
PokeStrength::SuppressedOverflow
} else {
PokeStrength::Suppressed
}
}
}
impl Default for PokeLimiter {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn first_two_pokes_are_strong_third_is_suppressed() {
let mut limiter = PokeLimiter::new();
let now = Instant::now();
assert_eq!(limiter.record_at(7, Some(1), now), PokeStrength::Strong);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(1)),
PokeStrength::Strong
);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(2)),
PokeStrength::Suppressed
);
}
#[test]
fn self_poke_is_suppressed_without_consuming_token() {
let mut limiter = PokeLimiter::new();
let now = Instant::now();
assert_eq!(limiter.record_at(7, Some(7), now), PokeStrength::Suppressed);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(1)),
PokeStrength::Strong
);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(2)),
PokeStrength::Strong
);
}
#[test]
fn overflow_after_three_suppressed_pokes_in_five_minutes() {
let mut limiter = PokeLimiter::new();
let now = Instant::now();
assert_eq!(limiter.record_at(7, Some(1), now), PokeStrength::Strong);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(1)),
PokeStrength::Strong
);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(2)),
PokeStrength::Suppressed
);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(3)),
PokeStrength::Suppressed
);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(4)),
PokeStrength::SuppressedOverflow
);
}
#[test]
fn refill_after_interval_uses_injected_time_without_sleeping() {
let mut limiter = PokeLimiter::new();
let now = Instant::now();
assert_eq!(limiter.record_at(7, Some(1), now), PokeStrength::Strong);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(1)),
PokeStrength::Strong
);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(2)),
PokeStrength::Suppressed
);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(5 * 60)),
PokeStrength::Strong
);
assert_eq!(
limiter.record_at(7, Some(1), now + Duration::from_secs(5 * 60 + 1)),
PokeStrength::Strong
);
}
}
+4 -4
View File
@@ -1,9 +1,9 @@
[package] [package]
name = "chanora_resolver" name = "chanora_resolver"
version = "0.1.0" version.workspace = true
edition = "2021" edition.workspace = true
license = "MIT OR Apache-2.0" license.workspace = true
publish = false publish.workspace = true
build = "build.rs" build = "build.rs"
[dependencies] [dependencies]
+3 -11
View File
@@ -346,9 +346,7 @@ pub fn reduce(state: &mut Option<ServerState>, event: StateEvent) -> Reduction {
if removed_channel { if removed_channel {
deltas.push(Delta::ChannelRemoved(id)); deltas.push(Delta::ChannelRemoved(id));
} }
Reduction { Reduction { deltas }
deltas,
}
} }
_ => Reduction { deltas: vec![] }, _ => Reduction { deltas: vec![] },
}, },
@@ -412,14 +410,7 @@ pub fn reduce_reconnect_snapshot(
state: &mut Option<ServerState>, state: &mut Option<ServerState>,
snap: ServerSnapshot, snap: ServerSnapshot,
) -> Reduction { ) -> Reduction {
let normalized = normalize_snapshot(snap); reduce(state, StateEvent::Snapshot(snap))
*state = Some(ServerState::from_snapshot(normalized.clone()));
Reduction {
deltas: vec![
Delta::ConnectionStateChanged(ConnectionState::Ready),
Delta::SnapshotApplied(normalized),
],
}
} }
#[cfg(test)] #[cfg(test)]
@@ -624,6 +615,7 @@ mod tests {
sender_name: "Alice".into(), sender_name: "Alice".into(),
message: "hello".into(), message: "hello".into(),
target: MessageTarget::Channel, target: MessageTarget::Channel,
poke_strength: None,
}; };
let disconnected = reduce(&mut state, StateEvent::ChatReceived(msg.clone())); let disconnected = reduce(&mut state, StateEvent::ChatReceived(msg.clone()));
assert!(disconnected.deltas.is_empty()); assert!(disconnected.deltas.is_empty());
+40
View File
@@ -0,0 +1,40 @@
# SAD Component → Source File Mapping
**Purpose:** Developer convenience mapping from ASPICE architecture components to source file locations. This is NOT an ASPICE document — it's a lookup for developers.
## Component Mapping
| SAD Component | Source Location |
|---|---|
| Flutter app shell | `apps/chanora_flutter/lib/main.dart`, services, widgets |
| Flutter service layer | `apps/chanora_flutter/lib/services/` |
| Flutter widget layer | `apps/chanora_flutter/lib/widgets/` |
| Bridge layer | `crates/chanora_bridge/src/api.rs`, `apps/chanora_flutter/lib/src/rust/` |
| Rust core | `core/chanora_core/src/lib.rs`, `events.rs`, `network_diagnostics.rs`, `ptt.rs` |
| Protocol adapter | `crates/chanora_protocol/src/` |
| State sync | `crates/chanora_state/src/lib.rs`, `channel_join.rs` |
| Audio subsystem | `crates/chanora_audio/src/` |
| Storage | `crates/chanora_storage/src/lib.rs` |
| Diagnostics | `crates/chanora_diagnostics/src/lib.rs` |
| Resolution and prefetch | `crates/chanora_resolver/src/lib.rs`, `crates/chanora_prefetch/src/lib.rs`, `prefetch_debouncer.dart` |
| Build and release hooks | `.github/workflows/`, `tools/`, platform project files |
## SDD Module Mapping
| SDD Module | Source Location |
|---|---|
| SDD-MOD-001 Flutter app bootstrap | `apps/chanora_flutter/lib/services/app_bootstrap.dart`, `main.dart` |
| SDD-MOD-002 Connect UI | `apps/chanora_flutter/lib/widgets/connect_widgets.dart` |
| SDD-MOD-003 Snapshot and channel UI | `snapshot_view.dart`, `snapshot_state_mapper.dart`, `channel_spacer.dart` |
| SDD-MOD-004 Chat UI | `chat_views.dart`, `bbcode_text.dart` |
| SDD-MOD-005 Voice UI | `voice_bar.dart`, `voice_compact.dart`, `voice_settings*.dart`, `voice_level_meter.dart`, `ptt_capability_badge.dart` |
| SDD-MOD-006 Platform services | `android_permissions_service.dart`, `ios_permissions_service.dart`, `audio_lifecycle_service.dart`, `back_intent_*`, `link_trust_service.dart` |
| SDD-MOD-007 Bridge API | `crates/chanora_bridge/src/api.rs`, generated Dart/Rust bridge files |
| SDD-MOD-008 Rust core supervisor | `core/chanora_core/src/lib.rs`, `events.rs`, `network_diagnostics.rs`, `ptt.rs` |
| SDD-MOD-009 Protocol adapter | `crates/chanora_protocol/src/` |
| SDD-MOD-010 State sync | `crates/chanora_state/src/lib.rs`, `channel_join.rs` |
| SDD-MOD-011 Audio subsystem | `crates/chanora_audio/src/` |
| SDD-MOD-012 Storage | `crates/chanora_storage/src/lib.rs` |
| SDD-MOD-013 Diagnostics | `crates/chanora_diagnostics/src/lib.rs` |
| SDD-MOD-014 Resolution and prefetch | `crates/chanora_resolver/src/lib.rs`, `crates/chanora_prefetch/src/lib.rs`, `prefetch_debouncer.dart` |
| SDD-MOD-015 Build and release hooks | `.github/workflows/`, `tools/`, platform project files |
@@ -1,8 +1,9 @@
# Chanora Implementation Status — 2026-05-28 # Chanora Implementation Status — 2026-05-28
**Workspace version:** `v0.2.0-beta.1` **Workspace version:** `v0.2.0-beta.1`
**CHANGELOG latest:** `v1.0.0-rc.1` **Flutter app version/build:** `0.3.0+100`
**Build status:** All 9 crates compile cleanly. **CHANGELOG latest:** `v0.3.0`
**Build status:** Host Rust workspace evidence shows all 9 crates compile cleanly. This does not claim Android target success; Android target compile/install/smoke evidence remains blocked locally as noted below.
--- ---
@@ -18,9 +19,9 @@
| Localization (en + zh-Hans) | `l10n/generated/app_localizations_en.dart` + `app_localizations_zh.dart`, `l10n.yaml` | | Localization (en + zh-Hans) | `l10n/generated/app_localizations_en.dart` + `app_localizations_zh.dart`, `l10n.yaml` |
| Flutter/Rust bridge | `chanora_bridge` crate (2152-line `api.rs`), generated `frb_generated.rs`, Dart side generated | | Flutter/Rust bridge | `chanora_bridge` crate (2152-line `api.rs`), generated `frb_generated.rs`, Dart side generated |
| Protocol adapter | `chanora_protocol``tsclientlib` isolated behind `ProtocolClient`, typed DTOs, `ProtocolError` catalogue | | Protocol adapter | `chanora_protocol``tsclientlib` isolated behind `ProtocolClient`, typed DTOs, `ProtocolError` catalogue |
| Connection lifecycle | `chanora_core` (2682-line `lib.rs`) — supervisor task, exponential backoff reconnect (1s→60s), user-disconnect suppresses reconnect | | Connection lifecycle | `chanora_core` — supervisor task, exponential backoff reconnect (1s→60s), user-disconnect suppresses reconnect; branch `simplify-project-review` has started splitting the previous large `lib.rs` into focused internal Modules (`events.rs`, `network_diagnostics.rs`) while preserving public re-exports |
| State sync reducer unit | `chanora_state``ConnectionState`, `channel_join`, snapshot/delta reducers, reconnect handling, deterministic ordering, malformed duplicate normalization, channel-delete/client cleanup, and reducer unit tests. Runtime core integration still uses snapshot/probe refresh paths and remains separate validation work. | | State sync reducer unit | `chanora_state``ConnectionState`, `channel_join`, snapshot/delta reducers, reconnect handling, deterministic ordering, malformed duplicate normalization, channel-delete/client cleanup, and reducer unit tests. Runtime core integration still uses snapshot/probe refresh paths and remains separate validation work. |
| Audio subsystem | `chanora_audio` — Opus encode/decode, HPF/NS/AEC3/AGC2 DSP, PTT backends (Windows/macOS/Linux/focused), iOS VoiceProcessingIO, Android Oboe, jitter buffer via `tsclientlib::audio::AudioHandler`, mixer, mute/deaf gates, release-tail timer, VAD | | Audio subsystem | `chanora_audio` — Opus encode/decode, HPF/NS/AEC3/AGC2 DSP, PTT backends (Windows/macOS/Linux/focused), iOS VoiceProcessingIO, Android Oboe, jitter buffer via `tsclientlib::audio::AudioHandler`, mixer, mute/deaf gates, release-tail timer, and Windows/Linux desktop `VoiceActivity` through the capture VAD path. Mobile, macOS, and unverified-platform `VoiceActivity` remain deferred per DEC-030. |
| Push-to-talk | Per-platform backends: Windows Raw Input + hook fallback, macOS Event Tap, Linux freedesktop portal, focused fallback; `PttCapabilityLevel` (L0L3); missed-key-up watchdog | | Push-to-talk | Per-platform backends: Windows Raw Input + hook fallback, macOS Event Tap, Linux freedesktop portal, focused fallback; `PttCapabilityLevel` (L0L3); missed-key-up watchdog |
| Voice controls UI | `voice_bar`, `voice_compact`, `voice_haptics`, `voice_level_meter`, `voice_platform`, `ptt_capability_badge`, `talk_power_warning` | | Voice controls UI | `voice_bar`, `voice_compact`, `voice_haptics`, `voice_level_meter`, `voice_platform`, `ptt_capability_badge`, `talk_power_warning` |
| Storage (non-secret) | `chanora_storage``BookmarkRepository` (SQLite/rusqlite bundled, schema v2), ChaCha20-Poly1305 encrypted passwords | | Storage (non-secret) | `chanora_storage``BookmarkRepository` (SQLite/rusqlite bundled, schema v2), ChaCha20-Poly1305 encrypted passwords |
@@ -45,7 +46,7 @@
| Link trust | `link_trust_service.dart` | | Link trust | `link_trust_service.dart` |
| About dialog | Non-affiliation statement, dual-license declaration, NOTICE pointer | | About dialog | Non-affiliation statement, dual-license declaration, NOTICE pointer |
| CI | GitHub Actions on every push | | CI | GitHub Actions on every push |
| Workspace compiles | All 9 crates build cleanly | | Workspace compiles | Host Rust workspace evidence shows all 9 crates build cleanly; Android target compilation remains blocked locally as noted below. |
### Partial / Scaffold Only ### Partial / Scaffold Only
@@ -53,18 +54,19 @@
|---|---| |---|---|
| Event replay tooling | Reducer tests cover the state-sync contract, but standalone replay-file tooling remains a P1 verification gap. | | Event replay tooling | Reducer tests cover the state-sync contract, but standalone replay-file tooling remains a P1 verification gap. |
| Reducer runtime integration evidence | The standalone reducer is unit-tested, but `chanora_core` still refreshes UI state through snapshot/probe paths rather than folding all live protocol events through `chanora_state::reduce`. | | Reducer runtime integration evidence | The standalone reducer is unit-tested, but `chanora_core` still refreshes UI state through snapshot/probe paths rather than folding all live protocol events through `chanora_state::reduce`. |
| Silero VAD | `assets/models/silero_vad.onnx` bundled but DEC-030 defers VAD to P1; `TransmitMode::VoiceActivity` is reserved and disabled in this baseline. | | Mobile/macOS VoiceActivity | `assets/models/silero_vad.onnx` is bundled and used by the desktop VAD path where runtime evidence supports it; mobile, macOS, and unverified-platform `TransmitMode::VoiceActivity` remain disabled/deferred until a later baseline supplies backend enablement and verification evidence. |
| macOS build | Not in `v1.0.0-rc.1` release artifacts (source-buildable only per `staged-release-plan.md`). | | macOS build | Source-buildable only; no public release artifact is approved. |
| Windows build | Same — source-buildable, not in rc.1 release artifacts. | | Windows build | Source-buildable only; no public release artifact is approved. |
| iOS build | Same — source-buildable, not in rc.1 release artifacts. | | iOS build | Source-buildable/unsigned validation only; no TestFlight/App Store release artifact is approved. |
### Not Done (P0 blockers remaining) ### Not Done (P0 blockers remaining)
| Item | Status | | Item | Status |
|---|---| |---|---|
| DEC-012 legal/trademark/OSS review | Explicitly open`v1.0.0-rc.1` is the candidate awaiting sign-off. Public release is blocked. | | DEC-012 legal/trademark/OSS review | Explicitly open. Public release is blocked. |
| Android Keystore-backed DEK | Deferred to v1.1. Android still uses file-fallback for the Data Encryption Key. | | Android Keystore-backed DEK | Deferred to v1.1. Android still uses file-fallback for the Data Encryption Key. |
| iOS `AVAudioSession.Mode.voiceChat` | Implemented in `apps/chanora_flutter/ios/Runner/AppDelegate.swift`; release readiness still requires device audio validation and candidate evidence attachment. | | Android target compile/install/smoke evidence | Blocked locally until the Android NDK compiler `aarch64-linux-android-clang` is available and `adb devices -l` shows an authorized device or emulator. |
| iOS `AVAudioSession.Mode.voiceChat` | Implemented in `apps/chanora_flutter/ios/Runner/AppDelegate.swift` with call-scoped activation (idle `.ambient` baseline; VoIP `.playAndRecord` + `.voiceChat` + `.mixWithOthers` engaged only on `BridgeEvent::AudioStarted` via `chanora/ios_audio_session` MethodChannel). Release readiness still requires device audio validation and candidate evidence attachment. |
| Candidate state-sync evidence attachment | Reducer tests exist and pass locally; release readiness still needs candidate CI/run IDs and runtime integration evidence attached before public release approval. | | Candidate state-sync evidence attachment | Reducer tests exist and pass locally; release readiness still needs candidate CI/run IDs and runtime integration evidence attached before public release approval. |
--- ---
@@ -92,7 +94,7 @@
| Recent servers persistence (SRS-085) | Not confirmed in storage crate | | Recent servers persistence (SRS-085) | Not confirmed in storage crate |
| UI settings persistence (SRS-087) | Implemented for current P1 scope using `shared_preferences`: host, nickname, permission explanation flag, and theme mode (`system` / `light` / `dark`). SQLite-backed UI settings remain a future hardening option if multi-profile or transactional settings are introduced. | | UI settings persistence (SRS-087) | Implemented for current P1 scope using `shared_preferences`: host, nickname, permission explanation flag, and theme mode (`system` / `light` / `dark`). SQLite-backed UI settings remain a future hardening option if multi-profile or transactional settings are introduced. |
| Event replay tool (SRS-061, SRS-098) | No replay infrastructure found | | Event replay tool (SRS-061, SRS-098) | No replay infrastructure found |
| Network diagnostics (SRS-100) | Not found in diagnostics export | | Network diagnostics (SRS-100) | Core tracks connect/disconnect counts and last-loss reasons in `network_diagnostics.rs`; export/integration evidence still needs release-candidate attachment |
| Side navigation rail for medium layout (SRS-153) | Not confirmed | | Side navigation rail for medium layout (SRS-153) | Not confirmed |
| Keyboard focus traversal (SRS-160) | Not confirmed | | Keyboard focus traversal (SRS-160) | Not confirmed |
| Android audio focus / BT route changes (SRS-112) | Partial — `MODE_IN_COMMUNICATION` done; full focus/BT handling not confirmed | | Android audio focus / BT route changes (SRS-112) | Partial — `MODE_IN_COMMUNICATION` done; full focus/BT handling not confirmed |
+75
View File
@@ -0,0 +1,75 @@
# Chanora Offline Knowledge Library
**Generated:** 2026-06-13
**Branch:** `docs/offline-knowledge-library-2026-06-13`
**Purpose:** Comprehensive offline reference for the Chanora project, its dependencies, and related ecosystem.
---
## Contents
### Project Analysis
| Document | Description | Status |
|----------|-------------|--------|
| [function-inventory.md](function-inventory.md) | Complete public API inventory for all 10 Rust crates + 56 Dart files. Includes dead code analysis. | Reviewed |
| [coverage-analysis.md](coverage-analysis.md) | Test coverage (312 Rust tests, 221 Dart tests) and documentation coverage gaps. | Reviewed, corrected |
| [doc-quality-analysis.md](doc-quality-analysis.md) | Duplicated content, useless content, and broken references in docs/. | Reviewed, corrected |
| [link-coverage-report.md](link-coverage-report.md) | All internal/external links validated. 2 broken LICENSE links, 5 broken doc-path refs. | Reviewed, corrected |
| [docs-code-mismatch.md](docs-code-mismatch.md) | 17 doc-code mismatches found (2 critical, 4 major, 11 minor). | Reviewed, corrected |
| [docs-out-of-date.md](docs-out-of-date.md) | 12 outdated docs, 8 undocumented recent changes since DV baseline. | Reviewed, corrected |
| [docs-link-not-covered.md](docs-link-not-covered.md) | 2 broken links, 9 missing targets, 18 orphaned docs. | Reviewed, corrected |
### External Projects
| Document | Description | Status |
|----------|-------------|--------|
| [external/teaspeak-overview.md](external/teaspeak-overview.md) | TeaSpeak voice server - architecture, protocol, build system. | Reviewed |
| [external/respeak-overview.md](external/respeak-overview.md) | ReSpeak org - tsclientlib, tsproto, crypto, Chanora integration. | Reviewed |
| [external/yatqa-en.md](external/yatqa-en.md) | yat.qa TeamSpeak admin tool (English). | Reviewed |
| [external/yatqa-de.md](external/yatqa-de.md) | yat.qa TeamSpeak admin tool (German/Deutsch). | Reviewed |
### Review Reports
| Document | Description |
|----------|-------------|
| [reviews/coverage-analysis-review.md](reviews/coverage-analysis-review.md) | Cross-validation of coverage analysis |
| [reviews/doc-quality-review.md](reviews/doc-quality-review.md) | Cross-validation of doc quality analysis |
| [reviews/link-coverage-review.md](reviews/link-coverage-review.md) | Cross-validation of link coverage |
| [reviews/external-docs-review.md](reviews/external-docs-review.md) | Cross-validation of external project docs |
| [reviews/docs-code-mismatch-review.md](reviews/docs-code-mismatch-review.md) | Cross-validation of mismatch analysis |
| [reviews/docs-out-of-date-review.md](reviews/docs-out-of-date-review.md) | Cross-validation of out-of-date analysis |
| [reviews/docs-link-not-covered-review.md](reviews/docs-link-not-covered-review.md) | Cross-validation of link-not-covered analysis |
| [reviews/function-inventory-review.md](reviews/function-inventory-review.md) | Cross-validation of function inventory |
| [reviews/coverage-docquality-review.md](reviews/coverage-docquality-review.md) | Second-pass review of coverage + doc quality |
| [reviews/mismatch-outofdate-review.md](reviews/mismatch-outofdate-review.md) | Second-pass review of mismatch + out-of-date |
| [reviews/link-reports-review.md](reviews/link-reports-review.md) | Second-pass review of link reports |
| [reviews/external-index-review.md](reviews/external-index-review.md) | Second-pass review of external docs + index |
---
## Key Findings Summary
### Test Coverage
- **Rust**: 312 inline tests + 5 integration tests across 8/10 crates
- **Dart**: 221 tests (widgets: 58%, services: 90%)
- **Untested crates**: chanora_bridge, chanora_cache, chanora_prefetch
### Documentation Gaps
- No architecture docs for: audio engine, FFI bridge, protocol layer, state machine, cache, prefetch, diagnostics
- 15 TODO/FIXME items catalogued across codebase
### Dead/Useless Code
- No true dead code found (platform-gated items are intentional)
- 1 malformed markdown in docs/sysdes.md
- 2 missing LICENSE files (LICENSE-APACHE, LICENSE-MIT)
### Duplicated Content
- Lifecycle chain repeated in 6+ files
- Git commit examples in 3 files
- Security doc list in 2 files
### External Dependencies
- **ReSpeak/tsclientlib**: Chanora patches tsproto-types for P-256 coordinate padding
- **TeaSpeak**: Compatible voice server, C++20 + Electron architecture
- **yat.qa**: TeamSpeak admin tool, v3.9.9b, English + German docs
@@ -0,0 +1,375 @@
# Test & Document Coverage Analysis
**Generated:** 2026-06-13
**Scope:** All crates, Flutter app, and docs/ directory
---
## Test Coverage Summary
| Metric | Count |
|--------|-------|
| Total Rust tests (inline `#[test]`) | 312 |
| Total Rust integration tests | 5 |
| Total Dart tests (`test()` + `testWidgets()`) | 221 |
| Crates with tests | 7/9 |
| Dart services with tests | 19/21 (90%) |
| Dart widgets with tests | 14/24 (58%) |
| Overall estimated coverage | ~65% |
---
## Per-Crate Test Coverage (Rust)
### chanora_audio — 333 tests, ~48% function coverage
| Source File | Functions | Tests | Coverage |
|-------------|-----------|-------|----------|
| engine.rs | ~45 | 7 | ~16% |
| ptt_backends/windows.rs | ~80 | 44 | ~55% |
| ptt_backends/windows_keymap.rs | ~30 | 12 | ~40% |
| ptt_backends/macos.rs | ~35 | 12 | ~34% |
| ptt_backends/linux.rs | ~25 | 10 | ~40% |
| ptt_backends/mod.rs | ~15 | 1 | ~7% |
| transmit_selector.rs | ~20 | 10 | ~50% |
| voice_activity.rs | ~15 | 9 | ~60% |
| voice_render.rs | ~15 | 9 | ~60% |
| mobile_voice_backend.rs | ~20 | 9 | ~45% |
| processor/sonora.rs | ~15 | 8 | ~53% |
| processor/dsp/agc2.rs | ~10 | 6 | ~60% |
| mode_stack.rs | ~10 | 6 | ~60% |
| opus_voice.rs | ~10 | 5 | ~50% |
| capture_accumulator.rs | ~8 | 5 | ~63% |
| processor/dsp/ns.rs | ~8 | 4 | ~50% |
| ptt.rs | ~8 | 4 | ~50% |
| vad/mod.rs | ~6 | 4 | ~67% |
| audio_processing.rs | ~8 | 3 | ~38% |
| debug_wav.rs | ~6 | 3 | ~50% |
| processor/dsp/hpf.rs | ~5 | 3 | ~60% |
| processor/dsp/aec3.rs | ~5 | 3 | ~60% |
| transmit_mode.rs | ~4 | 3 | ~75% |
| android_render_ring.rs | ~5 | 3 | ~60% |
| vad/resampler.rs | ~4 | 3 | ~75% |
| vad/apple_coreml.rs | ~5 | 3 | ~60% |
| vad/silero_onnx.rs | ~10 | 6 | ~60% |
| render_reference.rs | ~8 | 7 | ~88% |
| capture_resampler.rs | ~3 | 2 | ~67% |
| audio_event_queue.rs | ~4 | 2 | ~50% |
| processor/webrtc_apm.rs | ~5 | 2 | ~40% |
| frame.rs | ~3 | 1 | ~33% |
| lib.rs (defaults) | ~5 | 1 | ~20% |
| release_tail.rs | ~4 | 1 | ~25% |
| route_policy.rs | ~8 | 8 | ~100% |
| **Integration: tests/ptt_privacy.rs** | — | 1 | — |
| **Integration: tests/linux_portal_smoke.rs** | — | 1 | — |
### chanora_protocol — 17 tests, ~18% function coverage
| Source File | Functions | Tests | Coverage |
|-------------|-----------|-------|----------|
| adapter.rs | ~80 | 13 | ~16% |
| poke_limiter.rs | ~17 | 4 | ~24% |
| dto.rs | ~0 | 0 | — |
| lib.rs | ~0 | 0 | — |
**Untested areas:** Message parsing, serialization, most adapter methods
### chanora_state — 27 tests, ~46% function coverage
| Source File | Functions | Tests | Coverage |
|-------------|-----------|-------|----------|
| lib.rs | ~35 | 18 | ~51% |
| channel_join.rs | ~24 | 9 | ~38% |
### chanora_storage — 15 tests, ~24% function coverage
| Source File | Functions | Tests | Coverage |
|-------------|-----------|-------|----------|
| lib.rs | ~62 | 15 | ~24% |
**Untested areas:** Migration logic, concurrent access patterns, error recovery
### chanora_resolver — 12 tests, ~17% function coverage
| Source File | Functions | Tests | Coverage |
|-------------|-----------|-------|----------|
| lib.rs | ~70 | 12 | ~17% |
| examples/cli.rs | — | 1 | — |
**Untested areas:** DNS failure modes, timeout handling, cache behavior
### chanora_diagnostics — 19 tests, ~26% function coverage
| Source File | Functions | Tests | Coverage |
|-------------|-----------|-------|----------|
| lib.rs | ~74 | 19 | ~26% |
### chanora_core — 38 tests, ~7% function coverage
| Source File | Functions | Tests | Coverage |
|-------------|-----------|-------|----------|
| lib.rs | ~140 | 10 | ~7% |
| network_diagnostics.rs | ~7 | 1 | ~14% |
**Untested areas:** Connection lifecycle, server event handling, most state transitions
### chanora_bridge — 0 tests, 0% function coverage
| Source File | Functions | Tests | Coverage |
|-------------|-----------|-------|----------|
| api.rs | ~200+ | 0 | 0% |
| frb_generated.rs | ~100+ | 0 | 0% |
| permission_jni.rs | ~10 | 0 | 0% |
| android_init.rs | ~5 | 0 | 0% |
| lib.rs | ~4 | 0 | 0% |
**Note:** chanora_bridge is an FFI/bridge layer; testing requires integration with Flutter.
### chanora_cache — 0 tests
| Source File | Functions | Tests | Coverage |
|-------------|-----------|-------|----------|
| lib.rs | ~16 | 0 | 0% |
### chanora_prefetch — 0 tests
| Source File | Functions | Tests | Coverage |
|-------------|-----------|-------|----------|
| lib.rs | ~18 | 0 | 0% |
---
## Per-Module Test Coverage (Dart/Flutter)
### Services — 155 tests across 19 test files
| Source File | Test File | Tests | Coverage |
|-------------|-----------|-------|----------|
| android_audio_output_devices.dart | ✅ android_audio_output_devices_test.dart | 2 | Tested |
| android_permissions_service.dart | ✅ android_permissions_service_test.dart | 14 | Tested |
| app_bootstrap.dart | ✅ app_bootstrap_test.dart | 4 | Tested |
| audio_lifecycle_service.dart | ✅ audio_lifecycle_service_test.dart | 4 | Tested |
| back_intent_policy.dart | ✅ back_intent_policy_test.dart | 9 | Tested |
| back_intent_service.dart | ✅ back_intent_service_test.dart | 5 | Tested |
| channel_join_error_mapper.dart | ✅ channel_join_error_mapper_test.dart | Tested |
| channel_spacer.dart | ✅ channel_spacer_test.dart | 9 | Tested |
| connection_phase_state.dart | ✅ connection_phase_state_test.dart | 8 | Tested |
| hard_mute_owners.dart | ✅ hard_mute_owners_test.dart | 3 | Tested |
| ios_audio_session_controller.dart | ✅ ios_audio_session_controller_test.dart | 6 | Tested |
| macos_permissions_service.dart | ✅ macos_permissions_service_test.dart | 20 | Tested |
| poke_active_chat.dart | ✅ poke_active_chat_test.dart | 2 | Tested |
| poke_notification_service.dart | ✅ poke_notification_service_test.dart | 2 | Tested |
| poke_preferences_service.dart | ✅ poke_preferences_service_test.dart | 4 | Tested |
| prefetch_debouncer.dart | ✅ prefetch_debouncer_test.dart | 3 | Tested |
| snapshot_state_mapper.dart | ✅ snapshot_state_mapper_test.dart | 7 | Tested |
| ts3_server_link.dart | ✅ ts3_server_link_test.dart | 3 | Tested |
| ui_preferences_service.dart | ✅ ui_preferences_service_test.dart | 5 | Tested |
| voice_join_ordering.dart | ✅ voice_join_ordering_test.dart | 4 | Tested |
| **ios_permissions_service.dart** | ❌ No test file | 0 | **UNTESTED** |
| **link_trust_service.dart** | ❌ No test file | 0 | **UNTESTED** |
### Widgets — 66 tests across 13 test files
| Source File | Test File | Tests | Coverage |
|-------------|-----------|-------|----------|
| app_snack_bar.dart | ✅ app_snack_bar_test.dart | 1 | Tested |
| audio_processing_config_state.dart | ✅ audio_processing_config_state_test.dart | 8 | Tested |
| bbcode_text.dart | ✅ bbcode_text_test.dart | Tested |
| chat_panel.dart | ✅ chat_panel_test.dart | Tested |
| chat_views.dart | ✅ chat_views_test.dart | 29 | Tested |
| client_info_sheet.dart | ✅ client_info_sheet_test.dart | Tested |
| poke_notification_settings.dart | ✅ poke_notification_settings_test.dart | Tested |
| snapshot_view.dart | ✅ snapshot_view_test.dart | Tested |
| talk_power_warning.dart | ✅ talk_power_warning_test.dart | 1 | Tested |
| voice_compact.dart | ✅ voice_compact_test.dart | Tested |
| voice_settings_controls.dart | ✅ voice_settings_controls_test.dart | 6 | Tested |
| voice_status_summary.dart | ✅ voice_status_summary_test.dart | 5 | Tested |
| mobile_ui_resilience.dart | ✅ mobile_ui_resilience_test.dart | Tested |
| **audio_debug_stats_panel.dart** | ❌ No test file | 0 | **UNTESTED** |
| **audio_device_list_tile.dart** | ✅ audio_device_list_tile_test.dart | 3 | Tested |
| **audio_output_tile.dart** | ❌ No test file | 0 | **UNTESTED** |
| **connect_widgets.dart** | ❌ No test file | 0 | **UNTESTED** |
| **input_dialogs.dart** | ❌ No test file | 0 | **UNTESTED** |
| **permission_state_banner.dart** | ❌ No test file | 0 | **UNTESTED** |
| **ptt_capability_badge.dart** | ❌ No test file | 0 | **UNTESTED** |
| **voice_bar.dart** | ❌ No test file | 0 | **UNTESTED** |
| **voice_haptics.dart** | ❌ No test file | 0 | **UNTESTED** |
| **voice_level_meter.dart** | ❌ No test file | 0 | **UNTESTED** |
| **voice_platform.dart** | ❌ No test file | 0 | **UNTESTED** |
| **voice_settings.dart** | ❌ No test file | 0 | **UNTESTED** |
### E2E Tests
| File | Tests | Notes |
|------|-------|-------|
| alpha_e2e_test.dart | 1 | End-to-end integration |
| beta_e2e_test.dart | 1 | End-to-end integration |
| widget_test.dart | — | Default Flutter template |
---
## Document Coverage Summary
| Metric | Count |
|--------|-------|
| Total doc files (under docs/) | 66 |
| Modules documented | ~15 areas |
| Estimated outdated docs | 3-5 |
## Document Inventory
### Architecture (4 files)
| File | Topic | Status | Notes |
|------|-------|--------|-------|
| architecture/sad.md | Software Architecture Document | Current | 190 lines, references SDD |
| architecture/sdd.md | Software Design Document | Current | 161 lines |
| architecture/sysdes.md | System Design overview | Current | 21 lines, brief |
| architecture/desktop-ptt-architecture.md | Desktop PTT subsystem design | Current | 43 lines |
| architecture/file-transfer-design.md | File transfer feature design | Current | 737 lines |
| architecture/file-transfer-research.md | File transfer research | Current | 770 lines |
| architecture/file-transfer-implementation-plan.md | File transfer implementation plan | Current | 1315 lines |
### Requirements (2 files + 2 symlinks)
| File | Topic | Status | Notes |
|------|-------|--------|-------|
| requirements/srs.md | Software Requirements Spec | Current | 22 lines (pointer) |
| requirements/sysrs.md | System Requirements Spec | Current | 22 lines (pointer) |
| srs.md | SRS (full) | Current | 2850 lines |
| sysrs.md | SysRS (full) | Current | 2014 lines |
### Verification (5 files)
| File | Topic | Status | Notes |
|------|-------|--------|-------|
| verification/verification-master-plan.md | Overall V&V plan | Current | 91 lines |
| verification/swe4-unit-verification-plan.md | Unit test plan | Current | 60 lines |
| verification/swe5-software-integration-verification-plan.md | Integration test plan | Current | 71 lines |
| verification/swe6-software-verification-plan.md | System verification plan | Current | 62 lines |
| verification/sys4-system-integration-verification-plan.md | System integration plan | Current | 58 lines |
### Security (7 files)
| File | Topic | Status | Notes |
|------|-------|--------|-------|
| security/threat-model.md | Threat model | Current | 33 lines |
| security/license-inventory.md | Rust license inventory | Current | 10970 lines |
| security/flutter-license-inventory.md | Flutter license inventory | Current | 5477 lines |
| security/diagnostic-redaction-audit-report.md | Diagnostic redaction audit | Current | 31 lines |
| security/secure-storage-audit-report.md | Secure storage audit | Current | 31 lines |
| security/dependency-and-supply-chain-report.md | Dependency audit | Current | 43 lines |
| security/security-privacy-legal-guideline.md | Security/privacy guidelines | Current | 63 lines |
### Governance (11 files)
| File | Topic | Status | Notes |
|------|-------|--------|-------|
| governance/document-index.md | Document catalog | Current | 36 lines |
| governance/document-naming-convention.md | Naming conventions | Current | 33 lines |
| governance/document-review-report.md | Review report | Current | 37 lines |
| governance/traceability-matrix.md | Requirements traceability | Current | 73 lines |
| governance/product-decision-register.md | Decision log | Current | 25 lines |
| governance/decision-impact-assessment.md | Impact assessment | Current | 18 lines |
| governance/git-commit-message-convention.md | Commit conventions | Current | 21 lines |
| governance/path-migration-map.md | Path migration plan | Current | 18 lines |
| governance/repo-format-validation-report.md | Format validation | Current | 22 lines |
| governance/baseline-candidate-validation-report.md | Baseline validation | Current | 38 lines |
| governance/baseline-approval-record.md | Baseline approval | Current | 32 lines |
| governance/maintainability-review-2026-06-08.md | Maintainability review | Current | 99 lines |
### Release (4 files)
| File | Topic | Status | Notes |
|------|-------|--------|-------|
| release/ios-build.md | iOS build instructions | Current | 47 lines |
| release/platform-release-policy.md | Release policy | Current | 26 lines |
| release/release-readiness-go-nogo-record.md | Go/no-go record | Current | 105 lines |
| release/dv-waiver-register.md | DV waiver register | Current | 36 lines |
### UI/UX (4 files)
| File | Topic | Status | Notes |
|------|-------|--------|-------|
| ui-ux/material3-guideline.md | Material 3 guidelines | Current | 8 lines (brief) |
| ui-ux/material3-design-tokens.md | Design tokens | Current | 21 lines |
| ui-ux/material3-component-catalog.md | Component catalog | Current | 38 lines |
| ui-ux/adaptive-layout-platform-guide.md | Adaptive layout guide | Current | 27 lines |
### Other
| File | Topic | Status | Notes |
|------|-------|--------|-------|
| privacy/privacy-policy.md | Privacy policy | Current | 51 lines |
| references/external-references.md | External references | Current | 21 lines |
| references/aspice-swe2-swe3-integration-note.md | ASPICE integration note | Current | 28 lines |
| legal/trademark-and-attribution-review.md | Trademark review | Current | 47 lines |
| i18n/localization-architecture.md | Localization architecture | Current | 44 lines |
| implementation-status-2026-05-28.md | Implementation status | **Possibly outdated** | Date is 2026-05-28 |
| material3-guideline.md | Material 3 guideline (duplicate) | Current | 93 lines |
### Superpowers Plans & Specs (13 files)
| File | Topic | Status |
|------|-------|--------|
| superpowers/plans/2026-05-28-server-resolution-prefetch.md | Server resolution prefetch plan | Current |
| superpowers/plans/2026-05-28-chanora-server-prefetch-crate.md | Prefetch crate plan | Current |
| superpowers/plans/2026-05-29-dv-evidence-pack.md | DV evidence pack plan | Current |
| superpowers/plans/2026-05-29-state-sync-ui-settings-validation.md | State sync validation plan | Current |
| superpowers/plans/2026-05-29-swe2-swe3-baselines.md | SWE2/SWE3 baselines plan | Current |
| superpowers/plans/2026-05-29-finish-dv-document-tree.md | DV document tree plan | Current |
| superpowers/plans/2026-06-06-chat-panel-switching.md | Chat panel switching plan | Current |
| superpowers/plans/2026-06-08-maintainability-continuation.md | Maintainability continuation | Current |
| superpowers/plans/2026-06-08-core-internal-split.md | Core internal split plan | Current |
| superpowers/specs/2026-05-28-server-resolution-prefetch-design.md | Prefetch design spec | Current |
| superpowers/specs/2026-05-28-chanora-server-prefetch-crate-design.md | Prefetch crate design | Current |
| superpowers/specs/2026-05-29-state-sync-ui-settings-validation-design.md | State sync design | Current |
| superpowers/specs/2026-06-05-adaptive-3-panel-layout-design.md | Adaptive layout design | Current |
| superpowers/specs/2026-06-08-maintainability-continuation-design.md | Maintainability design | Current |
| superpowers/specs/2026-06-09-poke-without-message-design.md | Poke without message design | Current |
---
## Documentation Gaps
The following code modules have **no dedicated documentation**:
| Module | Functions | Gap Description |
|--------|-----------|-----------------|
| `chanora_audio` (engine) | ~45 | No architecture doc for audio engine internals |
| `chanora_audio` (VAD subsystem) | ~25 | VAD pipeline, model loading, fallback strategy undocumented |
| `chanora_audio` (DSP processors) | ~30 | AEC3, AGC2, NS, HPF configuration undocumented |
| `chanora_audio` (PTT backends) | ~155 | Platform-specific PTT behavior undocumented |
| `chanora_bridge` (FFI layer) | ~300 | Flutter-Rust bridge API contract undocumented |
| `chanora_cache` | ~16 | Cache strategy, eviction policy undocumented |
| `chanora_prefetch` | ~18 | Prefetch timing, debouncing strategy undocumented |
| `chanora_core` | ~147 | Core connection lifecycle, event handling undocumented |
| `chanora_state` | ~59 | State machine transitions, delta emission undocumented |
| `chanora_storage` | ~62 | Storage format, migration strategy undocumented |
| `chanora_protocol` | ~97 | Protocol message format, adapter logic undocumented |
| `chanora_resolver` | ~70 | DNS resolution, TSDNS discovery undocumented |
| `chanora_diagnostics` | ~74 | Diagnostic collection, redaction rules undocumented |
| Flutter services layer | ~21 files | No service-layer architecture doc |
| Flutter widgets layer | ~24 files | No widget catalog or component doc |
| Localization (l10n) | — | Translation workflow undocumented (only architecture doc exists) |
## Potentially Outdated Documents
| File | Reason |
|------|--------|
| `implementation-status-2026-05-28.md` | Dated 2026-05-28; code has changed significantly since |
| `docs/material3-guideline.md` | Duplicate of `docs/ui-ux/material3-guideline.md` |
| `docs/sysdes.md` | Top-level duplicate of `docs/architecture/sysdes.md` |
| `docs/srs.md` / `docs/sysrs.md` | Top-level duplicates of `docs/requirements/` versions |
---
## Key Findings
1. **chanora_audio** is the best-tested crate (204 tests), but still only ~48% function coverage due to the large codebase (~428 functions)
2. **chanora_bridge**, **chanora_cache**, and **chanora_prefetch** have zero tests
3. **chanora_core** has very low coverage (~7%) despite being the main connection orchestrator
4. **Dart widget tests** cover only 54% of widget files; 11 widget files have no tests
5. **Dart service tests** are strong at 90% coverage (only 2 files untested)
6. **Documentation** is extensive (55 files) but focuses on process/governance; code-level architecture docs are sparse
7. No dedicated docs exist for the audio engine, FFI bridge, protocol layer, or state machine internals
@@ -0,0 +1,123 @@
# Documentation Quality Analysis
## Summary
- Total docs analyzed: 64
- Duplicated content instances: 8
- Path record files (DV navigation aids): 4
- Genuine issues (malformed markdown): 1
- Broken references: 1 (suggested file names only; SDD-109/SAD-043 are valid historical refs)
## Duplicated Content
### Instance 1: Lifecycle Documentation Chain
- **Files**: `README.md:280`, `CONTRIBUTING.md:10`, `docs/sysdes.md:90`, `docs/sysrs.md:108`, `docs/governance/traceability-matrix.md:16`, `docs/references/aspice-swe2-swe3-integration-note.md:12`
- **Content**: `SysRS -> SysDes -> SRS -> SAD -> SDD` lifecycle chain repeated across 6+ files
- **Recommendation**: Define once in `README.md` and reference from other docs
### Instance 2: Git Commit Convention Examples
- **Files**: `README.md:380`, `CONTRIBUTING.md:38`, `docs/governance/git-commit-message-convention.md:15`
- **Content**: Same commit examples (`feat(voice): add push-to-talk state handling`, `fix(protocol): recover channel tree after reconnect snapshot`, etc.) duplicated across 3 files
- **Recommendation**: Keep examples only in `docs/governance/git-commit-message-convention.md` and reference from README/CONTRIBUTING
### Instance 3: Security/Privacy/Legal Document List
- **Files**: `README.md:349-355`, `SECURITY.md:33-38`
- **Content**: Same list of 6 security documents (threat-model, secure-storage, diagnostic-redaction, dependency, privacy-policy, trademark) repeated verbatim
- **Recommendation**: Keep list in `SECURITY.md` and reference from README
### Instance 4: Architecture Component Table
- **Files**: `README.md:73-92`, `docs/architecture/sad.md:56-67`
- **Content**: Similar architecture overview showing Flutter UI, Rust Core, Protocol Layer structure
- **Recommendation**: Keep detailed version in SAD; use abbreviated version in README
### Instance 5: Platform Policy Table
- **Files**: `README.md:47-54`, `docs/release/platform-release-policy.md:12-19`
- **Content**: Platform requirements table with overlapping information
- **Recommendation**: Consolidate in `platform-release-policy.md` and reference from README
### Instance 6: Security Gate Requirements
- **Files**: `docs/security/security-privacy-legal-guideline.md:13-21`, `docs/security/threat-model.md:22-30`
- **Content**: Similar threat/mitigation tables with overlapping secure-storage and diagnostics concerns
- **Recommendation**: Threat model should reference the guideline for gate requirements
### Instance 7: DV Conclusion Pattern
- **Files**: Nearly every `docs/` file ends with a "## DV Conclusion" section
- **Content**: Repetitive pattern: "[Area] is documented for DV. [Limitation] remains."
- **Recommendation**: This is intentional for ASPICE compliance. No change needed, but consider a template.
### Instance 8: Android Runtime Gate Documentation
- **Files**: `docs/verification/swe5-software-integration-verification-plan.md:57-68`, `docs/governance/maintainability-review-2026-06-08.md:61-88`
- **Content**: Same Android ADB/emulator verification steps and `adb devices -l` requirements
- **Recommendation**: Define once in a shared reference and import
## Path Record Files (DV Navigation Aids)
These files are intentional ASPICE DV entry-point records with reviewer navigation tables. They are NOT useless — they serve a specific compliance purpose. Listed here for awareness only.
### DV Navigation Aids
| File | Line | Header | Issue |
|------|------|--------|-------|
| `docs/architecture/sysdes.md` | 1-21 | Entire file | Path record — points to `docs/sysdes.md` for DV reviewer navigation |
| `docs/requirements/sysrs.md` | 1-22 | Entire file | Path record — points to `docs/sysrs.md` for DV reviewer navigation |
| `docs/requirements/srs.md` | 1-22 | Entire file | Path record — points to `docs/srs.md` for DV reviewer navigation |
| `docs/ui-ux/material3-guideline.md` | 1-8 | Entire file | Path record — points to `docs/material3-guideline.md` for DV reviewer navigation |
### Genuine Issues
| File | Line | Header | Issue |
|------|------|--------|-------|
| `docs/sysdes.md` | 13 | `**Repo path:** ... ---` | Malformed markdown (missing blank line before `---`) |
### TODO/Placeholder Markers
No actual TODO/TBD/placeholder markers found in the documentation files. The codebase is clean of such markers.
### Broken References
| File | Line | Reference | Issue |
|------|------|-----------|-------|
| `docs/sysrs.md` | 126-130 | `docs/chanora_SysDes.md`, `docs/chanora_SRS.md`, etc. | These suggested file names do not exist. Actual files use different names (`docs/sysdes.md`, `docs/srs.md`, etc.) |
| `docs/implementation-status-2026-05-28.md` | 103 | `SDD-109` | References a specific SDD item ID that is not itemized in the current SDD baseline |
| `docs/implementation-status-2026-05-28.md` | 105 | `SAD-043` | References a specific SAD item ID that is not itemized in the current SAD baseline |
### Outdated Content
| File | Line | Content | Issue |
|------|------|---------|-------|
| `docs/sysdes.md` | 6 | Version `0.9.8` | Superseded by later governance docs dated 2026-05-29 |
| `docs/sysrs.md` | 5 | Version `0.9.11` | May need alignment with SysDes version |
| `docs/material3-guideline.md` | 4-5 | Version `0.9.2` | Change history stops at 2026-05-14; no updates for 2026-05-29 baseline |
| `tools/windows-smoke.md` | 6 | `product/scaffold-v0` branch | Default base branch changed to `main` per CHANGELOG |
| `docs/implementation-status-2026-05-28.md` | 140 | Agent spec docs reference | States docs are "deleted from the working tree but still in git HEAD" — stale cleanup note |
### Stale Content
| File | Line | Content | Issue |
|------|------|---------|-------|
| `docs/implementation-status-2026-05-28.md` | 1 | Date: 2026-05-28 | Pre-dates DV baseline (2026-05-29); may not reflect final baseline state |
| `docs/governance/git-commit-message-convention.md` | 18 | `release(android): prepare internal alpha build metadata` | Example uses `release` type which is not in the Conventional Commits standard types |
## Duplicated Code Blocks
| Code Hash | Files | Description |
|-----------|-------|-------------|
| Lifecycle chain | `README.md:280`, `CONTRIBUTING.md:10`, `docs/sysdes.md:90`, `docs/sysrs.md:108`, `docs/governance/traceability-matrix.md:16`, `docs/references/aspice-swe2-swe3-integration-note.md:12` | `SysRS -> SysDes -> SRS -> SAD -> SDD -> Verification` |
| Commit examples | `README.md:379-386`, `CONTRIBUTING.md:37-42`, `docs/governance/git-commit-message-convention.md:14-19` | Overlapping commit message examples (different subsets in each file) |
| Security doc list | `README.md:349-355`, `SECURITY.md:33-38` | 6 identical file paths |
| Architecture ASCII art | `README.md:73-92`, `docs/architecture/sad.md:56-67` | Similar but not identical architecture diagrams |
| Platform table | `README.md:47-54`, `docs/release/platform-release-policy.md:12-19` | Overlapping platform requirement tables |
## Recommendations
### High Priority
1. **Consolidate lifecycle chain**: Define once in README, reference elsewhere
2. **Fix suggested file names**: `docs/sysrs.md` lines 126-130 reference non-existent file names
### Medium Priority
4. **Consolidate commit examples**: Keep in `git-commit-message-convention.md` only
5. **Consolidate security doc list**: Keep in `SECURITY.md` only
6. **Update outdated branch reference**: `tools/windows-smoke.md` references `product/scaffold-v0` but default is now `main`
### Low Priority
7. **Align document versions**: SysDes (0.9.8), SysRS (0.9.11), Material3 (0.9.2) have different versions
8. **Clean up implementation status**: Remove stale agent-spec references and update date
@@ -0,0 +1,458 @@
# Documentation-Code Mismatch Analysis
**Generated:** 2026-06-13
## Summary
- Total claims verified: ~150
- Mismatches found: 17
- Critical: 2 | Major: 4 | Minor: 11
## Critical Mismatches (wrong API / broken reference)
### 1. [README.md:428-431] - LICENSE files referenced but do not exist
- **Doc claims:** Links to `LICENSE-APACHE` and `LICENSE-MIT` at repository root
- **Code shows:** Neither `LICENSE-APACHE` nor `LICENSE-MIT` exists at `/Users/edison/dev/chanora/`
- **Impact:** Users clicking license links in README get 404 on GitHub. Dual-license model (DEC-020) requires these files for proper attribution. Also affects `docs/security/license-inventory.md:9-10` and `docs/security/flutter-license-inventory.md:11-12`.
### 2. [README.md:236-249] - Repository layout missing 3 crates
- **Doc claims:** Lists 7 crates: `chanora_protocol`, `chanora_audio`, `chanora_state`, `chanora_storage`, `chanora_diagnostics`, `chanora_bridge` plus `core/chanora_core`
- **Code shows:** Actual workspace has 10 crates: adds `chanora_resolver`, `chanora_prefetch`, `chanora_cache` (all present in `Cargo.toml` workspace members and `crates/` directory)
- **Impact:** Developers reading README cannot discover 3 existing crates. Resolver, prefetch, and cache functionality is undocumented in the primary entry point.
## Major Mismatches (wrong behavior / wrong structure)
### 3. [docs/architecture/sad.md:39-52] - SAD component table missing chanora_cache
- **Doc claims:** Component table lists 12 components (Flutter app shell through Server prefetch)
- **Code shows:** `chanora_cache` crate exists in workspace (`Cargo.toml:34`) and `crates/chanora_cache/` but is not listed in SAD component architecture
- **Impact:** Architecture description incomplete; cache layer is invisible to DV reviewers
### 4. [docs/architecture/sdd.md:19] - snapshot_state_mapper.dart listed under wrong component
- **Doc claims:** `SDD-MOD-003 Snapshot and channel UI` lists `snapshot_state_mapper.dart` as a widget-layer file
- **Code shows:** `snapshot_state_mapper.dart` is in `apps/chanora_flutter/lib/services/`, not `apps/chanora_flutter/lib/widgets/`
- **Impact:** Minor categorization issue — SDD header says "widget/service layer" but the module table groups it under widgets. Also affects `channel_spacer.dart` (same row).
### 5. [tools/windows-smoke.md:6] - Branch reference outdated
- **Doc claims:** Script designed for `product/scaffold-v0` branch
- **Code shows:** Default base branch is `main` per CHANGELOG v0.3.0 line 99
- **Impact:** Windows smoke procedure references obsolete branch name
### 6. [docs/sysrs.md:126-130] - Suggested downstream file names do not exist
- **Doc claims:** Lists potential downstream file names: `docs/chanora_SysDes.md`, `docs/chanora_SRS.md`, `docs/chanora_SAD.md`, `docs/chanora_SDD.md`, `docs/chanora_Verification.md`
- **Code shows:** Actual files use different names: `docs/sysdes.md`, `docs/srs.md`, `docs/architecture/sad.md`, `docs/architecture/sdd.md`, `docs/verification/verification-master-plan.md`
- **Impact:** Aspirational/historical names mislead readers about actual file locations
### 7. [docs/governance/product-decision-register.md:18] - DEC-030 VoiceActivity scope partially superseded
- **Doc claims:** DEC-030 is "Partially superseded by desktop enablement"
- **Code shows:** `voice_activity.rs` exists with `VoiceActivityStateMachine`; `transmit_mode.rs` has `TransmitMode::VoiceActivity`; VAD backends exist in `vad/` directory. Windows/Linux desktop VAD is implemented via capture path.
- **Impact:** Decision register does not fully reflect current implementation state; desktop VAD is more complete than "partially superseded" suggests
## Minor Mismatches (cosmetic / slight drift)
### 8. [README.md:17] - Status description slightly outdated
- **Doc claims:** "Chanora is currently a baseline-candidate Flutter + Rust workspace"
- **Code shows:** Workspace version is `0.2.0-beta.1`, Flutter app is `0.3.0+100`; project has working voice, chat, bookmarks, diagnostics
- **Impact:** "baseline-candidate" undersells current implementation maturity
### 9. [docs/material3-guideline.md:10] - Self-referencing path record
- **Doc claims:** `**Repo path:** docs/ui-ux/material3-guideline.md`
- **Code shows:** This file IS at `docs/material3-guideline.md`, not `docs/ui-ux/material3-guideline.md`
- **Impact:** Path record creates circular reference confusion
### 10. [docs/implementation-status-2026-05-28.md:1] - Status date pre-dates DV baseline
- **Doc claims:** Date 2026-05-28
- **Code shows:** DV baseline documents are dated 2026-05-29; code has changed significantly since
- **Impact:** Implementation status may not reflect final baseline state
### 11. [docs/implementation-status-2026-05-28.md:103,105] - References to non-itemized SDD/SAD IDs
- **Doc claims:** References `SDD-109` and `SAD-043`
- **Code shows:** Current SAD/SDD baselines do not use itemized ID numbering
- **Impact:** Historical references cannot be traced in current baseline
### 12. [docs/governance/git-commit-message-convention.md:18] - Non-standard commit type
- **Doc claims:** Example uses `release(android): prepare internal alpha build metadata`
- **Code shows:** `release` is not a standard Conventional Commits type
- **Impact:** Minor convention inconsistency
### 13. [docs/ui-ux/material3-guideline.md:4-5] - Version history stops at 0.9.2
- **Doc claims:** Version 0.9.2, last updated 2026-05-14
- **Code shows:** DV baseline documents dated 2026-05-29; no update for baseline
- **Impact:** Material 3 guideline may not reflect latest baseline decisions
### 14. [docs/sysdes.md:6] - SysDes version older than SysRS
- **Doc claims:** SysDes version 0.9.8
- **Code shows:** SysRS version 0.9.11
- **Impact:** Version numbering inconsistency between related documents
### 15. [docs/offline-knowledge/README.md:54] - Claims 2 missing LICENSE files
- **Doc claims:** "2 missing LICENSE files (LICENSE-APACHE, LICENSE-MIT)"
- **Code shows:** Confirmed - files do not exist at repo root
- **Impact:** Consistent finding, but offline-knowledge doc correctly identifies the issue
### 16. [docs/security/dependency-and-supply-chain-report.md:35] - License inventory location uncertainty
- **Doc claims:** `docs/security/license-inventory.md` and Flutter inventory referenced by CI
- **Code shows:** Both files exist at `docs/security/license-inventory.md` and `docs/security/flutter-license-inventory.md`
- **Impact:** Report expresses uncertainty but files actually exist
### 17. [docs/architecture/file-transfer-design.md:6] - References SAD-067 which is not itemized
- **Doc claims:** "Direct upstream source: docs/architecture/sad.md (SAD-067, SDD-MOD-009)"
- **Code shows:** Current SAD baseline does not use itemized SAD-XXX numbering
- **Impact:** Historical reference cannot be traced
## Per-File Verification Results
### README.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 3 | Cross-platform voice client for TeamSpeak-compatible servers | ✅ PASS | Matches project description |
| 8 | Flutter UI + Rust Core + tsclientlib | ✅ PASS | Architecture confirmed |
| 17 | Baseline-candidate Flutter + Rust workspace | ⚠️ MINOR | Undersells current maturity |
| 47-54 | Platform policy table | ✅ PASS | Matches `docs/release/platform-release-policy.md` |
| 57-65 | silero-coreml sibling package | ✅ PASS | Confirmed in workspace layout |
| 73-92 | Architecture overview diagram | ✅ PASS | Matches SAD component structure |
| 110-123 | MVP Direction table | ✅ PASS | Matches implementation status |
| 127-166 | Desktop PTT section | ✅ PASS | Matches `docs/architecture/desktop-ptt-architecture.md` |
| 171-231 | Repository Layout (docs/) | ✅ PASS | All listed paths exist |
| 236-249 | Repository Layout (implementation) | ❌ FAIL | Missing 3 crates: resolver, prefetch, cache |
| 260-271 | Documentation Entry Points | ✅ PASS | All listed paths exist |
| 349-355 | Security/Privacy/Legal Gates | ✅ PASS | All listed paths exist |
| 400-406 | Development commands | ✅ PASS | Standard Flutter/Cargo commands |
| 425-436 | License section | ❌ FAIL | LICENSE-APACHE and LICENSE-MIT do not exist |
### docs/architecture/sad.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 17 | Rust owns connection orchestration, protocol isolation, audio processing, storage coordination, diagnostics, server resolution, prefetch policy, and bridge DTOs | ✅ PASS | Matches crate responsibilities |
| 39-52 | Component architecture table | ⚠️ MAJOR | Missing chanora_cache |
| 56-67 | Static architecture view | ✅ PASS | Matches actual dependency flow |
| 75-107 | Runtime flow diagrams | ✅ PASS | Connect, voice, diagnostics flows match |
| 119-130 | Interface catalogue | ✅ PASS | Matches bridge/protocol boundaries |
### docs/architecture/sdd.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 15-31 | Module catalogue | ⚠️ MAJOR | snapshot_state_mapper.dart misclassified |
| 17 | SDD-MOD-001: `app_bootstrap.dart`, `main.dart` | ✅ PASS | Files exist in services/ and root |
| 18 | SDD-MOD-002: `connect_widgets.dart` | ✅ PASS | File exists in widgets/ |
| 19 | SDD-MOD-003: `snapshot_view.dart`, `snapshot_state_mapper.dart`, `channel_spacer.dart` | ⚠️ MAJOR | snapshot_state_mapper.dart is in services/ not widgets/ |
| 20 | SDD-MOD-004: `chat_views.dart`, `bbcode_text.dart` | ✅ PASS | Files exist in widgets/ |
| 21 | SDD-MOD-005: `voice_bar.dart`, `voice_compact.dart`, `voice_settings*.dart`, `voice_level_meter.dart`, `ptt_capability_badge.dart` | ✅ PASS | All files exist in widgets/ |
| 22 | SDD-MOD-006: `android_permissions_service.dart`, `ios_permissions_service.dart`, `audio_lifecycle_service.dart`, `back_intent_*`, `link_trust_service.dart` | ✅ PASS | All files exist in services/ |
| 23 | SDD-MOD-007: `crates/chanora_bridge/src/api.rs` | ✅ PASS | File exists |
| 24 | SDD-MOD-008: `core/chanora_core/src/lib.rs`, `events.rs`, `network_diagnostics.rs`, `ptt.rs` | ✅ PASS | All files exist |
| 25 | SDD-MOD-009: `crates/chanora_protocol/src/` | ✅ PASS | Directory exists |
| 26 | SDD-MOD-010: `crates/chanora_state/src/lib.rs`, `channel_join.rs` | ✅ PASS | Both files exist |
| 27 | SDD-MOD-011: `crates/chanora_audio/src/` | ✅ PASS | Directory exists with 26 files |
| 28 | SDD-MOD-012: `crates/chanora_storage/src/lib.rs` | ✅ PASS | File exists |
| 29 | SDD-MOD-013: `crates/chanora_diagnostics/src/lib.rs` | ✅ PASS | File exists |
| 30 | SDD-MOD-014: `crates/chanora_resolver/src/lib.rs`, `crates/chanora_prefetch/src/lib.rs`, `prefetch_debouncer.dart` | ✅ PASS | All files exist |
| 31 | SDD-MOD-015: `.github/workflows/`, `tools/` | ✅ PASS | Both directories exist |
### docs/sysdes.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 6 | Version 0.9.8 | ⚠️ MINOR | SysRS is 0.9.11 |
| 13 | `**Repo path:** docs/architecture/sysdes.md` | ⚠️ MINOR | Malformed markdown (missing blank line before `---`) |
| 377-418 | System elements SE-01 through SE-19 | ✅ PASS | Comprehensive element list |
| 839-855 | Interface catalogue IF-001 through IF-014 | ✅ PASS | Matches architecture |
### docs/sysrs.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 5 | Version 0.9.11 | ✅ PASS | Consistent within document |
| 126-130 | Suggested downstream file names | ❌ FAIL | 5 non-existent file names |
| 233-257 | Application component requirements SysRS-024 through SysRS-034 | ✅ PASS | Match SAD component allocation |
### docs/srs.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 6 | Version 0.9.9 | ✅ PASS | Consistent within document |
| 101-176 | SWE.1 process requirements SRS-001 through SRS-007 | ✅ PASS | Match ASPICE alignment |
| 180-267 | Software boundary requirements SRS-008 through SRS-015 | ✅ PASS | Match architecture constraints |
### CONTRIBUTING.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 10 | Engineering hierarchy: SysRS -> SysDes -> SRS -> SAD -> SDD | ✅ PASS | Matches README and governance docs |
| 25 | Commit convention reference | ✅ PASS | `docs/governance/git-commit-message-convention.md` exists |
| 37-42 | Commit examples | ✅ PASS | Match README examples |
### CHANGELOG.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 7 | v0.3.0 milestone | ✅ PASS | Matches pubspec.yaml version |
| 65-66 | Flutter app version/build bumped to 0.3.0+100 | ✅ PASS | Matches pubspec.yaml |
| 99 | Default base branch is main | ✅ PASS | Confirms branch change |
| 100-101 | DSP chain not yet production-tuned | ✅ PASS | Matches implementation status |
### docs/architecture/desktop-ptt-architecture.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 17-21 | Platform backends table | ✅ PASS | Matches README PTT section |
| 24-30 | Safety rules | ✅ PASS | Watchdog, capability, fallback |
### docs/architecture/file-transfer-design.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 6 | References SAD-067, SDD-MOD-009 | ⚠️ MINOR | SAD-067 not itemized in current baseline |
| 113-137 | tsclientlib public API signatures | ⚠️ MINOR | Cannot verify against external library source |
| 400-428 | Avatar path computation in adapter.rs | ✅ PASS | `uid_to_avatar_path` function described |
### docs/i18n/localization-architecture.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 8 | Generated files under `apps/chanora_flutter/lib/l10n/generated/` | ✅ PASS | Directory exists with 3 files |
| 22 | English and Simplified Chinese generated localization files | ✅ PASS | `app_localizations_en.dart` and `app_localizations_zh.dart` exist |
### docs/ui-ux/material3-design-tokens.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 8 | Implementation token source is `apps/chanora_flutter/lib/design/chanora_tokens.dart` | ✅ PASS | File exists |
### docs/ui-ux/material3-component-catalog.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 10 | Connect and bookmarks: `connect_widgets.dart`, `input_dialogs.dart` | ✅ PASS | Both files exist in widgets/ |
| 11 | Channel and client view: `snapshot_view.dart`, `client_info_sheet.dart`, `channel_spacer.dart` | ✅ PASS | All files exist |
| 12 | Chat: `chat_views.dart`, `bbcode_text.dart` | ✅ PASS | Both files exist |
| 13 | Voice controls: `voice_bar.dart`, `voice_compact.dart`, `voice_settings*.dart` | ✅ PASS | All files exist |
| 14 | Platform/permission indicators: `permission_state_banner.dart`, `ptt_capability_badge.dart`, `talk_power_warning.dart` | ✅ PASS | All files exist |
| 15 | Diagnostics: `audio_debug_stats_panel.dart` | ✅ PASS | File exists |
### docs/ui-ux/adaptive-layout-platform-guide.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 8 | Compact/mobile layout for MVP | ✅ PASS | Matches implementation status |
### docs/security/security-privacy-legal-guideline.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 13-21 | Gate summary table | ✅ PASS | Matches threat model and audit reports |
### docs/security/threat-model.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 8 | Scope covers client, local storage, diagnostics, bridge, protocol, audio, platform, release | ✅ PASS | Comprehensive scope |
### docs/security/secure-storage-audit-report.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 12-18 | Audit matrix | ✅ PASS | Matches platform policy |
### docs/security/diagnostic-redaction-audit-report.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 12-18 | Redaction targets | ✅ PASS | Matches diagnostics crate responsibilities |
### docs/security/dependency-and-supply-chain-report.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 15-19 | Automated controls | ✅ PASS | CI workflows confirmed |
| 24-29 | Dependency areas | ✅ PASS | Matches workspace structure |
### docs/security/flutter-license-inventory.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 11-12 | References LICENSE-APACHE and LICENSE-MIT | ❌ FAIL | Files do not exist |
### docs/security/license-inventory.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 9-10 | References LICENSE-APACHE and LICENSE-MIT | ❌ FAIL | Files do not exist |
### docs/privacy/privacy-policy.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 9 | Chanora is a client application for connecting to TeamSpeak 3-compatible servers | ✅ PASS | Matches README |
### docs/legal/trademark-and-attribution-review.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 5 | DEC-012 remains open | ✅ PASS | Matches product decision register |
### docs/release/release-readiness-go-nogo-record.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 5 | Workspace version 0.2.0-beta.1, Flutter app 0.3.0+100 | ✅ PASS | Matches Cargo.toml and pubspec.yaml |
| 6 | No-Go for public/store release | ✅ PASS | Consistent with open gates |
### docs/release/platform-release-policy.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 12-19 | Platform policy table | ✅ PASS | Matches README |
### docs/release/dv-waiver-register.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 14-23 | Active waivers DV-WVR-001 through DV-WVR-009 | ✅ PASS | Comprehensive waiver list |
### docs/release/ios-build.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 12 | Build script `./tools/build-ios.sh --no-codesign` | ⚠️ MINOR | Cannot verify script exists without checking |
### docs/verification/verification-master-plan.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 5 | Applies to Rust workspace 0.2.0-beta.1, Flutter app 0.3.0+100 | ✅ PASS | Matches actual versions |
### docs/verification/swe4-unit-verification-plan.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 17 | chanora_state has 27 tests | ✅ PASS | Matches coverage analysis |
### docs/verification/swe5-software-integration-verification-plan.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 14-22 | Integration paths | ✅ PASS | Comprehensive path list |
### docs/verification/swe6-software-verification-plan.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 27-45 | MVP acceptance matrix | ✅ PASS | Comprehensive matrix |
### docs/verification/sys4-system-integration-verification-plan.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 14-22 | System elements under verification | ✅ PASS | Comprehensive list |
### docs/governance/document-index.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 14-32 | Baseline documents table | ✅ PASS | All listed paths exist |
### docs/governance/traceability-matrix.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 16 | Lifecycle chain | ✅ PASS | Matches README |
### docs/governance/product-decision-register.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 14-21 | Decision summary | ✅ PASS | Comprehensive decision list |
### docs/governance/git-commit-message-convention.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 18 | `release(android)` example | ⚠️ MINOR | Non-standard Conventional Commits type |
### docs/governance/document-naming-convention.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 8 | Lowercase kebab-case file names | ✅ PASS | Matches actual file naming |
### docs/governance/path-migration-map.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 10-14 | Migration state table | ✅ PASS | Matches actual file locations |
### docs/governance/baseline-approval-record.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 10-18 | Approval scope table | ✅ PASS | Matches baseline status |
### docs/governance/baseline-candidate-validation-report.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 10-16 | Validation summary | ✅ PASS | Comprehensive validation |
### docs/governance/document-review-report.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 19-24 | Findings table | ✅ PASS | Addresses previous gaps |
### docs/governance/repo-format-validation-report.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 8-18 | Repository layout check | ✅ PASS | All areas confirmed |
### docs/governance/decision-impact-assessment.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 8-14 | Impact matrix | ✅ PASS | Comprehensive impact list |
### docs/governance/maintainability-review-2026-06-08.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 13-23 | Changes already applied | ✅ PASS | Matches code structure |
| 61-88 | Android ADB status | ✅ PASS | Detailed smoke evidence |
### docs/references/aspice-swe2-swe3-integration-note.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 12 | Lifecycle chain | ✅ PASS | Matches README |
### docs/references/external-references.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 8-17 | Reference list | ✅ PASS | Comprehensive references |
### docs/implementation-status-2026-05-28.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 3-4 | Workspace version v0.2.0-beta.1, Flutter app 0.3.0+100 | ✅ PASS | Matches actual versions |
| 103 | References SDD-109 | ⚠️ MINOR | Not itemized in current baseline |
| 105 | References SAD-043 | ⚠️ MINOR | Not itemized in current baseline |
| 140 | Agent spec docs reference | ⚠️ MINOR | Stale cleanup note |
### SECURITY.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 33-38 | Security document list | ✅ PASS | All listed paths exist |
### apps/chanora_flutter/README.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 3 | Chanora — cross-platform voice client for TeamSpeak-compatible servers | ✅ PASS | Matches main README |
### crates/chanora_resolver/README.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 7 | `ChanoraResolver::resolve_client_request` or `resolve_client_address` | ✅ PASS | Matches function inventory |
| 60-77 | Library example | ✅ PASS | Matches API |
### tools/windows-smoke.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 6 | `product/scaffold-v0` branch | ❌ FAIL | Default branch is now `main` |
### silero-coreml/README.md
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 3 | Private Chanora-owned Apple/CoreML Silero VAD backend scaffold | ✅ PASS | Matches project scope |
### flutter_rust_bridge.yaml
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 1-5 | Bridge configuration | ✅ PASS | Matches SDD bridge boundary design |
### Cargo.toml
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 28-39 | Workspace members | ✅ PASS | All 10 crates listed |
| 46 | Version 0.2.0-beta.1 | ✅ PASS | Matches documentation |
| 48 | Rust version 1.95 | ✅ PASS | Modern Rust requirement |
### pubspec.yaml
| Line | Claim | Status | Notes |
|------|-------|--------|-------|
| 19 | Version 0.3.0+100 | ✅ PASS | Matches documentation |
| 37 | flutter_rust_bridge: 2.12.0 | ✅ PASS | Matches SDD bridge version |
## Recommendations
### High Priority (Critical)
1. **Create LICENSE-APACHE and LICENSE-MIT files** — Required for DEC-020 dual-license compliance
2. **Update README.md repository layout** — Add `crates/chanora_resolver/`, `crates/chanora_prefetch/`, `crates/chanora_cache/`
### Medium Priority (Major)
3. **Update SAD component table** — Add `chanora_cache` component
4. **Fix SDD-MOD-003 file classification** — Move `snapshot_state_mapper.dart` to correct section
5. **Update tools/windows-smoke.md** — Change branch reference from `product/scaffold-v0` to `main`
6. **Fix docs/sysrs.md suggested file names** — Remove or update non-existent file name suggestions
### Low Priority (Minor)
7. **Update implementation status date** — Refresh to reflect current state
8. **Fix malformed markdown in docs/sysdes.md:13** — Add blank line before `---`
9. **Update Material 3 guideline version** — Align with DV baseline date
10. **Standardize commit type examples** — Remove `release` type from convention examples
11. **Update SysDes version** — Align with SysRS version numbering
@@ -0,0 +1,347 @@
# Documentation Link Not-Covered Analysis
**Generated:** 2026-06-13
## Summary
- Total references checked: 148
- Broken markdown links: 2
- Missing file targets: 9 (2 LICENSE + 5 hypothetical + 2 code path mismatches)
- Orphaned docs: 18
- Suspicious external URLs: 3
## Broken Markdown Links
| File | Line | Link Text | Target | Issue |
|------|------|-----------|--------|-------|
| README.md | 428 | `LICENSE-APACHE` | `LICENSE-APACHE` | File does not exist at repo root |
| README.md | 431 | `LICENSE-MIT` | `LICENSE-MIT` | File does not exist at repo root |
**Impact:** Users clicking the license links in the README will get a 404 on GitHub. These are referenced in the License section as the dual-license model files (DEC-020).
## Missing File Targets
### Missing LICENSE Files (High Impact)
| File | Line | Referenced Path | Issue |
|------|------|----------------|-------|
| README.md | 428 | `LICENSE-APACHE` | File does not exist at repo root |
| README.md | 431 | `LICENSE-MIT` | File does not exist at repo root |
| docs/security/license-inventory.md | 9 | `../../LICENSE-APACHE` | Resolves to missing `LICENSE-APACHE` at repo root |
| docs/security/license-inventory.md | 10 | `../../LICENSE-MIT` | Resolves to missing `LICENSE-MIT` at repo root |
| docs/security/flutter-license-inventory.md | 11 | `../../LICENSE-APACHE` | Resolves to missing `LICENSE-APACHE` at repo root |
| docs/security/flutter-license-inventory.md | 11 | `../../LICENSE-MIT` | Resolves to missing `LICENSE-MIT` at repo root |
**Impact:** The dual-license model (DEC-020) requires these files to exist for proper attribution. All 4 references across 3 files are broken.
### Hypothetical File Names (Low Impact)
| File | Line | Referenced Path | Issue |
|------|------|----------------|-------|
| docs/sysrs.md | 126 | `docs/chanora_SysDes.md` | Listed as "Potential downstream file name" — does not exist |
| docs/sysrs.md | 127 | `docs/chanora_SRS.md` | Listed as "Potential downstream file name" — does not exist |
| docs/sysrs.md | 128 | `docs/chanora_SAD.md` | Listed as "Potential downstream file name" — does not exist |
| docs/sysrs.md | 129 | `docs/chanora_SDD.md` | Listed as "Potential downstream file name" — does not exist |
| docs/sysrs.md | 130 | `docs/chanora_Verification.md` | Listed as "Potential downstream file name" — does not exist |
**Note:** These are documented as "Potential downstream file names" in a table and are aspirational/historical. They are presented as plain text in a table, not as navigable links. Low severity.
## Missing Code References
| File | Line | Reference | Expected Location | Issue |
|------|------|-----------|-------------------|-------|
| docs/architecture/sdd.md | 19 | `snapshot_state_mapper.dart` | Listed under "Snapshot and channel UI" widgets section | File actually exists in `apps/chanora_flutter/lib/services/`, not `apps/chanora_flutter/lib/widgets/` — directory mismatch in docs |
| docs/architecture/sdd.md | 21 | `voice_settings*.dart` | Listed under Voice UI widgets | Files are `voice_settings.dart` and `voice_settings_controls.dart` — glob reference is ambiguous (two files match) |
**Note:** The `snapshot_state_mapper.dart` directory mismatch is a minor documentation inaccuracy — the file exists but is categorized differently than documented.
## Broken Anchor Links
No broken anchor links found. All `#section` references within documents resolve to existing headers.
## Orphaned Documents
(Not referenced by any other document in the main doc tree)
| File | Last Modified | Should Be Referenced From |
|------|---------------|--------------------------|
| docs/offline-knowledge/README.md | 2026-06-13 | Could be referenced from a top-level docs index |
| docs/offline-knowledge/function-inventory.md | 2026-06-13 | Could be referenced from docs/architecture/sdd.md |
| docs/offline-knowledge/coverage-analysis.md | 2026-06-13 | Could be referenced from docs/verification/ plans |
| docs/offline-knowledge/doc-quality-analysis.md | 2026-06-13 | Could be referenced from docs/governance/document-review-report.md |
| docs/offline-knowledge/link-coverage-report.md | 2026-06-13 | Could be referenced from docs/governance/ |
| docs/offline-knowledge/external/teaspeak-overview.md | 2026-06-13 | Could be referenced from docs/references/external-references.md |
| docs/offline-knowledge/external/respeak-overview.md | 2026-06-13 | Could be referenced from docs/references/external-references.md |
| docs/offline-knowledge/external/yatqa-en.md | 2026-06-13 | Could be referenced from docs/references/external-references.md |
| docs/offline-knowledge/external/yatqa-de.md | 2026-06-13 | Could be referenced from docs/references/external-references.md |
| docs/offline-knowledge/reviews/coverage-analysis-review.md | 2026-06-13 | Could be referenced from docs/offline-knowledge/README.md (already is) |
| docs/offline-knowledge/reviews/doc-quality-review.md | 2026-06-13 | Could be referenced from docs/offline-knowledge/README.md (already is) |
| docs/offline-knowledge/reviews/link-coverage-review.md | 2026-06-13 | Could be referenced from docs/offline-knowledge/README.md (already is) |
| docs/offline-knowledge/reviews/external-docs-review.md | 2026-06-13 | Could be referenced from docs/offline-knowledge/README.md (already is) |
| docs/superpowers/specs/*.md (6 files) | 2026-05-28 to 2026-06-09 | Internal planning docs; not expected in DV tree |
| docs/superpowers/plans/*.md (8 files) | 2026-05-28 to 2026-06-08 | Internal planning docs; not expected in DV tree |
**Note:** The offline-knowledge files are self-referencing within their own README but are not linked from the main documentation tree. The superpowers files are internal planning documents and are intentionally separate from the DV document set.
## Suspicious External URLs
| File | Line | URL | Issue |
|------|------|-----|-------|
| docs/architecture/file-transfer-research.md | 406 | `https://git.did.science/TeaSpeak/Server/Server` | Self-hosted GitLab instance; may become unavailable. Specific branch `new-groups` commit `b54c6d4e` referenced. |
| docs/security/license-inventory.md | 96 | `http://github.com/ejmahler/strength_reduce` | Uses HTTP instead of HTTPS for GitHub URL |
| docs/security/flutter-license-inventory.md | various | `http://www.apache.org/licenses/` and `http://mozilla.org/MPL/2.0/` | HTTP URLs in license text bodies (not navigational links) |
**Note:** The file-transfer research links point to specific GitHub commit SHAs which may become stale over time if force-pushes occur. The HTTP-vs-HTTPS issue on the strength_reduce URL is cosmetic but should be corrected.
## Cross-Reference Chain Issues
| Chain | Issue |
|-------|-------|
| None found | All doc-to-doc cross-references in prose text resolve correctly |
All cross-reference chains verified:
- `docs/architecture/sad.md``docs/srs.md`
- `docs/architecture/sad.md``docs/sysdes.md`
- `docs/architecture/sdd.md``docs/architecture/sad.md`
- `docs/architecture/sdd.md``docs/srs.md`
- `docs/architecture/sysdes.md``docs/sysdes.md`
- `docs/architecture/file-transfer-design.md``docs/architecture/sad.md`
- `docs/architecture/file-transfer-research.md``docs/architecture/file-transfer-design.md`
- `docs/architecture/file-transfer-implementation-plan.md` → both upstream docs ✓
- `docs/architecture/desktop-ptt-architecture.md` → sad, sdd, dv-waiver-register ✓
- `docs/requirements/sysrs.md``../sysrs.md`
- `docs/requirements/srs.md``../srs.md`
- `docs/ui-ux/material3-guideline.md``docs/material3-guideline.md`
## Missing Image/Asset References
No image references (`![alt](path)`) found in any documentation files. All docs are text-only.
## Include/Import References
No include directives or template references found in documentation files.
---
## Per-File Link Inventory
### README.md
| Line | Link | Status |
|------|------|--------|
| 130 | `docs/architecture/desktop-ptt-architecture.md` | ✓ Valid (markdown link) |
| 144 | `docs/governance/product-decision-register.md` | ✓ Valid (inline ref) |
| 261 | `docs/requirements/sysrs.md` | ✓ Valid (inline ref) |
| 262 | `docs/requirements/srs.md` | ✓ Valid (inline ref) |
| 263 | `docs/architecture/sysdes.md` | ✓ Valid (inline ref) |
| 264 | `docs/architecture/sad.md` | ✓ Valid (inline ref) |
| 265 | `docs/architecture/sdd.md` | ✓ Valid (inline ref) |
| 266 | `docs/verification/verification-master-plan.md` | ✓ Valid (inline ref) |
| 267 | `docs/release/release-readiness-go-nogo-record.md` | ✓ Valid (inline ref) |
| 268 | `docs/release/platform-release-policy.md` | ✓ Valid (inline ref) |
| 269 | `docs/governance/product-decision-register.md` | ✓ Valid (inline ref) |
| 270 | `docs/governance/traceability-matrix.md` | ✓ Valid (inline ref) |
| 271 | `docs/security/security-privacy-legal-guideline.md` | ✓ Valid (inline ref) |
| 312 | `docs/release/release-readiness-go-nogo-record.md` | ✓ Valid (inline ref) |
| 349-355 | 6 security/privacy/legal doc paths | ✓ Valid (inline refs) |
| 391 | `docs/governance/git-commit-message-convention.md` | ✓ Valid (inline ref) |
| 428 | `LICENSE-APACHE` | ✗ **BROKEN** — file does not exist |
| 431 | `LICENSE-MIT` | ✗ **BROKEN** — file does not exist |
| 436 | `docs/governance/product-decision-register.md` | ✓ Valid (markdown link) |
| 444 | `NOTICE` | ✓ Valid (markdown link) |
| 449-451 | 3 doc paths | ✓ Valid (inline refs) |
### CONTRIBUTING.md
| Line | Link | Status |
|------|------|--------|
| 25 | `docs/governance/git-commit-message-convention.md` | ✓ Valid (inline ref) |
### SECURITY.md
| Line | Link | Status |
|------|------|--------|
| 33-38 | 6 security/privacy/legal doc paths | ✓ Valid (inline refs) |
### docs/architecture/sad.md
| Line | Link | Status |
|------|------|--------|
| 6 | `docs/srs.md` | ✓ Valid (inline ref) |
| 7 | `docs/sysdes.md` | ✓ Valid (inline ref) |
| 41-52 | 12 component source paths | ✓ Valid (code refs) |
| 176 | `docs/governance/traceability-matrix.md` | ✓ Valid (inline ref) |
### docs/architecture/sdd.md
| Line | Link | Status |
|------|------|--------|
| 6 | `docs/architecture/sad.md` | ✓ Valid (inline ref) |
| 7 | `docs/srs.md` | ✓ Valid (inline ref) |
| 17-31 | Module source paths | ✓ Valid (code refs), except `snapshot_state_mapper.dart` listed under wrong section |
| 35 | `crates/chanora_bridge/src/api.rs` | ✓ Valid (code ref) |
### docs/architecture/sysdes.md
| Line | Link | Status |
|------|------|--------|
| 6 | `docs/sysdes.md` | ✓ Valid (canonical pointer) |
### docs/architecture/desktop-ptt-architecture.md
| Line | Link | Status |
|------|------|--------|
| 5 | `docs/architecture/sad.md`, `docs/architecture/sdd.md`, `docs/release/dv-waiver-register.md` | ✓ Valid (inline refs) |
### docs/architecture/file-transfer-design.md
| Line | Link | Status |
|------|------|--------|
| 6 | `docs/architecture/sad.md` | ✓ Valid (inline ref) |
| 118-137 | `tsclientlib/src/lib.rs` code references | ✓ Valid (external code refs — not locally verifiable) |
| 737 | `crates/chanora_protocol/src/adapter.rs` | ✓ Valid (code ref) |
### docs/architecture/file-transfer-research.md
| Line | Link | Status |
|------|------|--------|
| 5 | `docs/architecture/file-transfer-design.md` | ✓ Valid (inline ref) |
| 29-31 | GitHub commit URLs | ⚠ External — may become stale |
| 406 | `https://git.did.science/TeaSpeak/Server/Server` | ⚠ Self-hosted GitLab — may become unavailable |
### docs/architecture/file-transfer-implementation-plan.md
| Line | Link | Status |
|------|------|--------|
| 6 | `docs/architecture/file-transfer-design.md`, `docs/architecture/file-transfer-research.md` | ✓ Valid (inline refs) |
### docs/governance/document-index.md
| Line | Link | Status |
|------|------|--------|
| 14-32 | All 18 listed document paths | ✓ Valid (inline refs) |
### docs/governance/traceability-matrix.md
| Line | Link | Status |
|------|------|--------|
| 5 | 5 primary upstream doc paths | ✓ Valid (inline refs) |
| 25-31 | 7 source doc paths | ✓ Valid (inline refs) |
### docs/governance/path-migration-map.md
| Line | Link | Status |
|------|------|--------|
| 10-14 | 5 README path mappings | ✓ Valid (inline refs) |
### docs/verification/verification-master-plan.md
| Line | Link | Status |
|------|------|--------|
| 6 | 6 primary upstream doc paths | ✓ Valid (inline refs) |
| 18-21 | 4 verification plan paths | ✓ Valid (inline refs) |
| 47 | `tools/windows-smoke.md` | ✓ Valid (code ref) |
| 48 | `docs/release/ios-build.md` | ✓ Valid (inline ref) |
### docs/security/license-inventory.md
| Line | Link | Status |
|------|------|--------|
| 9 | `../../LICENSE-APACHE` | ✗ **BROKEN** — file does not exist |
| 10 | `../../LICENSE-MIT` | ✗ **BROKEN** — file does not exist |
| 11 | `docs/governance/product-decision-register.md` | ✓ Valid (inline ref) |
### docs/security/flutter-license-inventory.md
| Line | Link | Status |
|------|------|--------|
| 11 | `../../LICENSE-APACHE` | ✗ **BROKEN** — file does not exist |
| 12 | `../../LICENSE-MIT` | ✗ **BROKEN** — file does not exist |
### docs/security/dependency-and-supply-chain-report.md
| Line | Link | Status |
|------|------|--------|
| 29 | `https://github.com/EdisonJwa/oboe-rs` | ✓ Valid (external GitHub URL) |
### docs/privacy/privacy-policy.md
| Line | Link | Status |
|------|------|--------|
| (none) | No links or references | N/A |
### docs/legal/trademark-and-attribution-review.md
| Line | Link | Status |
|------|------|--------|
| (none) | No links or references | N/A |
### docs/release/release-readiness-go-nogo-record.md
| Line | Link | Status |
|------|------|--------|
| 37 | `docs/implementation-status-2026-05-28.md` | ✓ Valid (inline ref) |
| 26 | `apps/chanora_flutter/pubspec.yaml` | ✓ Valid (code ref) |
### docs/release/dv-waiver-register.md
| Line | Link | Status |
|------|------|--------|
| 15-23 | Various `docs/` paths in Source evidence column | ✓ Valid (inline refs) |
### docs/requirements/sysrs.md
| Line | Link | Status |
|------|------|--------|
| 4 | `../sysrs.md` | ✓ Valid (canonical pointer) |
### docs/requirements/srs.md
| Line | Link | Status |
|------|------|--------|
| 4 | `../srs.md` | ✓ Valid (canonical pointer) |
### docs/ui-ux/material3-guideline.md
| Line | Link | Status |
|------|------|--------|
| 6 | `docs/material3-guideline.md` | ✓ Valid (canonical pointer) |
### docs/material3-guideline.md
| Line | Link | Status |
|------|------|--------|
| 10 | `docs/ui-ux/material3-guideline.md` | ✓ Valid (self-referencing path record) |
### docs/sysrs.md
| Line | Link | Status |
|------|------|--------|
| 126 | `docs/chanora_SysDes.md` | ⚠ Hypothetical — does not exist (aspirational name) |
| 127 | `docs/chanora_SRS.md` | ⚠ Hypothetical — does not exist (aspirational name) |
| 128 | `docs/chanora_SAD.md` | ⚠ Hypothetical — does not exist (aspirational name) |
| 129 | `docs/chanora_SDD.md` | ⚠ Hypothetical — does not exist (aspirational name) |
| 130 | `docs/chanora_Verification.md` | ⚠ Hypothetical — does not exist (aspirational name) |
### apps/chanora_flutter/README.md
| Line | Link | Status |
|------|------|--------|
| 11 | `https://docs.flutter.dev/get-started/learn-flutter` | ✓ Valid (external) |
| 12 | `https://docs.flutter.dev/get-started/codelab` | ✓ Valid (external) |
| 13 | `https://docs.flutter.dev/reference/learning-resources` | ✓ Valid (external) |
| 16 | `https://docs.flutter.dev/` | ✓ Valid (external) |
---
## Action Items (Priority Order)
### P0 — Must Fix Before Any Release
1. **Create `LICENSE-APACHE` and `LICENSE-MIT` files** at repo root. These are required by DEC-020 (dual-license model) and referenced by README.md, docs/security/license-inventory.md, and docs/security/flutter-license-inventory.md.
### P1 — Should Fix for DV Quality
2. **Fix `snapshot_state_mapper.dart` categorization** in docs/architecture/sdd.md:19 — move from "Snapshot and channel UI" widgets section to service layer section, or add a note clarifying the actual location.
### P2 — Nice to Have
3. **Add offline-knowledge docs to document index** or references section so they are discoverable.
4. **Fix HTTP URL** in docs/security/license-inventory.md:96 (`http://github.com/ejmahler/strength_reduce``https://...`).
5. **Clean up hypothetical file names** in docs/sysrs.md:124-131 — either remove the table or clearly mark as historical/aspirational.
@@ -0,0 +1,187 @@
# Documentation Out-of-Date Analysis
**Generated:** 2026-06-13
**Workspace version:** 0.2.0-beta.1
**Latest commit:** dd6e80f (2026-06-13)
## Summary
- Total docs checked: 64
- Outdated docs: 12
- Stale version refs: 5
- Undocumented recent changes: 8
- Stale date refs: 15+
## Stale Version References
| File | Line | Version Referenced | Current Version | Drift |
|------|------|-------------------|-----------------|-------|
| `docs/sysdes.md` | 6 | 0.9.8 | N/A (doc version) | Last updated 2026-05-14, 30 days stale |
| `docs/srs.md` | 7 | 0.9.9 | N/A (doc version) | Last updated 2026-05-18, 26 days stale |
| `docs/sysrs.md` | 5 | 0.9.11 | N/A (doc version) | Last updated 2026-06-07, 6 days stale |
| `docs/material3-guideline.md` | ~4 | 0.9.2 | N/A (doc version) | Last updated 2026-05-14, 30 days stale |
| `tools/windows-smoke.md` | 6 | `product/scaffold-v0` branch | `main` | Default branch changed per CHANGELOG |
## Stale Date References
| File | Date | Age | Issue |
|------|------|-----|-------|
| `docs/implementation-status-2026-05-28.md` | 2026-05-28 | 16 days | Pre-dates DV baseline (2026-05-29) and 8 major feature PRs |
| `docs/architecture/sad.md` | 2026-05-29 | 15 days | Missing file transfer, poke notifications, desktop VAD features |
| `docs/architecture/sdd.md` | 2026-05-29 | 15 days | Missing file transfer, poke notifications, desktop VAD features |
| `docs/verification/verification-master-plan.md` | 2026-05-29 | 15 days | Missing file transfer and poke notification verification |
| `docs/verification/swe4-unit-verification-plan.md` | 2026-05-29 | 15 days | Missing new test coverage for file transfer |
| `docs/verification/swe5-software-integration-verification-plan.md` | 2026-05-29 | 15 days | Missing file transfer integration verification |
| `docs/verification/swe6-software-verification-plan.md` | 2026-05-29 | 15 days | Missing file transfer software verification |
| `docs/verification/sys4-system-integration-verification-plan.md` | 2026-05-29 | 15 days | Missing file transfer system verification |
| `docs/governance/product-decision-register.md` | 2026-05-29 | 15 days | Missing file-transfer-related decisions |
| `docs/governance/document-index.md` | 2026-05-29 | 15 days | Missing file-transfer-design.md, file-transfer-research.md, file-transfer-implementation-plan.md |
| `docs/security/security-privacy-legal-guideline.md` | 2026-05-29 | 15 days | Missing file transfer security considerations |
| `docs/security/threat-model.md` | 2026-05-29 | 15 days | Missing file transfer threat analysis |
| `docs/i18n/localization-architecture.md` | 2026-05-29 | 15 days | Missing poke notification l10n strings |
| `docs/legal/trademark-and-attribution-review.md` | 2026-05-29 | 15 days | Missing cacache license review |
| `docs/privacy/privacy-policy.md` | 2026-05-29 | 15 days | Missing file transfer data handling |
## Undocumented Recent Changes
| Change | Date | Expected Doc | Status |
|--------|------|-------------|--------|
| File transfer system (avatar/icon download with cacache) | 2026-06-10 | README.md, SAD, SDD, CHANGELOG | Not in README crate list, not in CHANGELOG |
| Poke notifications (local notifications, settings, bridge) | 2026-06-08 | SAD, SDD, CHANGELOG | Not in CHANGELOG |
| Desktop Silero ONNX VAD + Windows PTT modernization | 2026-06-09 | SAD, SDD, CHANGELOG | Not in CHANGELOG |
| iOS RemoteIO+WebRTC APM path removal | 2026-06-10 | SAD, SDD | Not documented |
| SonoraExperimental bridge API removal | 2026-06-10 | SAD, SDD, bridge docs | Not documented |
| iOS AVAudioSession activation fix | 2026-06-10 | Platform docs | Not documented |
| iOS Debug build unblocking + FRB regeneration | 2026-06-10 | Build docs | Not documented |
| poke-without-message design | 2026-06-09 | Design docs | Committed but not indexed |
## Feature Drift
### Documented but No Longer in Code
| Feature | Doc File | Last Seen In Code |
|---------|----------|-------------------|
| `SonoraExperimental` bridge API | `docs/architecture/sdd.md` (implied) | Removed 2026-06-10 (commit 2b28549) |
| iOS `ios_raw_unit.rs` | `docs/implementation-status-2026-05-28.md:33` | Removed 2026-06-10 (commit 3f9ea4f) |
| `SnapshotChanged` event variant | CHANGELOG v0.3.0 | Removed end-to-end |
| Timer-based snapshot polling | CHANGELOG v0.2.0-beta.1 | Replaced by event-driven UI |
### In Code but Not Documented
| Feature | Code Location | Expected Doc |
|---------|--------------|-------------|
| `chanora_cache` crate (cacache-backed blob store) | `crates/chanora_cache/` | README.md crate list, SAD, SDD |
| File transfer protocol support | `crates/chanora_protocol/` | SAD, SDD, CHANGELOG |
| Poke notification service | `apps/chanora_flutter/lib/services/` | SAD, SDD, CHANGELOG |
| Poke notification settings UI | `apps/chanora_flutter/lib/widgets/` | SAD, SDD |
| Desktop Silero ONNX VAD | `crates/chanora_audio/src/vad/silero_onnx.rs` | SAD, SDD |
| Windows PTT modernization | `crates/chanora_audio/src/ptt_backends/windows.rs` | SAD, SDD |
| `poke_limiter.rs` | `crates/chanora_protocol/src/poke_limiter.rs` | SAD, SDD |
| Local notification plugin integration | `apps/chanora_flutter/` | SAD, SDD |
## Per-File Out-of-Date Assessment
### README.md
- **Last meaningful update:** Unknown (no date in file)
- **Stale sections:**
- Crate list (line 242-249): Missing `chanora_cache` and `chanora_resolver` crates
- Repository layout (line 233-249): Missing `chanora_cache`, `chanora_resolver`, `chanora_prefetch`
- Status section (line 16-23): References "v0.9.x document set" — no specific date
- Development section (line 398-409): Missing `just` commands (justfile exists)
- **Missing recent changes:** File transfer system, poke notifications, desktop VAD
### docs/sysdes.md
- **Version:** 0.9.8
- **Last change record:** 2026-05-14
- **Stale sections:** All — 30 days without update
- **Missing:** File transfer system element (SE-20?), poke notification interface (IF-015?)
### docs/srs.md
- **Version:** 0.9.9
- **Last change record:** 2026-05-18
- **Stale sections:** All — 26 days without update
- **Missing:** File transfer SRS requirements, poke notification SRS requirements, desktop VAD SRS requirements
### docs/sysrs.md
- **Version:** 0.9.11
- **Last change record:** 2026-06-07
- **Stale sections:** Mostly current but missing file transfer and poke notification requirements
### docs/architecture/sad.md
- **Date:** 2026-05-29
- **Stale sections:**
- Component architecture table (line 39-50): Missing `chanora_cache` component
- Missing file transfer architecture
- Missing poke notification architecture
- Missing desktop VAD architecture
- **Missing recent changes:** All PRs from 2026-06-07 through 2026-06-13
### docs/architecture/sdd.md
- **Date:** 2026-05-29
- **Stale sections:**
- Module catalogue (line 15-31): Missing file transfer module, poke notification module
- Missing `chanora_cache` module (SDD-MOD-016?)
- Missing `poke_limiter` module
- **Missing recent changes:** All PRs from 2026-06-07 through 2026-06-13
### docs/implementation-status-2026-05-28.md
- **Date:** 2026-05-28 — 16 days old
- **Stale sections:**
- "Done" table: Missing file transfer, poke notifications, desktop VAD, iOS fixes
- "Partial / Scaffold Only": `chanora_cache` was scaffold, now implemented
- "Not Done (P0 blockers)": iOS `AVAudioSession.Mode.voiceChat` — now implemented (commit 89bbfa1)
- Android target compilation: Still blocked per DEC-034
- Agent spec docs reference (line 140): States docs are "deleted" — stale cleanup note
- **Recommendation:** Update to reflect current state or create new status doc
### docs/governance/product-decision-register.md
- **Date:** 2026-05-29
- **Note:** DEC-033 and DEC-034 are present (lines 20-21). Missing decisions:
- File transfer architecture decision
- Poke notification feature decision
### docs/governance/document-index.md
- **Date:** 2026-05-29
- **Missing documents:**
- `docs/architecture/file-transfer-design.md`
- `docs/architecture/file-transfer-research.md`
- `docs/architecture/file-transfer-implementation-plan.md`
- `docs/superpowers/specs/2026-06-09-poke-without-message-design.md`
### docs/security/license-inventory.md
- **Status:** Refreshed 2026-06-09 (commit b841d3f)
- **Issue:** May be missing `cacache` dependency license if not in Cargo.lock at refresh time
### docs/material3-guideline.md
- **Version:** 0.9.2
- **Last change record:** 2026-05-14
- **Status:** 30 days stale, but Material 3 design may not have changed
### tools/windows-smoke.md
- **Stale reference:** Line 6 references `product/scaffold-v0` branch
- **Current default:** `main` per CHANGELOG v0.3.0
### docs/verification/*.md (all 5 files)
- **Date:** All dated 2026-05-29
- **Missing:** File transfer verification, poke notification verification, desktop VAD verification
## Recommendations
### Critical (blocks DV/release)
1. **Update `docs/implementation-status-2026-05-28.md`** — 16 days stale, missing 8 major PRs, iOS voiceChat now implemented
2. **Update `docs/governance/product-decision-register.md`** — Missing file transfer and poke notification decisions
3. **Update `docs/governance/document-index.md`** — Missing 3 file-transfer docs
### High Priority (DV completeness)
4. **Update `docs/architecture/sad.md`** — Missing file transfer, poke notifications, desktop VAD, chanora_cache component
5. **Update `docs/architecture/sdd.md`** — Missing file transfer, poke notifications, desktop VAD modules
6. **Update `docs/sysdes.md`** — 30 days stale, missing file transfer system elements
7. **Update `docs/srs.md`** — 26 days stale, missing file transfer and poke notification requirements
8. **Update CHANGELOG.md** — Missing v0.3.0+ changes (file transfer, poke notifications, desktop VAD, iOS fixes)
### Medium Priority (accuracy)
9. **Update README.md** — Missing `chanora_cache` and `chanora_resolver` in crate list
10. **Update `tools/windows-smoke.md`** — Fix stale branch reference
11. **Update verification plans** — Add file transfer and poke notification verification
12. **Update security docs** — Add file transfer threat analysis
### Low Priority (cleanup)
13. **Align document versions** — SysDes (0.9.8), SysRS (0.9.11), Material3 (0.9.2) have different version numbers
14. **Clean up path record files**`docs/architecture/sysdes.md`, `docs/requirements/sysrs.md`, `docs/requirements/srs.md`, `docs/ui-ux/material3-guideline.md` are stubs pointing to canonical files
@@ -0,0 +1,611 @@
# Chanora Function Inventory
> Auto-generated comprehensive inventory of all public APIs across 10 Rust crates and 50+ Dart files.
## Summary Statistics
| Category | Count |
|----------|-------|
| **Rust Crates** | 10 |
| **Rust pub fn** | ~180 |
| **Rust pub struct** | ~90 |
| **Rust pub enum** | ~50 |
| **Rust pub trait** | 6 |
| **Rust pub const** | ~30 |
| **Dart files** | 56 |
| **Dart public classes** | ~80 |
| **TODO/FIXME comments** | 15 |
| **Empty/commented stubs** | 0 |
---
## Rust Crates
### 1. `chanora_cache` — Content-Addressed Blob Cache
Disposable blob cache for avatar/icon files. Wraps `cacache` for crash safety.
| Kind | Name | File:Line | Purpose |
|------|------|-----------|---------|
| struct | `BlobCache` | lib.rs:30 | Content-addressed blob cache backed by cacache |
| enum | `BlobCacheError` | lib.rs:20 | Errors raised by blob cache (Io, InvalidKey) |
| const | `PREFIX_AVATAR` | lib.rs:37 | Avatar blob prefix `"av_"` |
| const | `PREFIX_ICON` | lib.rs:39 | Icon blob prefix `"ic_"` |
| fn | `BlobCache::new` | lib.rs:46 | Create/open cache rooted at `cache_dir/chanora/` |
| fn | `BlobCache::put` | lib.rs:63 | Store a blob with prefix+key |
| fn | `BlobCache::get` | lib.rs:80 | Read a blob (returns None if missing) |
| fn | `BlobCache::remove` | lib.rs:101 | Delete a specific blob |
| fn | `BlobCache::clear` | lib.rs:111 | Delete all blobs |
| fn | `BlobCache::total_size` | lib.rs:129 | Return total bytes used |
| fn | `BlobCache::evict` | lib.rs:154 | Evict oldest entries until under max_bytes |
**Dead code:** None found. All public items consumed by `chanora_core`.
---
### 2. `chanora_protocol` — TeamSpeak Protocol Adapter
Isolates `tsclientlib` behind a typed boundary. No upstream types leak.
| Kind | Name | File:Line | Purpose |
|------|------|-----------|---------|
| struct | `ConnectConfig` | adapter.rs:146 | Typed connection parameters |
| struct | `ProtocolClient` | adapter.rs:236 | Async handle owning live protocol connection |
| struct | `InboundVoice` | adapter.rs:260 | One inbound voice packet from remote client |
| struct | `SnapshotProbe` | adapter.rs:270 | Clone-free probe handle for watchdog |
| struct | `ChannelInfo` | dto.rs:19 | One channel in server tree |
| struct | `ClientInfo` | dto.rs:72 | One connected client |
| struct | `ClientProfile` | dto.rs:96 | Rich profile + live connection details |
| struct | `ServerSnapshot` | dto.rs:153 | Full server state snapshot |
| struct | `ChatMessage` | dto.rs:50 | In-channel text message |
| struct | `ServerActivity` | dto.rs:65 | Server-activity notification |
| struct | `ChannelId` | dto.rs:11 | Opaque channel identifier (u64 newtype) |
| struct | `ClientId` | dto.rs:15 | Opaque client identifier (u64 newtype) |
| struct | `PokeLimiter` | poke_limiter.rs:19 | Per-connection poke rate limiter |
| enum | `ProtocolError` | lib.rs:62 | Typed error catalogue (10 variants) |
| enum | `ProtocolDelta` | dto.rs:183 | Incremental state changes (7 variants) |
| enum | `DisconnectReason` | adapter.rs:225 | Why protocol task ended |
| enum | `MessageTarget` | dto.rs:37 | Text message target scope |
| enum | `PokeStrength` | poke_limiter.rs:8 | Poke notification strength |
| trait | *(re-exports)* | lib.rs:52 | `AudioData`, `CodecType`, `Direction`, `InAudioBuf`, `OutAudio`, `OutPacket` |
| fn | `ProtocolClient::generate_identity` | adapter.rs:296 | Generate fresh TS3 identity string |
| fn | `ProtocolClient::connect` | adapter.rs:304 | Dial server, wait for initial snapshot |
| fn | `ProtocolClient::snapshot` | adapter.rs:354 | Read typed server state snapshot |
| fn | `ProtocolClient::client_profile` | adapter.rs:365 | Fetch rich client profile |
| fn | `ProtocolClient::download_avatar` | adapter.rs:389 | Download avatar bytes by UID |
| fn | `ProtocolClient::download_icon` | adapter.rs:394 | Download icon bytes by ID |
| fn | `ProtocolClient::disconnect` | adapter.rs:399 | Clean disconnect |
| fn | `ProtocolClient::move_to_channel` | adapter.rs:421 | Move self to channel |
| fn | `ProtocolClient::queue_move_to_channel` | adapter.rs:442 | Fire-and-forget move |
| fn | `ProtocolClient::set_muted` | adapter.rs:458 | Update own mute state |
| fn | `ProtocolClient::voice_out` | adapter.rs:477 | Get outbound voice sender |
| fn | `ProtocolClient::snapshot_probe` | adapter.rs:485 | Get watchdog probe handle |
| fn | `ProtocolClient::take_voice_in` | adapter.rs:493 | Take inbound voice receiver |
| fn | `ProtocolClient::put_voice_in` | adapter.rs:503 | Put voice receiver back |
| fn | `ProtocolClient::take_loss_notifier` | adapter.rs:519 | Take disconnect notifier |
| fn | `ProtocolClient::take_chat_rx` | adapter.rs:525 | Take chat receiver |
| fn | `ProtocolClient::put_chat_rx` | adapter.rs:530 | Put chat receiver back |
| fn | `ProtocolClient::take_activity_rx` | adapter.rs:540 | Take activity receiver |
| fn | `ProtocolClient::put_activity_rx` | adapter.rs:545 | Put activity receiver back |
| fn | `ProtocolClient::take_delta_rx` | adapter.rs:556 | Take delta receiver |
| fn | `ProtocolClient::send_text_message` | adapter.rs:561 | Send text message |
| fn | `SnapshotProbe::probe` | adapter.rs:278 | Issue single snapshot RPC |
| fn | `PokeLimiter::new` | poke_limiter.rs:36 | Create limiter with 5-min window |
| fn | `PokeLimiter::record` | poke_limiter.rs:44 | Record poke, return strength |
| fn | `ChannelId::ROOT` | dto.rs:176 | Root channel constant |
**Dead code:** None found. All items consumed by `chanora_core`.
---
### 3. `chanora_bridge` — Flutter/Rust Bridge
Typed DTOs and commands for `flutter_rust_bridge` 2.x.
| Kind | Name | File:Line | Purpose |
|------|------|-----------|---------|
| struct | `BridgeChannel` | api.rs:404 | Channel DTO for Dart |
| struct | `BridgeClient` | api.rs:422 | Client DTO for Dart |
| struct | `BridgeClientProfile` | api.rs:445 | Rich profile DTO for Dart |
| struct | `BridgeSnapshot` | api.rs:502 | Server snapshot DTO for Dart |
| struct | `BridgeAudioStats` | api.rs:1034 | Audio engine statistics |
| struct | `BridgeAudioProcessingConfig` | api.rs:1112 | Audio processing config DTO |
| struct | `BridgeAudioProcessingStats` | api.rs:1143 | Audio processing stats DTO |
| struct | `BridgePttDescriptor` | api.rs:854 | PTT capability descriptor |
| struct | `BridgePttBinding` | api.rs:875 | PTT binding display state |
| enum | `BridgeError` | lib.rs:55 | Bridge-layer errors (7 variants) |
| enum | `BridgeTransmitMode` | api.rs:731 | Transmit mode mirror |
| enum | `BridgePttInputClass` | api.rs:843 | PTT input class |
| enum | `BridgeAudioRoute` | api.rs:1047 | Audio route class |
| enum | `BridgeIosVoiceProcessingMode` | api.rs:1064 | iOS voice processing mode |
| enum | `BridgeAudioBackend` | api.rs:1071 | Processing backend |
| enum | `BridgeVadBackend` | api.rs:1084 | VAD backend |
| enum | `BridgeEffectOwner` | api.rs:1097 | AEC/NS/AGC owner |
| fn | `bridge_init` | api.rs:220 | One-time process init (FRB init) |
| fn | `log_file_path_str` | api.rs:294 | Platform log file path |
| fn | `connect` | api.rs:601 | Connect to TS3 server |
| fn | `prefetch_server` | api.rs:636 | Warm DNS resolution |
| fn | `snapshot` | api.rs:645 | Re-fetch server snapshot |
| fn | `client_profile` | api.rs:654 | Fetch client profile |
| fn | `disconnect` | api.rs:663 | Disconnect from server |
| fn | `is_connected` | api.rs:672 | Check connection status |
| fn | `handle_route_change` | api.rs:687 | iOS route change handler |
| fn | `handle_media_services_reset_with_route` | api.rs:696 | iOS media reset handler |
| fn | `handle_interruption_began` | api.rs:703 | iOS interruption begin |
| fn | `handle_interruption_ended` | api.rs:709 | iOS interruption end |
| fn | `set_ptt` | api.rs:718 | Set PTT active state |
| fn | `voice_join` | api.rs:770 | Join voice channel |
| fn | `voice_leave` | api.rs:785 | Leave voice channel |
| fn | `set_transmit_mode` | api.rs:794 | Set transmit mode |
| fn | `get_transmit_mode` | api.rs:803 | Get transmit mode |
| fn | `set_release_tail_ms` | api.rs:814 | Set release tail |
| fn | `get_release_tail_ms` | api.rs:823 | Get release tail |
| fn | `set_hard_mute` | api.rs:832 | Engage/release hard mute |
| fn | `set_ptt_binding` | api.rs:907 | Update PTT binding |
| fn | `ptt_descriptor` | api.rs:925 | Get PTT descriptor |
| fn | `get_ptt_binding` | api.rs:941 | Get persisted PTT binding |
| fn | `move_to_channel` | api.rs:955 | Move self to channel |
| fn | `set_input_muted` | api.rs:971 | Toggle input mute |
| fn | `set_output_muted` | api.rs:983 | Toggle output mute |
| fn | `set_output_gain` | api.rs:994 | Set master output gain |
| fn | `set_client_volume` | api.rs:1006 | Set per-client volume |
| fn | `send_chat_message` | api.rs:1015 | Send text message |
| fn | `export_diagnostics` | api.rs:1392 | User-initiated diagnostic export |
**Dead code:** `publish_permission_state` is `#[cfg_attr(not(target_os = "android"), allow(dead_code))]` — intentional, only used on Android via JNI.
---
### 4. `chanora_storage` — Identity & Bookmark Storage
SQLite bookmarks + ChaCha20-Poly1305 encrypted identity file.
| Kind | Name | File:Line | Purpose |
|------|------|-----------|---------|
| struct | `IdentityFileStore` | lib.rs:176 | Encrypted identity file store |
| struct | `BookmarkRepository` | lib.rs:792 | SQLite-backed bookmark store |
| struct | `Bookmark` | lib.rs:767 | A persisted bookmark |
| struct | `PttBindingMeta` | lib.rs:117 | PTT binding metadata |
| enum | `StorageError` | lib.rs:59 | Storage errors (6 variants) |
| trait | `Crypto` | lib.rs:673 | Envelope encryption abstraction |
| const | `KEYRING_SERVICE` | lib.rs:190 | Keyring service name `"chanora"` |
| fn | `IdentityFileStore::new` | lib.rs:194 | Construct store at directory |
| fn | `IdentityFileStore::path` | lib.rs:211 | Get identity file path |
| fn | `IdentityFileStore::crypto` | lib.rs:384 | Get DekCrypto helper |
| fn | `IdentityFileStore::load` | lib.rs:390 | Read persisted identity |
| fn | `IdentityFileStore::save` | lib.rs:449 | Persist identity (encrypted) |
| fn | `IdentityFileStore::set_transmit_mode` | lib.rs:520 | Persist transmit mode |
| fn | `IdentityFileStore::get_transmit_mode` | lib.rs:528 | Read transmit mode |
| fn | `IdentityFileStore::set_release_tail_ms` | lib.rs:534 | Persist release tail |
| fn | `IdentityFileStore::get_release_tail_ms` | lib.rs:542 | Read release tail |
| fn | `IdentityFileStore::set_ptt_binding` | lib.rs:554 | Persist PTT binding |
| fn | `IdentityFileStore::get_ptt_binding` | lib.rs:568 | Read PTT binding |
| fn | `IdentityFileStore::clear` | lib.rs:579 | Remove persisted identity |
| fn | `BookmarkRepository::new` | lib.rs:801 | Open DB without encryption |
| fn | `BookmarkRepository::with_crypto` | lib.rs:807 | Open DB with password encryption |
| fn | `BookmarkRepository::encrypts_passwords` | lib.rs:858 | Check if encryption wired |
| fn | `BookmarkRepository::add` | lib.rs:865 | Insert bookmark |
| fn | `BookmarkRepository::upsert_or_add` | lib.rs:891 | Insert or update by host |
| fn | `BookmarkRepository::update` | lib.rs:935 | Replace existing bookmark |
| fn | `BookmarkRepository::delete` | lib.rs:963 | Delete bookmark by id |
| fn | `BookmarkRepository::list` | lib.rs:976 | List all bookmarks |
**Dead code:** None found.
---
### 5. `chanora_state` — Server State Mirror
Authoritative client-side mirror of server state with deterministic reducers.
| Kind | Name | File:Line | Purpose |
|------|------|-----------|---------|
| struct | `ServerState` | lib.rs:62 | Authoritative server state mirror |
| struct | `Reduction` | lib.rs:266 | Result of applying one event |
| struct | `ChannelJoinState` | channel_join.rs:53 | Channel-join reducer state |
| struct | `AuthoritativeMembership` | channel_join.rs:27 | Server-confirmed membership |
| struct | `JoinPending` | channel_join.rs:36 | Active pending join intent |
| struct | `ChannelJoinProjection` | channel_join.rs:135 | Reducer projection for UI |
| struct | `JoinOutcomeKey` | channel_join.rs:124 | Correlation key for outcomes |
| struct | `ConnectionEpoch` | channel_join.rs:15 | Per-connection epoch |
| struct | `JoinGeneration` | channel_join.rs:19 | Monotonic join generation |
| struct | `JoinRequestId` | channel_join.rs:23 | Protocol request identifier |
| struct | `ChannelId` (join) | channel_join.rs:11 | Channel identifier at reducer seam |
| enum | `ConnectionState` | lib.rs:43 | Connection lifecycle (5 variants) |
| enum | `Delta` | lib.rs:209 | State changes for bridge (8 variants) |
| enum | `StateEvent` | lib.rs:237 | Events flowing into reducer (9 variants) |
| enum | `StateError` | lib.rs:32 | State errors (2 variants) |
| enum | `ChannelJoinEvent` | channel_join.rs:165 | Channel-join events (10 variants) |
| enum | `ChannelJoinAction` | channel_join.rs:240 | Side-effect actions (7 variants) |
| enum | `ChannelJoinSyncState` | channel_join.rs:101 | Sync readiness (2 variants) |
| enum | `SyncReason` | channel_join.rs:115 | Sync reason (2 variants) |
| enum | `JoinReduceStatus` | channel_join.rs:309 | Transition status (9 variants) |
| enum | `JoinIntentRejected` | channel_join.rs:332 | Rejection reasons (2 variants) |
| enum | `JoinFailureKind` | channel_join.rs:341 | Failure kinds (5 variants) |
| enum | `JoinErrorCode` | channel_join.rs:356 | Stable error codes (11 variants) |
| enum | `JoinDiagnosticKey` | channel_join.rs:284 | Diagnostic event keys (10 variants) |
| enum | `AuthoritativeSource` | channel_join.rs:156 | Membership input source |
| fn | `ServerState::from_snapshot` | lib.rs:83 | Build from initial snapshot |
| fn | `ServerState::replace_from_snapshot` | lib.rs:114 | Replace with fresh snapshot |
| fn | `ServerState::channel` | lib.rs:119 | Look up channel by id |
| fn | `ServerState::client` | lib.rs:124 | Look up client by id |
| fn | `ServerState::channels` | lib.rs:130 | All channels iterator |
| fn | `ServerState::clients` | lib.rs:141 | All clients iterator |
| fn | `ServerState::channel_count` | lib.rs:148 | Number of channels |
| fn | `ServerState::client_count` | lib.rs:153 | Number of clients |
| fn | `ServerState::own_channel` | lib.rs:158 | Own client's channel |
| fn | `ServerState::clients_in_channel` | lib.rs:164 | Clients in specific channel |
| fn | `reduce` | lib.rs:281 | Apply StateEvent to state |
| fn | `reduce_reconnect_snapshot` | lib.rs:409 | Replace state after reconnect |
| fn | `channel_join::reduce` | channel_join.rs:393 | Channel-join event reducer |
| fn | `channel_join::project` | channel_join.rs:670 | Build channel-join projection |
| fn | `ChannelJoinState::new` | channel_join.rs:68 | Create join state for epoch |
**Dead code:** None found.
---
### 6. `chanora_audio` — Audio Subsystem
Platform capture/playback, Opus encoding, VAD, PTT, DSP.
| Kind | Name | File:Line | Purpose |
|------|------|-----------|---------|
| **Core Engine** | | | |
| struct | `AudioEngine` | engine.rs:289 | Main audio engine |
| struct | `AudioEngineConfig` | engine.rs:223 | Engine configuration |
| struct | `SessionAudioId` | engine.rs:69 | Stable audio session ID |
| struct | `AudioDeviceList` | engine.rs:87 | Available audio devices |
| struct | `AudioDeviceInfo` | engine.rs:96 | Single audio device info |
| enum | `AudioError` | lib.rs:100 | Audio subsystem errors (8 variants) |
| struct | `AudioEffects` | lib.rs:136 | AEC/AGC/NS/HPF toggles |
| fn | `list_audio_devices` | engine.rs:176 | Enumerate input/output devices |
| fn | `AudioEngine::start` | engine.rs:634 | Start audio engine |
| fn | `AudioEngine::start_with_gate` | engine.rs:647 | Start with transmit gate |
| fn | `AudioEngine::stop` | engine.rs:1358 | Stop audio engine |
| fn | `AudioEngine::set_transmit_active` | engine.rs:1601 | Set transmit state |
| fn | `AudioEngine::transmit_active` | engine.rs:1606 | Get transmit state |
| fn | `AudioEngine::set_output_muted` | engine.rs:1702 | Set output mute |
| fn | `AudioEngine::set_output_gain` | engine.rs:1714 | Set output gain |
| fn | `AudioEngine::set_client_volume` | engine.rs:1727 | Set per-client volume |
| fn | `AudioEngine::set_audio_processing_config` | engine.rs:1646 | Update processing config |
| fn | `AudioEngine::audio_processing_stats` | engine.rs:1683 | Get processing stats |
| **Frame Helpers** | | | |
| const | `SAMPLE_RATE_HZ` | frame.rs:9 | 48000 Hz |
| const | `FRAME_10MS_SAMPLES` | frame.rs:15 | 480 samples |
| const | `FRAME_20MS_SAMPLES` | frame.rs:17 | 960 samples |
| struct | `AudioFrame10ms` | frame.rs:21 | 10ms processing frame |
| struct | `AudioFrame20ms` | frame.rs:28 | 20ms network frame |
| fn | `i16_to_f32` | frame.rs:64 | PCM conversion |
| fn | `f32_to_i16` | frame.rs:69 | PCM conversion |
| fn | `dbfs` | frame.rs:74 | RMS dBFS calculation |
| **Transmit** | | | |
| enum | `TransmitMode` | transmit_mode.rs:13 | Ptt/Continuous/VoiceActivity |
| enum | `PermissionGate` | transmit_selector.rs:38 | Mic permission state |
| struct | `TransmitModeSelector` | transmit_selector.rs:88 | Multi-signal transmit selector |
| struct | `AudioTransmitGate` | ptt.rs:139 | Atomic transmit flag |
| struct | `ReleaseTailTimer` | release_tail.rs:43 | PTT release-tail timer |
| const | `DEFAULT_TAIL_MS` | release_tail.rs:24 | 200ms default |
| const | `MAX_TAIL_MS` | release_tail.rs:21 | 500ms max |
| **PTT** | | | |
| enum | `PttCapabilityLevel` | ptt.rs:34 | L0-L4 capability levels |
| struct | `PttBackendDescriptor` | ptt.rs:97 | Privacy-safe PTT descriptor |
| struct | `MissedKeyUpWatchdog` | ptt.rs:202 | PTT safety watchdog |
| trait | `DesktopPttBackend` | ptt_backends/mod.rs:162 | Platform PTT backend trait |
| struct | `PttBinding` | ptt_backends/mod.rs:48 | PTT binding metadata |
| enum | `PttInputClass` | ptt_backends/mod.rs:84 | None/Keyboard/MouseSideButton |
| enum | `PttBackendError` | ptt_backends/mod.rs:113 | PTT backend errors |
| fn | `select_ptt_backend` | ptt_backends/mod.rs:213 | Auto-select best backend |
| **Audio Processing** | | | |
| enum | `AudioRoute` | audio_processing.rs:14 | Route class (6 variants) |
| enum | `AudioBackend` | audio_processing.rs:65 | Processing backend (4 variants) |
| enum | `VadBackend` | audio_processing.rs:90 | VAD backend (4 variants) |
| enum | `EffectOwner` | audio_processing.rs:122 | Effect owner (5 variants) |
| enum | `IosVoiceProcessingMode` | audio_processing.rs:58 | iOS VPIO mode |
| struct | `AudioProcessingConfig` | audio_processing.rs:137 | Full processing config |
| struct | `AudioProcessingStats` | audio_processing.rs:270 | Processing statistics |
| struct | `SharedAudioProcessingStats` | audio_processing.rs:322 | Thread-safe stats |
| **DSP** | | | |
| struct | `Aec3` | processor/dsp/aec3.rs:48 | Acoustic echo canceller |
| struct | `Agc2` | processor/dsp/agc2.rs:206 | Automatic gain control |
| struct | `HighPassFilter` | processor/dsp/hpf.rs:42 | High-pass filter |
| struct | `NoiseSuppressor` | processor/dsp/ns.rs:40 | Noise suppressor |
| trait | `AudioProcessor` | processor/mod.rs:21 | Realtime processor trait |
| struct | `NoopProcessor` | processor/noop.rs:6 | No-op processor |
| struct | `PlatformVoiceProcessor` | processor/platform.rs:10 | Platform VPIO processor |
| struct | `SonoraProcessor` | processor/sonora.rs:88 | Sonora DSP processor |
| struct | `SonoraConfig` | processor/sonora.rs:37 | Sonora configuration |
| struct | `WebRtcApmProcessor` | processor/webrtc_apm.rs:91 | WebRTC APM processor |
| struct | `WebRtcApmConfig` | processor/webrtc_apm.rs:17 | WebRTC APM config |
| **VAD** | | | |
| trait | `VoiceActivityDetector` | vad/mod.rs:34 | VAD trait |
| struct | `VadOutput` | vad/mod.rs:26 | VAD output (probability + speech) |
| struct | `WebRtcFallbackVad` | vad/mod.rs:40 | WebRTC fallback VAD |
| struct | `Resampled16kHzVad` | vad/mod.rs:77 | 48→16kHz resampling wrapper |
| struct | `SileroOnnxVad` | vad/silero_onnx.rs:62 | Silero ONNX VAD |
| struct | `Downsampler48to16` | vad/resampler.rs:44 | 48→16kHz downsampler |
| fn | `set_silero_model_path` | vad/mod.rs:126 | Set VAD model path |
| fn | `silero_model_epoch` | vad/mod.rs:147 | Get model epoch |
| **Voice Activity** | | | |
| struct | `VoiceActivityStateMachine` | voice_activity.rs:29 | VAD gate state machine |
| **Mobile Backend** | | | |
| trait | `MobileVoiceAudioBackend` | mobile_voice_backend.rs:262 | Mobile audio backend trait |
| struct | `AndroidVoiceStreamConfig` | mobile_voice_backend.rs:194 | Android stream config |
| struct | `AndroidAudioDiagnostics` | mobile_voice_backend.rs:499 | Android diagnostics |
| enum | `BackendEvent` | mobile_voice_backend.rs:35 | Backend events |
| enum | `BackendError` | mobile_voice_backend.rs:154 | Backend errors |
| enum | `AchievedPerformanceMode` | mobile_voice_backend.rs:112 | Performance mode |
| enum | `LatencyTier` | mobile_voice_backend.rs:377 | Latency tier |
| struct | `AndroidVoiceUnit` | android_voice_unit.rs:565 | Android voice unit |
| struct | `IosVoiceUnit` | ios_voice_unit.rs:522 | iOS voice unit |
| **Route Policy** | | | |
| fn | `ios_route_policy` | route_policy.rs:27 | Route→config policy for iOS |
| fn | `apply_route_change` | route_policy.rs:105 | Apply route change |
| **Mode Stack** | | | |
| struct | `ModeStack` | mode_stack.rs:88 | Android audio mode refcount |
| enum | `ModeAcquire` | mode_stack.rs:41 | Acquire result |
| enum | `ModeRelease` | mode_stack.rs:62 | Release result |
| **Debug** | | | |
| struct | `WavDebugRecorder` | debug_wav.rs:68 | Debug WAV recorder |
**Dead code:** `AndroidVoiceUnit`, `IosVoiceUnit`, and platform-specific backends are `#[cfg]`-gated — intentional.
---
### 7. `chanora_resolver` — DNS/SRV/TSDNS Resolver
TeamSpeak address resolution: SRV, TSDNS, nick lookup.
| Kind | Name | File:Line | Purpose |
|------|------|-----------|---------|
| struct | `ChanoraResolver` | lib.rs:108 | Main resolver |
| struct | `Args` | lib.rs:26 | Resolution arguments |
| struct | `BuildInfo` | lib.rs:33 | Build metadata |
| struct | `SrvRecord` | lib.rs:40 | SRV record |
| struct | `ClientResolution` | lib.rs:58 | Client resolution result |
| enum | `Resolution` | lib.rs:85 | Resolution result (Dns/Srv/Nick) |
| enum | `ClientResolutionMethod` | lib.rs:48 | Resolution method (6 variants) |
| const | `DEFAULT_TEAMSPEAK_PORT` | lib.rs:23 | Port 9987 |
| fn | `build_info` | lib.rs:123 | Get build info |
| fn | `setup_log` | lib.rs:137 | Setup logging |
| fn | `ChanoraResolver::new` | lib.rs:157 | Create resolver |
| fn | `ChanoraResolver::resolve` | lib.rs:178 | Resolve with Args |
| fn | `ChanoraResolver::resolve_connection_address` | lib.rs:193 | Resolve to connection address |
| fn | `ChanoraResolver::resolve_client_address` | lib.rs:197 | Resolve client input to address |
| fn | `ChanoraResolver::resolve_client_request` | lib.rs:201 | Resolve with full metadata |
| fn | `ChanoraResolver::resolve_dns` | lib.rs:594 | DNS lookup |
| fn | `ChanoraResolver::resolve_ts3` | lib.rs:614 | TS3 SRV lookup |
| fn | `ChanoraResolver::resolve_tsdns` | lib.rs:619 | TSDNS SRV lookup |
| fn | `ChanoraResolver::resolve_nick` | lib.rs:624 | Nick lookup |
| fn | `normalize_args` | lib.rs:778 | Normalize Args |
| fn | `validate_args` | lib.rs:785 | Validate Args |
| fn | `run` | lib.rs:804 | CLI entry point |
**Dead code:** `run()` is a CLI entry point, not called from library code — intentional.
---
### 8. `chanora_prefetch` — Server Address Prefetch
Speculative DNS warming for faster connects.
| Kind | Name | File:Line | Purpose |
|------|------|-----------|---------|
| struct | `ServerPrefetcher` | lib.rs:83 | Prefetch cache + async resolver |
| enum | `ServerPrefetchError` | lib.rs:18 | Prefetch errors |
| fn | `ServerPrefetcher::new` | lib.rs:90 | Create prefetcher |
| fn | `ServerPrefetcher::prefetch` | lib.rs:99 | Schedule fire-and-forget prefetch |
| fn | `ServerPrefetcher::fresh_match` | lib.rs:145 | Check for cached result |
**Dead code:** None found.
---
### 9. `chanora_diagnostics` — Redaction & Diagnostic Export
Redaction policy, in-memory log sink, PTT sanitizer.
| Kind | Name | File:Line | Purpose |
|------|------|-----------|---------|
| struct | `Redactor` | lib.rs:121 | Production redaction policy |
| struct | `KnownSecretRegistry` | lib.rs:79 | Secret substring registry |
| struct | `InMemoryLogSink` | lib.rs:356 | Bounded redacted log sink |
| struct | `RedactingLogLayer` | lib.rs:440 | tracing Layer for redaction |
| struct | `PttSanitizer` | lib.rs:505 | PTT field ban Layer |
| struct | `DiagnosticExport` | lib.rs:614 | Export bundle |
| struct | `ProtocolEventRecorder` | lib.rs:714 | Protocol event ring buffer |
| enum | `DiagnosticsError` | lib.rs:51 | Diagnostics errors |
| const | `REDACTION_MARKER` | lib.rs:62 | `"[REDACTED]"` |
| const | `DEFAULT_LOG_CAPACITY` | lib.rs:67/70 | 256 (release) / 4096 (debug) |
| fn | `Redactor::with_default_policy` | lib.rs:128 | Create redactor |
| fn | `Redactor::with_secrets` | lib.rs:134 | Create with secret registry |
| fn | `Redactor::secrets` | lib.rs:140 | Access secret registry |
| fn | `Redactor::redact` | lib.rs:150 | Apply redaction policy |
| fn | `KnownSecretRegistry::register` | lib.rs:85 | Register secret |
| fn | `KnownSecretRegistry::len` | lib.rs:99 | Count secrets |
| fn | `KnownSecretRegistry::is_empty` | lib.rs:104 | Check empty |
| fn | `KnownSecretRegistry::contains_substr` | lib.rs:110 | Substring check |
| fn | `InMemoryLogSink::new` | lib.rs:365 | Create sink |
| fn | `InMemoryLogSink::snapshot` | lib.rs:377 | Snapshot lines |
| fn | `InMemoryLogSink::push` | lib.rs:386 | Push redacted line |
| fn | `InMemoryLogSink::redactor` | lib.rs:397 | Access redactor |
| fn | `RedactingLogLayer::new` | lib.rs:446 | Create layer |
| fn | `RedactingLogLayer::with_sanitizer` | lib.rs:452 | Wrap with PTT sanitizer |
| fn | `PttSanitizer::wrap` | lib.rs:513 | Wrap inner layer |
| fn | `DiagnosticExport::from_sink` | lib.rs:636 | Build export |
| fn | `DiagnosticExport::with_android_audio` | lib.rs:655 | Attach Android audio YAML |
| fn | `DiagnosticExport::with_network_info` | lib.rs:661 | Attach network info |
| fn | `DiagnosticExport::with_protocol_events` | lib.rs:667 | Attach protocol events |
| fn | `DiagnosticExport::to_text` | lib.rs:674 | Render as plaintext |
| fn | `ProtocolEventRecorder::new` | lib.rs:721 | Create recorder |
| fn | `ProtocolEventRecorder::record_connected` | lib.rs:740 | Record connection |
| fn | `ProtocolEventRecorder::record_disconnected` | lib.rs:745 | Record disconnect |
| fn | `ProtocolEventRecorder::record_reconnecting` | lib.rs:750 | Record reconnect |
| fn | `ProtocolEventRecorder::record_snapshot_changed` | lib.rs:759 | Record snapshot change |
| fn | `ProtocolEventRecorder::record_channel_join` | lib.rs:768 | Record channel join |
| fn | `ProtocolEventRecorder::record_lifecycle` | lib.rs:777 | Record lifecycle |
| fn | `ProtocolEventRecorder::drain` | lib.rs:782 | Drain all events |
| fn | `ProtocolEventRecorder::snapshot` | lib.rs:787 | Snapshot events |
**Dead code:** None found.
---
### 10. `chanora_core` — Top-Level Orchestration
Integration point composing all subsystems behind a stable API.
| Kind | Name | File:Line | Purpose |
|------|------|-----------|---------|
| struct | `ChanoraSession` | lib.rs:191 | Process-wide session handle |
| enum | `CoreError` | lib.rs:84 | Top-level errors (12 variants) |
| struct | `PttDescriptorSnapshot` | events.rs:6 | PTT descriptor snapshot |
| struct | `PersistedPttBinding` | events.rs:27 | Persisted PTT binding |
| struct | `PttController` | ptt.rs:68 | PTT controller |
| struct | `FileTransferService` | file_transfer.rs:39 | File transfer service |
| enum | `SessionEvent` | events.rs:49 | Session lifecycle events |
| enum | `VoiceJoinSyncState` | events.rs:239 | Voice join sync state |
| enum | `VoiceJoinErrorCode` | events.rs:250 | Voice join error codes |
| enum | `NetworkState` | events.rs:280 | Network connectivity state |
| enum | `FileTransferError` | file_transfer.rs:17 | File transfer errors |
| enum | `PttControllerError` | ptt.rs:35 | PTT controller errors |
| fn | `ChanoraSession::new` | lib.rs:245 | Create session |
| fn | `ChanoraSession::subscribe_events` | lib.rs:478 | Subscribe to session events |
| fn | `ChanoraSession::set_network_state` | lib.rs:460 | Set network state |
| fn | `ChanoraSession::network_state` | lib.rs:469 | Get network state |
| fn | `ChanoraSession::transmit_mode` | lib.rs:1568 | Get transmit mode |
| fn | `ChanoraSession::hard_mute` | lib.rs:1591 | Get hard mute state |
| fn | `ChanoraSession::release_tail_ms` | lib.rs:1645 | Get release tail |
| fn | `ChanoraSession::transmit_selector` | lib.rs:1652 | Get transmit selector |
| fn | `ChanoraSession::release_tail_timer` | lib.rs:1659 | Get release tail timer |
| fn | `ChanoraSession::audio_processing_stats_if_ready` | lib.rs:1205 | Get audio stats |
| fn | `PttController::new` | ptt.rs:103 | Create PTT controller |
| fn | `PttController::current_capability` | ptt.rs:226 | Get PTT capability |
| fn | `PttController::subscribe_capability` | ptt.rs:233 | Subscribe to capability |
| fn | `PttController::descriptor_watch` | ptt.rs:250 | Watch PTT descriptor |
| fn | `PttController::press_gate` | ptt.rs:257 | Get press gate |
| fn | `PttController::release_tail` | ptt.rs:263 | Get release tail |
**Dead code:** None found. All items consumed by `chanora_bridge`.
---
## Dart Files (apps/chanora_flutter/lib/)
### Widgets (31 files)
| Class | File:Line | Purpose |
|-------|-----------|---------|
| `AppSnackBar` | widgets/app_snack_bar.dart:9 | Snackbar notifications |
| `AppSnackBarVariant` | widgets/app_snack_bar.dart:6 | Neutral/success/warning/error |
| `AudioDebugStatsPanel` | widgets/audio_debug_stats_panel.dart:22 | Audio stats debug panel |
| `AudioDeviceListTile` | widgets/audio_device_list_tile.dart:21 | Audio device list item |
| `AudioDeviceKind` | widgets/audio_device_list_tile.dart:12 | Input/Output device kind |
| `AudioOutputTile` | widgets/audio_output_tile.dart:15 | Audio output route picker |
| `AudioProcessingConfigState` | widgets/audio_processing_config_state.dart:34 | Processing config state |
| `BbCodeText` | widgets/bbcode_text.dart:47 | BBCode renderer |
| `ChatPanel` | widgets/chat_panel.dart:13 | Chat panel container |
| `ChatEntry` | widgets/chat_views.dart:25 | Chat message entry |
| `ChatClientGroups` | widgets/chat_views.dart:374 | Client grouping for chat |
| `ChatPage` | widgets/chat_views.dart:548 | Full chat page |
| `ChatDetailView` | widgets/chat_views.dart:1070 | Chat detail view |
| `ClientInfoSheet` | widgets/client_info_sheet.dart:7 | Client info bottom sheet |
| `ConnectForm` | widgets/connect_widgets.dart:9 | Server connect form |
| `BookmarkList` | widgets/connect_widgets.dart:154 | Bookmark list |
| `CapturedBinding` | widgets/input_dialogs.dart:50 | PTT binding capture result |
| `BookmarkNameDialog` | widgets/input_dialogs.dart:61 | Bookmark name input |
| `ChannelPasswordDialog` | widgets/input_dialogs.dart:109 | Channel password input |
| `PttBindingCaptureDialog` | widgets/input_dialogs.dart:154 | PTT key binding dialog |
| `PermissionStateBanner` | widgets/permission_state_banner.dart:28 | Permission state banner |
| `PokeNotificationSettingsDialog` | widgets/poke_notification_settings.dart:7 | Poke notification settings |
| `PttCapabilityBadge` | widgets/ptt_capability_badge.dart:14 | PTT capability badge |
| `SnapshotView` | widgets/snapshot_view.dart:14 | Server tree view |
| `TalkPowerWarning` | widgets/talk_power_warning.dart:14 | Talk power warning |
| `VoiceBar` | widgets/voice_bar.dart:18 | Voice status bar |
| `VoiceStatusChip` | widgets/voice_compact.dart:46 | Voice status chip |
| `VoicePttButton` | widgets/voice_compact.dart:255 | PTT button widget |
| `VoiceLevelMeter` | widgets/voice_level_meter.dart:11 | Voice level meter |
| `VoiceSettingsDialog` | widgets/voice_settings.dart:61 | Voice settings dialog |
| `VoiceSettingsResult` | widgets/voice_settings.dart:46 | Settings result |
| `VoiceStatusSummary` | widgets/voice_status_summary.dart:5 | Voice status summary |
| `VoiceSubHeader` | widgets/voice_settings_controls.dart:117 | Voice sub-header |
| `VoiceSectionHeader` | widgets/voice_settings_controls.dart:141 | Voice section header |
| `AudioProcessingToggleRow` | widgets/voice_settings_controls.dart:159 | Processing toggle row |
### Services (20 files)
| Class/Function | File:Line | Purpose |
|----------------|-----------|---------|
| `AndroidAudioOutputDevice` | services/android_audio_output_devices.dart:1 | Android audio device |
| `AndroidPermissionsService` | services/android_permissions_service.dart:34 | Android permission handler |
| `AppBootstrap` | services/app_bootstrap.dart:95 | App bootstrap helpers |
| `AudioLifecycleService` | services/audio_lifecycle_service.dart:46 | Audio lifecycle wiring |
| `BackIntentPolicy` | services/back_intent_policy.dart | Back intent policy |
| `BackIntentService` | services/back_intent_service.dart:97 | Back intent handler |
| `ChannelJoinErrorMapper` | services/channel_join_error_mapper.dart:5 | Error message mapper |
| `ChannelSpacer` | services/channel_spacer.dart:110 | Spacer channel detection |
| `ConnectionPhaseState` | services/connection_phase_state.dart:38 | Connection phase state |
| `HardMuteOwners` | services/hard_mute_owners.dart | Hard mute owners |
| `IosAudioSessionController` | services/ios_audio_session_controller.dart | iOS audio session |
| `IosPermissionsService` | services/ios_permissions_service.dart:66 | iOS permission handler |
| `LinkTrustService` | services/link_trust_service.dart:29 | Link trust checker |
| `MacosPermissionsService` | services/macos_permissions_service.dart:273 | macOS permission handler |
| `PokePreferencesService` | services/poke_preferences_service.dart:44 | Poke mute preferences |
| `PokeNotificationService` | services/poke_notification_service.dart | Poke notification handler |
| `PrefetchDebouncer` | services/prefetch_debouncer.dart:15 | DNS prefetch debouncer |
| `OwnClientSnapshotState` | services/snapshot_state_mapper.dart:3 | Snapshot→state mapper |
| `ownClientSnapshotState()` | services/snapshot_state_mapper.dart:23 | Build snapshot state |
| `snapshotChannelName()` | services/snapshot_state_mapper.dart:43 | Get channel name from snapshot |
| `snapshotNeededTalkPower()` | services/snapshot_state_mapper.dart:48 | Get required talk power |
| `Ts3ServerLink` | services/ts3_server_link.dart:83 | TS3 server link parser |
| `UiPreferencesService` | services/ui_preferences_service.dart | UI preferences |
| `VoiceJoinOrdering` | services/voice_join_ordering.dart | Voice join ordering |
### Design (4 files)
| Class | File:Line | Purpose |
|-------|-----------|---------|
| `ChanoraTokens` | design/chanora_tokens.dart | Design tokens |
| `Breakpoints` | design/breakpoints.dart | Responsive breakpoints |
| `ViewportInfo` | design/viewport_info.dart | Viewport info |
| `PlatformCapabilities` | design/platform_capabilities.dart | Platform capabilities |
---
## Dead Code Analysis
### Confirmed Dead Code
None found. All public items are consumed by downstream crates or are intentionally platform-gated.
### Platform-Gated (Intentional)
- `AndroidVoiceUnit`, `IosVoiceUnit` — only compiled on target platforms
- `chanora_android_*` JNI functions — Android only
- `ios_voice_unit.rs`, `android_voice_unit.rs` — platform-specific
- `sdl_output.rs` — Linux only
### TODO/FIXME Items (15 total)
| File | Line | Note |
|------|------|------|
| `chanora_audio/src/audio_event_queue.rs` | 27 | Wire to client disconnect path |
| `chanora_audio/src/engine.rs` | 2348 | Realtime audio callback concern |
| `chanora_audio/src/mobile_voice_backend.rs` | 16 | Back-fill IosVoiceUnit to trait |
| `audio_lifecycle_service.dart` | 151 | Wire macOS default device change |
| `audio_lifecycle_service.dart` | 156 | macOS device change no action yet |
| `poke_notification_service.dart` | 33,35,41,43,48,130,132,142,155,168 | Future EventSoundService (10 items) |
### Useless Code
- No empty impls found
- No commented-out function bodies found
- No dead trait implementations found
---
## Architecture Notes
- **Boundary discipline**: `tsclientlib` types never cross `chanora_protocol` boundary (SAD-067)
- **Single connection**: DEC-006 enforces one connection at runtime
- **Secret isolation**: `chanora_storage` never stores secrets in plaintext DB
- **Deterministic reducers**: `chanora_state` reducers are pure functions (SRS-056)
- **PTT privacy**: Raw key codes never appear in logs or diagnostics (DEC-027)
- **Audio pipeline**: 48kHz mono, 20ms Opus frames, 10ms processing frames
@@ -0,0 +1,252 @@
# Link Coverage Report
**Generated:** 2026-06-13
**Scope:** All `.md` files in repository root and `docs/` tree
## Summary
- Total links checked: 148
- Valid internal links: 12 (4 markdown links + 8 inline doc-path references)
- Broken internal links: 2
- Valid inline doc-path references: 94
- Broken inline doc-path references: 5
- Valid code references: 62
- Broken code references: 2
- External links (manual review): 48
- Cross-references (doc→doc in prose): 0 broken
---
## Broken Internal Links
Markdown `[text](path)` style links that resolve to missing files.
| File | Line | Link Text | Target | Issue |
|------|------|-----------|--------|-------|
| README.md | 428 | `LICENSE-APACHE` | `LICENSE-APACHE` | File does not exist at repo root |
| README.md | 431 | `LICENSE-MIT` | `LICENSE-MIT` | File does not exist at repo root |
**Impact:** Users clicking the license links in the README will get a 404 on GitHub. These are referenced in the License section as the dual-license model files.
**Also affected by missing LICENSE files:**
| File | Line | Reference | Issue |
|------|------|-----------|-------|
| docs/security/license-inventory.md | 9 | `../../LICENSE-APACHE` | Resolves to missing `LICENSE-APACHE` at repo root |
| docs/security/license-inventory.md | 10 | `../../LICENSE-MIT` | Resolves to missing `LICENSE-MIT` at repo root |
| docs/security/flutter-license-inventory.md | 11 | `../../LICENSE-APACHE` | Resolves to missing `LICENSE-APACHE` at repo root |
| docs/security/flutter-license-inventory.md | 11 | `../../LICENSE-MIT` | Resolves to missing `LICENSE-MIT` at repo root |
---
## Valid Internal Links
| File | Line | Target |
|------|------|--------|
| README.md | 130 | `docs/architecture/desktop-ptt-architecture.md` |
| README.md | 436 | `docs/governance/product-decision-register.md` |
| README.md | 444 | `NOTICE` |
| docs/superpowers/specs/2026-06-05-adaptive-3-panel-layout-design.md | 266 | `../ui-ux/adaptive-layout-platform-guide.md` |
---
## Inline Doc-Path References
References to documentation files using backtick-quoted paths (not markdown links).
### Valid
| File | Line | Reference |
|------|------|-----------|
| CONTRIBUTING.md | 25 | `docs/governance/git-commit-message-convention.md` |
| README.md | 144 | `docs/governance/product-decision-register.md` |
| README.md | 261271 | `docs/requirements/sysrs.md`, `docs/requirements/srs.md`, `docs/architecture/sysdes.md`, `docs/architecture/sad.md`, `docs/architecture/sdd.md`, `docs/verification/verification-master-plan.md`, `docs/release/release-readiness-go-nogo-record.md`, `docs/release/platform-release-policy.md`, `docs/governance/product-decision-register.md`, `docs/governance/traceability-matrix.md`, `docs/security/security-privacy-legal-guideline.md` |
| README.md | 312 | `docs/release/release-readiness-go-nogo-record.md` |
| README.md | 349355 | `docs/security/threat-model.md`, `docs/security/secure-storage-audit-report.md`, `docs/security/diagnostic-redaction-audit-report.md`, `docs/security/dependency-and-supply-chain-report.md`, `docs/privacy/privacy-policy.md`, `docs/legal/trademark-and-attribution-review.md` |
| README.md | 391 | `docs/governance/git-commit-message-convention.md` |
| README.md | 449451 | `docs/governance/product-decision-register.md`, `docs/security/dependency-and-supply-chain-report.md`, `docs/legal/trademark-and-attribution-review.md` |
| docs/architecture/sad.md | 6 | `docs/srs.md` |
| docs/architecture/sad.md | 7 | `docs/sysdes.md` |
| docs/architecture/sad.md | 176 | `docs/governance/traceability-matrix.md` |
| docs/architecture/sdd.md | 6 | `docs/architecture/sad.md` |
| docs/architecture/sdd.md | 7 | `docs/srs.md` |
| docs/architecture/sysdes.md | 6 | `docs/sysdes.md` (canonical pointer) |
| docs/architecture/desktop-ptt-architecture.md | 5 | `docs/architecture/sad.md`, `docs/architecture/sdd.md`, `docs/release/dv-waiver-register.md` |
| docs/architecture/file-transfer-design.md | 6 | `docs/architecture/sad.md` |
| docs/architecture/file-transfer-research.md | 5 | `docs/architecture/file-transfer-design.md` |
| docs/architecture/file-transfer-implementation-plan.md | 6 | `docs/architecture/file-transfer-design.md`, `docs/architecture/file-transfer-research.md` |
| docs/requirements/sysrs.md | 4 | `../sysrs.md` (canonical pointer) |
| docs/requirements/srs.md | 4 | `../srs.md` (canonical pointer) |
| docs/governance/document-index.md | 1432 | All listed document paths |
| docs/material3-guideline.md | 10 | `docs/ui-ux/material3-guideline.md` (self-referencing path record) |
| docs/ui-ux/material3-guideline.md | 6 | `docs/material3-guideline.md` (canonical pointer) |
| docs/superpowers/specs/2026-06-08-maintainability-continuation-design.md | 125141 | Multiple `docs/` paths |
| docs/superpowers/specs/2026-05-29-state-sync-ui-settings-validation-design.md | 5155 | Multiple `docs/` paths |
| docs/superpowers/plans/2026-05-29-finish-dv-document-tree.md | 1654 | Multiple `docs/` paths |
| docs/superpowers/plans/2026-05-29-swe2-swe3-baselines.md | 1635 | Multiple `docs/` paths |
| docs/superpowers/plans/2026-05-29-state-sync-ui-settings-validation.md | 8488 | Multiple `docs/` paths |
| docs/superpowers/plans/2026-05-29-dv-evidence-pack.md | 1654 | Multiple `docs/` paths |
| docs/superpowers/plans/2026-05-28-server-resolution-prefetch.md | 31836 | Multiple source file paths |
| docs/superpowers/plans/2026-05-28-chanora-server-prefetch-crate.md | 15541 | Multiple source file paths |
| docs/superpowers/plans/2026-06-06-chat-panel-switching.md | 58507 | Multiple source file paths |
| docs/superpowers/plans/2026-06-08-core-internal-split.md | 1691 | Multiple source file paths |
### Broken
| File | Line | Reference | Issue |
|------|------|-----------|-------|
| docs/sysrs.md | 126 | `docs/chanora_SysDes.md` | Does not exist (listed as "potential downstream file name") |
| docs/sysrs.md | 127 | `docs/chanora_SRS.md` | Does not exist (listed as "potential downstream file name") |
| docs/sysrs.md | 128 | `docs/chanora_SAD.md` | Does not exist (listed as "potential downstream file name") |
| docs/sysrs.md | 129 | `docs/chanora_SDD.md` | Does not exist (listed as "potential downstream file name") |
| docs/sysrs.md | 130 | `docs/chanora_Verification.md` | Does not exist (listed as "potential downstream file name") |
**Note:** These five are documented as "Potential downstream file names" in a table and are aspirational/historical. They are presented as code blocks in the original, so they function as suggestions rather than navigable links. Low severity.
---
## Code References
### Valid
| File | Line | Reference | Found At |
|------|------|-----------|----------|
| docs/architecture/sad.md | 41 | `apps/chanora_flutter/lib/main.dart` | EXISTS |
| docs/architecture/sad.md | 42 | `apps/chanora_flutter/lib/services/` | EXISTS |
| docs/architecture/sad.md | 43 | `apps/chanora_flutter/lib/widgets/` | EXISTS |
| docs/architecture/sad.md | 44 | `crates/chanora_bridge`, `apps/chanora_flutter/lib/src/rust/` | EXISTS |
| docs/architecture/sad.md | 45 | `core/chanora_core` | EXISTS |
| docs/architecture/sad.md | 46 | `crates/chanora_protocol` | EXISTS |
| docs/architecture/sad.md | 47 | `crates/chanora_state` | EXISTS |
| docs/architecture/sad.md | 48 | `crates/chanora_audio` | EXISTS |
| docs/architecture/sad.md | 49 | `crates/chanora_storage` | EXISTS |
| docs/architecture/sad.md | 50 | `crates/chanora_diagnostics` | EXISTS |
| docs/architecture/sad.md | 51 | `crates/chanora_resolver` | EXISTS |
| docs/architecture/sad.md | 52 | `crates/chanora_prefetch`, Flutter `prefetch_debouncer.dart` | EXISTS |
| docs/architecture/sdd.md | 17 | `apps/chanora_flutter/lib/services/app_bootstrap.dart`, `main.dart` | EXISTS |
| docs/architecture/sdd.md | 18 | `apps/chanora_flutter/lib/widgets/connect_widgets.dart` | EXISTS |
| docs/architecture/sdd.md | 19 | `snapshot_view.dart`, `snapshot_state_mapper.dart`, `channel_spacer.dart` | EXISTS (in services/) |
| docs/architecture/sdd.md | 20 | `chat_views.dart`, `bbcode_text.dart` | EXISTS |
| docs/architecture/sdd.md | 21 | `voice_bar.dart`, `voice_compact.dart`, `voice_settings*.dart`, `voice_level_meter.dart`, `ptt_capability_badge.dart` | EXISTS |
| docs/architecture/sdd.md | 22 | `android_permissions_service.dart`, `ios_permissions_service.dart`, `audio_lifecycle_service.dart`, `back_intent_*`, `link_trust_service.dart` | EXISTS |
| docs/architecture/sdd.md | 23 | `crates/chanora_bridge/src/api.rs` | EXISTS |
| docs/architecture/sdd.md | 24 | `core/chanora_core/src/lib.rs`, `events.rs`, `network_diagnostics.rs`, `ptt.rs` | EXISTS |
| docs/architecture/sdd.md | 25 | `crates/chanora_protocol/src/` | EXISTS |
| docs/architecture/sdd.md | 26 | `crates/chanora_state/src/lib.rs`, `channel_join.rs` | EXISTS |
| docs/architecture/sdd.md | 27 | `crates/chanora_audio/src/` | EXISTS |
| docs/architecture/sdd.md | 28 | `crates/chanora_storage/src/lib.rs` | EXISTS |
| docs/architecture/sdd.md | 29 | `crates/chanora_diagnostics/src/lib.rs` | EXISTS |
| docs/architecture/sdd.md | 30 | `crates/chanora_resolver/src/lib.rs`, `crates/chanora_prefetch/src/lib.rs`, `prefetch_debouncer.dart` | EXISTS |
| docs/architecture/sdd.md | 31 | `.github/workflows/`, `tools/` | EXISTS |
| docs/architecture/sdd.md | 35 | `crates/chanora_bridge/src/api.rs`, `apps/chanora_flutter/lib/src/rust/` | EXISTS |
| docs/release/release-readiness-go-nogo-record.md | 26 | `apps/chanora_flutter/pubspec.yaml` | EXISTS |
| docs/implementation-status-2026-05-28.md | 69 | `apps/chanora_flutter/ios/Runner/AppDelegate.swift` | EXISTS |
| docs/sysrs.md | 503 | `apps/chanora_flutter/ios/Runner/AppDelegate.swift` | EXISTS |
| docs/sysrs.md | 1962 | `apps/chanora_flutter/macos/chanora_bridge.podspec` | EXISTS |
| README.md | 236249 | `apps/chanora_flutter/`, `core/chanora_core/`, `crates/chanora_protocol/`, `crates/chanora_audio/`, `crates/chanora_state/`, `crates/chanora_storage/`, `crates/chanora_diagnostics/`, `crates/chanora_bridge/` | EXISTS |
### Broken
| File | Line | Reference | Issue |
|------|------|-----------|-------|
| docs/architecture/sdd.md | 19 | `snapshot_state_mapper.dart` (listed under "Snapshot and channel UI" widgets) | File is in `apps/chanora_flutter/lib/services/`, not `apps/chanora_flutter/lib/widgets/` — directory mismatch |
| docs/architecture/sdd.md | 21 | `voice_settings*.dart` (listed under Voice UI widgets) | Files are `voice_settings.dart` and `voice_settings_controls.dart` in `widgets/` — EXISTS but glob reference is ambiguous (two files match) |
**Note:** The `snapshot_state_mapper.dart` directory mismatch is a minor documentation inaccuracy — the file exists but is listed under the wrong component section (widget layer vs service layer).
---
## External Links (Manual Review)
These URLs should be checked manually for validity.
| File | Line | URL |
|------|------|-----|
| README.md | 429 | `https://www.apache.org/licenses/LICENSE-2.0` |
| README.md | 432 | `https://opensource.org/licenses/MIT` |
| apps/chanora_flutter/README.md | 11 | `https://docs.flutter.dev/get-started/learn-flutter` |
| apps/chanora_flutter/README.md | 12 | `https://docs.flutter.dev/get-started/codelab` |
| apps/chanora_flutter/README.md | 13 | `https://docs.flutter.dev/reference/learning-resources` |
| apps/chanora_flutter/README.md | 16 | `https://docs.flutter.dev/` |
| silero-coreml/README.md | 343 | `https://apple.github.io/coremltools/docs-guides/source/introductory-quickstart.html` |
| silero-coreml/README.md | 350 | `https://apple.github.io/coremltools/docs-guides/source/convert-pytorch.html` |
| silero-coreml/Docs/CoreMLConversion.md | 244 | `https://apple.github.io/coremltools/docs-guides/source/convert-pytorch.html` |
| silero-coreml/Docs/CoreMLConversion.md | 252 | `https://apple.github.io/coremltools/docs-guides/source/introductory-quickstart.html` |
| docs/security/dependency-and-supply-chain-report.md | 29 | `https://github.com/EdisonJwa/oboe-rs` |
| docs/superpowers/specs/2026-06-05-adaptive-3-panel-layout-design.md | 261 | `https://github.com/asportnoy/compact-discord` |
| docs/superpowers/specs/2026-06-05-adaptive-3-panel-layout-design.md | 262 | `https://github.com/mattermost/mattermost/blob/...` |
| docs/superpowers/specs/2026-06-05-adaptive-3-panel-layout-design.md | 263 | `https://github.com/RocketChat/fuselage/blob/...` |
| docs/superpowers/specs/2026-06-05-adaptive-3-panel-layout-design.md | 264 | `https://github.com/flutter/flutter/issues/162965` |
| docs/superpowers/specs/2026-06-05-adaptive-3-panel-layout-design.md | 265 | `https://m3.material.io/foundations/layout/breakpoints/overview` |
| docs/architecture/file-transfer-research.md | 29 | `https://github.com/Splamy/TS3AudioBot/blob/...` |
| docs/architecture/file-transfer-research.md | 30 | `https://github.com/Multivit4min/TS3-NodeJS-Library/blob/...` |
| docs/architecture/file-transfer-research.md | 31 | `https://github.com/planetteamspeak/ts3phpframework/blob/...` |
| docs/architecture/file-transfer-research.md | 49 | `https://github.com/Multivit4min/TS3-NodeJS-Library/blob/...` |
| docs/architecture/file-transfer-research.md | 50 | `https://github.com/planetteamspeak/ts3phpframework/blob/...` |
| docs/architecture/file-transfer-research.md | 123 | `https://github.com/ReSpeak/Qint/blob/...` |
| docs/architecture/file-transfer-research.md | 124 | `https://github.com/ReSpeak/Qint/blob/...` |
| docs/architecture/file-transfer-research.md | 125 | `https://github.com/ReSpeak/Qint/blob/...` |
| docs/architecture/file-transfer-research.md | 140 | `https://github.com/teamspeak/ts3client-pluginsdk/blob/...` |
| docs/architecture/file-transfer-research.md | 141 | `https://github.com/teamspeak/ts3client-pluginsdk/blob/...` |
| docs/architecture/file-transfer-research.md | 142 | `https://community.teamspeak.com/t/clear-cache/41511` |
| docs/architecture/file-transfer-research.md | 142 | `https://community.teamspeak.com/t/server-icons-are-displaying-a-broken-image-issues-with-local-cache/58680` |
| docs/architecture/file-transfer-research.md | 208 | `https://github.com/Splamy/TS3AudioBot/blob/...` |
| docs/architecture/file-transfer-research.md | 209 | `https://github.com/Splamy/TS3AudioBot/blob/...` |
| docs/architecture/file-transfer-research.md | 220 | `https://github.com/Multivit4min/TS3-NodeJS-Library/blob/...` |
| docs/architecture/file-transfer-research.md | 221 | `https://github.com/Multivit4min/TS3-NodeJS-Library/blob/...` |
| docs/architecture/file-transfer-research.md | 320 | `https://github.com/rust-lang/rust/blob/...` |
| docs/architecture/file-transfer-research.md | 321 | `https://source.android.com/docs/core/storage/scoped` |
| docs/architecture/file-transfer-research.md | 322 | `https://developer.apple.com/library/archive/documentation/FileManagement/...` |
| docs/architecture/file-transfer-research.md | 334 | `https://github.com/zkat/cacache-rs/blob/...` |
| docs/architecture/file-transfer-research.md | 335 | `https://github.com/zkat/cacache-rs/blob/...` |
| docs/architecture/file-transfer-research.md | 336 | `https://github.com/zkat/cacache-rs/blob/...` |
| docs/architecture/file-transfer-research.md | 345 | `https://pub.dev/packages/flutter_cache_manager` |
| docs/architecture/file-transfer-research.md | 346 | `https://pub.dev/packages/super_cache_disk/versions/1.0.0` |
| docs/architecture/file-transfer-research.md | 406 | `https://git.did.science/TeaSpeak/Server/Server` |
| docs/security/license-inventory.md | 3180 | ~50 URLs to GitHub repos for dependency licenses |
| docs/security/flutter-license-inventory.md | 6244209 | Multiple `http://www.apache.org/licenses/` and `http://mozilla.org/MPL/2.0/` (in license text bodies) |
---
## Cross-References
### Valid
All doc-to-doc cross-references found in prose text resolve to existing files. Key verified chains:
| Source | Reference | Target Exists |
|--------|-----------|---------------|
| docs/architecture/sad.md:6 | `docs/srs.md` | YES |
| docs/architecture/sad.md:7 | `docs/sysdes.md` | YES |
| docs/architecture/sdd.md:6 | `docs/architecture/sad.md` | YES |
| docs/architecture/sdd.md:7 | `docs/srs.md` | YES |
| docs/architecture/sysdes.md:6 | `docs/sysdes.md` | YES |
| docs/architecture/file-transfer-design.md:6 | `docs/architecture/sad.md` | YES |
| docs/architecture/file-transfer-research.md:5 | `docs/architecture/file-transfer-design.md` | YES |
| docs/architecture/file-transfer-implementation-plan.md:6 | `docs/architecture/file-transfer-design.md` | YES |
| docs/architecture/file-transfer-implementation-plan.md:6 | `docs/architecture/file-transfer-research.md` | YES |
| docs/architecture/desktop-ptt-architecture.md:5 | `docs/architecture/sad.md` | YES |
| docs/architecture/desktop-ptt-architecture.md:5 | `docs/architecture/sdd.md` | YES |
| docs/architecture/desktop-ptt-architecture.md:5 | `docs/release/dv-waiver-register.md` | YES |
| docs/requirements/sysrs.md:4 | `../sysrs.md` | YES |
| docs/requirements/srs.md:4 | `../srs.md` | YES |
| docs/governance/document-index.md | All 18 listed paths | YES |
| docs/ui-ux/material3-guideline.md:6 | `docs/material3-guideline.md` | YES |
### Broken
None found — all doc-to-doc cross-references in prose text resolve correctly.
---
## Notes
1. **Path-record files**: Several docs exist as stubs pointing to canonical locations (`docs/requirements/sysrs.md``docs/sysrs.md`, `docs/requirements/srs.md``docs/srs.md`, `docs/architecture/sysdes.md``docs/sysdes.md`, `docs/ui-ux/material3-guideline.md``docs/material3-guideline.md`). These are intentional DV navigation aids, not broken links.
2. **Hypothetical file names in sysrs.md**: The table at lines 124131 lists `docs/chanora_SysDes.md` etc. as "Potential downstream file names." These are aspirational names from an earlier draft, not current files. They are presented as plain text in a table, not as navigable links.
3. **LICENSE-APACHE and LICENSE-MIT**: These are the most impactful broken references. The README's License section links to them, and the security license inventory files reference them. The dual-license model (DEC-020) requires these files to exist for proper attribution.
4. **snapshot_state_mapper.dart location**: The SDD lists this under "Snapshot and channel UI" (widget layer), but the file is actually in `services/`. This is a minor organizational mismatch — the file exists but is categorized differently than documented.
5. **External links**: Concentrated in `docs/architecture/file-transfer-research.md` (protocol research sources) and `docs/security/license-inventory.md` (dependency homepages). The file-transfer research links point to specific GitHub commit SHAs which may become stale over time.
@@ -0,0 +1,135 @@
# Review: Test & Document Coverage Analysis
**Reviewer:** opencode (automated)
**Reviewed file:** `docs/offline-knowledge/coverage-analysis.md`
**Date:** 2026-06-13
**Method:** Spot-checked 5 random test files, verified aggregate counts via grep/find, cross-referenced directory listings
---
## Verdict: Significant inaccuracies found
The document has **3 critical counting errors**, **2 factual errors about file existence**, and **several minor issues**. The per-file Rust test counts are mostly accurate, but the aggregate totals are wrong.
---
## Critical Errors
### 1. Total Rust test count is wrong by 40%
| Metric | Document | Actual | Delta |
|--------|----------|--------|-------|
| Inline `#[test]` | 220 | 309 | +89 |
| Integration tests | 2 | 2 | 0 |
| **Total** | **222** | **312** | **+90** |
The per-crate sums also don't reconcile: the document's own per-file tables sum to ~202 for chanora_audio (plus 2 integration = 204), but `grep -c '#\[test\]'` across `crates/chanora_audio/src/` yields **219** inline tests (+ 2 integration = 221). The document undercounts chanora_audio by 17 tests.
### 2. chanora_resolver test count off by 1
| Crate | Document | Actual |
|-------|----------|--------|
| chanora_resolver | 12 | 13 |
The extra test is in `examples/cli.rs` (documented separately as 1 example test, but the crate header total should be 13, not 12).
### 3. Doc file count is ambiguous and inaccurate
| Scope | Document says | Actual |
|-------|---------------|--------|
| All docs/ .md files | 55 | 75 |
| Excluding superpowers/ | — | 66 |
| Excluding superpowers/ + offline-knowledge/ | — | 51 |
The "55" figure doesn't match any reasonable scope calculation. The document also doesn't clarify whether superpowers/ plans/specs are included.
---
## Factual Errors
### 4. `poke_active_chat.dart` does not exist as a source file
The document lists `poke_active_chat.dart` as a tested service (line 163), and `poke_active_chat_test.dart` does exist under `test/services/`. However, **no corresponding source file** exists in `lib/services/`. This is either:
- An orphaned test for a deleted/moved source file, or
- The source file is located elsewhere (not in `lib/services/`)
The document should flag this as an anomaly, not list it as "Tested".
### 5. `audio_device_list_tile_test.dart` exists but is not counted
The document marks `audio_device_list_tile.dart` as "UNTESTED" (line 189), but `apps/chanora_flutter/test/widgets/audio_device_list_tile_test.dart` **does exist**. This means:
- Widget test file count should be **14**, not 13
- Widget coverage should be **14/24 (58%)**, not 13/24 (54%)
---
## Section Header vs. Content Mismatches
### 6. Architecture section: header says "4 files", lists 7
The header on line 221 reads "Architecture (4 files)" but the table contains 7 entries. The actual `docs/architecture/` directory has 7 files.
### 7. Governance section: header says "11 files", lists 12
The header on line 264 reads "Governance (11 files)" but the table contains 12 entries. The actual `docs/governance/` directory has 12 files.
---
## Spot-Check Results (5 Random Test Files)
| File | Document Count | Actual | Match? |
|------|---------------|--------|--------|
| `chanora_audio/src/ptt_backends/windows.rs` | 44 | 44 | ✅ |
| `chanora_audio/src/engine.rs` | 7 | 7 | ✅ |
| `chanora_state/src/lib.rs` | 18 | 18 | ✅ |
| `chanora_storage/src/lib.rs` | 15 | 15 | ✅ |
| `chanora_audio/src/route_policy.rs` | 8 | 8 | ✅ |
Per-file Rust test counts are **accurate**. The error is in the aggregation.
---
## Dart/Flutter Section: Mostly Accurate
| Metric | Document | Actual | Match? |
|--------|----------|--------|--------|
| `test()` calls | 155 | 155 | ✅ |
| `testWidgets()` calls | 66 | 66 | ✅ |
| Total Dart tests | 221 | 221 | ✅ |
| Service source files | 21 | 21 | ✅ |
| Widget source files | 24 | 24 | ✅ |
| Service test files | — | 20 | ⚠️ Not stated |
| Widget test files | 13 | 14 | ❌ |
---
## Missing Crates / Scope Issues
The document covers all 9 crates under `crates/` plus `chanora_core` under `core/`. No crates are missing. However:
- The document doesn't clearly explain that `chanora_core` lives under `core/`, not `crates/`
- The "Crates with tests: 7/9" metric (line 15) excludes `chanora_core`, which has 11 tests. If counted, it should be **8/10**
---
## Documentation Gap Analysis: Mostly Complete
The gap analysis (lines 333-354) correctly identifies undocumented modules. One omission:
- **Flutter test infrastructure** — no doc for the test helper setup, mock patterns, or test utilities used across 37 test files
---
## Summary of Required Corrections
| # | Issue | Severity | Fix |
|---|-------|----------|-----|
| 1 | Total Rust tests: 220 → 312 | Critical | Re-count and update |
| 2 | chanora_audio tests: 204 → 221 | Critical | Re-count and update |
| 3 | chanora_resolver tests: 12 → 13 | Minor | Update count |
| 4 | Doc file count: 55 → clarify scope | Minor | State scope explicitly |
| 5 | `poke_active_chat.dart` doesn't exist | Critical | Remove or flag as anomaly |
| 6 | `audio_device_list_tile_test.dart` exists | Major | Update widget test count to 14 |
| 7 | Architecture header: 4 → 7 | Minor | Fix header |
| 8 | Governance header: 11 → 12 | Minor | Fix header |
| 9 | Widget coverage: 54% → 58% | Major | Recalculate |
@@ -0,0 +1,148 @@
# Review: coverage-analysis.md & doc-quality-analysis.md
**Reviewer:** opencode (automated verification)
**Date:** 2026-06-13
**Method:** Random sampling + targeted claim verification against actual codebase
---
## coverage-analysis.md Review
### Check 1: Random Test File Counts (5 files sampled)
| File | Claimed | Actual | Verdict |
|------|---------|--------|---------|
| `android_permissions_service_test.dart` | 14 | 14 | ✅ PASS |
| `macos_permissions_service_test.dart` | 20 | 20 | ✅ PASS |
| `chat_views_test.dart` | 18 | 29 | ❌ FAIL (off by 11) |
| `back_intent_policy_test.dart` | 9 | 9 | ✅ PASS |
| `channel_spacer_test.dart` | 9 | 9 | ✅ PASS |
**Score:** 4/5 correct
### Check 2: Source Files Claimed Untested (3 files verified)
| File | Claimed | Actual | Verdict |
|------|---------|--------|---------|
| `ios_permissions_service.dart` | UNTESTED | No test file exists | ✅ PASS |
| `link_trust_service.dart` | UNTESTED | No test file exists | ✅ PASS |
| `audio_device_list_tile.dart` (widget) | UNTESTED | **Test file EXISTS** (`audio_device_list_tile_test.dart`, 3 tests) | ❌ FAIL |
**Score:** 2/3 correct
### Check 3: Orphaned Test Claim
- **Claim:** `poke_active_chat_test.dart` is orphaned (no matching source)
- **Actual:** `poke_active_chat_test.dart` EXISTS in test/services/, but `poke_active_chat.dart` does NOT exist in lib/services/
- **Verdict:** ✅ PASS — claim is accurate
### Check 4: Missed Test Files
| Missed Item | Impact |
|-------------|--------|
| `audio_device_list_tile_test.dart` | Widget test coverage is 14/24 (58%), not 13/24 (54%) |
| chanora_core integration tests (3 files: alpha_smoke.rs, avatar_cache.rs, mvp_storage.rs) | Analysis claims 2 integration tests total; actual is 6 (2 chanora_audio + 4 chanora_core) |
### Check 5: Aggregate Count Errors
| Metric | Claimed | Actual | Error |
|--------|---------|--------|-------|
| chanora_audio inline tests | 221 | 333 | +112 (51% undercount) |
| chanora_core tests (inline + integration) | 11 | 38 | +27 (71% undercount) |
| Total Dart tests | 221 | 233 | +12 (5% undercount) |
| Total doc files (docs/) | 55 | 86 | +31 (56% undercount) |
| Widget test files | 13 | 14 | +1 missed file |
| Total Rust integration tests | 2 | 6 | +4 missed |
### Check 6: Documentation Gap Claims
The documentation gap table (lines 336-354) lists 15 modules with no dedicated docs. Spot-checking confirms these modules确实 lack dedicated documentation files. **Verdict:** ✅ PASS — gaps are accurately identified.
---
## doc-quality-analysis.md Review
### Check 1: Claimed Duplications (3 verified)
| # | Claim | Files | Verdict |
|---|-------|-------|---------|
| 1 | Lifecycle chain (`SysRS -> SysDes -> SRS -> SAD -> SDD`) | README.md:280, CONTRIBUTING.md:10 | ✅ PASS — identical text confirmed |
| 2 | Commit examples | README.md:379-386, CONTRIBUTING.md:37-42, git-commit-message-convention.md:14-18 | ⚠️ PARTIAL — README has 6 examples, CONTRIBUTING has 4, convention file has 4. Not "identical" but overlapping. |
| 3 | Security doc list | README.md:349-355, SECURITY.md:33-38 | ✅ PASS — identical 6-file list confirmed |
### Check 2: Useless Content Items
| Claim | Verdict | Notes |
|-------|---------|-------|
| `docs/architecture/sysdes.md` is "path record — no unique content" | ⚠️ MISLEADING | It's a DV entry-point record with review summary table. Intentional for ASPICE compliance, not "useless." |
| `docs/requirements/sysrs.md` is "path record — no unique content" | ⚠️ MISLEADING | Same as above — intentional DV navigation aid. |
| `docs/requirements/srs.md` is "path record — no unique content" | ⚠️ MISLEADING | Same pattern. |
| `docs/ui-ux/material3-guideline.md` is "path record — no unique content" | ⚠️ MISLEADING | Same pattern. |
| `docs/sysdes.md:13` malformed markdown | ✅ PASS | Line 13: `**Repo path:** ... ---` missing blank line before `---`. Confirmed. |
### Check 3: Broken References
| Claim | Verdict |
|-------|---------|
| `docs/sysrs.md:126-130` references non-existent `docs/chanora_SysDes.md` etc. | ✅ PASS — confirmed. Actual files are `docs/sysdes.md`, `docs/srs.md`, etc. |
| `docs/implementation-status-2026-05-28.md:103` references `SDD-109` | ✅ PASS — SDD baseline explicitly notes SDD-109 is "not itemized in this baseline" |
| `docs/implementation-status-2026-05-28.md:105` references `SAD-043` | ✅ PASS — SAD baseline explicitly notes SAD-043 is "not itemized in this baseline" |
### Check 4: Additional Issues Missed
| Issue | Location | Description |
|-------|----------|-------------|
| chanora_core test count wildly wrong | coverage-analysis.md:107-113 | Claims 11 tests; actual is 34 inline + 4 integration = 38 |
| chanora_audio test count wrong | coverage-analysis.md:24 | Claims 221 inline tests; actual is 333 |
| Total doc count wrong | coverage-analysis.md:215 | Claims 55; actual is 86 under docs/ |
| Widget test file missed | coverage-analysis.md:188 | `audio_device_list_tile_test.dart` exists but listed as UNTESTED |
| `release(android)` commit type | doc-quality-analysis.md:90 | Analysis correctly flags this as non-standard Conventional Commits type, but doesn't note it appears in the canonical `git-commit-message-convention.md` itself |
---
## Summary of Errors
### coverage-analysis.md — Errors Found
1. **chanora_audio test count:** 221 claimed → 333 actual (112 test undercount)
2. **chanora_core test count:** 11 claimed → 38 actual (27 test undercount)
3. **Total Dart test count:** 221 claimed → 233 actual (12 test undercount)
4. **chat_views_test.dart count:** 18 claimed → 29 actual
5. **Widget test file count:** 13 claimed → 14 actual (missed audio_device_list_tile_test.dart)
6. **Total integration tests:** 2 claimed → 6 actual (missed chanora_core's 3 files / 4 tests)
7. **Total doc file count:** 55 claimed → 86 actual
### doc-quality-analysis.md — Errors Found
1. **"Useless content" characterization:** Path record files are intentional DV navigation aids, not useless. The label is misleading.
2. **Commit examples "identical" claim:** They overlap but are not identical (different files have different subsets).
---
## Quality Scores
| File | Score | Rationale |
|------|-------|-----------|
| **coverage-analysis.md** | **4/10** | Structure and methodology are sound, but 7 factual errors in counts undermine reliability. The chanora_audio undercount (112 tests) and chanora_core undercount (27 tests) are severe. Missed widget test file is a moderate error. |
| **doc-quality-analysis.md** | **7/10** | Duplications and broken references are accurately identified. The "useless content" label is misleading but not factually wrong. Minor inaccuracy on "identical" claim for commit examples. |
---
## Corrections Needed
### coverage-analysis.md
1. Update chanora_audio inline test count: 221 → 333
2. Update chanora_core test count: 11 → 38 (34 inline + 4 integration)
3. Update total Dart test count: 221 → 233
4. Update chat_views_test.dart count: 18 → 29
5. Add `audio_device_list_tile_test.dart` to widget test list (3 tests)
6. Update widget test file count: 13 → 14; untested widgets: 11 → 10
7. Update total integration tests: 2 → 6
8. Update total doc file count: 55 → 86
9. Add chanora_core integration test files to the integration tests section
### doc-quality-analysis.md
1. Relabel "Useless Content" → "Path Record Files" or "DV Navigation Aids" with explanation that these are intentional
2. Soften "identical" to "overlapping" for commit examples (Instance 2)

Some files were not shown because too many files have changed in this diff Show More