Preserve authorized Android background calls and stop on task removal
android-ci / android-arm64 (push) Failing after 3h5m22s
android-ci / android-arm64 (push) Failing after 3h5m22s
This commit is contained in:
1 parent
f403dd5fcf
commit
3fe8c82354
14 files changed
+254
-8
No files matched your search
@@ -240,6 +240,7 @@ jobs:
|
|||||||
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 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
|
||||||
cargo test --locked -p teamspeach-core --target x86_64-unknown-linux-gnu --lib audio::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
cargo test --locked -p teamspeach-core --target x86_64-unknown-linux-gnu --lib audio::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||||
|
cargo test --locked -p teamspeach-core --target x86_64-unknown-linux-gnu --lib output::tests --jobs "$CARGO_BUILD_JOBS" -- --test-threads=1
|
||||||
} 2>&1 | tee .android-ci/audio-test-results/tests.log
|
} 2>&1 | tee .android-ci/audio-test-results/tests.log
|
||||||
|
|
||||||
- name: Save successful Linux audio test compilation
|
- name: Save successful Linux audio test compilation
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
|
- 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
|
||||||
|
ownership to the foreground call. Removing the app from Recents ends its call and capture services.
|
||||||
- Distinguish stale/future capture-frame rejection from revoked stream authorization. Keep valid capture
|
- Distinguish stale/future capture-frame rejection from revoked stream authorization. Keep valid capture
|
||||||
running after a rejected frame, and retire an old worker input without revoking a newer manager permit.
|
running after a rejected frame, and retire an old worker input without revoking a newer manager permit.
|
||||||
Android records only the first ingress rejection of each kind, with numeric age/epoch diagnostics.
|
Android records only the first ingress rejection of each kind, with numeric age/epoch diagnostics.
|
||||||
|
|||||||
@@ -584,6 +584,56 @@ Updated **2026-11-11**. Windows baseline remains `05e8d34bcf0e24a44f76e65220293c
|
|||||||
cannot stop valid capture, a fresh frame remains accepted, and an old frame after replacement cannot
|
cannot stop valid capture, a fresh frame remains accepted, and an old frame after replacement cannot
|
||||||
revoke the new permit. This exercises real offline core acknowledgments with connected reducer
|
revoke the new permit. This exercises real offline core acknowledgments with connected reducer
|
||||||
bookkeeping, not server/device proof. CI verification pending; working phone not toggled/restarted.
|
bookkeeping, not server/device proof. CI verification pending; working phone not toggled/restarted.
|
||||||
|
- f403dd5fcfb7b64c8fc7de0a3f5b65d6ada29ab7 run4931/job5527 SUCCESS: native146,capture18,
|
||||||
|
lifecycle2,manager7,DSP15,catalog4,timestamp3,core23 passed/1ignored. Actual new ingress regression
|
||||||
|
passed. APK downloaded, all6 hashes verified: c91deecac9ae5bc973a057faf94a94daec35bc50decbe30d5a799e8fadf942d9.
|
||||||
|
Owner authorized install-now; test signature mismatch handled by previously authorized disposable
|
||||||
|
uninstall/reinstall, both Success; launched4931. Owner then explicitly reports «всее, урааа, все
|
||||||
|
работает!» after requested first-TX scenario. Record this as manual Android voice acceptance for4931,
|
||||||
|
not proof of Bluetooth/background/network-handover/iOS/full feature parity or exact prior fault cause.
|
||||||
|
- Owner now asks whether to move to UI or do more technical work. Recommend UI on working audio baseline;
|
||||||
|
no further speculative audio/gain refactor. Keep separate acceptance matrix for cold reconnect, mute/
|
||||||
|
deafen repetition, routes, background/interruption, long calls, multiple sessions, Windows shared-code
|
||||||
|
regression and iOS. No UI implementation or new platform expansion authorized by that question alone.
|
||||||
|
|
||||||
|
### Agreed seven-item pre-UI scope (owner request, 2026-11-14)
|
||||||
|
|
||||||
|
1. **No release:** retain working4931/f403dd5 and APK receipt above as engineering evidence only;
|
||||||
|
do not create release/tag, merge main or imply production readiness.
|
||||||
|
2. **Stable test signing:** approved separate durable TEST key via protected Gitea secret; never key
|
||||||
|
in repository/cache/artifact/log. Verify reinstall-free update with matching certificate. Production
|
||||||
|
signing remains separate. Browser relay secret settings access timed out25s; manual secure bootstrap
|
||||||
|
needed if authenticated tooling remains inaccessible.
|
||||||
|
3. **Short manual voice check (owner performs):** cold launch/permission → connect/channel → RX → one
|
||||||
|
explicit mic enable/TX → mic mute/unmute → deafen/undeafen → channel change → reconnect. Note APK
|
||||||
|
run/revision and first failing step; no requirement for automated server playback or repeated private
|
||||||
|
Listen. CI covers implementation regressions, not replacement for listening acceptance.
|
||||||
|
4. **Background:** Home and screen-off preserve an already-authorized call. Swiping the app from Recents
|
||||||
|
ends runtime/call/capture; no sticky/background restart. Explicit permission loss/focus interruption/
|
||||||
|
requested mute still fence capture; PTT/whisper holds must never stick after UI loss.
|
||||||
|
5. **Bluetooth:** owner has headphones; test connected route + unplug/disconnect with owner. Do not
|
||||||
|
assume physical device pass from catalog metadata tests.
|
||||||
|
6. **Network:** exercise reachable deterministic generation/disconnect scenarios; real Wi-Fi/cellular
|
||||||
|
handover unavailable to owner, record that limit. Never fabricate device reconnect success.
|
||||||
|
7. **Long calls:** ordinary usage observation only, no special endurance run now.
|
||||||
|
|
||||||
|
After these seven, move to UI. New discoveries go into a separate deferred list, not automatic extra
|
||||||
|
implementation. Prior outstanding Windows/iOS/general UI parity are deferred requirements, not additions
|
||||||
|
to this pre-UI scope. No speculative microphone gain/audio refactor on accepted voice baseline.
|
||||||
|
- Owner subsequently DECLINED stable TEST signing/bootstrap as unnecessary friction, accepting profile
|
||||||
|
resets on disposable installs. Removed all uncommitted stable-signing Gradle/workflow/helper changes;
|
||||||
|
existing isolated-per-package signing retained. Bootstrap window closed without setup acknowledgement;
|
||||||
|
no repository secret creation confirmed. Do not revive signing work before UI.
|
||||||
|
- Background candidate: retain explicitly authorized steady Android call during Home/screen-off/UI
|
||||||
|
recreation, but release PTT/whisper and reject queued local starts while controls suspended. Permission
|
||||||
|
denial/audio focus interruption/explicit osMuteWhenLocked retain fail-closed behavior. Foreground voice
|
||||||
|
service holds scoped partial CPU lock; Recents task removal shuts down matching runtime/call/capture
|
||||||
|
services with token/generation checks, no process kill or sticky restart. Six deterministic background
|
||||||
|
regressions added; device behavior not yet verified.
|
||||||
|
- Network scope: existing core automatic reconnect inspected, generation/old-capture fencing already
|
||||||
|
tested. Added actual runtime NetworkChanged privacy-boundary regression plus core playback generation
|
||||||
|
tests in CI. Physical Wi-Fi/cellular handover remains unavailable/unproven; do not promise transparent
|
||||||
|
handover. Any further recovery UX work belongs in deferred findings after this agreed list.
|
||||||
|
|
||||||
|
|
||||||
## First Android APK build
|
## First Android APK build
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ pub struct TransmissionState {
|
|||||||
pub gate_inhibited:bool,
|
pub gate_inhibited:bool,
|
||||||
/// Explicit authorization to resume capture; hardware events are observations only.
|
/// Explicit authorization to resume capture; hardware events are observations only.
|
||||||
pub capture_desired:bool,
|
pub capture_desired:bool,
|
||||||
|
/// Fences queued local momentary-control starts after UI focus/visibility loss.
|
||||||
|
pub ui_controls_suspended:bool,
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct MicrophoneTestResume {
|
pub struct MicrophoneTestResume {
|
||||||
|
|||||||
@@ -250,6 +250,7 @@ impl RuntimeServices {
|
|||||||
pub async fn apply_key_events(self:&Arc<Self>,events:Vec<ActionEvent>)->Result<()> {
|
pub async fn apply_key_events(self:&Arc<Self>,events:Vec<ActionEvent>)->Result<()> {
|
||||||
let prefs=self.profile()?.prefs.get();let mut forwarded=Vec::new();let mut refresh=false;
|
let prefs=self.profile()?.prefs.get();let mut forwarded=Vec::new();let mut refresh=false;
|
||||||
for event in events {
|
for event in events {
|
||||||
|
if event.phase==Phase::Start&&event.scope==Scope::Local&&matches!(event.binding.action,Action::PushToTalk|Action::PushToMute|Action::ReplyWhisper|Action::QuickWhisper|Action::WhisperList)&&lock(&self.transmission)?.ui_controls_suspended{continue}
|
||||||
if event.phase==Phase::End&&matches!(event.binding.action,Action::ReplyWhisper|Action::QuickWhisper|Action::WhisperList){
|
if event.phase==Phase::End&&matches!(event.binding.action,Action::ReplyWhisper|Action::QuickWhisper|Action::WhisperList){
|
||||||
self.audio.set_transmission_enabled(false);
|
self.audio.set_transmission_enabled(false);
|
||||||
self.audio.revoke_capture();
|
self.audio.revoke_capture();
|
||||||
|
|||||||
@@ -9,6 +9,13 @@ fn suspend_immediate(ctx:&RuntimeServices,retain_capture:bool){
|
|||||||
if let Ok(mut tx)=ctx.transmission.lock(){if !retain_capture{tx.capture_desired=false;tx.deactivated.clear();}tx.revision=tx.revision.wrapping_add(1);tx.ptt_holders.clear();tx.release_at=None;tx.bound_permit=None;}
|
if let Ok(mut tx)=ctx.transmission.lock(){if !retain_capture{tx.capture_desired=false;tx.deactivated.clear();}tx.revision=tx.revision.wrapping_add(1);tx.ptt_holders.clear();tx.release_at=None;tx.bound_permit=None;}
|
||||||
}
|
}
|
||||||
pub fn release_immediate(ctx:&RuntimeServices){suspend_immediate(ctx,false);}
|
pub fn release_immediate(ctx:&RuntimeServices){suspend_immediate(ctx,false);}
|
||||||
|
/// A foreground call owns steady-state capture; momentary controls remain UI-owned.
|
||||||
|
pub fn release_ui_immediate(ctx:&RuntimeServices,background_capture:bool)->Option<crate::services::whisper::RoutedCommand>{
|
||||||
|
if let Ok(mut tx)=ctx.transmission.lock(){tx.ui_controls_suspended=true;}
|
||||||
|
let preserve=ctx.transmission.lock().map(|tx|background_capture&&tx.capture_desired&&tx.ptt_holders.is_empty()&&tx.release_at.is_none()&&tx.deactivated.is_empty()&&!tx.whisper.held()).unwrap_or(false);
|
||||||
|
if !preserve{release_immediate(ctx);}
|
||||||
|
ctx.transmission.lock().ok().and_then(|mut tx|tx.whisper.release(None))
|
||||||
|
}
|
||||||
pub async fn release_voice(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()>{suspend_voice_to(ctx,key,false).await}
|
pub async fn release_voice(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()>{suspend_voice_to(ctx,key,false).await}
|
||||||
/// A user-selected receive/channel transition closes forwarding, not microphone consent.
|
/// A user-selected receive/channel transition closes forwarding, not microphone consent.
|
||||||
pub(super) async fn suspend_voice(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()>{suspend_voice_to(ctx,key,true).await}
|
pub(super) async fn suspend_voice(ctx:&Arc<RuntimeServices>,key:&SessionKey)->Result<()>{suspend_voice_to(ctx,key,true).await}
|
||||||
@@ -106,12 +113,13 @@ async fn server_form(ctx:&Arc<RuntimeServices>,target:&Target,operation:Operatio
|
|||||||
}
|
}
|
||||||
pub async fn ptt(ctx:Arc<RuntimeServices>,target:Target,held:bool)->Result<()> {
|
pub async fn ptt(ctx:Arc<RuntimeServices>,target:Target,held:bool)->Result<()> {
|
||||||
let key=target.session.ok_or_else(changed)?;ctx.require_key(&key,true)?;
|
let key=target.session.ok_or_else(changed)?;ctx.require_key(&key,true)?;
|
||||||
{let mut state=ctx.transmission.lock().map_err(|_|changed())?;if state.key.as_ref()!=Some(&key){return Err(changed())}if held{state.ptt_holders.insert("screen".into());state.release_at=None;}else{state.ptt_holders.remove("screen");}state.revision=state.revision.wrapping_add(1);}
|
{let mut state=ctx.transmission.lock().map_err(|_|changed())?;if held&&state.ui_controls_suspended{return Err(ServiceError::new("ui_not_focused","Push-to-talk requires the active UI"))}if state.key.as_ref()!=Some(&key){return Err(changed())}if held{state.ptt_holders.insert("screen".into());state.release_at=None;}else{state.ptt_holders.remove("screen");}state.revision=state.revision.wrapping_add(1);}
|
||||||
let prefs=ctx.profile()?.prefs.get();ctx.refresh_transmission_gate(&key,&prefs)?;ctx.refresh_capture().await
|
let prefs=ctx.profile()?.prefs.get();ctx.refresh_transmission_gate(&key,&prefs)?;ctx.refresh_capture().await
|
||||||
}
|
}
|
||||||
pub async fn key_events(ctx:Arc<RuntimeServices>,events:Vec<crate::services::keybinds::ActionEvent>)->Result<()> {
|
pub async fn key_events(ctx:Arc<RuntimeServices>,events:Vec<crate::services::keybinds::ActionEvent>)->Result<()> {
|
||||||
use crate::services::keybinds::{Action as A,Phase};
|
use crate::services::keybinds::{Action as A,Phase};
|
||||||
for event in events {
|
for event in events {
|
||||||
|
if event.phase==Phase::Start&&event.scope==crate::services::keybinds::Scope::Local&&matches!(event.binding.action,A::PushToTalk|A::PushToMute|A::ReplyWhisper|A::QuickWhisper|A::WhisperList)&&ctx.transmission.lock().map_err(|_|changed())?.ui_controls_suspended{continue}
|
||||||
let sessions=ctx.connected.connections.snapshot();
|
let sessions=ctx.connected.connections.snapshot();
|
||||||
if !sessions.connections.iter().any(|session|session.is_connected())&&event.phase!=Phase::End&&matches!(event.binding.action,A::MicrophoneToggle|A::MicrophoneMute|A::MicrophoneUnmute|A::SpeakerToggle|A::SpeakerMute|A::SpeakerUnmute){let mut defaults=ctx.audio_defaults.lock().map_err(|_|changed())?;match event.binding.action{A::MicrophoneToggle=>defaults.0=!defaults.0,A::MicrophoneMute=>defaults.0=true,A::MicrophoneUnmute=>defaults.0=false,A::SpeakerToggle=>defaults.1=!defaults.1,A::SpeakerMute=>defaults.1=true,A::SpeakerUnmute=>defaults.1=false,_=>{}}continue}
|
if !sessions.connections.iter().any(|session|session.is_connected())&&event.phase!=Phase::End&&matches!(event.binding.action,A::MicrophoneToggle|A::MicrophoneMute|A::MicrophoneUnmute|A::SpeakerToggle|A::SpeakerMute|A::SpeakerUnmute){let mut defaults=ctx.audio_defaults.lock().map_err(|_|changed())?;match event.binding.action{A::MicrophoneToggle=>defaults.0=!defaults.0,A::MicrophoneMute=>defaults.0=true,A::MicrophoneUnmute=>defaults.0=false,A::SpeakerToggle=>defaults.1=!defaults.1,A::SpeakerMute=>defaults.1=true,A::SpeakerUnmute=>defaults.1=false,_=>{}}continue}
|
||||||
let snapshots=ctx.connected.connections.snapshot();let preferred=if matches!(event.binding.action,A::RecordingStart|A::RecordingStop|A::RecordingTogglePause){snapshots.viewed_id.as_ref().or(snapshots.input_id.as_ref())}else{snapshots.input_id.as_ref().or(snapshots.viewed_id.as_ref())};let Some(connection)=preferred.and_then(|id|snapshots.get(id)).filter(|c|c.is_connected())else{continue};
|
let snapshots=ctx.connected.connections.snapshot();let preferred=if matches!(event.binding.action,A::RecordingStart|A::RecordingStop|A::RecordingTogglePause){snapshots.viewed_id.as_ref().or(snapshots.input_id.as_ref())}else{snapshots.input_id.as_ref().or(snapshots.viewed_id.as_ref())};let Some(connection)=preferred.and_then(|id|snapshots.get(id)).filter(|c|c.is_connected())else{continue};
|
||||||
|
|||||||
@@ -54,3 +54,130 @@ async fn audit_lifecycle_permission_grant_alone_does_not_present_enabled_microph
|
|||||||
assert!(!ctx.audio.input_active());
|
assert!(!ctx.audio.input_active());
|
||||||
cleanup(owner).await;
|
cleanup(owner).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor="current_thread")]
|
||||||
|
async fn audit_lifecycle_background_call_preserves_only_existing_steady_capture_intent() {
|
||||||
|
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
|
||||||
|
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
|
||||||
|
{let mut tx=ctx.transmission.lock().unwrap();tx.observe_owner(Some(key));tx.capture_desired=true;}
|
||||||
|
let revision=ctx.transmission.lock().unwrap().revision;
|
||||||
|
// The bool is the OS-lease decision, not a fabricated device/manager ACK.
|
||||||
|
// Repeated Focus/Visibility/UiDestroyed notifications must be idempotent.
|
||||||
|
for _ in 0..3{assert!(controller::release_ui_immediate(ctx,true).is_none());}
|
||||||
|
{let tx=ctx.transmission.lock().unwrap();assert!(tx.capture_desired);assert!(tx.ui_controls_suspended);assert_eq!(tx.revision,revision);}
|
||||||
|
assert!(!ctx.audio.input_active(),"retained intent alone cannot open hardware");
|
||||||
|
controller::release_ui_immediate(ctx,false);
|
||||||
|
assert!(!ctx.transmission.lock().unwrap().capture_desired,"no lease retains no capture authorization");
|
||||||
|
controller::release_ui_immediate(ctx,true);
|
||||||
|
assert!(!ctx.transmission.lock().unwrap().capture_desired,"background observation must never regrant consent");
|
||||||
|
cleanup(owner).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor="current_thread")]
|
||||||
|
async fn audit_lifecycle_background_releases_ptt_delay_and_whisper_without_late_ack() {
|
||||||
|
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
|
||||||
|
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
|
||||||
|
for delayed in [false,true]{
|
||||||
|
{let mut tx=ctx.transmission.lock().unwrap();tx.capture_desired=true;if delayed{tx.release_at=Some(Instant::now()+Duration::from_secs(30));}else{tx.ptt_holders.insert("screen".into());}}
|
||||||
|
controller::release_ui_immediate(ctx,true);
|
||||||
|
let tx=ctx.transmission.lock().unwrap();assert!(tx.ptt_holders.is_empty());assert!(tx.release_at.is_none());assert!(!tx.capture_desired);
|
||||||
|
}
|
||||||
|
let token={let mut tx=ctx.transmission.lock().unwrap();tx.capture_desired=true;tx.whisper.prepare("held-whisper",key.clone()).0};
|
||||||
|
let stop=controller::release_ui_immediate(ctx,true).expect("held whisper requires an ordered stop");
|
||||||
|
assert_eq!(stop.key,key);
|
||||||
|
{let mut tx=ctx.transmission.lock().unwrap();assert!(!tx.whisper.held());assert!(!tx.whisper.acknowledge(&token,&key,true),"late start ACK cannot resurrect a released whisper");assert!(!tx.capture_desired);}
|
||||||
|
cleanup(owner).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor="current_thread")]
|
||||||
|
async fn audit_lifecycle_background_rejects_queued_local_momentary_starts() {
|
||||||
|
use crate::services::keybinds::{Action,ActionEvent,Phase,Scope};
|
||||||
|
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
|
||||||
|
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
|
||||||
|
ctx.connected.connections.fixture_control(&key,json!({"event":"snapshot","generation":0,"own_channel_id":1,"channels":[{"id":1}],"clients":[]})).await.unwrap();
|
||||||
|
{let mut tx=ctx.transmission.lock().unwrap();tx.observe_owner(Some(key.clone()));tx.capture_desired=true;}
|
||||||
|
controller::release_ui_immediate(ctx,true);
|
||||||
|
let target=Target{session:Some(key.clone()),entity:Entity::Connection,name:String::new(),own_channel_id:None};
|
||||||
|
assert_eq!(controller::ptt(ctx.clone(),target,true).await.unwrap_err().code,"ui_not_focused");
|
||||||
|
for action in [Action::PushToTalk,Action::PushToMute,Action::QuickWhisper,Action::ReplyWhisper,Action::WhisperList]{
|
||||||
|
let binding=serde_json::from_value(json!({"id":"queued","action":action,"code":"Space","global":false})).unwrap();
|
||||||
|
ctx.apply_key_events(vec![ActionEvent{binding,scope:Scope::Local,phase:Phase::Start}]).await.unwrap();
|
||||||
|
}
|
||||||
|
{let tx=ctx.transmission.lock().unwrap();assert!(tx.capture_desired);assert!(tx.ptt_holders.is_empty());assert!(tx.deactivated.is_empty());assert!(!tx.whisper.held());}
|
||||||
|
assert!(!ctx.audio.input_active());cleanup(owner).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor="current_thread")]
|
||||||
|
async fn audit_lifecycle_background_permission_and_os_focus_loss_still_revoke() {
|
||||||
|
use crate::platform::lifecycle::{PlatformEvent,Permission};
|
||||||
|
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
|
||||||
|
let mut state=AppState::default();
|
||||||
|
ctx.transmission.lock().unwrap().capture_desired=true;
|
||||||
|
platform(ctx,&Weak::new(),&mut state,PlatformEvent::PermissionChanged{permission:Permission::Microphone,granted:false}).await.unwrap();
|
||||||
|
assert!(!ctx.transmission.lock().unwrap().capture_desired);
|
||||||
|
platform(ctx,&Weak::new(),&mut state,PlatformEvent::PermissionChanged{permission:Permission::Microphone,granted:true}).await.unwrap();
|
||||||
|
assert!(!ctx.transmission.lock().unwrap().capture_desired,"permission grant does not restore capture intent");
|
||||||
|
ctx.transmission.lock().unwrap().capture_desired=true;
|
||||||
|
platform(ctx,&Weak::new(),&mut state,PlatformEvent::AudioInterruption{began:true,should_resume:false}).await.unwrap();
|
||||||
|
assert!(!ctx.transmission.lock().unwrap().capture_desired);
|
||||||
|
platform(ctx,&Weak::new(),&mut state,PlatformEvent::AudioInterruption{began:false,should_resume:true}).await.unwrap();
|
||||||
|
assert!(!ctx.transmission.lock().unwrap().capture_desired);assert!(!ctx.audio.input_active());
|
||||||
|
cleanup(owner).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor="current_thread")]
|
||||||
|
async fn audit_lifecycle_background_screen_lock_honors_explicit_mute_policy() {
|
||||||
|
use crate::platform::lifecycle::PlatformEvent;
|
||||||
|
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
|
||||||
|
let mut state=AppState::default();
|
||||||
|
ctx.profile().unwrap().prefs.set(json!({"osMuteWhenLocked":false})).unwrap();
|
||||||
|
ctx.transmission.lock().unwrap().capture_desired=true;
|
||||||
|
platform(ctx,&Weak::new(),&mut state,PlatformEvent::ScreenLocked(true)).await.unwrap();
|
||||||
|
assert!(ctx.transmission.lock().unwrap().capture_desired,"screen off alone must not revoke an authorized call");
|
||||||
|
ctx.profile().unwrap().prefs.set(json!({"osMuteWhenLocked":true})).unwrap();
|
||||||
|
platform(ctx,&Weak::new(),&mut state,PlatformEvent::ScreenLocked(true)).await.unwrap();
|
||||||
|
assert!(!ctx.transmission.lock().unwrap().capture_desired);
|
||||||
|
platform(ctx,&Weak::new(),&mut state,PlatformEvent::ScreenLocked(false)).await.unwrap();
|
||||||
|
assert!(!ctx.transmission.lock().unwrap().capture_desired,"unlock is not microphone consent");
|
||||||
|
cleanup(owner).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor="current_thread")]
|
||||||
|
async fn audit_lifecycle_background_terminal_shutdown_fences_capture_before_cleanup() {
|
||||||
|
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");
|
||||||
|
crate::services::profile_import::initialize_native_root(&root).unwrap();
|
||||||
|
let runtime=AppRuntime::start(AppConfig::isolated(root)).unwrap();
|
||||||
|
let mut snapshots=runtime.subscribe();
|
||||||
|
let ctx=loop{
|
||||||
|
if let Some(ctx)=runtime.services.lock().unwrap().upgrade(){break ctx}
|
||||||
|
snapshots.changed().await.unwrap();
|
||||||
|
};
|
||||||
|
ctx.transmission.lock().unwrap().capture_desired=true;
|
||||||
|
runtime.request_shutdown();
|
||||||
|
assert!(*runtime.cancel.borrow());
|
||||||
|
assert!(!ctx.transmission.lock().unwrap().capture_desired,"terminal OS event must fence capture synchronously");
|
||||||
|
tokio::time::timeout(Duration::from_secs(20),runtime.shutdown()).await.unwrap().unwrap();
|
||||||
|
assert!(!ctx.audio.input_active());assert!(!ctx.audio.output_active());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor="current_thread")]
|
||||||
|
async fn audit_lifecycle_network_change_fences_old_capture_without_automatic_resume() {
|
||||||
|
use crate::platform::lifecycle::PlatformEvent;
|
||||||
|
let(_directory,owner,_events,_controls)=fixture().await;let ctx=&owner.ctx;
|
||||||
|
let key=ctx.connected.connections.snapshot().connections[0].key.clone();
|
||||||
|
ctx.connected.connections.fixture_control(&key,json!({"event":"snapshot","generation":0,
|
||||||
|
"own_channel_id":1,"channels":[{"id":1}],"clients":[]})).await.unwrap();
|
||||||
|
let permit=ctx.connected.connections.set_input(Some(&key),crate::app::connections::InputConfiguration::default()).await.unwrap().unwrap();
|
||||||
|
{let mut tx=ctx.transmission.lock().unwrap();tx.observe_owner(Some(key.clone()));tx.capture_desired=true;tx.bound_permit=Some(permit.clone());}
|
||||||
|
ctx.microphone_granted.store(true,Ordering::Release);
|
||||||
|
let mut state=AppState::default();
|
||||||
|
platform(ctx,&Weak::new(),&mut state,PlatformEvent::NetworkChanged).await.unwrap();
|
||||||
|
assert!(!ctx.transmission.lock().unwrap().capture_desired);
|
||||||
|
assert!(ctx.connected.connections.current_capture_permit().is_none());
|
||||||
|
let old=teamspeach_core::audio::CapturedFrame{pcm:[1;960],captured_at:Instant::now(),
|
||||||
|
connection_generation:key.generation,capture_epoch:permit.capture_epoch,whisper:None};
|
||||||
|
assert_eq!(ctx.connected.connections.push_audio(&key,old),crate::app::connections::CaptureIngress::PermitRevoked);
|
||||||
|
platform(ctx,&Weak::new(),&mut state,PlatformEvent::NetworkChanged).await.unwrap();
|
||||||
|
assert!(!ctx.audio.input_active());assert!(!ctx.transmission.lock().unwrap().capture_desired);
|
||||||
|
cleanup(owner).await;
|
||||||
|
}
|
||||||
@@ -4,6 +4,17 @@ use super::context::RuntimeServices;
|
|||||||
use super::context::closed;
|
use super::context::closed;
|
||||||
use crate::{app::connections::SessionKey,services::Result};
|
use crate::{app::connections::SessionKey,services::Result};
|
||||||
impl RuntimeServices {
|
impl RuntimeServices {
|
||||||
|
/// Observation only: cannot create a lease or grant/re-enable capture.
|
||||||
|
pub fn background_capture_authorized(&self)->bool {
|
||||||
|
#[cfg(target_os="android")]
|
||||||
|
{
|
||||||
|
if !self.policy.allow_os_actions||!self.microphone_granted.load(std::sync::atomic::Ordering::Acquire){return false}
|
||||||
|
let snapshot=self.connected.connections.snapshot();
|
||||||
|
return snapshot.input_id.as_deref().and_then(|id|snapshot.get(id)).is_some_and(|session|session.is_connected()&&crate::platform::android::voice_audio_allowed(&session.key,true));
|
||||||
|
}
|
||||||
|
#[cfg(not(target_os="android"))]
|
||||||
|
false
|
||||||
|
}
|
||||||
/// Created only by a current foreground Connect/microphone action, never profile load or resume.
|
/// Created only by a current foreground Connect/microphone action, never profile load or resume.
|
||||||
pub async fn ensure_mobile_call(self:&Arc<Self>,key:&SessionKey,microphone:bool)->Result<()> {
|
pub async fn ensure_mobile_call(self:&Arc<Self>,key:&SessionKey,microphone:bool)->Result<()> {
|
||||||
let configuration=self.audio_configuration.lock().await;
|
let configuration=self.audio_configuration.lock().await;
|
||||||
|
|||||||
+11
-4
@@ -64,7 +64,7 @@ impl AppRuntime {
|
|||||||
pub fn build_description(&self)->String{format!("Version {}\nRust + Slint 1.18.1\n{} / {}",self.config.build_version,std::env::consts::OS,std::env::consts::ARCH)}
|
pub fn build_description(&self)->String{format!("Version {}\nRust + Slint 1.18.1\n{} / {}",self.config.build_version,std::env::consts::OS,std::env::consts::ARCH)}
|
||||||
pub fn policy(&self)->platform::resources::ActionPolicy{platform::resources::ActionPolicy{allow_os_actions:self.config.allow_os_actions}}
|
pub fn policy(&self)->platform::resources::ActionPolicy{platform::resources::ActionPolicy{allow_os_actions:self.config.allow_os_actions}}
|
||||||
pub fn next_ui_generation(&self)->u64 {
|
pub fn next_ui_generation(&self)->u64 {
|
||||||
self.release_held();
|
self.release_ui_holds();
|
||||||
let generation=NEXT_UI_GENERATION.fetch_update(Ordering::AcqRel,Ordering::Acquire,|g|g.checked_add(1)).expect("UI generation exhausted")+1;
|
let generation=NEXT_UI_GENERATION.fetch_update(Ordering::AcqRel,Ordering::Acquire,|g|g.checked_add(1)).expect("UI generation exhausted")+1;
|
||||||
self.active_ui.store(generation,Ordering::Release);generation
|
self.active_ui.store(generation,Ordering::Release);generation
|
||||||
}
|
}
|
||||||
@@ -73,12 +73,16 @@ impl AppRuntime {
|
|||||||
pub fn is_ui_current(&self,generation:u64)->bool{generation!=0&&self.ui_generation()==generation}
|
pub fn is_ui_current(&self,generation:u64)->bool{generation!=0&&self.ui_generation()==generation}
|
||||||
pub fn release_ui(&self,generation:u64){
|
pub fn release_ui(&self,generation:u64){
|
||||||
if self.active_ui.compare_exchange(generation,0,Ordering::AcqRel,Ordering::Acquire).is_ok(){
|
if self.active_ui.compare_exchange(generation,0,Ordering::AcqRel,Ordering::Acquire).is_ok(){
|
||||||
self.release_held();self.wake.lock().expect("UI wake").take();
|
self.release_ui_holds();self.wake.lock().expect("UI wake").take();
|
||||||
#[cfg(not(any(target_os="android",target_os="ios")))] self.desktop.lock().expect("desktop handle").take();
|
#[cfg(not(any(target_os="android",target_os="ios")))] self.desktop.lock().expect("desktop handle").take();
|
||||||
let _=self.commands.try_send(app::runtime::RuntimeCommand::Detached(generation));
|
let _=self.commands.try_send(app::runtime::RuntimeCommand::Detached(generation));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn release_held(&self){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){app::runtime::controller::release_immediate(&ctx);let stop=ctx.transmission.lock().ok().and_then(|mut tx|tx.whisper.release(None));if let Some(stop)=stop{if self.commands.try_send(app::runtime::RuntimeCommand::WhisperStop(stop)).is_err(){self.cancel.send_replace(true);}}}}
|
pub fn release_held(&self){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){app::runtime::controller::release_immediate(&ctx);let stop=ctx.transmission.lock().ok().and_then(|mut tx|tx.whisper.release(None));if let Some(stop)=stop{if self.commands.try_send(app::runtime::RuntimeCommand::WhisperStop(stop)).is_err(){self.cancel.send_replace(true);}}}}
|
||||||
|
/// UI loss releases momentary controls, not an already-authorized Android call.
|
||||||
|
pub fn release_ui_holds(&self){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){let stop=app::runtime::controller::release_ui_immediate(&ctx,ctx.background_capture_authorized());if let Some(stop)=stop{if self.commands.try_send(app::runtime::RuntimeCommand::WhisperStop(stop)).is_err(){self.cancel.send_replace(true);}}}}
|
||||||
|
/// Nonblocking OS shutdown: synchronous capture fence followed by worker cleanup.
|
||||||
|
pub(crate) fn request_shutdown(&self){self.release_held();self.cancel.send_replace(true);}
|
||||||
fn release_screen(&self,target:&ui::shell::Target){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){
|
fn release_screen(&self,target:&ui::shell::Target){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){
|
||||||
let delay=ctx.profile().ok().map(|profile|profile.prefs.get()["pttReleaseDelay"].clone());
|
let delay=ctx.profile().ok().map(|profile|profile.prefs.get()["pttReleaseDelay"].clone());
|
||||||
let revoke=if let Ok(mut tx)=ctx.transmission.lock(){if tx.key.as_ref()!=target.session.as_ref(){return}let removed=tx.ptt_holders.remove("screen");if removed{tx.revision=tx.revision.wrapping_add(1);if tx.ptt_holders.is_empty(){tx.release_at=delay.filter(|d|d["active"]==true).and_then(|d|d["ms"].as_u64()).map(|ms|std::time::Instant::now()+std::time::Duration::from_millis(ms));}}removed&&!tx.whisper.held()}else{true};
|
let revoke=if let Ok(mut tx)=ctx.transmission.lock(){if tx.key.as_ref()!=target.session.as_ref(){return}let removed=tx.ptt_holders.remove("screen");if removed{tx.revision=tx.revision.wrapping_add(1);if tx.ptt_holders.is_empty(){tx.release_at=delay.filter(|d|d["active"]==true).and_then(|d|d["ms"].as_u64()).map(|ms|std::time::Instant::now()+std::time::Duration::from_millis(ms));}}removed&&!tx.whisper.held()}else{true};
|
||||||
@@ -94,14 +98,17 @@ impl AppRuntime {
|
|||||||
use platform::lifecycle::PlatformEvent::*;
|
use platform::lifecycle::PlatformEvent::*;
|
||||||
let generation=match &event{Visibility{ui_generation,..}|UiDestroyed{ui_generation}|Insets{ui_generation,..}|Accessibility{ui_generation,..}|DesktopTheme{ui_generation,..}|DesktopWindow{ui_generation,..}|PhysicalKey{ui_generation,..}|Focus{ui_generation,..}=>Some(*ui_generation),_=>None};
|
let generation=match &event{Visibility{ui_generation,..}|UiDestroyed{ui_generation}|Insets{ui_generation,..}|Accessibility{ui_generation,..}|DesktopTheme{ui_generation,..}|DesktopWindow{ui_generation,..}|PhysicalKey{ui_generation,..}|Focus{ui_generation,..}=>Some(*ui_generation),_=>None};
|
||||||
if generation.is_some_and(|generation|!self.is_ui_current(generation)){return}
|
if generation.is_some_and(|generation|!self.is_ui_current(generation)){return}
|
||||||
|
if matches!(&event,Focus{focused:true,..})||(!cfg!(target_os="android")&&matches!(&event,Visibility{visible:true,..})){if let Some(ctx)=self.services.lock().expect("runtime services").upgrade(){if let Ok(mut tx)=ctx.transmission.lock(){tx.ui_controls_suspended=false;}}}
|
||||||
#[cfg(target_os="android")]
|
#[cfg(target_os="android")]
|
||||||
if let AndroidCallAudio{key,token,revision,..}=&event {
|
if let AndroidCallAudio{key,token,revision,..}=&event {
|
||||||
if !platform::android::voice_audio_current(key,*token,*revision){return}
|
if !platform::android::voice_audio_current(key,*token,*revision){return}
|
||||||
self.release_held();
|
self.release_held();
|
||||||
}
|
}
|
||||||
|
if matches!(&event,Focus{focused:false,..}|UiDestroyed{..}){self.release_ui_holds();}
|
||||||
#[cfg(target_os="android")]
|
#[cfg(target_os="android")]
|
||||||
if matches!(&event,Visibility{visible:false,..}){self.release_held();}
|
if matches!(&event,Visibility{visible:false,..}){self.release_ui_holds();}
|
||||||
if matches!(&event,Focus{focused:false,..}|UiDestroyed{..}|AudioInterruption{began:true,..}|AudioRouteChanged|NetworkChanged|PermissionChanged{permission:platform::lifecycle::Permission::Microphone,granted:false}|CallLeaseEnded{..}|Quit){self.release_held();}
|
if matches!(&event,AudioInterruption{began:true,..}|AudioRouteChanged|NetworkChanged|PermissionChanged{permission:platform::lifecycle::Permission::Microphone,granted:false}|CallLeaseEnded{..}|Quit){self.release_held();}
|
||||||
|
if matches!(&event,ScreenLocked(true))&&self.services.lock().expect("runtime services").upgrade().is_some_and(|ctx|ctx.profile().is_ok_and(|profile|profile.prefs.get()["osMuteWhenLocked"]==true)){self.release_held();}
|
||||||
if self.enqueue(app::runtime::RuntimeCommand::Platform(event)).is_err(){self.cancel.send_replace(true);}
|
if self.enqueue(app::runtime::RuntimeCommand::Platform(event)).is_err(){self.cancel.send_replace(true);}
|
||||||
}
|
}
|
||||||
fn enqueue(&self,command:app::runtime::RuntimeCommand)->services::Result<()>{self.commands.try_send(command).map_err(|_|services::ServiceError::new("runtime_busy","Application action queue is full or stopped; retry the action"))}
|
fn enqueue(&self,command:app::runtime::RuntimeCommand)->services::Result<()>{self.commands.try_send(command).map_err(|_|services::ServiceError::new("runtime_busy","Application action queue is full or stopped; retry the action"))}
|
||||||
|
|||||||
@@ -205,8 +205,15 @@ pub(crate) fn acknowledge_voice_output(key:&SessionKey,token:u64,revision:u64,ac
|
|||||||
if let Some(voice)=VOICE.lock().expect("Android voice").as_mut().filter(|voice|&voice.key==key&&voice.token==token){voice.audio.acknowledge_output(revision,active);}
|
if let Some(voice)=VOICE.lock().expect("Android voice").as_mut().filter(|voice|&voice.key==key&&voice.token==token){voice.audio.acknowledge_output(revision,active);}
|
||||||
}
|
}
|
||||||
fn end_voice(token: u64) -> bool {
|
fn end_voice(token: u64) -> bool {
|
||||||
|
end_voice_with_shutdown(token,false)
|
||||||
|
}
|
||||||
|
/// Task dismissal is terminal only for the exact lease that owns this callback.
|
||||||
|
fn end_voice_with_shutdown(token:u64,shutdown:bool)->bool {
|
||||||
let voice = { let mut voice = VOICE.lock().expect("Android voice"); if voice.as_ref().is_some_and(|voice| voice.token == token) { voice.take() } else { None } };
|
let voice = { let mut voice = VOICE.lock().expect("Android voice"); if voice.as_ref().is_some_and(|voice| voice.token == token) { voice.take() } else { None } };
|
||||||
if let Some(voice) = voice { lifecycle::emit(PlatformEvent::CallLeaseEnded { key: voice.key.clone() }); complete(token, Err(error("call_lease_ended", "Android foreground call ended"))); if let Some(id)=voice.capture_change{complete(id,Err(error("call_lease_ended","Android foreground call ended")));} true } else { false }
|
if let Some(voice) = voice {
|
||||||
|
if shutdown{voice._runtime.request_shutdown();}
|
||||||
|
lifecycle::emit(PlatformEvent::CallLeaseEnded { key: voice.key.clone() }); complete(token, Err(error("call_lease_ended", "Android foreground call ended"))); if let Some(id)=voice.capture_change{complete(id,Err(error("call_lease_ended","Android foreground call ended")));} true
|
||||||
|
} else { false }
|
||||||
}
|
}
|
||||||
pub fn stop_voice(key: &SessionKey) -> Result<()> {
|
pub fn stop_voice(key: &SessionKey) -> Result<()> {
|
||||||
let token = VOICE.lock().expect("Android voice").as_ref().filter(|voice| &voice.key == key).map(|voice| voice.token);
|
let token = VOICE.lock().expect("Android voice").as_ref().filter(|voice| &voice.key == key).map(|voice| voice.token);
|
||||||
@@ -341,7 +348,9 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeEvent(_en
|
|||||||
let value=value!=0; let generation=generation as u64;
|
let value=value!=0; let generation=generation as u64;
|
||||||
let event=match event {
|
let event=match event {
|
||||||
0 if generation!=0 && UI.load(Ordering::Acquire)==generation=>PlatformEvent::Visibility{ui_generation:generation,visible:value},
|
0 if generation!=0 && UI.load(Ordering::Acquire)==generation=>PlatformEvent::Visibility{ui_generation:generation,visible:value},
|
||||||
|
8 if generation!=0&&UI.load(Ordering::Acquire)==generation=>PlatformEvent::Focus{ui_generation:generation,focused:value},
|
||||||
1=>{destroy_ui(generation);return;}, 2=>PlatformEvent::AudioInterruption{began:value,should_resume:!value},
|
1=>{destroy_ui(generation);return;}, 2=>PlatformEvent::AudioInterruption{began:value,should_resume:!value},
|
||||||
|
7 if generation!=0&&UI.load(Ordering::Acquire)==generation=>{if let Some(runtime)=RUNTIME.lock().expect("Android runtime").upgrade(){runtime.request_shutdown();}return;},
|
||||||
3=>PlatformEvent::AudioRouteChanged,4=>PlatformEvent::NetworkChanged,5=>PlatformEvent::ScreenLocked(value),6=>PlatformEvent::MemoryPressure,_=>return,
|
3=>PlatformEvent::AudioRouteChanged,4=>PlatformEvent::NetworkChanged,5=>PlatformEvent::ScreenLocked(value),6=>PlatformEvent::MemoryPressure,_=>return,
|
||||||
}; lifecycle::emit(event);
|
}; lifecycle::emit(event);
|
||||||
}
|
}
|
||||||
@@ -371,7 +380,7 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceStar
|
|||||||
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}
|
||||||
#[unsafe(no_mangle)]
|
#[unsafe(no_mangle)]
|
||||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceEvent(_env:JNIEnv,_class:JClass,token:jlong,event:jint,value:jboolean){
|
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceEvent(_env:JNIEnv,_class:JClass,token:jlong,event:jint,value:jboolean){
|
||||||
match event{2=>voice_audio_changed(token as u64,Some(value==0),true),3=>voice_audio_changed(token as u64,None,true),_=>{}}
|
match event{2=>voice_audio_changed(token as u64,Some(value==0),true),3=>voice_audio_changed(token as u64,None,true),7=>{end_voice_with_shutdown(token as u64,true);},_=>{}}
|
||||||
}
|
}
|
||||||
#[unsafe(no_mangle)]
|
#[unsafe(no_mangle)]
|
||||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureValid(_env:JNIEnv,_class:JClass,token:jlong,id:jlong)->jboolean{
|
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCaptureValid(_env:JNIEnv,_class:JClass,token:jlong,id:jlong)->jboolean{
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
<uses-permission android:name="android.permission.CAMERA" />
|
<uses-permission android:name="android.permission.CAMERA" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
|||||||
@@ -108,6 +108,10 @@ public final class TeamsPeachActivity extends NativeActivity {
|
|||||||
resumed = false; CaptureBridge.unbindActivity(this);
|
resumed = false; CaptureBridge.unbindActivity(this);
|
||||||
PlatformBridge.nativeEvent(generation, 0, isInPictureInPictureMode()); super.onPause();
|
PlatformBridge.nativeEvent(generation, 0, isInPictureInPictureMode()); super.onPause();
|
||||||
}
|
}
|
||||||
|
@Override public void onWindowFocusChanged(boolean focused) {
|
||||||
|
super.onWindowFocusChanged(focused);
|
||||||
|
PlatformBridge.nativeEvent(generation,8,focused);
|
||||||
|
}
|
||||||
@Override protected void onDestroy() {
|
@Override protected void onDestroy() {
|
||||||
CaptureBridge.unbindActivity(this);
|
CaptureBridge.unbindActivity(this);
|
||||||
getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(insetLayout);
|
getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(insetLayout);
|
||||||
@@ -119,6 +123,8 @@ public final class TeamsPeachActivity extends NativeActivity {
|
|||||||
if (sharedGrant != null) { sharedGrant.close(); sharedGrant=null; }
|
if (sharedGrant != null) { sharedGrant.close(); sharedGrant=null; }
|
||||||
if(installerRequest>0)PlatformBridge.nativeText(installerRequest,null,"activity_destroyed");
|
if(installerRequest>0)PlatformBridge.nativeText(installerRequest,null,"activity_destroyed");
|
||||||
InstallProvider.release(installerUri);installerUri=null;
|
InstallProvider.release(installerUri);installerUri=null;
|
||||||
|
// Finishing is terminal; configuration/UI recreation alone keeps an active call.
|
||||||
|
if(isFinishing()&&!isChangingConfigurations())PlatformBridge.nativeEvent(generation,7,true);
|
||||||
PlatformBridge.nativeEvent(generation, 1, false);
|
PlatformBridge.nativeEvent(generation, 1, false);
|
||||||
if (PlatformBridge.activity.get() == this) PlatformBridge.activity.clear();
|
if (PlatformBridge.activity.get() == this) PlatformBridge.activity.clear();
|
||||||
super.onDestroy();
|
super.onDestroy();
|
||||||
@@ -140,6 +146,7 @@ public final class TeamsPeachActivity extends NativeActivity {
|
|||||||
@Override public void onConfigurationChanged(Configuration value) { super.onConfigurationChanged(value); reportConfiguration(); }
|
@Override public void onConfigurationChanged(Configuration value) { super.onConfigurationChanged(value); reportConfiguration(); }
|
||||||
@Override public void onTrimMemory(int level) { super.onTrimMemory(level); if (level >= TRIM_MEMORY_RUNNING_LOW) PlatformBridge.nativeEvent(generation, 6, true); }
|
@Override public void onTrimMemory(int level) { super.onTrimMemory(level); if (level >= TRIM_MEMORY_RUNNING_LOW) PlatformBridge.nativeEvent(generation, 6, true); }
|
||||||
void reportConfiguration() {
|
void reportConfiguration() {
|
||||||
|
PlatformBridge.nativeEvent(generation,8,hasWindowFocus());
|
||||||
AccessibilityManager manager = getSystemService(AccessibilityManager.class);
|
AccessibilityManager manager = getSystemService(AccessibilityManager.class);
|
||||||
boolean reduced = Settings.Global.getFloat(getContentResolver(), Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f;
|
boolean reduced = Settings.Global.getFloat(getContentResolver(), Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f;
|
||||||
boolean contrast = Settings.Secure.getInt(getContentResolver(), "high_text_contrast_enabled", 0) != 0;
|
boolean contrast = Settings.Secure.getInt(getContentResolver(), "high_text_contrast_enabled", 0) != 0;
|
||||||
|
|||||||
@@ -15,12 +15,14 @@ public final class VoiceService extends Service {
|
|||||||
private AudioDeviceCallback devices;
|
private AudioDeviceCallback devices;
|
||||||
private boolean focused;
|
private boolean focused;
|
||||||
private boolean communicationMode;
|
private boolean communicationMode;
|
||||||
|
private PowerManager.WakeLock callWakeLock;
|
||||||
private java.util.Set<Integer> deviceIds = java.util.Collections.emptySet();
|
private java.util.Set<Integer> deviceIds = java.util.Collections.emptySet();
|
||||||
private AudioManager.OnCommunicationDeviceChangedListener communicationDeviceListener;
|
private AudioManager.OnCommunicationDeviceChangedListener communicationDeviceListener;
|
||||||
private int communicationDeviceId;
|
private int communicationDeviceId;
|
||||||
private static final int ID = 7240;
|
private static final int ID = 7240;
|
||||||
private static java.lang.ref.WeakReference<VoiceService> current = new java.lang.ref.WeakReference<>(null);
|
private static java.lang.ref.WeakReference<VoiceService> current = new java.lang.ref.WeakReference<>(null);
|
||||||
static void stop(long token) { VoiceService service=current.get(); if(service!=null && (token==0 || token==service.token)){CaptureBridge.revokeAll();service.stopSelf();} }
|
static void stop(long token) { VoiceService service=current.get(); if(service!=null && (token==0 || token==service.token)){CaptureBridge.revokeAll();service.stopSelf();} }
|
||||||
|
private void releaseWakeLock() { if(callWakeLock!=null){if(callWakeLock.isHeld())callWakeLock.release();callWakeLock=null;} }
|
||||||
private void foreground(boolean capture) {
|
private void foreground(boolean capture) {
|
||||||
if(capture && !PlatformBridge.granted(0))throw new SecurityException("Microphone permission required");
|
if(capture && !PlatformBridge.granted(0))throw new SecurityException("Microphone permission required");
|
||||||
Notification notification = new Notification.Builder(this, "voice").setSmallIcon(android.R.drawable.stat_sys_phone_call).setContentTitle("TeamsPeach voice call").setContentText(capture ? "Microphone is controlled by your call settings" : "Listening only — microphone off").setOngoing(true)
|
Notification notification = new Notification.Builder(this, "voice").setSmallIcon(android.R.drawable.stat_sys_phone_call).setContentTitle("TeamsPeach voice call").setContentText(capture ? "Microphone is controlled by your call settings" : "Listening only — microphone off").setOngoing(true)
|
||||||
@@ -74,7 +76,7 @@ public final class VoiceService extends Service {
|
|||||||
@Override public int onStartCommand(Intent intent, int flags, int startId) {
|
@Override public int onStartCommand(Intent intent, int flags, int startId) {
|
||||||
long incoming = intent == null ? 0 : intent.getLongExtra("token", 0);
|
long incoming = intent == null ? 0 : intent.getLongExtra("token", 0);
|
||||||
boolean capture=intent!=null && intent.getBooleanExtra("microphone",false);
|
boolean capture=intent!=null && intent.getBooleanExtra("microphone",false);
|
||||||
if (incoming == 0 || (capture && (!PlatformBridge.granted(0)||PlatformBridge.visible()==null)) || !PlatformBridge.nativeVoiceValid(incoming)) { if(token==0)stopSelf(); return START_NOT_STICKY; }
|
if (incoming == 0 || PlatformBridge.visible()==null || (capture && !PlatformBridge.granted(0)) || !PlatformBridge.nativeVoiceValid(incoming)) { if(token==0)stopSelf(); return START_NOT_STICKY; }
|
||||||
if (token != 0 && token != incoming) {
|
if (token != 0 && token != incoming) {
|
||||||
PlatformBridge.nativeVoiceStopped(token);
|
PlatformBridge.nativeVoiceStopped(token);
|
||||||
if(focus!=null)getSystemService(AudioManager.class).abandonAudioFocusRequest(focus);
|
if(focus!=null)getSystemService(AudioManager.class).abandonAudioFocusRequest(focus);
|
||||||
@@ -86,6 +88,8 @@ public final class VoiceService extends Service {
|
|||||||
token = incoming;
|
token = incoming;
|
||||||
try {
|
try {
|
||||||
foreground(capture);
|
foreground(capture);
|
||||||
|
// Foreground notification alone does not keep the native audio/network worker awake.
|
||||||
|
if(callWakeLock==null){callWakeLock=getSystemService(PowerManager.class).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"TeamsPeach:voice-call");callWakeLock.setReferenceCounted(false);callWakeLock.acquire();}
|
||||||
AudioManager audio = getSystemService(AudioManager.class);
|
AudioManager audio = getSystemService(AudioManager.class);
|
||||||
audio.setMode(AudioManager.MODE_IN_COMMUNICATION);
|
audio.setMode(AudioManager.MODE_IN_COMMUNICATION);
|
||||||
communicationMode=true;
|
communicationMode=true;
|
||||||
@@ -119,7 +123,17 @@ public final class VoiceService extends Service {
|
|||||||
} catch (RuntimeException error) { PlatformBridge.nativeVoiceStopped(token); stopSelf(); }
|
} catch (RuntimeException error) { PlatformBridge.nativeVoiceStopped(token); stopSelf(); }
|
||||||
return START_NOT_STICKY;
|
return START_NOT_STICKY;
|
||||||
}
|
}
|
||||||
|
@Override public void onTaskRemoved(Intent rootIntent) {
|
||||||
|
// Validate the lease in native code before ending it: a stale service must not
|
||||||
|
// terminate a replacement runtime. Never restart this service after task removal.
|
||||||
|
if(token!=0)PlatformBridge.nativeVoiceEvent(token,7,true);
|
||||||
|
CaptureBridge.revokeAll();
|
||||||
|
releaseWakeLock();
|
||||||
|
stopForeground(STOP_FOREGROUND_REMOVE);stopSelf();
|
||||||
|
super.onTaskRemoved(rootIntent);
|
||||||
|
}
|
||||||
@Override public void onDestroy() {
|
@Override public void onDestroy() {
|
||||||
|
releaseWakeLock();
|
||||||
if (focus != null) getSystemService(AudioManager.class).abandonAudioFocusRequest(focus);
|
if (focus != null) getSystemService(AudioManager.class).abandonAudioFocusRequest(focus);
|
||||||
if (devices != null) getSystemService(AudioManager.class).unregisterAudioDeviceCallback(devices);
|
if (devices != null) getSystemService(AudioManager.class).unregisterAudioDeviceCallback(devices);
|
||||||
if(Build.VERSION.SDK_INT>=31&&communicationDeviceListener!=null)getSystemService(AudioManager.class).removeOnCommunicationDeviceChangedListener(communicationDeviceListener);
|
if(Build.VERSION.SDK_INT>=31&&communicationDeviceListener!=null)getSystemService(AudioManager.class).removeOnCommunicationDeviceChangedListener(communicationDeviceListener);
|
||||||
|
|||||||
@@ -62,6 +62,11 @@ public final class CaptureService extends Service {
|
|||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
static void released(CaptureSession session) { RELEASING.remove(session.request.id, session); }
|
static void released(CaptureSession session) { RELEASING.remove(session.request.id, session); }
|
||||||
|
@Override public void onTaskRemoved(Intent rootIntent) {
|
||||||
|
CaptureBridge.revokeAll();
|
||||||
|
stopForeground(STOP_FOREGROUND_REMOVE);stopSelf();
|
||||||
|
super.onTaskRemoved(rootIntent);
|
||||||
|
}
|
||||||
@Override public void onDestroy() {
|
@Override public void onDestroy() {
|
||||||
for (CaptureSession session : sessions.values()) { RELEASING.put(session.request.id, session); session.close(); CaptureBridge.nativeEnded(session.request.id, "Capture foreground service stopped"); CaptureBridge.REQUESTS.remove(session.request.id); }
|
for (CaptureSession session : sessions.values()) { RELEASING.put(session.request.id, session); session.close(); CaptureBridge.nativeEnded(session.request.id, "Capture foreground service stopped"); CaptureBridge.REQUESTS.remove(session.request.id); }
|
||||||
sessions.clear(); if (current.get() == this) current.clear(); super.onDestroy();
|
sessions.clear(); if (current.get() == this) current.clear(); super.onDestroy();
|
||||||
|
|||||||
Reference in new issue
Block a user