Repair Android route settlement, failed recovery and AAudio startup contracts
android-ci / android-arm64 (push) Successful in 20m13s
android-ci / android-arm64 (push) Successful in 20m13s
This commit is contained in:
1 parent
e619f66d59
commit
4664be0818
22 files changed
+775
-70
No files matched your search
@@ -236,9 +236,8 @@ jobs:
|
|||||||
.android-ci/audio-test-results/capture-timing-tests --test-threads=1
|
.android-ci/audio-test-results/capture-timing-tests --test-threads=1
|
||||||
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/output_usage.rs -o .android-ci/audio-test-results/output-usage-tests
|
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/output_usage.rs -o .android-ci/audio-test-results/output-usage-tests
|
||||||
.android-ci/audio-test-results/output-usage-tests --test-threads=1
|
.android-ci/audio-test-results/output-usage-tests --test-threads=1
|
||||||
printf '#[path = "%s/native/src/platform/android/call_audio.rs"] mod call_audio;\n' "$GITHUB_WORKSPACE" > .android-ci/audio-test-results/call-audio-check.rs
|
rustc --edition=2021 --test native/vendor/cpal-0.18.2/src/host/aaudio/stream_start.rs -o .android-ci/audio-test-results/stream-start-tests
|
||||||
rustc --edition=2021 --test .android-ci/audio-test-results/call-audio-check.rs -o .android-ci/audio-test-results/call-audio-tests
|
.android-ci/audio-test-results/stream-start-tests --test-threads=1
|
||||||
.android-ci/audio-test-results/call-audio-tests --test-threads=1
|
|
||||||
mkdir -p .android-ci/audio-test-results/java
|
mkdir -p .android-ci/audio-test-results/java
|
||||||
javac -d .android-ci/audio-test-results/java platform/android/src/main/java/dev/teamspeach/mobile/CommunicationRoutePolicy.java platform/android/src/test/java/dev/teamspeach/mobile/CommunicationRoutePolicyTest.java
|
javac -d .android-ci/audio-test-results/java platform/android/src/main/java/dev/teamspeach/mobile/CommunicationRoutePolicy.java platform/android/src/test/java/dev/teamspeach/mobile/CommunicationRoutePolicyTest.java
|
||||||
java -cp .android-ci/audio-test-results/java dev.teamspeach.mobile.CommunicationRoutePolicyTest
|
java -cp .android-ci/audio-test-results/java dev.teamspeach.mobile.CommunicationRoutePolicyTest
|
||||||
@@ -246,6 +245,7 @@ jobs:
|
|||||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib media::audio:: --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib media::audio:: --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib capture_transition_tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib capture_transition_tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib audit_lifecycle --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib audit_lifecycle --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||||
|
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib android_call_authorization --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib only_explicit_output_device_actions_request_platform_routing --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib only_explicit_output_device_actions_request_platform_routing --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib android_attachment_ --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib android_attachment_ --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||||
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib app::connections::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
cargo test --locked -p teamspeach-native --no-default-features --target x86_64-unknown-linux-gnu --lib app::connections::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||||
|
|||||||
@@ -12,6 +12,12 @@
|
|||||||
exact built-in microphone selections are retained, and only explicit playback actions change the
|
exact built-in microphone selections are retained, and only explicit playback actions change the
|
||||||
communication route. Voice outputs use runtime-resolved AAudio voice/speech attributes on API28+;
|
communication route. Voice outputs use runtime-resolved AAudio voice/speech attributes on API28+;
|
||||||
API26/27 keep the link-safe legacy behavior. Independent notification output retains media policy.
|
API26/27 keep the link-safe legacy behavior. Independent notification output retains media policy.
|
||||||
|
- Preserve the concrete output stream fault when startup publication fails instead of replacing it
|
||||||
|
with a generic device error; failed streams remain unpublished and inactive.
|
||||||
|
- Wait for Android default-route settlement, retain a valid recovery continuation after failed manual
|
||||||
|
switches, and reject late startup acknowledgement after focus loss. Validate explicit Bluetooth
|
||||||
|
capture transport without automatically changing playback. Resolve default PCM capabilities before
|
||||||
|
opening and require AAudio to reach Started, retaining safe backend failure-stage diagnostics.
|
||||||
- Keep already-authorized steady Android voice calls alive across Home, screen-off and UI recreation;
|
- Keep already-authorized steady Android voice calls alive across Home, screen-off and UI recreation;
|
||||||
release momentary PTT/whisper controls, preserve permission/audio-focus revocation, and scope CPU wake
|
release momentary PTT/whisper controls, preserve permission/audio-focus revocation, and scope CPU wake
|
||||||
ownership to the foreground call. Removing the app from Recents ends its call and capture services.
|
ownership to the foreground call. Removing the app from Recents ends its call and capture services.
|
||||||
|
|||||||
@@ -750,5 +750,133 @@ held-inhibitor invariants; (3) reconcile manager permit changes for same owner a
|
|||||||
drive actual command/event consumers with controlled startup/ACK/callback barriers and connected
|
drive actual command/event consumers with controlled startup/ACK/callback barriers and connected
|
||||||
snapshot ordering. No queue-limit increase, blind retry or stale-audio bypass as a substitute.
|
snapshot ordering. No queue-limit increase, blind retry or stale-audio bypass as a substitute.
|
||||||
|
|
||||||
|
### Audit remediation verification — 8f74404 / run4920
|
||||||
|
|
||||||
|
Owner authorized all audit fixes. Live PCM service now delegates slow thread-affine CPAL construction,
|
||||||
|
play/drop, DSP reconstruction and notification decoding to `native/src/media/audio/lifecycle.rs`.
|
||||||
|
`engine.rs::Worker::lifecycle` continues normal queue/reference/capture/mix servicing while awaiting
|
||||||
|
bounded completion. StreamOwner never crosses threads; DeviceLease revokes immediately and retires on
|
||||||
|
the lifecycle owner. Durable output authorization is separate from temporary playback activity;
|
||||||
|
superseded reset cannot latch RX off and later explicit stops remain authoritative.
|
||||||
|
|
||||||
|
Runtime retains negative PushToMute inhibitors, revokes before waiting on config lock, reconciles the
|
||||||
|
actual owner after batch changes and consumes same-owner acknowledged permit replacements without
|
||||||
|
ticker set_input/retries. Manager publishes capture revision/acknowledged config; current_capture_permit
|
||||||
|
checks live core epoch. Private reservations fence stale Finish and newer output intent; failure status
|
||||||
|
is updated. Voice projection and toggle share effective microphone readiness. Runtime ignores obsolete
|
||||||
|
connecting observers before/after awaits; manager publishes before observer dispatch. Android reads OS
|
||||||
|
grant at construction and queued permission handling, and suppresses duplicate AppOps notifications.
|
||||||
|
|
||||||
|
Linux CI4920 SUCCESS: actual native145, capture transitions18, lifecycle observer/UI2, manager7,
|
||||||
|
DSP15, Android metadata4/timestamp3, core23 passed/1ignored. Full Android build/package passed.
|
||||||
|
Unlike former mute tests, new production Worker::run regression keeps concurrent production callbacks
|
||||||
|
running across a blocked capture-start barrier for multiple reference-ring capacities. Other regressions
|
||||||
|
cover reset interleaving, mute waiting behind activation, delayed same-owner move, non-owner playback,
|
||||||
|
idle/stale private finish and late connecting observers. Synthetic backend/reducer fixtures do not
|
||||||
|
prove physical CPAL/server behavior; phone and current Windows runtime acceptance remain separate.
|
||||||
|
First CI4917 failed guard-reference type coercion; fixed2716aa5. CI4918 passed native145 and17/18 runtime
|
||||||
|
tests; removed an obsolete expected-error assertion for now-idempotent inactive private Stop in8f74404.
|
||||||
|
No failed assertion was suppressed or test path narrowed. Additional mic gain not changed.
|
||||||
|
|
||||||
|
### Owner-confirmed Android voice — f403dd5 / run4931
|
||||||
|
|
||||||
|
After4920 the owner observed first TX working briefly, then target_changed; second unmute was stable.
|
||||||
|
No retained fault record identified that occurrence. Source inspection found push_audio's boolean
|
||||||
|
conflated individual frame expiry/future rejection and lost authorization; capture_failed then revoked
|
||||||
|
the manager, potentially destroying an already-acknowledged replacement. f403dd5 introduces typed
|
||||||
|
CaptureIngress outcomes, preserving strict core frame validation while retiring only the old worker
|
||||||
|
capture on permit loss. The actual manager/core + Worker forwarding regression passed in CI4931.
|
||||||
|
Native146, capture18, lifecycle2, manager7, DSP15, metadata4, timestamp3, core23 passed/1ignored;
|
||||||
|
Android compile/package passed. APK SHA256c91deecac9ae5bc973a057faf94a94daec35bc50decbe30d5a799e8fadf942d9
|
||||||
|
verified locally against receipts and installed with explicit owner authorization. Owner then confirmed
|
||||||
|
«всее, урааа, все работает!» following the requested cold-entry/first-TX scenario. This is manual
|
||||||
|
two-way Android voice acceptance, not proof of the exact former failure cause or the entire device matrix.
|
||||||
|
|
||||||
|
Record test was previously accepted on4911. Repeated mute/deafen, external route plug/unplug, current
|
||||||
|
device-selector presentation, long calls, background/network recovery, Windows runtime regression and
|
||||||
|
iOS acceptance remain separately unverified. UI work can proceed on this working voice baseline;
|
||||||
|
do not infer authority to merge main, publish a release, change signing or start UI implementation
|
||||||
|
from the owner's question about priorities. No additional microphone gain was applied.
|
||||||
|
|
||||||
|
### Read-only headset regression audit — e619f66 / APK4948, 2026-11-14
|
||||||
|
|
||||||
|
Scope: compare4ea413f (APK4943) with63861be+e619f66; capture selection, Android communication
|
||||||
|
route acknowledgement, AAudio output policy/default resolution, Worker publication and tests.
|
||||||
|
Installed4948 SHA25670d5bf26fd4148944f934de790e36e938dc40d7c912f5c9bcb321b7caec81341 verified.
|
||||||
|
Owner reports regression: headset microphone unavailable and default RX silent until manual speakers.
|
||||||
|
Screenshot captured immediately without taps. No source edits, builds, tests, microphone/server
|
||||||
|
actions or route changes during this audit. Existing full graph is stale; no regeneration performed.
|
||||||
|
|
||||||
|
**Observed device evidence:** first retained input failure is `input_publish`, `DeviceLost`,
|
||||||
|
`audio_device_missing`, before native CaptureCallback delivery. Host lookup/open/initial validation
|
||||||
|
and play returned before this stage; it is not the absent-ID branch (engine.rs:1042-1083).
|
||||||
|
AAudio maps Disconnected/Unavailable/NoService/InvalidHandle to the same error category
|
||||||
|
(vendor/cpal-0.18.2/src/host/aaudio/convert.rs:52-62); exact backend code was not retained.
|
||||||
|
Zero native counters do not rule out earlier AAudio callbacks withheld awaiting a timestamp.
|
||||||
|
Java explicit Bluetooth communication selection was acknowledged; output opened with verified
|
||||||
|
VOICE_COMMUNICATION/SPEECH, mono16kHz I16, then start_output returned audio_device_error.
|
||||||
|
Another open reported stereo48kHz I16 then audio_device_busy after2051ms. Attribute/shape/route
|
||||||
|
match is logged BEFORE play/publication, not proof of successful playback or audibility.
|
||||||
|
Default clear was followed by an observed earpiece route and a fence/settings failure. Logs do not
|
||||||
|
prove that system default always selected headphones. Endpoint ID (e.g. aaudio:2) is not device type.
|
||||||
|
|
||||||
|
**Source-supported findings:**
|
||||||
|
|
||||||
|
1. **P1: premature CLEAR acknowledgement.** VoiceService.java:161 calls clearCommunicationDevice
|
||||||
|
and immediately finishPlayback(success). Later OS callback can fence the in-flight settings/native
|
||||||
|
reconstruction (172-193). Retained ordering supports this race. `current_type` on the immediate
|
||||||
|
ACK can itself be stale; it is not a fresh getter result. CLEAR needs bounded settled completion
|
||||||
|
with one configuration/recovery owner, not treating request submission as settled physical routing.
|
||||||
|
2. **P2: failed manual recovery invalidates its own event.** VoiceService.java:126-128 calls
|
||||||
|
receiveOnly (93-96), then nativeVoicePlaybackFinished increments route revision without emitting
|
||||||
|
recovery (native/src/platform/android.rs:502-508). The error return skips caller synchronization
|
||||||
|
(settings_actions/audio.rs:191-192); event_handlers.rs:103-105 rejects the earlier revision.
|
||||||
|
Failure must finalize revision before handing off recovery; success can remain caller-owned.
|
||||||
|
3. **P2: resolved-default endpoint and PCM format diverge.** DeviceHost::select chooses format
|
||||||
|
(devices.rs:202-204), then SelectedDevice::prepare_output changes device/ID but not format (92-100).
|
||||||
|
Worker invokes those in that order (engine.rs:1108-1120). A default resolving to mono16kHz/I16
|
||||||
|
can retain synthetic stereo48kHz/F32, unlike exact selection. Recompute compatible format after
|
||||||
|
resolution, before conversion/open. This is proven structurally, not the proven cause of this
|
||||||
|
phone's asynchronous DeviceLost or its start timeout.
|
||||||
|
4. **P2: startup route ACK can overwrite lost focus.** VoiceService.java:123-124 completes startup
|
||||||
|
without rechecking focused; nativeVoiceStarted calls CallAudioState::start, which sets focused=true
|
||||||
|
(android.rs:460-462; android/call_audio.rs:12). Revalidate current focus/consent at completion.
|
||||||
|
5. **Failure-state clarity:** output selection persists intent before platform application, as before
|
||||||
|
this patch. New early UNAVAILABLE returns after revoke_capture but before synchronization
|
||||||
|
(settings_actions/audio.rs:128,189-192; VoiceService.java:146). Desired selection, applied route
|
||||||
|
and active stream can therefore differ. Do not silently roll back exact preferences or imply that
|
||||||
|
preserved selection means active hardware; clearly report the unsupported/unavailable combination.
|
||||||
|
|
||||||
|
**Bluetooth contract gap [INFERENCE]:** removing automatic priority selection also removed automatic
|
||||||
|
SCO activation, while capture selection deliberately does not request any communication output.
|
||||||
|
Android setCommunicationDevice selects a sink and automatically pairs the source. Independent UI
|
||||||
|
selectors cannot guarantee independent physical Bluetooth input/output. Opening an enumerated SCO
|
||||||
|
input while the conversation route stays on the phone is consistent with the observed backend loss,
|
||||||
|
but raw backend cause and exact physical pairing remain unknown. Do not fix by restoring automatic
|
||||||
|
headset priority, name-based remapping or removing exact-route/privacy validation. Reconcile the
|
||||||
|
explicit user pair against supported transport, or explain the unsupported pair before opening it.
|
||||||
|
Platform reference: https://developer.android.com/reference/android/media/AudioManager#setCommunicationDevice(android.media.AudioDeviceInfo)
|
||||||
|
|
||||||
|
**Diagnostics/tests:** output fence publication replaces a latched fault with audio_device_error
|
||||||
|
(engine.rs:108-112), while capture preserves its category. AAudio play discards the state returned by
|
||||||
|
wait_for_state_change (mod.rs:940-953); Timeout/WouldBlock both become device_busy. These are existing
|
||||||
|
blind spots exposed by this change, not proof that another app owns the device. Preserve bounded
|
||||||
|
backend enum/start phase and distinguish stream-open, Started, publication and actual callbacks.
|
||||||
|
The five new Worker fixtures inject OpenedOutput before host/JNI/open (engine.rs:1102-1107;
|
||||||
|
engine_tests.rs:387-503,1447-1490). Manual capture fixture injects capture and submits SelectInput
|
||||||
|
directly (lifecycle_tests.rs:291-316); Java policy fixture does not execute VoiceService callbacks.
|
||||||
|
Passed CI therefore misses CLEAR callback interleavings, failed-ACK revisions, focus loss during
|
||||||
|
startup, endpoint-specific default format, and actual SCO duplex readiness. It remains valid for
|
||||||
|
its synthetic ownership/privacy contracts, not headset acceptance. No new tests run during audit.
|
||||||
|
|
||||||
|
**Correction/proof order:** repair the four source defects as one scoped route-state correction;
|
||||||
|
cover their actual asynchronous boundaries and reject invalid start states without relaxing privacy;
|
||||||
|
then verify on the selected phone: exact headset pair, explicit phone pair, default, supported mixed
|
||||||
|
pair (or clear unsupported result), failed switch recovery, mic mute and disconnect. No UI rewrite,
|
||||||
|
desktop behavior change, broad refactor or automatic gain/route fallback is justified by this audit.
|
||||||
|
Headset RX/TX acceptance remains FAILED; exact raw backend cause remains UNKNOWN.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -743,6 +743,45 @@ to this pre-UI scope. No speculative microphone gain/audio refactor on accepted
|
|||||||
failed audio_closed before second open. Fixture destructuring discarded event receiver, so first
|
failed audio_closed before second open. Fixture destructuring discarded event receiver, so first
|
||||||
Started event correctly stopped orphaned worker. Retain receiver for whole fixture; production
|
Started event correctly stopped orphaned worker. Retain receiver for whole fixture; production
|
||||||
shutdown semantics unchanged. APK stage was skipped; corrected tests require the next CI run.
|
shutdown semantics unchanged. APK stage was skipped; corrected tests require the next CI run.
|
||||||
|
- Corrected e619f66d59c98400c77aa837bd39bf22308b7e88 run4948/job5544 SUCCESS: native audio164,
|
||||||
|
capture18,lifecycle13,restart3,manual-action1,manager7,DSP15,catalog5,timestamp3,usage4,route-state7,
|
||||||
|
core23+output2 passed/1ignored. All five output role/alias regression fixtures passed; ARM64 APK
|
||||||
|
compile/package passed. Owner selected install-ready on the same disposable TECNO KJ7, including
|
||||||
|
signature-mismatch replacement if needed; server/mic actions remain owner-operated. Download pending.
|
||||||
|
- APK4948 ZIP and all six receipt hashes verified; APK SHA256
|
||||||
|
70d5bf26fd4148944f934de790e36e938dc40d7c912f5c9bcb321b7caec81341. USB disconnected on initial
|
||||||
|
update attempt; owner reconnected. Signature mismatch confirmed, authorized disposable uninstall
|
||||||
|
and install both Success. Activity already foreground on launch request; installed APK hash matches.
|
||||||
|
- Owner REJECTS4948 headset behavior: G435 capture now fails audio_device_missing; default playback
|
||||||
|
reportedly silent until manual speaker choice. Immediate screenshot captured without inputs; no
|
||||||
|
further phone manipulation, source fixes, tests or builds during requested detailed read-only audit.
|
||||||
|
- Retained bounded logs identify first capture failure at input_publish with DeviceLost before native
|
||||||
|
capture delivery, not exact-ID lookup. Java Bluetooth communication ACK succeeds, but following
|
||||||
|
output start fails audio_device_error; another start fails audio_device_busy after2051ms. Default
|
||||||
|
clear ACK precedes later observed earpiece route and another fence/settings failure. Do not call
|
||||||
|
VOICE_COMMUNICATION attribute match or passed host fixtures a device routing success.
|
||||||
|
- Detailed read-only audit recorded in assessment §Read-only headset regression audit — e619f66 /
|
||||||
|
APK4948. Source defects: premature CLEAR ACK, failed-completion recovery event superseded by newer
|
||||||
|
revision, resolved-default endpoint retaining generic PCM format, startup ACK restoring lost focus.
|
||||||
|
Capture's first fault is asynchronous backend loss, not missing catalog ID; underlying raw AAudio
|
||||||
|
reason remains unknown. Bluetooth source/sink coupling must be reconciled without automatic priority
|
||||||
|
or silent substitutions. Test seams bypass the failing JNI/VoiceService/open boundaries. No app
|
||||||
|
fixes or new build/install during audit; only bounded evidence and documentation updated.
|
||||||
|
- Owner explicitly approved moving from audit to fixes: scoped CLEAR/ACK/recovery/focus correction,
|
||||||
|
endpoint-resolved PCM format, strict AAudio Started-state validation and bounded backend diagnostics.
|
||||||
|
No automatic headset priority or silent exact-device replacement. Parent preserves output-publication
|
||||||
|
fault category and tests failed streams never publish active; CI/device results still pending.
|
||||||
|
- Repairs implemented pending CI: production CLEAR settlement waits fresh route observations with
|
||||||
|
bounded quiet/completion windows; explicit JNI accepted flag separates successful caller continuation
|
||||||
|
from finalized failed-route recovery. Startup checks focus and authorization revision. Failure recovery
|
||||||
|
preserves saved exact choices and last applied state without automatically remapping devices; later
|
||||||
|
mute/focus loss still wins. Capture pair preflight runs on settings, recovery and shared StartInput.
|
||||||
|
- Physical default output now recomputes capabilities/PCM; AAudio startup requires Started from both
|
||||||
|
bounded wait and current state. Safe audio_backend enums identify open/callback/start phases without
|
||||||
|
identifiers/PCM. Output publication preserves specific latched faults instead of generic device error.
|
||||||
|
- Java production settlement fixture compiled and passed locally (delay, null/denied route, timeout,
|
||||||
|
cancellation and repeated callbacks); async Rust authorization tests migrated from standalone rustc
|
||||||
|
to native Cargo harness for Tokio. Native/Android compile and device behavior not yet verified.
|
||||||
|
|
||||||
|
|
||||||
## First Android APK build
|
## First Android APK build
|
||||||
|
|||||||
@@ -241,7 +241,16 @@ impl RuntimeServices {
|
|||||||
self.require_key(&key,true)?;
|
self.require_key(&key,true)?;
|
||||||
if self.connected.connections.current_capture_permit().as_ref()!=Some(&permit){self.audio.revoke_local_capture();return Err(changed())}
|
if self.connected.connections.current_capture_permit().as_ref()!=Some(&permit){self.audio.revoke_local_capture();return Err(changed())}
|
||||||
{let mut state=lock(&self.transmission)?;if let Err(error)=state.acknowledge_capture_configuration(&key,revision,config,true){self.audio.revoke_capture();return Err(error)}state.bound_permit=Some(permit.clone());}
|
{let mut state=lock(&self.transmission)?;if let Err(error)=state.acknowledge_capture_configuration(&key,revision,config,true){self.audio.revoke_capture();return Err(error)}state.bound_permit=Some(permit.clone());}
|
||||||
if resume&&allowed&&self.microphone_granted.load(Ordering::Acquire){capture_stage(self.audio.request(AudioCommand::StartInput(StartPermission::Granted)).await,"start_input",&key)?;}
|
if resume&&allowed&&self.microphone_granted.load(Ordering::Acquire){
|
||||||
|
#[cfg(target_os="android")]
|
||||||
|
{
|
||||||
|
let (input,output)=lock(&self.applied_audio_selections)?.clone().unwrap_or_else(||(
|
||||||
|
prefs["inputDeviceId"].as_str().unwrap_or_default().to_owned(),
|
||||||
|
prefs["outputDeviceId"].as_str().unwrap_or_default().to_owned()));
|
||||||
|
capture_stage(crate::platform::android::validate_voice_capture_pair(&input,&output,true),"validate_capture_route",&key)?;
|
||||||
|
}
|
||||||
|
capture_stage(self.audio.request(AudioCommand::StartInput(StartPermission::Granted)).await,"start_input",&key)?;
|
||||||
|
}
|
||||||
if self.connected.connections.current_capture_permit().as_ref()!=Some(&permit){self.audio.revoke_local_capture();lock(&self.transmission)?.bound_permit=None;return Err(changed())}
|
if self.connected.connections.current_capture_permit().as_ref()!=Some(&permit){self.audio.revoke_local_capture();lock(&self.transmission)?.bound_permit=None;return Err(changed())}
|
||||||
if let Err(error)=lock(&self.transmission)?.capture_intent(&key,revision){self.audio.revoke_capture();return Err(error)}
|
if let Err(error)=lock(&self.transmission)?.capture_intent(&key,revision){self.audio.revoke_capture();return Err(error)}
|
||||||
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
|
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ async fn platform(ctx:&Arc<RuntimeServices>,runtime:&Weak<AppRuntime>,state:&mut
|
|||||||
AndroidCallAudio{key,token,revision,restart_output}=>{
|
AndroidCallAudio{key,token,revision,restart_output}=>{
|
||||||
if !crate::platform::android::voice_audio_current(key,*token,*revision){return Ok(false)}
|
if !crate::platform::android::voice_audio_current(key,*token,*revision){return Ok(false)}
|
||||||
ctx.android_audio_changed(key,*token,*revision,*restart_output).await?;
|
ctx.android_audio_changed(key,*token,*revision,*restart_output).await?;
|
||||||
state.snapshot.status=if crate::platform::android::voice_audio_allowed(key,true)&&ctx.audio.input_active(){"Audio route updated."}else if crate::platform::android::voice_audio_allowed(key,false){"Listening resumed. Enable the microphone explicitly."}else{"Audio paused by Android. Waiting for audio focus."}.into();
|
state.snapshot.status=if crate::platform::android::voice_audio_allowed(key,true)&&ctx.audio.input_active(){"Microphone active."}else if crate::platform::android::voice_audio_allowed(key,false)&&ctx.audio.output_active(){"Listening active. Microphone inactive."}else{"Audio inactive. Check device selection and Android audio focus."}.into();
|
||||||
},
|
},
|
||||||
AudioInterruption{began,should_resume}=>{if *began{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;ctx.audio.request(crate::media::audio::engine::AudioCommand::StopOutput).await?;}else if *should_resume{state.snapshot.status="Audio interruption ended. Resume the call with an explicit microphone action.".into();}},
|
AudioInterruption{began,should_resume}=>{if *began{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;ctx.audio.request(crate::media::audio::engine::AudioCommand::StopOutput).await?;}else if *should_resume{state.snapshot.status="Audio interruption ended. Resume the call with an explicit microphone action.".into();}},
|
||||||
AudioRouteChanged|NetworkChanged=>{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;state.snapshot.status="Audio/network route changed; stale capture was discarded. Resume microphone explicitly.".into();},
|
AudioRouteChanged|NetworkChanged=>{controller::release_immediate(ctx);ctx.audio.request(crate::media::audio::engine::AudioCommand::StopInput).await?;state.snapshot.status="Audio/network route changed; stale capture was discarded. Resume microphone explicitly.".into();},
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
//! Runtime observer regressions use the real actor/core/engine with an isolated profile.
|
//! Runtime observer regressions use the real actor/core/engine with an isolated profile.
|
||||||
use super::*;
|
use super::*;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
#[path="../../platform/android/call_audio.rs"]
|
||||||
|
mod android_call_authorization;
|
||||||
|
|
||||||
async fn fixture() -> (tempfile::TempDir, Owner, mpsc::Receiver<ServiceEvent>, mpsc::Receiver<ConnectionEvent>) {
|
async fn fixture() -> (tempfile::TempDir, Owner, mpsc::Receiver<ServiceEvent>, mpsc::Receiver<ConnectionEvent>) {
|
||||||
let directory=tempfile::tempdir().unwrap();
|
let directory=tempfile::tempdir().unwrap();
|
||||||
@@ -315,3 +317,53 @@ async fn audit_lifecycle_manual_phone_capture_keeps_playback_selection_and_later
|
|||||||
assert!(!ctx.audio.input_active());assert!(!ctx.transmission.lock().unwrap().capture_desired);
|
assert!(!ctx.audio.input_active());assert!(!ctx.transmission.lock().unwrap().capture_desired);
|
||||||
drop(configuration);cleanup(owner).await;
|
drop(configuration);cleanup(owner).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor="current_thread")]
|
||||||
|
async fn audit_lifecycle_failed_manual_ack_retains_applied_pair_and_saved_intent_until_newer_mute() {
|
||||||
|
use crate::media::audio::{devices::DeviceSelection,engine::{AudioCommand,AudioEvent}};
|
||||||
|
use android_call_authorization::CallAudioState;
|
||||||
|
let(_directory,mut owner,_events,_controls)=fixture().await;
|
||||||
|
let key=route_capture_fixture(&owner).await;let ctx=owner.ctx.clone();
|
||||||
|
let old_pair=("aaudio:11".to_string(),"aaudio:80".to_string());
|
||||||
|
ctx.audio.request(AudioCommand::SelectInput(DeviceSelection::Exact(old_pair.0.clone()))).await.unwrap();
|
||||||
|
ctx.audio.request(AudioCommand::SelectOutput(DeviceSelection::Exact(old_pair.1.clone()))).await.unwrap();
|
||||||
|
*ctx.applied_audio_selections.lock().unwrap()=Some(old_pair.clone());
|
||||||
|
let(_entered,release)=route_capture_barrier(&mut owner);release.send(()).unwrap();ctx.refresh_capture().await.unwrap();
|
||||||
|
let authorization=Arc::new(std::sync::Mutex::new(CallAudioState::default()));
|
||||||
|
assert!(authorization.lock().unwrap().start(true));
|
||||||
|
// These remain desired settings after a platform failure, NOT selected
|
||||||
|
// endpoints and NOT fabricated hardware acceptance.
|
||||||
|
ctx.profile().unwrap().prefs.set(json!({"inputDeviceId":"aaudio:99","outputDeviceId":"aaudio:100"})).unwrap();
|
||||||
|
for newer_mute in [false,true] {
|
||||||
|
owner.audio_events.try_iter().for_each(drop);
|
||||||
|
authorization.lock().unwrap().begin_route();
|
||||||
|
controller::suspend_route_immediate(&ctx,&key,true);
|
||||||
|
let intent=ctx.transmission.lock().unwrap().revision;
|
||||||
|
let(event,received)=tokio::sync::oneshot::channel();
|
||||||
|
let(entered,release)=route_capture_barrier(&mut owner);
|
||||||
|
let recovery=tokio::spawn({let ctx=ctx.clone();let key=key.clone();let authorization=authorization.clone();async move {
|
||||||
|
let revision=received.await.unwrap();
|
||||||
|
assert!(authorization.lock().unwrap().is_current(revision),"failed ACK must not invalidate its own queued continuation");
|
||||||
|
let configuration=ctx.audio_configuration.lock().await;
|
||||||
|
ctx.resume_mobile_route_capture_locked(&key,intent,&configuration).await
|
||||||
|
}});
|
||||||
|
// Same state transition used by the JNI completion chooses event ownership
|
||||||
|
// and finalizes revision before the receiver is allowed to run.
|
||||||
|
let(revision,recover)=authorization.lock().unwrap().finish_manual_route(false);
|
||||||
|
assert!(recover);event.send(revision).unwrap();
|
||||||
|
tokio::task::spawn_blocking(move||entered.recv_timeout(Duration::from_secs(10))).await.unwrap().unwrap();
|
||||||
|
assert!(!ctx.audio.input_active(),"real StartInput ACK is still behind the backend barrier");
|
||||||
|
if newer_mute {
|
||||||
|
let mut mute=Box::pin(controller::set_audio_flags(&ctx,&key,Some(true),None));
|
||||||
|
std::future::poll_fn(|cx|{assert!(Future::poll(mute.as_mut(),cx).is_pending());std::task::Poll::Ready(())}).await;
|
||||||
|
authorization.lock().unwrap().revoke_capture();
|
||||||
|
release.send(()).unwrap();assert!(recovery.await.unwrap().is_err());mute.await.unwrap();
|
||||||
|
assert!(!ctx.audio.input_active());assert!(!ctx.transmission.lock().unwrap().capture_desired);
|
||||||
|
}else{release.send(()).unwrap();assert!(recovery.await.unwrap().unwrap());assert!(ctx.audio.input_active());}
|
||||||
|
assert_eq!(ctx.applied_audio_selections.lock().unwrap().as_ref(),Some(&old_pair));
|
||||||
|
let prefs=ctx.profile().unwrap().prefs.get();
|
||||||
|
assert_eq!(prefs["inputDeviceId"],"aaudio:99");assert_eq!(prefs["outputDeviceId"],"aaudio:100");
|
||||||
|
assert!(!owner.audio_events.try_iter().any(|event|matches!(event,AudioEvent::Selected{..})),"failed recovery preserves the existing worker pair, not saved unavailable choices or a default fallback");
|
||||||
|
}
|
||||||
|
cleanup(owner).await;
|
||||||
|
}
|
||||||
@@ -24,6 +24,11 @@ impl RuntimeServices {
|
|||||||
pub async fn ensure_mobile_call_locked(self:&Arc<Self>,key:&SessionKey,microphone:bool,_configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
|
pub async fn ensure_mobile_call_locked(self:&Arc<Self>,key:&SessionKey,microphone:bool,_configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
|
||||||
self.policy.check()?;self.require_key(key,true)?;let generation=self.current_ui_generation()?;
|
self.policy.check()?;self.require_key(key,true)?;let generation=self.current_ui_generation()?;
|
||||||
let mut call=self.mobile_call.lock().await;
|
let mut call=self.mobile_call.lock().await;
|
||||||
|
#[cfg(target_os="android")]
|
||||||
|
if microphone {
|
||||||
|
let prefs=self.profile()?.prefs.get();
|
||||||
|
crate::platform::android::validate_voice_capture_pair(prefs["inputDeviceId"].as_str().unwrap_or_default(),prefs["outputDeviceId"].as_str().unwrap_or_default(),call.is_some())?;
|
||||||
|
}
|
||||||
let cached=call.as_ref().is_some_and(|(current,enabled)|current==key&&(*enabled||!microphone));
|
let cached=call.as_ref().is_some_and(|(current,enabled)|current==key&&(*enabled||!microphone));
|
||||||
#[cfg(target_os="android")]
|
#[cfg(target_os="android")]
|
||||||
let cached=cached&&crate::platform::android::voice_audio_allowed(key,microphone);
|
let cached=cached&&crate::platform::android::voice_audio_allowed(key,microphone);
|
||||||
@@ -41,9 +46,13 @@ impl RuntimeServices {
|
|||||||
if let Some(lease)=lease.as_ref(){lease.set_capture_enabled(microphone,self.policy).await?;}
|
if let Some(lease)=lease.as_ref(){lease.set_capture_enabled(microphone,self.policy).await?;}
|
||||||
else{*lease=Some(crate::platform::apple::begin_call(key.clone(),self.runtime.upgrade().ok_or_else(closed)?,microphone,self.policy).await?);}
|
else{*lease=Some(crate::platform::apple::begin_call(key.clone(),self.runtime.upgrade().ok_or_else(closed)?,microphone,self.policy).await?);}
|
||||||
}
|
}
|
||||||
self.require_key(key,true)?;self.require_ui_generation(generation)?;*call=Some((key.clone(),microphone));
|
self.require_key(key,true)?;self.require_ui_generation(generation)?;
|
||||||
#[cfg(target_os="android")]
|
#[cfg(target_os="android")]
|
||||||
if !crate::platform::android::voice_audio_allowed(key,microphone){return Err(crate::services::ServiceError::new("audio_focus_unavailable","Android revoked call audio authorization during startup"))}
|
{
|
||||||
|
if !crate::platform::android::voice_audio_allowed(key,microphone){return Err(crate::services::ServiceError::new("audio_focus_unavailable","Android revoked call audio authorization during startup"))}
|
||||||
|
if microphone {let prefs=self.profile()?.prefs.get();crate::platform::android::validate_voice_capture_pair(prefs["inputDeviceId"].as_str().unwrap_or_default(),prefs["outputDeviceId"].as_str().unwrap_or_default(),true)?;}
|
||||||
|
}
|
||||||
|
*call=Some((key.clone(),microphone));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
/// Complete only the steady intent captured by the synchronous route fence.
|
/// Complete only the steady intent captured by the synchronous route fence.
|
||||||
@@ -82,21 +91,31 @@ impl RuntimeServices {
|
|||||||
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
|
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
|
||||||
if let Err(changed)=current(){reason=changed;return Ok(())}
|
if let Err(changed)=current(){reason=changed;return Ok(())}
|
||||||
let prefs=self.profile()?.prefs.get();
|
let prefs=self.profile()?.prefs.get();
|
||||||
// Recovery preserves both exact IDs. Observing an OS topology change
|
// Observation never requests or ranks a communication output device.
|
||||||
// must never request or rank a new communication output device.
|
let failed_request=crate::platform::android::voice_playback_failed(key,token,revision);
|
||||||
|
let applied=self.applied_audio_selections.lock().map_err(|_|super::context::changed())?.clone();
|
||||||
|
let pair=if failed_request {
|
||||||
|
// Recover only the last acknowledged worker selections after a
|
||||||
|
// FAILED request. Never rewrite desired preferences or choose a sink.
|
||||||
|
applied.ok_or_else(||crate::services::ServiceError::new("audio_route_unapplied","The saved playback choice was not applied and no previous acknowledged pair is available"))?
|
||||||
|
}else{(prefs["inputDeviceId"].as_str().unwrap_or_default().into(),prefs["outputDeviceId"].as_str().unwrap_or_default().into())};
|
||||||
phase=Phase::SelectInput;
|
phase=Phase::SelectInput;
|
||||||
self.audio.request(AudioCommand::SelectInput(crate::platform::android::voice_device_selection(prefs["inputDeviceId"].as_str().unwrap_or_default())?)).await?;
|
if !failed_request{self.audio.request(AudioCommand::SelectInput(crate::platform::android::voice_device_selection(&pair.0)?)).await?;}
|
||||||
if let Err(changed)=current(){reason=changed;return Ok(())}
|
if let Err(changed)=current(){reason=changed;return Ok(())}
|
||||||
phase=Phase::SelectOutput;
|
phase=Phase::SelectOutput;
|
||||||
self.audio.request(AudioCommand::SelectOutput(crate::platform::android::voice_device_selection(prefs["outputDeviceId"].as_str().unwrap_or_default())?)).await?;
|
if !failed_request{self.audio.request(AudioCommand::SelectOutput(crate::platform::android::voice_device_selection(&pair.1)?)).await?;}
|
||||||
if let Err(changed)=current(){reason=changed;return Ok(())}
|
if let Err(changed)=current(){reason=changed;return Ok(())}
|
||||||
if restart_output {
|
let mut playback_error=None;
|
||||||
|
// A failed selection must not tear down still-live permitted RX merely
|
||||||
|
// to reopen its exact old endpoint. No arbitrary fallback is attempted.
|
||||||
|
let keep_live=failed_request&&self.audio.output_active()&&self.output_granted.load(Ordering::Acquire)&&crate::platform::android::voice_audio_allowed(key,false);
|
||||||
|
if restart_output&&!keep_live {
|
||||||
phase=Phase::StopOutput;
|
phase=Phase::StopOutput;
|
||||||
self.audio.request(AudioCommand::StopOutput).await?;
|
self.audio.request(AudioCommand::StopOutput).await?;
|
||||||
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
|
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
|
||||||
if current().is_ok()&&self.output_granted.load(Ordering::Acquire)&&crate::platform::android::voice_audio_allowed(key,false) {
|
if current().is_ok()&&self.output_granted.load(Ordering::Acquire)&&crate::platform::android::voice_audio_allowed(key,false) {
|
||||||
phase=Phase::StartOutput;
|
phase=Phase::StartOutput;
|
||||||
self.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;
|
playback_error=self.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await.err();
|
||||||
if current().is_err()||!crate::platform::android::voice_audio_allowed(key,false){
|
if current().is_err()||!crate::platform::android::voice_audio_allowed(key,false){
|
||||||
reason=current().err().unwrap_or(Reason::PlaybackRevoked);
|
reason=current().err().unwrap_or(Reason::PlaybackRevoked);
|
||||||
phase=Phase::StopOutput;
|
phase=Phase::StopOutput;
|
||||||
@@ -105,6 +124,8 @@ impl RuntimeServices {
|
|||||||
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
|
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
|
||||||
}else if !self.output_granted.load(Ordering::Acquire){reason=Reason::OutputNotGranted;}
|
}else if !self.output_granted.load(Ordering::Acquire){reason=Reason::OutputNotGranted;}
|
||||||
else{reason=Reason::PlaybackRevoked;}
|
else{reason=Reason::PlaybackRevoked;}
|
||||||
|
}
|
||||||
|
if restart_output {
|
||||||
phase=Phase::OutputAck;
|
phase=Phase::OutputAck;
|
||||||
if current().is_ok(){crate::platform::android::acknowledge_voice_output(key,token,revision,self.audio.output_active());}
|
if current().is_ok(){crate::platform::android::acknowledge_voice_output(key,token,revision,self.audio.output_active());}
|
||||||
log_voice_route(key,phase,reason,started.elapsed(),restart_output,self.audio.output_active(),self.audio.input_active());
|
log_voice_route(key,phase,reason,started.elapsed(),restart_output,self.audio.output_active(),self.audio.input_active());
|
||||||
@@ -115,6 +136,7 @@ impl RuntimeServices {
|
|||||||
phase=Phase::CaptureIntent;
|
phase=Phase::CaptureIntent;
|
||||||
if self.transmission.lock().map_err(|_|super::context::changed())?.revision!=intent_revision{reason=Reason::CaptureIntentChanged;return Ok(())}
|
if self.transmission.lock().map_err(|_|super::context::changed())?.revision!=intent_revision{reason=Reason::CaptureIntentChanged;return Ok(())}
|
||||||
if migrate&&self.microphone_granted.load(Ordering::Acquire){
|
if migrate&&self.microphone_granted.load(Ordering::Acquire){
|
||||||
|
crate::platform::android::validate_voice_capture_pair(&pair.0,&pair.1,true)?;
|
||||||
phase=Phase::ResumeCapture;
|
phase=Phase::ResumeCapture;
|
||||||
if !self.resume_mobile_route_capture_locked(key,intent_revision,&configuration).await?{reason=Reason::CaptureIntentChanged;}
|
if !self.resume_mobile_route_capture_locked(key,intent_revision,&configuration).await?{reason=Reason::CaptureIntentChanged;}
|
||||||
}else if self.connected.connections.snapshot().input_id.as_deref()==Some(key.connection_id.as_str()) {
|
}else if self.connected.connections.snapshot().input_id.as_deref()==Some(key.connection_id.as_str()) {
|
||||||
@@ -125,9 +147,12 @@ impl RuntimeServices {
|
|||||||
if current().is_ok(){self.audio.request(AudioCommand::Enumerate).await?;}
|
if current().is_ok(){self.audio.request(AudioCommand::Enumerate).await?;}
|
||||||
else if let Err(changed)=current(){reason=changed;return Ok(())}
|
else if let Err(changed)=current(){reason=changed;return Ok(())}
|
||||||
phase=Phase::Complete;
|
phase=Phase::Complete;
|
||||||
|
if let Some(error)=playback_error{return Err(error)}
|
||||||
Ok(())
|
Ok(())
|
||||||
}.await;
|
}.await;
|
||||||
if result.is_err(){reason=Reason::Failed;}
|
if result.is_err(){reason=Reason::Failed;}
|
||||||
|
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
|
||||||
|
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
|
||||||
log_voice_route(key,phase,reason,started.elapsed(),restart_output,self.audio.output_active(),self.audio.input_active());
|
log_voice_route(key,phase,reason,started.elapsed(),restart_output,self.audio.output_active(),self.audio.input_active());
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,6 +38,10 @@ async fn sync_audio_to(ctx:&Arc<RuntimeServices>,resume:Option<(bool,bool)>,expe
|
|||||||
#[cfg(target_os="android")]
|
#[cfg(target_os="android")]
|
||||||
let active=(active.0&&owner.as_ref().is_some_and(|key|crate::platform::android::voice_audio_allowed(key,true)),active.1&&snapshot.connections.iter().any(|session|crate::platform::android::voice_audio_allowed(&session.key,false)));
|
let active=(active.0&&owner.as_ref().is_some_and(|key|crate::platform::android::voice_audio_allowed(key,true)),active.1&&snapshot.connections.iter().any(|session|crate::platform::android::voice_audio_allowed(&session.key,false)));
|
||||||
if expected_owner.is_some()&&(!active.0||!allowed||!ctx.microphone_granted.load(Ordering::Acquire)){return Err(ServiceError::new("audio_activation_revoked","Microphone authorization ended before audio startup; enable it explicitly"))}
|
if expected_owner.is_some()&&(!active.0||!allowed||!ctx.microphone_granted.load(Ordering::Acquire)){return Err(ServiceError::new("audio_activation_revoked","Microphone authorization ended before audio startup; enable it explicitly"))}
|
||||||
|
// Validate before any capture open, but still restore permitted RX when the
|
||||||
|
// desired capture transport is incompatible. Preferences remain exact intent.
|
||||||
|
#[cfg(target_os="android")]
|
||||||
|
let capture_pair=if active.0 {crate::platform::android::validate_voice_capture_pair(prefs["inputDeviceId"].as_str().unwrap_or_default(),prefs["outputDeviceId"].as_str().unwrap_or_default(),true)}else{Ok(())};
|
||||||
ctx.audio.revoke_capture();
|
ctx.audio.revoke_capture();
|
||||||
stage="configure_workflow";
|
stage="configure_workflow";
|
||||||
ctx.connected.connections.configure_workflow(WorkflowSettings{auto_enable_microphone:prefs["autoEnableMicrophone"]==true,auto_reactivate_previous:prefs["autoReactivateMicOnPreviousTarget"]==true}).await.map_err(super::super::context::connection_error)?;
|
ctx.connected.connections.configure_workflow(WorkflowSettings{auto_enable_microphone:prefs["autoEnableMicrophone"]==true,auto_reactivate_previous:prefs["autoReactivateMicOnPreviousTarget"]==true}).await.map_err(super::super::context::connection_error)?;
|
||||||
@@ -58,11 +62,27 @@ async fn sync_audio_to(ctx:&Arc<RuntimeServices>,resume:Option<(bool,bool)>,expe
|
|||||||
ctx.audio.request(AudioCommand::TypingEnabled(profile(&prefs,DeviceKind::Input)["typing"]==true)).await?;
|
ctx.audio.request(AudioCommand::TypingEnabled(profile(&prefs,DeviceKind::Input)["typing"]==true)).await?;
|
||||||
// Resolve/open authorized voice output before configuring voice-follow notifications.
|
// Resolve/open authorized voice output before configuring voice-follow notifications.
|
||||||
// Otherwise a retained Explicit sink can reject recovery before StartOutput repairs it.
|
// Otherwise a retained Explicit sink can reject recovery before StartOutput repairs it.
|
||||||
if active.1&&ctx.output_granted.load(Ordering::Acquire){stage="start_output";ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;ctx.audio_output_active.store(ctx.audio.output_active(),Ordering::Release);}
|
#[cfg(target_os="android")]
|
||||||
|
let mut playback_error=None;
|
||||||
|
if active.1&&ctx.output_granted.load(Ordering::Acquire){
|
||||||
|
stage="start_output";
|
||||||
|
let playback=ctx.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await;
|
||||||
|
#[cfg(target_os="android")]
|
||||||
|
{playback_error=playback.err();}
|
||||||
|
#[cfg(not(target_os="android"))]
|
||||||
|
playback?;
|
||||||
|
ctx.audio_output_active.store(ctx.audio.output_active(),Ordering::Release);
|
||||||
|
}
|
||||||
stage="notification_route";
|
stage="notification_route";
|
||||||
sync_notifications(&ctx).await?;
|
let notifications=sync_notifications(&ctx).await;
|
||||||
|
#[cfg(target_os="android")]
|
||||||
|
if let Err(error)=notifications{if playback_error.is_none(){playback_error=Some(error);}}
|
||||||
|
#[cfg(not(target_os="android"))]
|
||||||
|
notifications?;
|
||||||
stage="server_playback_dsp";
|
stage="server_playback_dsp";
|
||||||
for session in snapshot.connections.iter().filter(|s|s.is_connected()) {ctx.request(&session.key,teamspeach_core::protocol::Command::SetPlaybackDsp{agc:output["agc"]==true}).await?;ctx.require_key(&session.key,true)?;}
|
for session in snapshot.connections.iter().filter(|s|s.is_connected()) {ctx.request(&session.key,teamspeach_core::protocol::Command::SetPlaybackDsp{agc:output["agc"]==true}).await?;ctx.require_key(&session.key,true)?;}
|
||||||
|
#[cfg(target_os="android")]
|
||||||
|
{stage="capture_transport";capture_pair?;}
|
||||||
if let Some(key)=owner {
|
if let Some(key)=owner {
|
||||||
stage="configure_capture";
|
stage="configure_capture";
|
||||||
ctx.require_key(&key,true)?;
|
ctx.require_key(&key,true)?;
|
||||||
@@ -94,9 +114,18 @@ async fn sync_audio_to(ctx:&Arc<RuntimeServices>,resume:Option<(bool,bool)>,expe
|
|||||||
ctx.audio_input_active.store(ctx.audio.input_active(),Ordering::Release);
|
ctx.audio_input_active.store(ctx.audio.input_active(),Ordering::Release);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#[cfg(target_os="android")]
|
||||||
|
if let Some(error)=playback_error{return Err(error)}
|
||||||
Ok(())
|
Ok(())
|
||||||
}.await;
|
}.await;
|
||||||
#[cfg(target_os="android")]
|
#[cfg(target_os="android")]
|
||||||
|
{
|
||||||
|
// Failed commands need not produce Started events. Never leave a previous
|
||||||
|
// selection marked active after an unsuccessful Android reconstruction.
|
||||||
|
ctx.audio_input_active.store(ctx.audio.input_active(),Ordering::Release);
|
||||||
|
ctx.audio_output_active.store(ctx.audio.output_active(),Ordering::Release);
|
||||||
|
}
|
||||||
|
#[cfg(target_os="android")]
|
||||||
if let Some(key)=stage_key.as_ref(){
|
if let Some(key)=stage_key.as_ref(){
|
||||||
use crate::platform::android::{VoiceRoutePhase as Phase,VoiceRouteReason as Reason,log_voice_route};
|
use crate::platform::android::{VoiceRoutePhase as Phase,VoiceRouteReason as Reason,log_voice_route};
|
||||||
let phase=match stage{"select_input"=>Phase::SelectInput,"select_output"=>Phase::SelectOutput,"start_output"=>Phase::StartOutput,"start_input"=>Phase::ResumeCapture,"stop_input"=>Phase::StopInput,_=>Phase::Settings};
|
let phase=match stage{"select_input"=>Phase::SelectInput,"select_output"=>Phase::SelectOutput,"start_output"=>Phase::StartOutput,"start_input"=>Phase::ResumeCapture,"stop_input"=>Phase::StopInput,_=>Phase::Settings};
|
||||||
@@ -186,11 +215,11 @@ pub(super) async fn invoke(ctx:Arc<RuntimeServices>,op:Operation)->Result<Workfl
|
|||||||
#[cfg(target_os="android")]
|
#[cfg(target_os="android")]
|
||||||
if playback_selection {
|
if playback_selection {
|
||||||
let configuration=ctx.audio_configuration.lock().await;
|
let configuration=ctx.audio_configuration.lock().await;
|
||||||
ctx.audio.revoke_capture();
|
|
||||||
let prefs=ctx.profile()?.prefs.get();
|
let prefs=ctx.profile()?.prefs.get();
|
||||||
let route=crate::platform::android::select_voice_playback(prefs["outputDeviceId"].as_str().unwrap_or_default()).await?;
|
let route=crate::platform::android::select_voice_playback(prefs["outputDeviceId"].as_str().unwrap_or_default()).await?;
|
||||||
sync_audio_to(&ctx,None,None,&configuration).await?;
|
let result=sync_audio_to(&ctx,None,None,&configuration).await;
|
||||||
if let Some((token,revision))=route{crate::platform::android::acknowledge_voice_playback(token,revision,ctx.audio.output_active());}
|
if let Some((token,revision))=route{crate::platform::android::acknowledge_voice_playback(token,revision,ctx.audio.output_active());}
|
||||||
|
result?;
|
||||||
return done()
|
return done()
|
||||||
}
|
}
|
||||||
if notification_only{update_notifications(&ctx).await?;}else{sync_audio(ctx).await?;}done()
|
if notification_only{update_notifications(&ctx).await?;}else{sync_audio(ctx).await?;}done()
|
||||||
|
|||||||
@@ -84,6 +84,8 @@ pub struct SelectedDevice {
|
|||||||
pub direction: Direction,
|
pub direction: Direction,
|
||||||
pub format: DeviceFormat,
|
pub format: DeviceFormat,
|
||||||
device: cpal::Device,
|
device: cpal::Device,
|
||||||
|
#[cfg(target_os = "android")]
|
||||||
|
requested: Option<DeviceFormat>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SelectedDevice {
|
impl SelectedDevice {
|
||||||
@@ -95,7 +97,11 @@ impl SelectedDevice {
|
|||||||
let resolved = if let cpal::platform::DeviceInner::AAudio(device) = self.device.as_inner_mut() {
|
let resolved = if let cpal::platform::DeviceInner::AAudio(device) = self.device.as_inner_mut() {
|
||||||
device.prepare_output(_voice).map_err(audio_error)?
|
device.prepare_output(_voice).map_err(audio_error)?
|
||||||
} else { true };
|
} else { true };
|
||||||
self.id = self.device.id().map_err(audio_error)?.to_string();
|
let id = self.device.id().map_err(audio_error)?.to_string();
|
||||||
|
let format = resolved_output_format(self.format, self.requested, self.id != id,
|
||||||
|
|| configurations(&self.device, Direction::Output).map_err(audio_error))?;
|
||||||
|
self.format = format;
|
||||||
|
self.id = id;
|
||||||
Ok(resolved)
|
Ok(resolved)
|
||||||
}
|
}
|
||||||
#[cfg(not(target_os = "android"))]
|
#[cfg(not(target_os = "android"))]
|
||||||
@@ -201,7 +207,10 @@ impl DeviceHost {
|
|||||||
}.ok_or_else(|| ServiceError::new("audio_device_missing", "The selected audio device is unavailable; its selection was preserved"))?;
|
}.ok_or_else(|| ServiceError::new("audio_device_missing", "The selected audio device is unavailable; its selection was preserved"))?;
|
||||||
let ranges = configurations(&device, direction).map_err(audio_error)?;
|
let ranges = configurations(&device, direction).map_err(audio_error)?;
|
||||||
let format = select_format(&ranges, direction, requested)?;
|
let format = select_format(&ranges, direction, requested)?;
|
||||||
Ok(SelectedDevice { id: device.id().map_err(audio_error)?.to_string(), direction, format, device })
|
Ok(SelectedDevice { id: device.id().map_err(audio_error)?.to_string(), direction, format, device,
|
||||||
|
#[cfg(target_os = "android")]
|
||||||
|
requested,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -269,6 +278,15 @@ fn select_format(ranges: &[SupportedStreamConfigRange], direction: Direction, re
|
|||||||
}
|
}
|
||||||
Err(ServiceError::new("audio_configuration_unsupported", "The selected device does not support the requested PCM configuration"))
|
Err(ServiceError::new("audio_configuration_unsupported", "The selected device does not support the requested PCM configuration"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Re-query the physical endpoint after Android resolves a synthetic default.
|
||||||
|
/// Exact endpoints and unresolved roles retain their already validated format.
|
||||||
|
#[cfg(any(target_os = "android", test))]
|
||||||
|
fn resolved_output_format(current: DeviceFormat, requested: Option<DeviceFormat>, endpoint_changed: bool,
|
||||||
|
ranges: impl FnOnce() -> Result<Vec<SupportedStreamConfigRange>>) -> Result<DeviceFormat> {
|
||||||
|
if !endpoint_changed { return Ok(current); }
|
||||||
|
select_format(&ranges()?, Direction::Output, requested)
|
||||||
|
}
|
||||||
fn audio_error(error: cpal::Error) -> ServiceError {
|
fn audio_error(error: cpal::Error) -> ServiceError {
|
||||||
let code = match error.kind() {
|
let code = match error.kind() {
|
||||||
cpal::ErrorKind::PermissionDenied => "audio_permission_denied",
|
cpal::ErrorKind::PermissionDenied => "audio_permission_denied",
|
||||||
@@ -440,6 +458,8 @@ impl StreamState {
|
|||||||
let _ = self.fault.compare_exchange(0, fault as u8, Ordering::AcqRel, Ordering::Acquire);
|
let _ = self.fault.compare_exchange(0, fault as u8, Ordering::AcqRel, Ordering::Acquire);
|
||||||
self.suspend();
|
self.suspend();
|
||||||
}
|
}
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(super) fn test_backend_error(&self, error: cpal::Error) { self.on_error(error); }
|
||||||
fn on_error(&self, error: cpal::Error) {
|
fn on_error(&self, error: cpal::Error) {
|
||||||
let fault = match error.kind() {
|
let fault = match error.kind() {
|
||||||
cpal::ErrorKind::RealtimeDenied => { self.realtime_denied.store(true, Ordering::Relaxed); return; }
|
cpal::ErrorKind::RealtimeDenied => { self.realtime_denied.store(true, Ordering::Relaxed); return; }
|
||||||
|
|||||||
@@ -90,6 +90,31 @@ fn explicit_unsupported_configuration_never_silently_changes_rate() {
|
|||||||
assert!(select_format(&[range(2, 48_000, 48_000, SampleFormat::DsdU8)], Direction::Output, None).is_err());
|
assert!(select_format(&[range(2, 48_000, 48_000, SampleFormat::DsdU8)], Direction::Output, None).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolved_default_uses_physical_mono_16k_i16_before_stream_preparation() {
|
||||||
|
let generic = select_format(&[range(2, 48_000, 48_000, SampleFormat::F32)], Direction::Output, None).unwrap();
|
||||||
|
let physical = || Ok(vec![range(1, 16_000, 16_000, SampleFormat::I16)]);
|
||||||
|
let resolved = resolved_output_format(generic, None, true, physical).unwrap();
|
||||||
|
assert_eq!((resolved.channels, resolved.sample_rate, resolved.sample_format), (1, 16_000, SampleFormat::I16));
|
||||||
|
assert_eq!(resolved.stream_config().channels, 1);
|
||||||
|
assert_eq!(resolved.stream_config().sample_rate, 16_000);
|
||||||
|
assert_eq!(resolved.buffer_size, BufferSize::Fixed(160));
|
||||||
|
// An explicit PCM request is still exact: resolving default must not grant
|
||||||
|
// permission to replace an unsupported requested shape.
|
||||||
|
assert_eq!(resolved_output_format(generic, Some(generic), true, physical).unwrap_err().code,
|
||||||
|
"audio_configuration_unsupported");
|
||||||
|
assert_eq!(resolved_output_format(generic, Some(resolved), true, physical).unwrap(), resolved);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn exact_and_unresolved_output_keep_format_without_another_capability_probe() {
|
||||||
|
let current = format(48_000, 2);
|
||||||
|
assert_eq!(resolved_output_format(current, None, false, || panic!("unchanged endpoint must not be probed")).unwrap(), current);
|
||||||
|
let failure = resolved_output_format(current, None, true,
|
||||||
|
|| Err(ServiceError::new("audio_device_missing", "Physical endpoint disappeared"))).unwrap_err();
|
||||||
|
assert_eq!(failure.code, "audio_device_missing");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn capture_splits_variable_callback_and_preserves_hardware_clock() {
|
fn capture_splits_variable_callback_and_preserves_hardware_clock() {
|
||||||
let (mut callback, mut samples, origin) = capture_fixture(48_000, 2, 4);
|
let (mut callback, mut samples, origin) = capture_fixture(48_000, 2, 4);
|
||||||
@@ -525,6 +550,10 @@ mod android_capture_timing;
|
|||||||
#[path = "../../../vendor/cpal-0.18.2/src/host/aaudio/output_usage.rs"]
|
#[path = "../../../vendor/cpal-0.18.2/src/host/aaudio/output_usage.rs"]
|
||||||
mod android_output_usage;
|
mod android_output_usage;
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "android"))]
|
||||||
|
#[path = "../../../vendor/cpal-0.18.2/src/host/aaudio/stream_start.rs"]
|
||||||
|
mod android_stream_start;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn android_end_counter_projects_complete_capture_buffers_without_time_compression() {
|
fn android_end_counter_projects_complete_capture_buffers_without_time_compression() {
|
||||||
for rate in [44_100_u32, 48_000] {
|
for rate in [44_100_u32, 48_000] {
|
||||||
|
|||||||
@@ -1178,6 +1178,7 @@ impl Worker {
|
|||||||
self.shared.outputs.publish(self.output_revision, output.port.state.clone(), |state| {
|
self.shared.outputs.publish(self.output_revision, output.port.state.clone(), |state| {
|
||||||
!self.shared.stop.load(Ordering::Acquire) && self.stream_revision == self.shared.outputs.stream_revision.load(Ordering::Acquire) && state.resume()
|
!self.shared.stop.load(Ordering::Acquire) && self.stream_revision == self.shared.outputs.stream_revision.load(Ordering::Acquire) && state.resume()
|
||||||
}).map_err(|error| {
|
}).map_err(|error| {
|
||||||
|
let error = if error.code == "audio_device_error" { output.port.state.fault().service_error().unwrap_or(error) } else { error };
|
||||||
if error.code != "target_changed" { self.record_fault("output_publish", Some(Direction::Output), &error, Some(output.port.state.stats())); }
|
if error.code != "target_changed" { self.record_fault("output_publish", Some(Direction::Output), &error, Some(output.port.state.stats())); }
|
||||||
error
|
error
|
||||||
})?;
|
})?;
|
||||||
|
|||||||
@@ -390,6 +390,32 @@ fn opened_playback_fixture(id: &str, epoch: u64) -> OpenedOutput {
|
|||||||
OpenedOutput::New(owner, port, PreparedOutput::new(48_000).unwrap())
|
OpenedOutput::New(owner, port, PreparedOutput::new(48_000).unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn output_fault_before_publication_retains_backend_category_and_never_becomes_active() {
|
||||||
|
for (kind, code) in [(cpal::ErrorKind::DeviceNotAvailable, "audio_device_missing"),
|
||||||
|
(cpal::ErrorKind::DeviceChanged, "audio_route_changed"),
|
||||||
|
(cpal::ErrorKind::PermissionDenied, "audio_permission_denied")] {
|
||||||
|
let (mut worker, handle, _commands, events) = command_fixture();
|
||||||
|
worker.current_command = "start_output";
|
||||||
|
worker.playback_start.push_back(Box::new(move |epoch, _, _| {
|
||||||
|
let opened = opened_playback_fixture("physical-output", epoch);
|
||||||
|
if let OpenedOutput::New(_, port, _) = &opened {
|
||||||
|
port.state.test_backend_error(cpal::Error::new(kind));
|
||||||
|
}
|
||||||
|
Ok(opened)
|
||||||
|
}));
|
||||||
|
let error = worker.open_output_for_policy(DeviceSelection::SystemDefault, StartPermission::Granted, true, true).unwrap_err();
|
||||||
|
assert_eq!(error.code, code);
|
||||||
|
assert!(worker.outputs.is_empty());
|
||||||
|
assert!(!handle.output_active());
|
||||||
|
assert!(events.try_iter().all(|event| !matches!(event, AudioEvent::Started { direction: Direction::Output, .. })));
|
||||||
|
let fault = handle.first_fault().unwrap();
|
||||||
|
assert_eq!(fault.code, code);
|
||||||
|
assert_eq!(fault.stage, "output_publish");
|
||||||
|
assert!(!fault.outputs[0].unwrap().enabled);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn android_notification_first_owner_is_retired_before_voice_policy_upgrade() {
|
fn android_notification_first_owner_is_retired_before_voice_policy_upgrade() {
|
||||||
let (mut worker, _handle, _commands, _events) = command_fixture();
|
let (mut worker, _handle, _commands, _events) = command_fixture();
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ static UI: AtomicU64 = AtomicU64::new(0);
|
|||||||
static SCREEN_READER: AtomicBool = AtomicBool::new(false);
|
static SCREEN_READER: AtomicBool = AtomicBool::new(false);
|
||||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||||
static REQUESTS: LazyLock<Mutex<HashMap<u64, oneshot::Sender<Result<Response>>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
static REQUESTS: LazyLock<Mutex<HashMap<u64, oneshot::Sender<Result<Response>>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||||
struct Voice { token: u64, key: SessionKey, microphone: bool, capture_revision: u64, capture_change: Option<u64>, audio: call_audio::CallAudioState, _runtime: Arc<AppRuntime> }
|
struct Voice { token: u64, key: SessionKey, microphone: bool, capture_revision: u64, capture_change: Option<u64>, failed_playback_revision: Option<u64>, audio: call_audio::CallAudioState, _runtime: Arc<AppRuntime> }
|
||||||
static VOICE: LazyLock<Mutex<Option<Voice>>> = LazyLock::new(|| Mutex::new(None));
|
static VOICE: LazyLock<Mutex<Option<Voice>>> = LazyLock::new(|| Mutex::new(None));
|
||||||
static ROUTE_LOG_BUDGET: LazyLock<Mutex<call_audio::RouteLogBudget>> = LazyLock::new(|| Mutex::new(Default::default()));
|
static ROUTE_LOG_BUDGET: LazyLock<Mutex<call_audio::RouteLogBudget>> = LazyLock::new(|| Mutex::new(Default::default()));
|
||||||
#[derive(Clone, Copy, Debug)]
|
#[derive(Clone, Copy, Debug)]
|
||||||
@@ -170,8 +170,8 @@ pub async fn request_permission(permission: Permission, policy: ActionPolicy) ->
|
|||||||
}
|
}
|
||||||
/// Caller revalidates `key` and active-call intent before this explicit foreground action.
|
/// Caller revalidates `key` and active-call intent before this explicit foreground action.
|
||||||
pub async fn start_voice(runtime: Arc<AppRuntime>, key: SessionKey, microphone: bool, playback:&str, policy: ActionPolicy) -> Result<()> {
|
pub async fn start_voice(runtime: Arc<AppRuntime>, key: SessionKey, microphone: bool, playback:&str, policy: ActionPolicy) -> Result<()> {
|
||||||
policy.check()?; let endpoint=voice_playback_endpoint(playback)?;let request = Request::new()?; let token = request.id;
|
policy.check()?; let endpoint=voice_endpoint(playback)?;let request = Request::new()?; let token = request.id;
|
||||||
{ let mut voice = VOICE.lock().expect("Android voice"); if voice.is_some() { return Err(error("call_lease_exists", "An Android foreground call already owns the audio session")); } *voice = Some(Voice { token, key: key.clone(), microphone: false, capture_revision: 0, capture_change: None, audio: Default::default(), _runtime: runtime }); }
|
{ let mut voice = VOICE.lock().expect("Android voice"); if voice.is_some() { return Err(error("call_lease_exists", "An Android foreground call already owns the audio session")); } *voice = Some(Voice { token, key: key.clone(), microphone: false, capture_revision: 0, capture_change: None, failed_playback_revision: None, audio: Default::default(), _runtime: runtime }); }
|
||||||
struct PendingVoice(u64, bool);
|
struct PendingVoice(u64, bool);
|
||||||
impl Drop for PendingVoice { fn drop(&mut self) { if !self.1 { end_voice(self.0); let _ = call_void("stopVoice", "(J)V", &[JValue::Long(self.0 as i64)]); } } }
|
impl Drop for PendingVoice { fn drop(&mut self) { if !self.1 { end_voice(self.0); let _ = call_void("stopVoice", "(J)V", &[JValue::Long(self.0 as i64)]); } } }
|
||||||
let mut pending = PendingVoice(token, false);
|
let mut pending = PendingVoice(token, false);
|
||||||
@@ -181,7 +181,7 @@ pub async fn start_voice(runtime: Arc<AppRuntime>, key: SessionKey, microphone:
|
|||||||
}
|
}
|
||||||
log_voice_request(VoiceRoutePhase::CallStart,VoiceRouteReason::Queued,started,microphone);
|
log_voice_request(VoiceRoutePhase::CallStart,VoiceRouteReason::Queued,started,microphone);
|
||||||
let (result,reason)=match tokio::time::timeout(std::time::Duration::from_secs(15), request.receive()).await {
|
let (result,reason)=match tokio::time::timeout(std::time::Duration::from_secs(15), request.receive()).await {
|
||||||
Ok(Ok(Response::Voice)) if VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token && voice.microphone==microphone) => { pending.1 = true; (Ok(()),VoiceRouteReason::Completed) },
|
Ok(Ok(Response::Voice)) if VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token && voice.microphone==microphone && voice.audio.allows(microphone)) => { pending.1 = true; (Ok(()),VoiceRouteReason::Completed) },
|
||||||
Ok(Err(error)) => (Err(error),VoiceRouteReason::Failed),
|
Ok(Err(error)) => (Err(error),VoiceRouteReason::Failed),
|
||||||
Err(_) => (Err(error("call_start_failed", "Android did not grant a foreground voice session")),VoiceRouteReason::Timeout),
|
Err(_) => (Err(error("call_start_failed", "Android did not grant a foreground voice session")),VoiceRouteReason::Timeout),
|
||||||
_ => (Err(error("call_start_failed", "Android did not grant a foreground voice session")),VoiceRouteReason::AudioRevisionChanged),
|
_ => (Err(error("call_start_failed", "Android did not grant a foreground voice session")),VoiceRouteReason::AudioRevisionChanged),
|
||||||
@@ -242,17 +242,40 @@ pub(crate) fn voice_device_selection(raw:&str)->Result<crate::media::audio::devi
|
|||||||
if raw.is_empty(){log_voice_selection(VoiceRouteReason::DefaultSelection);Ok(DeviceSelection::SystemDefault)}
|
if raw.is_empty(){log_voice_selection(VoiceRouteReason::DefaultSelection);Ok(DeviceSelection::SystemDefault)}
|
||||||
else{log_voice_selection(VoiceRouteReason::ExactSelection);Ok(DeviceSelection::Exact(raw.into()))}
|
else{log_voice_selection(VoiceRouteReason::ExactSelection);Ok(DeviceSelection::Exact(raw.into()))}
|
||||||
}
|
}
|
||||||
fn voice_playback_endpoint(raw:&str)->Result<i32> {
|
fn voice_endpoint(raw:&str)->Result<i32> {
|
||||||
if raw.is_empty(){return Ok(0)}
|
if raw.is_empty(){return Ok(0)}
|
||||||
let id=raw.parse::<cpal::DeviceId>().map_err(|_|error("device_unavailable","Invalid exact Android playback endpoint"))?;
|
let id=raw.parse::<cpal::DeviceId>().map_err(|_|error("device_unavailable","Invalid exact Android audio endpoint"))?;
|
||||||
if id.host()!=cpal::HostId::AAudio{return Err(error("device_unavailable","The exact playback endpoint is not an Android audio device"))}
|
if id.host()!=cpal::HostId::AAudio{return Err(error("device_unavailable","The exact endpoint is not an Android audio device"))}
|
||||||
match id.id().parse::<i32>(){Ok(-1)=>Ok(0),Ok(id) if id>0=>Ok(id),_=>Err(error("device_unavailable","The exact Android playback endpoint is unavailable"))}
|
match id.id().parse::<i32>(){Ok(-1)=>Ok(0),Ok(id) if id>0=>Ok(id),_=>Err(error("device_unavailable","The exact Android audio endpoint is unavailable"))}
|
||||||
|
}
|
||||||
|
/// Validate the user's exact pair using platform types/addresses, never names or
|
||||||
|
/// a guessed input->output remapping. Read-only: does not activate any transport.
|
||||||
|
pub(crate) fn validate_voice_capture_pair(input:&str,output:&str,settled:bool)->Result<()> {
|
||||||
|
let input=voice_endpoint(input)?;
|
||||||
|
if input==0{return Ok(())}
|
||||||
|
let output=voice_endpoint(output)?;
|
||||||
|
let result=with_env(|env,class|{
|
||||||
|
// Use the installed application class loader, not FindClass on a native
|
||||||
|
// Tokio thread (whose bootstrap loader cannot resolve app classes).
|
||||||
|
let loader=java(env.call_method(class,"getClassLoader","()Ljava/lang/ClassLoader;",&[]))?.l().map_err(|_|error("android_os_error","Android class loader unavailable"))?;
|
||||||
|
let name=java(env.new_string("dev.teamspeach.mobile.VoiceService"))?;
|
||||||
|
let service=java(env.call_method(&loader,"loadClass","(Ljava/lang/String;)Ljava/lang/Class;",&[JValue::Object(name.as_ref())]))?.l().map_err(|_|error("android_os_error","Android route validator unavailable"))?;
|
||||||
|
let service=JClass::from(service);
|
||||||
|
java(env.call_static_method(&service,"validateCapturePair","(IIZ)I",&[JValue::Int(input),JValue::Int(output),JValue::Bool(settled as u8)]))?.i().map_err(|_|error("android_os_error","Invalid Android route validation response"))
|
||||||
|
})?;
|
||||||
|
match result {
|
||||||
|
0=>Ok(()),
|
||||||
|
1=>Err(error("device_unavailable","The exact capture endpoint is no longer available; the saved choice has not changed")),
|
||||||
|
2=>Err(error("audio_route_incompatible","The exact Bluetooth capture endpoint requires a matching active communication playback transport. Choose a compatible Capture/Playback pair explicitly; neither saved choice was changed")),
|
||||||
|
3=>Err(error("audio_route_incompatible","The chosen playback communication route is not active for the exact Bluetooth capture endpoint; explicitly select a compatible playback route")),
|
||||||
|
_=>Err(error("android_os_error","Invalid Android route validation response")),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
/// Only an explicit playback action requests a communication-device override.
|
/// Only an explicit playback action requests a communication-device override.
|
||||||
/// Its caller owns configuration and recovery; capture/DSP refresh never calls it.
|
/// Its caller owns configuration and recovery; capture/DSP refresh never calls it.
|
||||||
pub(crate) async fn select_voice_playback(raw:&str)->Result<Option<(u64,u64)>> {
|
pub(crate) async fn select_voice_playback(raw:&str)->Result<Option<(u64,u64)>> {
|
||||||
let token=match VOICE.lock().expect("Android voice").as_ref(){Some(voice)=>voice.token,None=>return Ok(None)};
|
let token=match VOICE.lock().expect("Android voice").as_ref(){Some(voice)=>voice.token,None=>return Ok(None)};
|
||||||
let endpoint=voice_playback_endpoint(raw)?;
|
let endpoint=voice_endpoint(raw)?;
|
||||||
let request=Request::new()?;let id=request.id;
|
let request=Request::new()?;let id=request.id;
|
||||||
struct PlaybackChange {token:u64,id:u64,completed:bool}
|
struct PlaybackChange {token:u64,id:u64,completed:bool}
|
||||||
impl Drop for PlaybackChange {fn drop(&mut self){if !self.completed{let _=call_void("cancelVoicePlayback","(JJ)V",&[JValue::Long(self.token as i64),JValue::Long(self.id as i64)]);}}}
|
impl Drop for PlaybackChange {fn drop(&mut self){if !self.completed{let _=call_void("cancelVoicePlayback","(JJ)V",&[JValue::Long(self.token as i64),JValue::Long(self.id as i64)]);}}}
|
||||||
@@ -281,6 +304,9 @@ pub(crate) fn voice_capture_retained(key:&SessionKey)->bool {
|
|||||||
pub(crate) fn voice_audio_current(key:&SessionKey,token:u64,revision:u64)->bool {
|
pub(crate) fn voice_audio_current(key:&SessionKey,token:u64,revision:u64)->bool {
|
||||||
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.token==token&&voice.audio.is_current(revision))
|
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.token==token&&voice.audio.is_current(revision))
|
||||||
}
|
}
|
||||||
|
pub(crate) fn voice_playback_failed(key:&SessionKey,token:u64,revision:u64)->bool {
|
||||||
|
VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|&voice.key==key&&voice.token==token&&voice.audio.is_current(revision)&&voice.failed_playback_revision==Some(revision))
|
||||||
|
}
|
||||||
pub(crate) fn acknowledge_voice_output(key:&SessionKey,token:u64,revision:u64,active:bool) {
|
pub(crate) fn acknowledge_voice_output(key:&SessionKey,token:u64,revision:u64,active:bool) {
|
||||||
let acknowledged={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|&voice.key==key&&voice.token==token){let current=voice.audio.is_current(revision);voice.audio.acknowledge_output(revision,active);current}else{false}};
|
let acknowledged={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|&voice.key==key&&voice.token==token){let current=voice.audio.is_current(revision);voice.audio.acknowledge_output(revision,active);current}else{false}};
|
||||||
log_voice_authorization(token,VoiceRoutePhase::OutputAck,if acknowledged{VoiceRouteReason::Completed}else{VoiceRouteReason::AudioRevisionChanged});
|
log_voice_authorization(token,VoiceRoutePhase::OutputAck,if acknowledged{VoiceRouteReason::Completed}else{VoiceRouteReason::AudioRevisionChanged});
|
||||||
@@ -458,8 +484,11 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeText(mut
|
|||||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceValid(_env:JNIEnv,_class:JClass,token:jlong)->jboolean {VOICE.lock().expect("Android voice").as_ref().is_some_and(|v|v.token==token as u64) as u8}
|
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceValid(_env:JNIEnv,_class:JClass,token:jlong)->jboolean {VOICE.lock().expect("Android voice").as_ref().is_some_and(|v|v.token==token as u64) as u8}
|
||||||
#[unsafe(no_mangle)]
|
#[unsafe(no_mangle)]
|
||||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStarted(_env:JNIEnv,_class:JClass,token:jlong,microphone:jboolean){
|
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStarted(_env:JNIEnv,_class:JClass,token:jlong,microphone:jboolean){
|
||||||
let active={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|voice.token==token as u64){voice.microphone=microphone!=0;voice.audio.start(microphone!=0);true}else{false}};
|
let active={let mut slot=VOICE.lock().expect("Android voice");if let Some(voice)=slot.as_mut().filter(|voice|voice.token==token as u64){
|
||||||
|
if voice.audio.start(microphone!=0){voice.microphone=microphone!=0;true}else{false}
|
||||||
|
}else{false}};
|
||||||
if active{log_voice_authorization(token as u64,VoiceRoutePhase::Authorization,VoiceRouteReason::Completed);complete(token as u64,Ok(Response::Voice));}
|
if active{log_voice_authorization(token as u64,VoiceRoutePhase::Authorization,VoiceRouteReason::Completed);complete(token as u64,Ok(Response::Voice));}
|
||||||
|
else{complete(token as u64,Err(error("audio_activation_revoked","Android focus or microphone consent changed before startup was acknowledged")));}
|
||||||
}
|
}
|
||||||
#[unsafe(no_mangle)]
|
#[unsafe(no_mangle)]
|
||||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStopped(_env:JNIEnv,_class:JClass,token:jlong)->jboolean{end_voice(token as u64) as u8}
|
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStopped(_env:JNIEnv,_class:JClass,token:jlong)->jboolean{end_voice(token as u64) as u8}
|
||||||
@@ -474,7 +503,7 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceEven
|
|||||||
let owner={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token as u64).map(|voice|{
|
let owner={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token as u64).map(|voice|{
|
||||||
let pending=voice.capture_change.take();
|
let pending=voice.capture_change.take();
|
||||||
if pending.is_some(){voice.microphone=false;voice.capture_revision=0;voice.audio.revoke_capture();}
|
if pending.is_some(){voice.microphone=false;voice.capture_revision=0;voice.audio.revoke_capture();}
|
||||||
let authorized=voice.audio.retains_capture();voice.audio.begin_route();
|
let authorized=voice.audio.retains_capture();voice.failed_playback_revision=None;voice.audio.begin_route();
|
||||||
(voice._runtime.clone(),voice.key.clone(),authorized,pending)
|
(voice._runtime.clone(),voice.key.clone(),authorized,pending)
|
||||||
})};
|
})};
|
||||||
if let Some((runtime,key,authorized,pending))=owner{
|
if let Some((runtime,key,authorized,pending))=owner{
|
||||||
@@ -499,13 +528,15 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoicePlay
|
|||||||
(VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token as u64)&&REQUESTS.lock().expect("Android requests").contains_key(&(id as u64))) as u8
|
(VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token as u64)&&REQUESTS.lock().expect("Android requests").contains_key(&(id as u64))) as u8
|
||||||
}
|
}
|
||||||
#[unsafe(no_mangle)]
|
#[unsafe(no_mangle)]
|
||||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoicePlaybackFinished(_env:JNIEnv,_class:JClass,token:jlong,id:jlong){
|
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoicePlaybackFinished(_env:JNIEnv,_class:JClass,token:jlong,_id:jlong,accepted:jboolean){
|
||||||
// The explicit settings caller resumes configuration after its Text ACK.
|
// Success returns ownership to the settings caller. Failure/cancellation
|
||||||
// Do not enqueue a second recovery worker that could revoke the new permit.
|
// finalizes and chooses the sole recovery revision under one authorization lock.
|
||||||
let mut slot=VOICE.lock().expect("Android voice");
|
let changed={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token as u64).and_then(|voice|{
|
||||||
if REQUESTS.lock().expect("Android requests").contains_key(&(id as u64)) {
|
let (revision,recover)=voice.audio.finish_manual_route(accepted!=0);
|
||||||
if let Some(voice)=slot.as_mut().filter(|voice|voice.token==token as u64){voice.audio.route_changed();}
|
voice.failed_playback_revision=recover.then_some(revision);
|
||||||
}
|
recover.then(||(voice.key.clone(),revision,voice.audio.restart_output()))
|
||||||
|
})};
|
||||||
|
if let Some((key,revision,restart_output))=changed{lifecycle::emit(PlatformEvent::AndroidCallAudio{key,token:token as u64,revision,restart_output});}
|
||||||
}
|
}
|
||||||
#[unsafe(no_mangle)]
|
#[unsafe(no_mangle)]
|
||||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureChanged(_env:JNIEnv,_class:JClass,token:jlong,id:jlong,enabled:jboolean)->jboolean{
|
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureChanged(_env:JNIEnv,_class:JClass,token:jlong,id:jlong,enabled:jboolean)->jboolean{
|
||||||
|
|||||||
@@ -9,7 +9,13 @@ pub(super) struct CallAudioState {
|
|||||||
}
|
}
|
||||||
impl CallAudioState {
|
impl CallAudioState {
|
||||||
pub fn revision(&self) -> u64 { self.revision }
|
pub fn revision(&self) -> u64 { self.revision }
|
||||||
pub fn start(&mut self, capture: bool) { self.focused = true; self.capture = capture; self.route_pending = false; }
|
pub fn start(&mut self, capture: bool) -> bool {
|
||||||
|
// A delayed startup ACK cannot overwrite any intervening focus/privacy
|
||||||
|
// event, even a loss followed by gain. Only a fresh user action may retry.
|
||||||
|
if self.revision != 0 { return false; }
|
||||||
|
self.focused = true; self.capture = capture; self.route_pending = false;
|
||||||
|
true
|
||||||
|
}
|
||||||
pub fn change_capture(&mut self, enabled: bool) -> bool {
|
pub fn change_capture(&mut self, enabled: bool) -> bool {
|
||||||
if enabled && (!self.focused || self.route_pending) { return false; }
|
if enabled && (!self.focused || self.route_pending) { return false; }
|
||||||
self.capture = enabled;
|
self.capture = enabled;
|
||||||
@@ -40,6 +46,11 @@ impl CallAudioState {
|
|||||||
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
|
self.revision = self.revision.checked_add(1).expect("Android audio revision exhausted");
|
||||||
self.revision
|
self.revision
|
||||||
}
|
}
|
||||||
|
/// The result is the sole continuation owner: success belongs to the settings
|
||||||
|
/// caller; failure publishes recovery with this already-finalized revision.
|
||||||
|
pub fn finish_manual_route(&mut self,accepted:bool)->(u64,bool) {
|
||||||
|
(self.route_changed(),!accepted)
|
||||||
|
}
|
||||||
pub fn restart_output(&self) -> bool { self.restart_output }
|
pub fn restart_output(&self) -> bool { self.restart_output }
|
||||||
pub fn acknowledge_output(&mut self, revision: u64, active: bool) {
|
pub fn acknowledge_output(&mut self, revision: u64, active: bool) {
|
||||||
// A focused call whose output has not started still owes recovery. Muting
|
// A focused call whose output has not started still owes recovery. Muting
|
||||||
@@ -167,4 +178,39 @@ mod tests {
|
|||||||
}
|
}
|
||||||
let mut state=CallAudioState::default();state.start(false);state.begin_route();state.route_changed();assert!(!state.allows(true));
|
let mut state=CallAudioState::default();state.start(false);state.begin_route();state.route_changed();assert!(!state.allows(true));
|
||||||
}
|
}
|
||||||
|
#[tokio::test(flavor="current_thread")]
|
||||||
|
async fn delayed_startup_ack_cannot_overwrite_interruption_or_revocation() {
|
||||||
|
for interruption in [0,1,2] {
|
||||||
|
let state=std::sync::Arc::new(std::sync::Mutex::new(CallAudioState::default()));
|
||||||
|
let (ack,received)=tokio::sync::oneshot::channel();
|
||||||
|
let startup=tokio::spawn({let state=state.clone();async move {
|
||||||
|
received.await.unwrap();state.lock().unwrap().start(true)
|
||||||
|
}});
|
||||||
|
tokio::task::yield_now().await;
|
||||||
|
if interruption==2{state.lock().unwrap().revoke_capture();}
|
||||||
|
else{state.lock().unwrap().interrupt(false);}
|
||||||
|
if interruption==1 {state.lock().unwrap().interrupt(true);}
|
||||||
|
ack.send(()).unwrap();
|
||||||
|
assert!(!startup.await.unwrap());
|
||||||
|
let state=state.lock().unwrap();
|
||||||
|
assert!(!state.allows(true));assert_eq!(state.allows(false),interruption==1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[tokio::test(flavor="current_thread")]
|
||||||
|
async fn failed_manual_ack_publishes_only_final_revision_and_keeps_consent() {
|
||||||
|
let state=std::sync::Arc::new(std::sync::Mutex::new(CallAudioState::default()));
|
||||||
|
assert!(state.lock().unwrap().start(true));
|
||||||
|
let pending=state.lock().unwrap().begin_route();
|
||||||
|
let (event,received)=tokio::sync::oneshot::channel();
|
||||||
|
let recovery=tokio::spawn({let state=state.clone();async move {
|
||||||
|
let revision=received.await.unwrap();
|
||||||
|
let state=state.lock().unwrap();
|
||||||
|
assert!(state.is_current(revision));assert!(state.allows(false));assert!(state.allows(true));
|
||||||
|
}});
|
||||||
|
tokio::task::yield_now().await;
|
||||||
|
let (final_revision,recover)=state.lock().unwrap().finish_manual_route(false);
|
||||||
|
assert!(recover);
|
||||||
|
assert_ne!(pending,final_revision);
|
||||||
|
event.send(final_revision).unwrap();recovery.await.unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,36 @@ extern crate ndk;
|
|||||||
|
|
||||||
use crate::{Error, ErrorKind, StreamInstant};
|
use crate::{Error, ErrorKind, StreamInstant};
|
||||||
|
|
||||||
|
/// Only typed backend values enter diagnostics; never CPAL/JNI error messages,
|
||||||
|
/// endpoint identifiers, product names or audio buffers.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub(super) enum BackendStage { Builder, Open, ErrorCallback, StartRequest }
|
||||||
|
|
||||||
|
pub(super) fn backend_error(error: ndk::audio::AudioError, stage: BackendStage, direction: crate::DeviceDirection) -> Error {
|
||||||
|
eprintln!("audio_backend platform=aaudio direction={direction:?} stage={stage:?} cause={error:?}");
|
||||||
|
Error::from(error)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn start_state(state: ndk::audio::AudioStreamState) -> super::stream_start::StartState {
|
||||||
|
use ndk::audio::AudioStreamState;
|
||||||
|
use super::stream_start::StartState;
|
||||||
|
match state {
|
||||||
|
AudioStreamState::Starting => StartState::Starting,
|
||||||
|
AudioStreamState::Started => StartState::Started,
|
||||||
|
AudioStreamState::Disconnected => StartState::Disconnected,
|
||||||
|
_ => StartState::Interrupted,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn start_failure(failure: super::stream_start::StartFailure<ndk::audio::AudioError>) -> Error {
|
||||||
|
use super::stream_start::StartFailure;
|
||||||
|
match failure {
|
||||||
|
StartFailure::Backend(error) => Error::from(error),
|
||||||
|
StartFailure::Disconnected => Error::with_message(ErrorKind::DeviceNotAvailable, "AAudio disconnected before start completed"),
|
||||||
|
StartFailure::Interrupted => Error::with_message(ErrorKind::StreamInvalidated, "AAudio did not reach the Started state"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns a [`StreamInstant`] for the current moment.
|
/// Returns a [`StreamInstant`] for the current moment.
|
||||||
pub fn now_stream_instant() -> StreamInstant {
|
pub fn now_stream_instant() -> StreamInstant {
|
||||||
let mut ts = libc::timespec {
|
let mut ts = libc::timespec {
|
||||||
|
|||||||
+22
-14
@@ -32,6 +32,7 @@ mod device_catalog;
|
|||||||
mod capture_timing;
|
mod capture_timing;
|
||||||
mod java_interface;
|
mod java_interface;
|
||||||
mod output_usage;
|
mod output_usage;
|
||||||
|
mod stream_start;
|
||||||
|
|
||||||
use convert::{input_stream_instant, now_stream_instant, output_stream_instant};
|
use convert::{input_stream_instant, now_stream_instant, output_stream_instant};
|
||||||
use java_interface::{AudioDeviceInfo, AudioDeviceType as AndroidDeviceType, AudioManager};
|
use java_interface::{AudioDeviceInfo, AudioDeviceType as AndroidDeviceType, AudioManager};
|
||||||
@@ -511,9 +512,9 @@ where
|
|||||||
ndk::audio::AudioCallbackResult::Continue
|
ndk::audio::AudioCallbackResult::Continue
|
||||||
}))
|
}))
|
||||||
.error_callback(Box::new(move |_stream, error| {
|
.error_callback(Box::new(move |_stream, error| {
|
||||||
emit_error(&error_callback_for_stream, Error::from(error));
|
emit_error(&error_callback_for_stream, convert::backend_error(error, convert::BackendStage::ErrorCallback, DeviceDirection::Input));
|
||||||
}))
|
}))
|
||||||
.open_stream()?;
|
.open_stream().map_err(|error| convert::backend_error(error, convert::BackendStage::Open, DeviceDirection::Input))?;
|
||||||
validate_stream_device(device, &stream)?;
|
validate_stream_device(device, &stream)?;
|
||||||
validate_opened_shape(&stream, config, sample_format)?;
|
validate_opened_shape(&stream, config, sample_format)?;
|
||||||
let endpoint = device.0.as_ref().map(|info| info.id).unwrap_or_else(|| stream.device_id());
|
let endpoint = device.0.as_ref().map(|info| info.id).unwrap_or_else(|| stream.device_id());
|
||||||
@@ -673,9 +674,9 @@ where
|
|||||||
ndk::audio::AudioCallbackResult::Continue
|
ndk::audio::AudioCallbackResult::Continue
|
||||||
}))
|
}))
|
||||||
.error_callback(Box::new(move |_stream, error| {
|
.error_callback(Box::new(move |_stream, error| {
|
||||||
emit_error(&error_callback_for_stream, Error::from(error));
|
emit_error(&error_callback_for_stream, convert::backend_error(error, convert::BackendStage::ErrorCallback, DeviceDirection::Output));
|
||||||
}))
|
}))
|
||||||
.open_stream()?;
|
.open_stream().map_err(|error| convert::backend_error(error, convert::BackendStage::Open, DeviceDirection::Output))?;
|
||||||
let (usage, content_type) = output_usage::observe(&stream);
|
let (usage, content_type) = output_usage::observe(&stream);
|
||||||
let route_matches = device_catalog::accepts_route(device.0.as_ref().map(|info| info.id), stream.device_id());
|
let route_matches = device_catalog::accepts_route(device.0.as_ref().map(|info| info.id), stream.device_id());
|
||||||
let shape_matches = stream_shape_matches(&stream, config, sample_format);
|
let shape_matches = stream_shape_matches(&stream, config, sample_format);
|
||||||
@@ -846,7 +847,8 @@ impl DeviceTrait for Device {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let builder = ndk::audio::AudioStreamBuilder::new()?
|
let builder = ndk::audio::AudioStreamBuilder::new()
|
||||||
|
.map_err(|error| convert::backend_error(error, convert::BackendStage::Builder, DeviceDirection::Input))?
|
||||||
.direction(ndk::audio::AudioDirection::Input)
|
.direction(ndk::audio::AudioDirection::Input)
|
||||||
.channel_count(config.channels as i32)
|
.channel_count(config.channels as i32)
|
||||||
.format(format);
|
.format(format);
|
||||||
@@ -893,7 +895,8 @@ impl DeviceTrait for Device {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let builder = ndk::audio::AudioStreamBuilder::new()?
|
let builder = ndk::audio::AudioStreamBuilder::new()
|
||||||
|
.map_err(|error| convert::backend_error(error, convert::BackendStage::Builder, DeviceDirection::Output))?
|
||||||
.direction(ndk::audio::AudioDirection::Output)
|
.direction(ndk::audio::AudioDirection::Output)
|
||||||
.channel_count(config.channels as i32)
|
.channel_count(config.channels as i32)
|
||||||
.format(format);
|
.format(format);
|
||||||
@@ -943,14 +946,19 @@ impl StreamTrait for Stream {
|
|||||||
Error::with_message(ErrorKind::StreamInvalidated, "Stream lock poisoned")
|
Error::with_message(ErrorKind::StreamInvalidated, "Stream lock poisoned")
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
stream.request_start().context("Failed to start stream")?;
|
stream.request_start().map_err(|error| convert::backend_error(error, convert::BackendStage::StartRequest, self.direction))?;
|
||||||
stream
|
// wait_for_state_change only promises departure from Starting. A pause,
|
||||||
.wait_for_state_change(
|
// disconnect or close is not a successful start, including on timeout.
|
||||||
ndk::audio::AudioStreamState::Starting,
|
let waited = stream.wait_for_state_change(
|
||||||
DEFAULT_TIMEOUT_NANOS,
|
ndk::audio::AudioStreamState::Starting,
|
||||||
)
|
DEFAULT_TIMEOUT_NANOS,
|
||||||
.map(|_| ())
|
);
|
||||||
.context("Failed to wait for stream to start")
|
let observed = stream.state();
|
||||||
|
let completion = stream_start::require_started(waited.map(convert::start_state), convert::start_state(observed));
|
||||||
|
// Both enums contain only backend constants (or a bounded raw integer),
|
||||||
|
// so the original Timeout/Disconnected cause survives classification.
|
||||||
|
eprintln!("audio_backend platform=aaudio direction={:?} stage=StartWait waited={waited:?} observed={observed:?} completion={completion:?}", self.direction);
|
||||||
|
completion.map_err(convert::start_failure)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pause(&self) -> Result<(), Error> {
|
fn pause(&self) -> Result<(), Error> {
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// AAudio waits for departure from Starting, not necessarily arrival at Started.
|
||||||
|
// Keep the completion decision portable so host tests exercise the production
|
||||||
|
// path without Android hardware, sleeps or invented successful stream owners.
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) enum StartState {
|
||||||
|
Starting,
|
||||||
|
Started,
|
||||||
|
Disconnected,
|
||||||
|
Interrupted,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) enum StartFailure<E> {
|
||||||
|
Disconnected,
|
||||||
|
Interrupted,
|
||||||
|
Backend(E),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn require_started<E>(waited: Result<StartState, E>, observed: StartState) -> Result<(), StartFailure<E>> {
|
||||||
|
// A timeout/WouldBlock must not hide a concurrent disconnect or pause/stop.
|
||||||
|
// Nor may a later Started observation erase an interrupted wait result.
|
||||||
|
if observed == StartState::Disconnected || matches!(&waited, Ok(StartState::Disconnected)) {
|
||||||
|
return Err(StartFailure::Disconnected);
|
||||||
|
}
|
||||||
|
if observed == StartState::Interrupted || matches!(&waited, Ok(StartState::Interrupted)) {
|
||||||
|
return Err(StartFailure::Interrupted);
|
||||||
|
}
|
||||||
|
match waited {
|
||||||
|
Ok(StartState::Started) if observed == StartState::Started => Ok(()),
|
||||||
|
Err(error) => Err(StartFailure::Backend(error)),
|
||||||
|
_ => Err(StartFailure::Interrupted),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
enum Backend { Timeout, WouldBlock, Disconnected }
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_a_completed_started_transition_succeeds() {
|
||||||
|
assert_eq!(require_started::<Backend>(Ok(StartState::Started), StartState::Started), Ok(()));
|
||||||
|
for state in [StartState::Starting, StartState::Disconnected, StartState::Interrupted] {
|
||||||
|
assert!(require_started::<Backend>(Ok(state), state).is_err());
|
||||||
|
assert!(require_started::<Backend>(Ok(state), StartState::Started).is_err());
|
||||||
|
assert!(require_started::<Backend>(Ok(StartState::Started), state).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn interrupted_or_disconnected_start_is_not_a_busy_timeout() {
|
||||||
|
for error in [Backend::Timeout, Backend::WouldBlock] {
|
||||||
|
assert_eq!(require_started(Err(error), StartState::Starting), Err(StartFailure::Backend(error)));
|
||||||
|
assert_eq!(require_started(Err(error), StartState::Disconnected), Err(StartFailure::Disconnected));
|
||||||
|
assert_eq!(require_started(Err(error), StartState::Interrupted), Err(StartFailure::Interrupted));
|
||||||
|
}
|
||||||
|
assert_eq!(require_started(Err(Backend::Disconnected), StartState::Starting),
|
||||||
|
Err(StartFailure::Backend(Backend::Disconnected)));
|
||||||
|
// A late state observation cannot silently turn a failed bounded wait
|
||||||
|
// into success and discard its backend cause.
|
||||||
|
assert_eq!(require_started(Err(Backend::Timeout), StartState::Started),
|
||||||
|
Err(StartFailure::Backend(Backend::Timeout)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,4 +13,56 @@ final class CommunicationRoutePolicy {
|
|||||||
static boolean observedChange(boolean starting,boolean topologyChanged,int previousId,int currentId) {
|
static boolean observedChange(boolean starting,boolean topologyChanged,int previousId,int currentId) {
|
||||||
return starting||topologyChanged||previousId!=currentId;
|
return starting||topologyChanged||previousId!=currentId;
|
||||||
}
|
}
|
||||||
|
interface Scheduler { void after(long delayMs,Runnable task); }
|
||||||
|
interface Route { int current(); boolean available(int id); }
|
||||||
|
interface Completion { void finish(boolean accepted); }
|
||||||
|
/** Owns the asynchronous getter/callback boundary, including CLEAR (which has no target ID).
|
||||||
|
* CLEAR observes for the whole platform deadline: submitting clear is not a route ACK.
|
||||||
|
* A final quiet window also consumes queued callbacks before handing configuration back. */
|
||||||
|
static final class Settlement {
|
||||||
|
private final int target;
|
||||||
|
private final long started;
|
||||||
|
private final java.util.function.LongSupplier clock;
|
||||||
|
private final Scheduler scheduler;
|
||||||
|
private final Route route;
|
||||||
|
private final Completion completion;
|
||||||
|
private int observed;
|
||||||
|
private long stableSince;
|
||||||
|
private boolean finished;
|
||||||
|
Settlement(int target,java.util.function.LongSupplier clock,Scheduler scheduler,Route route,Completion completion) {
|
||||||
|
this.target=target;this.clock=clock;this.scheduler=scheduler;this.route=route;this.completion=completion;
|
||||||
|
started=clock.getAsLong();stableSince=started;observed=route.current();
|
||||||
|
}
|
||||||
|
void start(){scheduler.after(100,this::poll);}
|
||||||
|
void observe(){
|
||||||
|
if(finished)return;
|
||||||
|
try {
|
||||||
|
int current=route.current();
|
||||||
|
if(current!=observed){observed=current;stableSince=clock.getAsLong();}
|
||||||
|
}catch(RuntimeException denied){finish(false);}
|
||||||
|
}
|
||||||
|
void cancel(){finished=true;}
|
||||||
|
private void finish(boolean accepted){if(!finished){finished=true;completion.finish(accepted);}}
|
||||||
|
private void poll(){
|
||||||
|
if(finished)return;
|
||||||
|
observe();
|
||||||
|
if(finished)return;
|
||||||
|
long now=clock.getAsLong(),elapsed=now-started;
|
||||||
|
boolean quiet=now-stableSince>=300;
|
||||||
|
boolean accepted=target==0?observed!=0&&elapsed>=3000&&quiet:observed==target&&quiet;
|
||||||
|
boolean unavailable;
|
||||||
|
try{unavailable=target!=0&&!route.available(target);}catch(RuntimeException denied){finish(false);return;}
|
||||||
|
if(accepted||unavailable||elapsed>=3500){
|
||||||
|
finish(accepted&&!unavailable);return;
|
||||||
|
}
|
||||||
|
scheduler.after(100,this::poll);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** Bluetooth capture needs a matching communication transport; phone + Bluetooth
|
||||||
|
* output is NOT rejected: an exact phone input can be independently routable. */
|
||||||
|
static boolean compatibleCapture(int inputType,String inputAddress,int outputType,String outputAddress) {
|
||||||
|
if(inputType!=7&&inputType!=26)return true; // TYPE_BLUETOOTH_SCO / TYPE_BLE_HEADSET
|
||||||
|
if(inputType!=outputType)return false;
|
||||||
|
return inputAddress.isEmpty()||outputAddress.isEmpty()||inputAddress.equals(outputAddress);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -159,7 +159,7 @@ public final class PlatformBridge {
|
|||||||
static native boolean nativeVoiceCaptureValid(long token,long request);
|
static native boolean nativeVoiceCaptureValid(long token,long request);
|
||||||
static native boolean nativeVoiceCaptureCurrent(long token,long request);
|
static native boolean nativeVoiceCaptureCurrent(long token,long request);
|
||||||
static native boolean nativeVoicePlaybackValid(long token,long request);
|
static native boolean nativeVoicePlaybackValid(long token,long request);
|
||||||
static native void nativeVoicePlaybackFinished(long token,long request);
|
static native void nativeVoicePlaybackFinished(long token,long request,boolean accepted);
|
||||||
static native boolean nativeVoiceCaptureChanged(long token,long request,boolean enabled);
|
static native boolean nativeVoiceCaptureChanged(long token,long request,boolean enabled);
|
||||||
static native void nativeVoiceCaptureRevoked(long token);
|
static native void nativeVoiceCaptureRevoked(long token);
|
||||||
static native void nativeVoiceEvent(long token,int event,boolean value);
|
static native void nativeVoiceEvent(long token,int event,boolean value);
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ public final class VoiceService extends Service {
|
|||||||
private long routeGeneration;
|
private long routeGeneration;
|
||||||
private int pendingDeviceId;
|
private int pendingDeviceId;
|
||||||
private boolean starting;
|
private boolean starting;
|
||||||
|
private boolean startupMicrophone;
|
||||||
|
private CommunicationRoutePolicy.Settlement settlement;
|
||||||
private enum RoutePhase { REQUEST, PLATFORM_ACCEPTED, CALLBACK, ACK, FINISH, FOCUS, RELEASE, CAPTURE }
|
private enum RoutePhase { REQUEST, PLATFORM_ACCEPTED, CALLBACK, ACK, FINISH, FOCUS, RELEASE, CAPTURE }
|
||||||
private enum RouteReason { NONE, DEVICE_CALLBACK, SYNCHRONOUS, OBSERVED, NO_TARGET, REQUEST_DENIED, PLATFORM_DENIED, TIMEOUT, SUPERSEDED, FOCUS_GRANTED, FOCUS_DENIED, FOCUS_GAIN, FOCUS_LOSS, CAPTURE_REQUEST, CAPTURE_ACK, CAPTURE_REVOKED, PERMISSION_DENIED, FOCUS_UNAVAILABLE, ROUTE_PENDING }
|
private enum RouteReason { NONE, DEVICE_CALLBACK, SYNCHRONOUS, OBSERVED, NO_TARGET, REQUEST_DENIED, PLATFORM_DENIED, TIMEOUT, SUPERSEDED, FOCUS_GRANTED, FOCUS_DENIED, FOCUS_GAIN, FOCUS_LOSS, CAPTURE_REQUEST, CAPTURE_ACK, CAPTURE_REVOKED, PERMISSION_DENIED, FOCUS_UNAVAILABLE, ROUTE_PENDING }
|
||||||
private int routeCurrentType;
|
private int routeCurrentType;
|
||||||
@@ -117,15 +119,27 @@ public final class VoiceService extends Service {
|
|||||||
}
|
}
|
||||||
private void finishPlayback(long owner,long generation,boolean accepted,RouteReason reason) {
|
private void finishPlayback(long owner,long generation,boolean accepted,RouteReason reason) {
|
||||||
if(token!=owner||routeGeneration!=generation||!PlatformBridge.nativeVoiceValid(owner)){routeLog(RoutePhase.FINISH,RouteReason.SUPERSEDED);return;}
|
if(token!=owner||routeGeneration!=generation||!PlatformBridge.nativeVoiceValid(owner)){routeLog(RoutePhase.FINISH,RouteReason.SUPERSEDED);return;}
|
||||||
|
if(settlement!=null){settlement.cancel();settlement=null;}
|
||||||
long request=pendingPlaybackRequest;pendingPlaybackRequest=0;pendingDeviceId=0;
|
long request=pendingPlaybackRequest;pendingPlaybackRequest=0;pendingDeviceId=0;
|
||||||
AudioManager audio=getSystemService(AudioManager.class);
|
AudioManager audio=getSystemService(AudioManager.class);
|
||||||
deviceIds=audioDevices(audio);communicationDeviceId=communicationDevice(audio);
|
try {
|
||||||
|
deviceIds=audioDevices(audio);communicationDeviceId=communicationDevice(audio);
|
||||||
|
AudioDeviceInfo current=Build.VERSION.SDK_INT>=31?audio.getCommunicationDevice():null;
|
||||||
|
routeCurrentType=current==null?AudioDeviceInfo.TYPE_UNKNOWN:current.getType();
|
||||||
|
}catch(RuntimeException denied){accepted=false;reason=RouteReason.PLATFORM_DENIED;}
|
||||||
boolean initial=starting;starting=false;
|
boolean initial=starting;starting=false;
|
||||||
|
// Focus/permission loss during an asynchronous route ACK must not regrant
|
||||||
|
// startup consent or turn a requested microphone call into silent success.
|
||||||
|
if(initial&&(!focused||startupMicrophone!=microphone||(microphone&&(!PlatformBridge.granted(0)||PlatformBridge.visible()==null))))accepted=false;
|
||||||
|
if(!initial&&!PlatformBridge.nativeVoicePlaybackValid(owner,request))accepted=false;
|
||||||
if(initial&&accepted)PlatformBridge.nativeVoiceStarted(owner,microphone);
|
if(initial&&accepted)PlatformBridge.nativeVoiceStarted(owner,microphone);
|
||||||
else {
|
else {
|
||||||
if(!accepted&&!initial)receiveOnly();
|
if(!initial){
|
||||||
if(!initial)PlatformBridge.nativeVoicePlaybackFinished(owner,request);
|
// Finalize the authorization revision BEFORE emitting recovery.
|
||||||
if(request!=0)PlatformBridge.nativeText(request,accepted?"":null,accepted?null:"Android could not acknowledge the exact playback communication route ("+reason+"); this microphone/headset combination may be unsupported");
|
// Success is caller-owned; failure/cancellation has one event owner.
|
||||||
|
PlatformBridge.nativeVoicePlaybackFinished(owner,request,accepted);
|
||||||
|
}
|
||||||
|
if(request!=0)PlatformBridge.nativeText(request,accepted?"":null,accepted?null:"Android could not settle the requested playback communication route ("+reason+"); the exact choice remains saved but is not active");
|
||||||
if(initial){PlatformBridge.nativeVoiceStopped(owner);stopSelf();}
|
if(initial){PlatformBridge.nativeVoiceStopped(owner);stopSelf();}
|
||||||
}
|
}
|
||||||
routeLog(accepted?RoutePhase.ACK:RoutePhase.FINISH,reason);
|
routeLog(accepted?RoutePhase.ACK:RoutePhase.FINISH,reason);
|
||||||
@@ -133,7 +147,36 @@ public final class VoiceService extends Service {
|
|||||||
static void changePlayback(long owner,long request,int id) {
|
static void changePlayback(long owner,long request,int id) {
|
||||||
VoiceService service=current.get();
|
VoiceService service=current.get();
|
||||||
if(service==null||service.token!=owner||!PlatformBridge.nativeVoicePlaybackValid(owner,request)){PlatformBridge.nativeText(request,null,"target_changed");return;}
|
if(service==null||service.token!=owner||!PlatformBridge.nativeVoicePlaybackValid(owner,request)){PlatformBridge.nativeText(request,null,"target_changed");return;}
|
||||||
try{service.selectPlayback(owner,request,id);}catch(RuntimeException denied){PlatformBridge.nativeText(request,null,"Android denied access to the exact playback communication route");}
|
try{service.selectPlayback(owner,request,id);}catch(RuntimeException denied){
|
||||||
|
if(service.pendingPlaybackRequest==request)service.finishPlayback(owner,service.routeGeneration,false,RouteReason.PLATFORM_DENIED);
|
||||||
|
else PlatformBridge.nativeText(request,null,"Android denied access to the exact playback communication route; the saved choice is not active");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** Read-only transport validation. Never chooses a sink for an input selection.
|
||||||
|
* 1 = missing input, 2 = incompatible transport, 3 = unacknowledged output. */
|
||||||
|
public static int validateCapturePair(int inputId,int outputId,boolean settled) {
|
||||||
|
if(inputId==0)return 0; // Default input follows Android; it is not an exact Bluetooth request.
|
||||||
|
AudioManager audio=PlatformBridge.application.getSystemService(AudioManager.class);
|
||||||
|
AudioDeviceInfo input=null,output=null;
|
||||||
|
for(AudioDeviceInfo device:audio.getDevices(AudioManager.GET_DEVICES_INPUTS))if(device.getId()==inputId)input=device;
|
||||||
|
if(input==null)return 1;
|
||||||
|
int type=input.getType();
|
||||||
|
if(type!=AudioDeviceInfo.TYPE_BLUETOOTH_SCO&&type!=26)return 0;
|
||||||
|
if(Build.VERSION.SDK_INT>=31){
|
||||||
|
if(settled||outputId==0)output=audio.getCommunicationDevice();
|
||||||
|
else for(AudioDeviceInfo device:audio.getAvailableCommunicationDevices())if(device.getId()==outputId)output=device;
|
||||||
|
if(settled&&outputId!=0&&(output==null||output.getId()!=outputId))return 3;
|
||||||
|
}else{
|
||||||
|
// API26-30 exposes no acknowledged exact communication-device API.
|
||||||
|
// Only an already-active SCO transport is evidence of readiness.
|
||||||
|
if(type!=AudioDeviceInfo.TYPE_BLUETOOTH_SCO||!audio.isBluetoothScoOn())return 2;
|
||||||
|
for(AudioDeviceInfo device:audio.getDevices(AudioManager.GET_DEVICES_OUTPUTS))
|
||||||
|
if((outputId==0||device.getId()==outputId)&&device.getType()==type){output=device;break;}
|
||||||
|
}
|
||||||
|
if(output==null)return 2;
|
||||||
|
String inputAddress=Build.VERSION.SDK_INT>=28?input.getAddress():"";
|
||||||
|
String outputAddress=Build.VERSION.SDK_INT>=28?output.getAddress():"";
|
||||||
|
return CommunicationRoutePolicy.compatibleCapture(type,inputAddress,output.getType(),outputAddress)?0:2;
|
||||||
}
|
}
|
||||||
static void cancelPlayback(long owner,long request) {
|
static void cancelPlayback(long owner,long request) {
|
||||||
VoiceService service=current.get();
|
VoiceService service=current.get();
|
||||||
@@ -158,15 +201,19 @@ public final class VoiceService extends Service {
|
|||||||
routeLog(RoutePhase.REQUEST,RouteReason.NONE);
|
routeLog(RoutePhase.REQUEST,RouteReason.NONE);
|
||||||
try {
|
try {
|
||||||
routeRequested=true;
|
routeRequested=true;
|
||||||
if(action==CommunicationRoutePolicy.Action.CLEAR){audio.clearCommunicationDevice();appliedPlaybackId=0;routeAccepted=true;communicationDeviceId=communicationDevice(audio);finishPlayback(owner,generation,true,RouteReason.SYNCHRONOUS);}
|
if(action==CommunicationRoutePolicy.Action.CLEAR){audio.clearCommunicationDevice();appliedPlaybackId=0;routeAccepted=true;}
|
||||||
else {
|
else {
|
||||||
routeAccepted=audio.setCommunicationDevice(target);
|
routeAccepted=audio.setCommunicationDevice(target);
|
||||||
routeLog(RoutePhase.PLATFORM_ACCEPTED,routeAccepted?RouteReason.NONE:RouteReason.REQUEST_DENIED);
|
if(routeAccepted)appliedPlaybackId=id;
|
||||||
if(!routeAccepted){finishPlayback(owner,generation,false,RouteReason.REQUEST_DENIED);return;}
|
|
||||||
appliedPlaybackId=id;
|
|
||||||
if(communicationDevice(audio)==id){communicationDeviceId=id;finishPlayback(owner,generation,true,RouteReason.SYNCHRONOUS);}
|
|
||||||
else PlatformBridge.MAIN.postDelayed(()->{if(pendingPlaybackRequest==request)finishPlayback(owner,generation,false,RouteReason.TIMEOUT);},3000);
|
|
||||||
}
|
}
|
||||||
|
routeLog(RoutePhase.PLATFORM_ACCEPTED,routeAccepted?RouteReason.NONE:RouteReason.REQUEST_DENIED);
|
||||||
|
if(!routeAccepted){finishPlayback(owner,generation,false,RouteReason.REQUEST_DENIED);return;}
|
||||||
|
settlement=new CommunicationRoutePolicy.Settlement(id,SystemClock::elapsedRealtime,(delay,task)->PlatformBridge.MAIN.postDelayed(task,delay),
|
||||||
|
new CommunicationRoutePolicy.Route(){
|
||||||
|
public int current(){return communicationDevice(audio);}
|
||||||
|
public boolean available(int endpoint){return availablePlayback(audio,endpoint)!=null;}
|
||||||
|
},accepted->finishPlayback(owner,generation,accepted,accepted?RouteReason.DEVICE_CALLBACK:RouteReason.TIMEOUT));
|
||||||
|
settlement.start();
|
||||||
}catch(RuntimeException denied){finishPlayback(owner,generation,false,RouteReason.PLATFORM_DENIED);}
|
}catch(RuntimeException denied){finishPlayback(owner,generation,false,RouteReason.PLATFORM_DENIED);}
|
||||||
}
|
}
|
||||||
private void routeChanged(long owner) {
|
private void routeChanged(long owner) {
|
||||||
@@ -178,23 +225,22 @@ public final class VoiceService extends Service {
|
|||||||
routeCurrentType=selectedDevice==null?AudioDeviceInfo.TYPE_UNKNOWN:selectedDevice.getType();
|
routeCurrentType=selectedDevice==null?AudioDeviceInfo.TYPE_UNKNOWN:selectedDevice.getType();
|
||||||
boolean topologyChanged=!next.equals(deviceIds);
|
boolean topologyChanged=!next.equals(deviceIds);
|
||||||
if(pendingPlaybackRequest!=0){
|
if(pendingPlaybackRequest!=0){
|
||||||
deviceIds=next;communicationDeviceId=selected;
|
if(settlement!=null)settlement.observe();
|
||||||
if(selected==pendingDeviceId)finishPlayback(owner,routeGeneration,true,RouteReason.DEVICE_CALLBACK);
|
routeLog(RoutePhase.CALLBACK,RouteReason.ROUTE_PENDING);
|
||||||
else if(topologyChanged&&availablePlayback(audio,pendingDeviceId)==null)finishPlayback(owner,routeGeneration,false,RouteReason.NO_TARGET);
|
|
||||||
else routeLog(RoutePhase.CALLBACK,RouteReason.ROUTE_PENDING);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if(!CommunicationRoutePolicy.observedChange(starting,topologyChanged,communicationDeviceId,selected))return;
|
if(!CommunicationRoutePolicy.observedChange(starting,topologyChanged,communicationDeviceId,selected))return;
|
||||||
routeStartedMs=SystemClock.elapsedRealtime();routeTopologyChanged=topologyChanged;routeRequested=false;routeAccepted=true;routeTargetType=routeCurrentType;
|
routeStartedMs=SystemClock.elapsedRealtime();routeTopologyChanged=topologyChanged;routeRequested=false;routeAccepted=true;routeTargetType=routeCurrentType;
|
||||||
deviceIds=next;communicationDeviceId=selected;availablePlayback(audio,0);
|
deviceIds=next;communicationDeviceId=selected;availablePlayback(audio,0);
|
||||||
// Observe the OS route and fence/recover streams; never choose a headset on plug/unplug.
|
// Observe the OS route and fence/recover streams; never choose a headset on plug/unplug.
|
||||||
if(starting){starting=false;PlatformBridge.nativeVoiceStarted(owner,microphone);}
|
if(starting){pendingPlaybackRequest=owner;finishPlayback(owner,++routeGeneration,true,RouteReason.OBSERVED);}
|
||||||
else{PlatformBridge.nativeVoiceEvent(owner,8,true);PlatformBridge.nativeVoiceEvent(owner,3,true);}
|
else{PlatformBridge.nativeVoiceEvent(owner,8,true);PlatformBridge.nativeVoiceEvent(owner,3,true);}
|
||||||
routeLog(RoutePhase.ACK,RouteReason.OBSERVED);
|
routeLog(RoutePhase.ACK,RouteReason.OBSERVED);
|
||||||
}
|
}
|
||||||
private void releaseCommunicationRoute(AudioManager audio) {
|
private void releaseCommunicationRoute(AudioManager audio) {
|
||||||
routeLog(RoutePhase.RELEASE,RouteReason.NONE);
|
routeLog(RoutePhase.RELEASE,RouteReason.NONE);
|
||||||
++routeGeneration;pendingDeviceId=0;
|
++routeGeneration;pendingDeviceId=0;
|
||||||
|
if(settlement!=null){settlement.cancel();settlement=null;}
|
||||||
if(pendingPlaybackRequest!=0){PlatformBridge.nativeText(pendingPlaybackRequest,null,"The Android call ended before playback selection was acknowledged");pendingPlaybackRequest=0;}
|
if(pendingPlaybackRequest!=0){PlatformBridge.nativeText(pendingPlaybackRequest,null,"The Android call ended before playback selection was acknowledged");pendingPlaybackRequest=0;}
|
||||||
if(Build.VERSION.SDK_INT>=31&&appliedPlaybackId!=0)audio.clearCommunicationDevice();
|
if(Build.VERSION.SDK_INT>=31&&appliedPlaybackId!=0)audio.clearCommunicationDevice();
|
||||||
appliedPlaybackId=0;
|
appliedPlaybackId=0;
|
||||||
@@ -238,8 +284,8 @@ public final class VoiceService extends Service {
|
|||||||
routeFocusRequestResult=audio.requestAudioFocus(focus);
|
routeFocusRequestResult=audio.requestAudioFocus(focus);
|
||||||
boolean focusGranted=routeFocusRequestResult==AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
|
boolean focusGranted=routeFocusRequestResult==AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
|
||||||
focused=focusGranted;routeLog(RoutePhase.FOCUS,focusGranted?RouteReason.FOCUS_GRANTED:RouteReason.FOCUS_DENIED);
|
focused=focusGranted;routeLog(RoutePhase.FOCUS,focusGranted?RouteReason.FOCUS_GRANTED:RouteReason.FOCUS_DENIED);
|
||||||
|
starting=true;startupMicrophone=capture;deviceIds=java.util.Collections.emptySet();communicationDeviceId=-1;
|
||||||
if(!focusGranted)throw new IllegalStateException("Audio focus denied");
|
if(!focusGranted)throw new IllegalStateException("Audio focus denied");
|
||||||
starting=true;deviceIds=java.util.Collections.emptySet();communicationDeviceId=-1;
|
|
||||||
if(Build.VERSION.SDK_INT>=31){
|
if(Build.VERSION.SDK_INT>=31){
|
||||||
communicationDeviceListener=device->routeChanged(owner);
|
communicationDeviceListener=device->routeChanged(owner);
|
||||||
audio.addOnCommunicationDeviceChangedListener(PlatformBridge.MAIN::post,communicationDeviceListener);
|
audio.addOnCommunicationDeviceChangedListener(PlatformBridge.MAIN::post,communicationDeviceListener);
|
||||||
|
|||||||
+61
@@ -3,6 +3,60 @@ package dev.teamspeach.mobile;
|
|||||||
/** Plain javac/java fixture: deliberately independent of the Android SDK and JUnit. */
|
/** Plain javac/java fixture: deliberately independent of the Android SDK and JUnit. */
|
||||||
public final class CommunicationRoutePolicyTest {
|
public final class CommunicationRoutePolicyTest {
|
||||||
private static void require(boolean value,String message){if(!value)throw new AssertionError(message);}
|
private static void require(boolean value,String message){if(!value)throw new AssertionError(message);}
|
||||||
|
/** Deterministic event loop for the production asynchronous settlement owner.
|
||||||
|
* Getter changes, delayed polls and platform callbacks are independent events. */
|
||||||
|
private static final class Loop implements CommunicationRoutePolicy.Scheduler,CommunicationRoutePolicy.Route {
|
||||||
|
long now;int current=80;boolean available=true;boolean denied;int completions;boolean accepted;
|
||||||
|
final java.util.TreeMap<Long,java.util.ArrayDeque<Runnable>> tasks=new java.util.TreeMap<>();
|
||||||
|
public int current(){if(denied)throw new SecurityException("denied");return current;}
|
||||||
|
public boolean available(int id){return available;}
|
||||||
|
public void after(long delay,Runnable task){tasks.computeIfAbsent(now+delay,key->new java.util.ArrayDeque<>()).add(task);}
|
||||||
|
CommunicationRoutePolicy.Settlement request(int target){
|
||||||
|
CommunicationRoutePolicy.Settlement pending=new CommunicationRoutePolicy.Settlement(target,()->now,this,this,
|
||||||
|
success->{++completions;accepted=success;});
|
||||||
|
pending.start();return pending;
|
||||||
|
}
|
||||||
|
void until(long time){
|
||||||
|
while(!tasks.isEmpty()&&tasks.firstKey()<=time){
|
||||||
|
now=tasks.firstKey();java.util.ArrayDeque<Runnable> ready=tasks.pollFirstEntry().getValue();
|
||||||
|
while(!ready.isEmpty())ready.remove().run();
|
||||||
|
}
|
||||||
|
now=time;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private static void asynchronousSettlement(){
|
||||||
|
Loop clear=new Loop();CommunicationRoutePolicy.Settlement pending=clear.request(0);
|
||||||
|
require(clear.completions==0,"CLEAR submission is not an ACK");
|
||||||
|
clear.until(900);require(clear.completions==0,"old getter value must not acknowledge CLEAR early");
|
||||||
|
clear.current=1;pending.observe(); // Actual OS callback arrives after request submission.
|
||||||
|
clear.until(2999);require(clear.completions==0,"CLEAR owns callbacks throughout the bounded settlement period");
|
||||||
|
clear.until(3000);require(clear.completions==1&&clear.accepted,"fresh stable getter completes CLEAR");
|
||||||
|
pending.observe();clear.until(6000);require(clear.completions==1,"late duplicate callback cannot create a second continuation");
|
||||||
|
|
||||||
|
Loop noChange=new Loop();noChange.request(0);noChange.until(3000);
|
||||||
|
require(noChange.completions==1&&noChange.accepted,"Android may legitimately keep the same device for default");
|
||||||
|
|
||||||
|
Loop noDevice=new Loop();noDevice.current=0;noDevice.request(0);noDevice.until(3500);
|
||||||
|
require(noDevice.completions==1&&!noDevice.accepted,"null communication getter is not settled physical default");
|
||||||
|
Loop denied=new Loop();CommunicationRoutePolicy.Settlement deniedRequest=denied.request(7);denied.denied=true;
|
||||||
|
deniedRequest.observe();denied.until(3500);
|
||||||
|
require(denied.completions==1&&!denied.accepted,"getter denial finalizes once instead of stranding a fenced request");
|
||||||
|
Loop select=new Loop();CommunicationRoutePolicy.Settlement selecting=select.request(7);
|
||||||
|
select.until(500);require(select.completions==0,"platform acceptance is not exact-route acknowledgement");
|
||||||
|
select.current=7;selecting.observe();select.until(799);require(select.completions==0,"callback is followed by a quiet getter window");
|
||||||
|
select.until(800);require(select.completions==1&&select.accepted,"exact settled callback completes once");
|
||||||
|
|
||||||
|
Loop lost=new Loop();lost.request(7);lost.available=false;lost.until(100);
|
||||||
|
require(lost.completions==1&&!lost.accepted,"removed exact target fails without default fallback");
|
||||||
|
Loop timeout=new Loop();timeout.request(7);timeout.until(3500);
|
||||||
|
require(timeout.completions==1&&!timeout.accepted,"unacknowledged exact target has a bounded failure");
|
||||||
|
Loop cancelled=new Loop();CommunicationRoutePolicy.Settlement obsolete=cancelled.request(0);obsolete.cancel();
|
||||||
|
cancelled.until(5000);require(cancelled.completions==0,"cancelled polls cannot ACK a replacement request");
|
||||||
|
|
||||||
|
Loop noisy=new Loop();CommunicationRoutePolicy.Settlement changing=noisy.request(0);
|
||||||
|
for(int time=100;time<=3500;time+=100){noisy.until(time-1);noisy.current=noisy.current==1?80:1;changing.observe();noisy.until(time);}
|
||||||
|
require(noisy.completions==1&&!noisy.accepted,"CLEAR cannot claim settlement amid continuing route changes");
|
||||||
|
}
|
||||||
public static void main(String[] args){
|
public static void main(String[] args){
|
||||||
require(CommunicationRoutePolicy.action(true,80,0,1,true)==CommunicationRoutePolicy.Action.SELECT,"explicit playback selects the exact available endpoint");
|
require(CommunicationRoutePolicy.action(true,80,0,1,true)==CommunicationRoutePolicy.Action.SELECT,"explicit playback selects the exact available endpoint");
|
||||||
require(CommunicationRoutePolicy.action(false,15,80,80,true)==CommunicationRoutePolicy.Action.NONE,"phone capture cannot redirect headset output");
|
require(CommunicationRoutePolicy.action(false,15,80,80,true)==CommunicationRoutePolicy.Action.NONE,"phone capture cannot redirect headset output");
|
||||||
@@ -17,5 +71,12 @@ public final class CommunicationRoutePolicyTest {
|
|||||||
require(CommunicationRoutePolicy.observedChange(false,false,1,80),"OS route-only change is observed");
|
require(CommunicationRoutePolicy.observedChange(false,false,1,80),"OS route-only change is observed");
|
||||||
require(!CommunicationRoutePolicy.observedChange(false,false,80,80),"unchanged topology and route are ignored");
|
require(!CommunicationRoutePolicy.observedChange(false,false,80,80),"unchanged topology and route are ignored");
|
||||||
require(CommunicationRoutePolicy.observedChange(true,false,80,80),"startup observes Android's route without ranking endpoints");
|
require(CommunicationRoutePolicy.observedChange(true,false,80,80),"startup observes Android's route without ranking endpoints");
|
||||||
|
require(CommunicationRoutePolicy.compatibleCapture(15,"phone",7,"headset"),"phone mic plus BT output is not blanket-rejected");
|
||||||
|
require(CommunicationRoutePolicy.compatibleCapture(7,"headset",7,"headset"),"explicit matched SCO pair supports duplex transport");
|
||||||
|
require(CommunicationRoutePolicy.compatibleCapture(26,"headset",26,"headset"),"explicit matched BLE pair supports duplex transport");
|
||||||
|
require(!CommunicationRoutePolicy.compatibleCapture(7,"headset",1,""),"BT input plus phone output needs explicit compatible transport, not auto-output selection");
|
||||||
|
require(!CommunicationRoutePolicy.compatibleCapture(7,"one",7,"two"),"different known hardware addresses cannot masquerade as a duplex pair");
|
||||||
|
require(!CommunicationRoutePolicy.compatibleCapture(26,"headset",7,"headset"),"BLE and SCO are not interchangeable by name");
|
||||||
|
asynchronousSettlement();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user