167 lines
11 KiB
Rust
167 lines
11 KiB
Rust
use std::sync::Arc;
|
|
use super::context::RuntimeServices;
|
|
#[cfg(any(target_os="android",target_os="ios"))]
|
|
use super::context::closed;
|
|
use crate::{app::connections::SessionKey,services::Result};
|
|
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_capture_retained(&session.key));
|
|
}
|
|
#[cfg(not(target_os="android"))]
|
|
false
|
|
}
|
|
/// 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<()> {
|
|
let configuration=self.audio_configuration.lock().await;
|
|
self.ensure_mobile_call_locked(key,microphone,&configuration).await
|
|
}
|
|
/// Callers retain this guard through capture permit binding and hardware startup.
|
|
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()?;
|
|
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));
|
|
#[cfg(target_os="android")]
|
|
let cached=cached&&crate::platform::android::voice_audio_allowed(key,microphone);
|
|
if cached{return Ok(())}
|
|
#[cfg(target_os="android")]
|
|
{
|
|
if let Some((current,_))=call.as_ref(){if current!=key{crate::platform::android::stop_voice(current)?;*call=None;}}
|
|
if call.is_none(){let runtime=self.runtime.upgrade().ok_or_else(closed)?;let prefs=self.profile()?.prefs.get();crate::platform::android::start_voice(runtime,key.clone(),microphone,prefs["outputDeviceId"].as_str().unwrap_or_default(),self.policy).await?;}
|
|
else{crate::platform::android::set_voice_capture(key,microphone,self.policy).await?;}
|
|
}
|
|
#[cfg(target_os="ios")]
|
|
{
|
|
let mut lease=self.apple_call.lock().await;
|
|
if lease.as_ref().is_some_and(|lease|lease.key()!=key){lease.take();}
|
|
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?);}
|
|
}
|
|
self.require_key(key,true)?;self.require_ui_generation(generation)?;
|
|
#[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 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(())
|
|
}
|
|
/// Complete only the steady intent captured by the synchronous route fence.
|
|
/// Shared with host consumer regressions; hardware/core ACKs remain real.
|
|
#[cfg(any(target_os="android",test))]
|
|
pub(super) async fn resume_mobile_route_capture_locked(self:&Arc<Self>,key:&SessionKey,intent_revision:u64,configuration:&tokio::sync::MutexGuard<'_,()>)->Result<bool>{
|
|
self.require_key(key,true)?;
|
|
if self.transmission.lock().map_err(|_|super::context::changed())?.capture_intent(key,intent_revision).is_err(){return Ok(false)}
|
|
self.refresh_capture_locked(configuration,false).await
|
|
}
|
|
#[cfg(target_os="android")]
|
|
pub async fn android_audio_changed(self:&Arc<Self>,key:&SessionKey,token:u64,revision:u64,restart_output:bool)->Result<()> {
|
|
use crate::media::audio::{engine::AudioCommand,devices::StartPermission};
|
|
use std::sync::atomic::Ordering;
|
|
use crate::platform::android::{VoiceRoutePhase as Phase,VoiceRouteReason as Reason,log_voice_route};
|
|
let started=std::time::Instant::now();
|
|
let mut phase=Phase::Validate;
|
|
let mut reason=Reason::Completed;
|
|
let current=||{
|
|
if self.require_key(key,true).is_err(){Err(Reason::OwnerChanged)}
|
|
else if !crate::platform::android::voice_audio_current(key,token,revision){Err(Reason::AudioRevisionChanged)}
|
|
else{Ok(())}
|
|
};
|
|
let result:Result<()>=async {
|
|
if let Err(changed)=current(){reason=changed;return Ok(())}
|
|
phase=Phase::Configuration;
|
|
let configuration=self.audio_configuration.lock().await;
|
|
if let Err(changed)=current(){reason=changed;return Ok(())}
|
|
let migrate=crate::platform::android::voice_audio_allowed(key,true);
|
|
// The callback already fenced PCM and dropped momentary controls. Do not
|
|
// revoke retained steady consent a second time on the queued worker.
|
|
if !migrate{super::controller::release_immediate(self);}
|
|
let intent_revision=self.transmission.lock().map_err(|_|super::context::changed())?.revision;
|
|
phase=Phase::StopInput;
|
|
self.audio.request(AudioCommand::StopInput).await?;
|
|
self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
|
|
if let Err(changed)=current(){reason=changed;return Ok(())}
|
|
let prefs=self.profile()?.prefs.get();
|
|
// Observation never requests or ranks a 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;
|
|
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(())}
|
|
phase=Phase::SelectOutput;
|
|
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(())}
|
|
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;
|
|
self.audio.request(AudioCommand::StopOutput).await?;
|
|
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) {
|
|
phase=Phase::StartOutput;
|
|
playback_error=self.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await.err();
|
|
if current().is_err()||!crate::platform::android::voice_audio_allowed(key,false){
|
|
reason=current().err().unwrap_or(Reason::PlaybackRevoked);
|
|
phase=Phase::StopOutput;
|
|
self.audio.request(AudioCommand::StopOutput).await?;return Ok(())
|
|
}
|
|
self.audio_output_active.store(self.audio.output_active(),Ordering::Release);
|
|
}else if !self.output_granted.load(Ordering::Acquire){reason=Reason::OutputNotGranted;}
|
|
else{reason=Reason::PlaybackRevoked;}
|
|
}
|
|
if restart_output {
|
|
phase=Phase::OutputAck;
|
|
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());
|
|
}
|
|
if let Err(changed)=current(){reason=changed;return Ok(())}
|
|
// Permission/mute/owner changes that arrived while hardware was replaced
|
|
// supersede this migration. Never infer consent from an old route event.
|
|
phase=Phase::CaptureIntent;
|
|
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){
|
|
crate::platform::android::validate_voice_capture_pair(&pair.0,&pair.1,true)?;
|
|
phase=Phase::ResumeCapture;
|
|
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()) {
|
|
phase=Phase::MuteCapture;
|
|
self.request(key,teamspeach_core::protocol::Command::SetAudio{input_muted:Some(true),output_muted:None}).await?;
|
|
}
|
|
phase=Phase::Enumerate;
|
|
if current().is_ok(){self.audio.request(AudioCommand::Enumerate).await?;}
|
|
else if let Err(changed)=current(){reason=changed;return Ok(())}
|
|
phase=Phase::Complete;
|
|
if let Some(error)=playback_error{return Err(error)}
|
|
Ok(())
|
|
}.await;
|
|
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());
|
|
result
|
|
}
|
|
pub async fn end_mobile_call(&self,key:&SessionKey)->Result<()> {
|
|
let mut call=self.mobile_call.lock().await;
|
|
if call.as_ref().is_none_or(|(current,_)|current!=key){return Ok(())}
|
|
#[cfg(target_os="android")]if self.policy.allow_os_actions{crate::platform::android::stop_voice(key)?;}
|
|
#[cfg(target_os="ios")]self.apple_call.lock().await.take();
|
|
*call=None;Ok(())
|
|
}
|
|
}
|