Add bounded private Android route and audio pipeline diagnostics
android-ci / android-arm64 (push) Successful in 14m44s

This commit is contained in:
bit9992 committed 2026-11-14 15:12:54 +03:00
1 parent 3b56013d0d
commit 4ea413f589
12 files changed
+712 -104

No files matched your search

+5 -1
View File
@@ -2,6 +2,10 @@
## Unreleased ## Unreleased
- Add rate-bounded Android audio-route/command diagnostics and active five-second RX/TX pipeline
summaries. Record only enums, booleans, format/count/timing fields and coarse signal buckets;
never PCM, endpoint identities, server addresses, chat or credentials. Callbacks increment counters
without logging; dropped output blocks and suppressed diagnostic events are counted separately.
- Join a terminated Android runtime before first re-entry instead of attaching to its frozen snapshot; - Join a terminated Android runtime before first re-entry instead of attaching to its frozen snapshot;
ordinary Activity recreation retains a live call and stale UI generations cannot stop the new owner. ordinary Activity recreation retains a live call and stale UI generations cannot stop the new owner.
- Follow connected communication headsets and restore the prior handset route on removal. Fence old - Follow connected communication headsets and restore the prior handset route on removal. Fence old
@@ -12,7 +16,7 @@
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.
- 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 aggregates ingress rejection counts in bounded diagnostic summaries.
- Separate slow CPAL/DSP/notification lifecycle ownership from live PCM servicing, preserving output - Separate slow CPAL/DSP/notification lifecycle ownership from live PCM servicing, preserving output
callbacks and reference draining while capture opens. Keep durable output authorization across reset callbacks and reference draining while capture opens. Keep durable output authorization across reset
races; later stops still win. Reconcile acknowledged same-owner capture changes without retries. races; later stops still win. Reconcile acknowledged same-owner capture changes without retries.
+28
View File
@@ -670,6 +670,34 @@ to this pre-UI scope. No speculative microphone gain/audio refactor on accepted
Missing ACK3seconds becomes receive-only, no loop/retry. Built-in verified numeric endpoints follow Missing ACK3seconds becomes receive-only, no loop/retry. Built-in verified numeric endpoints follow
active call communication default; exact external/unknown IDs remain exact, persisted prefs unchanged. active call communication default; exact external/unknown IDs remain exact, persisted prefs unchanged.
Pure Java selection and real-runtime migration regressions added; integrated results pending. Pure Java selection and real-runtime migration regressions added; integrated results pending.
- Route/reopen candidate2565e55: Java route selection fixture passed locally. CI4938 reached runtime
test and failed because fixture discarded startup observer (`let(_,release)`); fixed61f748c retaining
receiver. CI4939 route tests passed; reopen assertions incorrectly equated preferred input owner with
capture activity. Removed that incidental assertion in3b56013; absent permit/audio/voice/tree and
disconnected-state assertions retained.
- Run4941/job5537 SUCCESS on3b56013d0d96d14d36593e64ff75d589642d25c9: catalog4,timestamp3,route-state6,
Java policy fixture,DSP15,native146,capture18,lifecycle12,real runtime restart3,manager7,core23+output2
passed/1ignored. Full Android package verified. Default handset speaker/receiver preference preserved
and remembered for headset removal. Download active; real Bluetooth and first-reopen proof pending.
- APK4941 downloaded, ZIP+6 hashes verified, SHA256
77eeac86f1724b164d39e4c4f99c5e08f7152d7119fe4ab23b91903cda3690b7. Initial streamed adb attempt
transport failed; installed4936 hash remained unchanged. Nonstreaming retry confirmed signature
mismatch; standing authorized uninstall/install4941 both Success and cold launch complete.
- Owner reports automatic headset adoption still not working; after manual Bluetooth capture selection
TX works continuously but RX silent. This is partial route success, not Bluetooth acceptance. Requested
comprehensive logs. No retained first_fault/ingress records; screenshot android-4941-bluetooth-rx-silent.png.
Adding bounded Android engine/route lifecycle diagnostics, counters and numeric format/age/revision/
timing fields only; never PCM, chat, identities, server addresses, device names/IDs/MACs, secrets.
Engine periodic summaries distinguish decoded binding input, route drops, mixer/submission/callbacks;
Android communication logs identify type selection, ACK/timeout and restoration stages. Cause of RX
silence remains unproved; no speculative audio gain/format workaround.
- Diagnostic candidate implemented: audio_summary every5s while active with binding/core-decoded
ingress, queue/mixer/route/time drops, TX accepted/rejected/revoked, nonzero mixed blocks/coarse peak
bucket, submitted/callback/discard/underrun counts and format/revisions. Command begin/end admitted
once per kind/5s with fixed reason/duration; suppressed counts visible. Callback path only counters.
audio_route Java/native each <=16records/10s reports actual type selection, request/ACK/timeout/focus
and recovery phase/supersession. No arbitrary ServiceError text, PCM or endpoint identities logged.
New counter/rate-gate/route suppression tests await CI; no speculative route behavior change.
## First Android APK build ## First Android APK build
+2 -1
View File
@@ -21,10 +21,11 @@ impl ConnectionSink for AudioSessionBinding {
match event{ match event{
ConnectionEvent::InputReset=>{audio.revoke_local_capture();}, ConnectionEvent::InputReset=>{audio.revoke_local_capture();},
ConnectionEvent::Playback{key,frame}=>{ ConnectionEvent::Playback{key,frame}=>{
audio.record_binding_received();
let routes=self.routes.lock().expect("playback routes poisoned"); let routes=self.routes.lock().expect("playback routes poisoned");
if let Some(route)=routes.get(&key.connection_id).filter(|r|r.key==key&&r.enabled){ if let Some(route)=routes.get(&key.connection_id).filter(|r|r.key==key&&r.enabled){
self.report(audio.push_voice(key,route.epoch,frame.pcm,frame.emitted_at)); self.report(audio.push_voice(key,route.epoch,frame.pcm,frame.emitted_at));
} }else{audio.record_binding_route_drop();}
}, },
ConnectionEvent::Control{key,value}=>{ ConnectionEvent::Control{key,value}=>{
let mut routes=self.routes.lock().expect("playback routes poisoned"); let mut routes=self.routes.lock().expect("playback routes poisoned");
+68 -36
View File
@@ -58,44 +58,76 @@ impl RuntimeServices {
pub async fn android_audio_changed(self:&Arc<Self>,key:&SessionKey,token:u64,revision:u64,restart_output:bool)->Result<()> { 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 crate::media::audio::{engine::AudioCommand,devices::StartPermission};
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
let current=||self.require_key(key,true).is_ok()&&crate::platform::android::voice_audio_current(key,token,revision); use crate::platform::android::{VoiceRoutePhase as Phase,VoiceRouteReason as Reason,log_voice_route};
if !current(){return Ok(())} let started=std::time::Instant::now();
let configuration=self.audio_configuration.lock().await; let mut phase=Phase::Validate;
if !current(){return Ok(())} let mut reason=Reason::Completed;
let migrate=crate::platform::android::voice_audio_allowed(key,true); let current=||{
// The callback already fenced PCM and dropped momentary controls. Do not if self.require_key(key,true).is_err(){Err(Reason::OwnerChanged)}
// revoke retained steady consent a second time on the queued worker. else if !crate::platform::android::voice_audio_current(key,token,revision){Err(Reason::AudioRevisionChanged)}
if !migrate{super::controller::release_immediate(self);} else{Ok(())}
let intent_revision=self.transmission.lock().map_err(|_|super::context::changed())?.revision; };
self.audio.request(AudioCommand::StopInput).await?; let result:Result<()>=async {
self.audio_input_active.store(self.audio.input_active(),Ordering::Release); if let Err(changed)=current(){reason=changed;return Ok(())}
if !current(){return Ok(())} phase=Phase::Configuration;
let prefs=self.profile()?.prefs.get(); let configuration=self.audio_configuration.lock().await;
self.audio.request(AudioCommand::SelectInput(crate::platform::android::voice_device_selection(prefs["inputDeviceId"].as_str().unwrap_or_default())?)).await?; if let Err(changed)=current(){reason=changed;return Ok(())}
if !current(){return Ok(())} let migrate=crate::platform::android::voice_audio_allowed(key,true);
self.audio.request(AudioCommand::SelectOutput(crate::platform::android::voice_device_selection(prefs["outputDeviceId"].as_str().unwrap_or_default())?)).await?; // The callback already fenced PCM and dropped momentary controls. Do not
if !current(){return Ok(())} // revoke retained steady consent a second time on the queued worker.
if restart_output { if !migrate{super::controller::release_immediate(self);}
self.audio.request(AudioCommand::StopOutput).await?; let intent_revision=self.transmission.lock().map_err(|_|super::context::changed())?.revision;
self.audio_output_active.store(self.audio.output_active(),Ordering::Release); phase=Phase::StopInput;
if current()&&self.output_granted.load(Ordering::Acquire)&&crate::platform::android::voice_audio_allowed(key,false) { self.audio.request(AudioCommand::StopInput).await?;
self.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?; self.audio_input_active.store(self.audio.input_active(),Ordering::Release);
if !current()||!crate::platform::android::voice_audio_allowed(key,false){self.audio.request(AudioCommand::StopOutput).await?;return Ok(())} if let Err(changed)=current(){reason=changed;return Ok(())}
let prefs=self.profile()?.prefs.get();
phase=Phase::SelectInput;
self.audio.request(AudioCommand::SelectInput(crate::platform::android::voice_device_selection(prefs["inputDeviceId"].as_str().unwrap_or_default())?)).await?;
if let Err(changed)=current(){reason=changed;return Ok(())}
phase=Phase::SelectOutput;
self.audio.request(AudioCommand::SelectOutput(crate::platform::android::voice_device_selection(prefs["outputDeviceId"].as_str().unwrap_or_default())?)).await?;
if let Err(changed)=current(){reason=changed;return Ok(())}
if restart_output {
phase=Phase::StopOutput;
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) {
phase=Phase::StartOutput;
self.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await?;
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;}
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 current(){crate::platform::android::acknowledge_voice_output(key,token,revision,self.audio.output_active());} if let Err(changed)=current(){reason=changed;return Ok(())}
} // Permission/mute/owner changes that arrived while hardware was replaced
if !current(){return Ok(())} // supersede this migration. Never infer consent from an old route event.
// Permission/mute/owner changes that arrived while hardware was replaced phase=Phase::CaptureIntent;
// supersede this migration. Never infer consent from an old route event. 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{return Ok(())} if migrate&&self.microphone_granted.load(Ordering::Acquire){
if migrate&&self.microphone_granted.load(Ordering::Acquire){ phase=Phase::ResumeCapture;
self.resume_mobile_route_capture_locked(key,intent_revision,&configuration).await?; 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()) {
self.request(key,teamspeach_core::protocol::Command::SetAudio{input_muted:Some(true),output_muted:None}).await?; phase=Phase::MuteCapture;
} self.request(key,teamspeach_core::protocol::Command::SetAudio{input_muted:Some(true),output_muted:None}).await?;
if current(){self.audio.request(AudioCommand::Enumerate).await?;} }
Ok(()) 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;
Ok(())
}.await;
if result.is_err(){reason=Reason::Failed;}
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<()> { pub async fn end_mobile_call(&self,key:&SessionKey)->Result<()> {
let mut call=self.mobile_call.lock().await; let mut call=self.mobile_call.lock().await;
@@ -23,6 +23,8 @@ pub(crate) async fn activate_microphone(ctx:Arc<RuntimeServices>,key:&crate::app
sync_audio_to(&ctx,Some((true,true)),Some(key),configuration).await sync_audio_to(&ctx,Some((true,true)),Some(key),configuration).await
} }
async fn sync_audio_to(ctx:&Arc<RuntimeServices>,resume:Option<(bool,bool)>,expected_owner:Option<&crate::app::connections::SessionKey>,_configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> { async fn sync_audio_to(ctx:&Arc<RuntimeServices>,resume:Option<(bool,bool)>,expected_owner:Option<&crate::app::connections::SessionKey>,_configuration:&tokio::sync::MutexGuard<'_,()>)->Result<()> {
#[cfg(target_os="android")]
let route_started=std::time::Instant::now();
let mut stage="validate_activation"; let mut stage="validate_activation";
let mut stage_key=expected_owner.cloned(); let mut stage_key=expected_owner.cloned();
let result:Result<()>=async { let result:Result<()>=async {
@@ -95,6 +97,12 @@ async fn sync_audio_to(ctx:&Arc<RuntimeServices>,resume:Option<(bool,bool)>,expe
} }
Ok(()) Ok(())
}.await; }.await;
#[cfg(target_os="android")]
if let Some(key)=stage_key.as_ref(){
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};
log_voice_route(key,phase,if result.is_ok(){Reason::Completed}else{Reason::Failed},route_started.elapsed(),false,ctx.audio.output_active(),ctx.audio.input_active());
}
if let Some(key)=stage_key.as_ref(){super::super::context_helpers::capture_stage(result,stage,key)}else{result} if let Some(key)=stage_key.as_ref(){super::super::context_helpers::capture_stage(result,stage,key)}else{result}
} }
pub(crate) async fn sync_notifications(ctx:&RuntimeServices)->Result<()> { pub(crate) async fn sync_notifications(ctx:&RuntimeServices)->Result<()> {
+93 -3
View File
@@ -351,6 +351,9 @@ pub struct StreamState {
callbacks: AtomicU64, callbacks: AtomicU64,
frames: AtomicU64, frames: AtomicU64,
xruns: AtomicU64, xruns: AtomicU64,
submitted_frames: AtomicU64,
discarded_route_blocks: AtomicU64,
discarded_time_blocks: AtomicU64,
} }
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub struct StreamStats { pub struct StreamStats {
@@ -364,10 +367,17 @@ pub struct StreamStats {
pub frames: u64, pub frames: u64,
/// Number of CPAL Xrun error notifications, not a backend-specific cumulative count. /// Number of CPAL Xrun error notifications, not a backend-specific cumulative count.
pub xruns: u64, pub xruns: u64,
/// Device-rate frames successfully enqueued by the worker, including mixed silence.
pub submitted_frames: u64,
/// Unconsumed blocks discarded by callback generation/format/enable gates.
pub discarded_route_blocks: u64,
/// Unconsumed blocks discarded by queue age or hardware presentation deadlines.
pub discarded_time_blocks: u64,
} }
impl StreamState { impl StreamState {
pub(super) fn new(epoch: u64, origin: Instant) -> Self { pub(super) fn new(epoch: u64, origin: Instant) -> Self {
Self { origin, epoch: AtomicU64::new(epoch), boundary_ns: AtomicU64::new(0), enabled: AtomicBool::new(false), fault: AtomicU8::new(0), dropped_blocks: AtomicU64::new(0), underrun_frames: AtomicU64::new(0), realtime_denied: AtomicBool::new(false), callbacks: AtomicU64::new(0), frames: AtomicU64::new(0), xruns: AtomicU64::new(0) } Self { origin, epoch: AtomicU64::new(epoch), boundary_ns: AtomicU64::new(0), enabled: AtomicBool::new(false), fault: AtomicU8::new(0), dropped_blocks: AtomicU64::new(0), underrun_frames: AtomicU64::new(0), realtime_denied: AtomicBool::new(false), callbacks: AtomicU64::new(0), frames: AtomicU64::new(0), xruns: AtomicU64::new(0),
submitted_frames: AtomicU64::new(0), discarded_route_blocks: AtomicU64::new(0), discarded_time_blocks: AtomicU64::new(0) }
} }
pub fn epoch(&self) -> u64 { self.epoch.load(Ordering::Acquire) } pub fn epoch(&self) -> u64 { self.epoch.load(Ordering::Acquire) }
/// Call before an acknowledged capture-boundary cutover. Samples physically /// Call before an acknowledged capture-boundary cutover. Samples physically
@@ -395,8 +405,12 @@ impl StreamState {
} }
} }
pub fn stats(&self) -> StreamStats { pub fn stats(&self) -> StreamStats {
StreamStats { epoch: self.epoch(), enabled: self.enabled.load(Ordering::Acquire), fault: self.fault(), dropped_blocks: self.dropped_blocks.load(Ordering::Relaxed), underrun_frames: self.underrun_frames.load(Ordering::Relaxed), realtime_denied: self.realtime_denied.load(Ordering::Relaxed), callbacks: self.callbacks.load(Ordering::Relaxed), frames: self.frames.load(Ordering::Relaxed), xruns: self.xruns.load(Ordering::Relaxed) } StreamStats { epoch: self.epoch(), enabled: self.enabled.load(Ordering::Acquire), fault: self.fault(), dropped_blocks: self.dropped_blocks.load(Ordering::Relaxed), underrun_frames: self.underrun_frames.load(Ordering::Relaxed), realtime_denied: self.realtime_denied.load(Ordering::Relaxed), callbacks: self.callbacks.load(Ordering::Relaxed), frames: self.frames.load(Ordering::Relaxed), xruns: self.xruns.load(Ordering::Relaxed),
submitted_frames: self.submitted_frames.load(Ordering::Relaxed), discarded_route_blocks: self.discarded_route_blocks.load(Ordering::Relaxed), discarded_time_blocks: self.discarded_time_blocks.load(Ordering::Relaxed) }
} }
pub(super) fn record_submission(&self, frames: usize) { self.submitted_frames.fetch_add(frames as u64, Ordering::Relaxed); }
#[cfg(target_os = "android")]
pub(super) fn enabled(&self) -> bool { self.enabled.load(Ordering::Acquire) }
fn active(&self, epoch: u64) -> bool { fn active(&self, epoch: u64) -> bool {
self.enabled.load(Ordering::Acquire) && self.epoch() == epoch && self.fault.load(Ordering::Acquire) == 0 self.enabled.load(Ordering::Acquire) && self.epoch() == epoch && self.fault.load(Ordering::Acquire) == 0
} }
@@ -586,7 +600,12 @@ struct PlaybackCallback {
} }
impl PlaybackCallback { impl PlaybackCallback {
fn next_frame(&mut self, epoch: u64, now: Instant, playback_at: Instant, output_offset: usize, deadline_checked: &mut bool, scan_budget: &mut usize) -> Option<[f32; 2]> { fn next_frame(&mut self, epoch: u64, now: Instant, playback_at: Instant, output_offset: usize, deadline_checked: &mut bool, scan_budget: &mut usize) -> Option<[f32; 2]> {
if !self.state.active(epoch) { self.current = None; return None; } if !self.state.active(epoch) {
if self.current.as_ref().is_some_and(|block| self.current_offset < block.frames) {
self.state.discarded_route_blocks.fetch_add(1, Ordering::Relaxed);
}
self.current = None; return None;
}
loop { loop {
if let Some(block) = self.current.as_ref() { if let Some(block) = self.current.as_ref() {
if block.epoch == epoch && block.sample_rate == self.format.sample_rate && block.frames <= BLOCK_FRAMES if block.epoch == epoch && block.sample_rate == self.format.sample_rate && block.frames <= BLOCK_FRAMES
@@ -601,6 +620,7 @@ impl PlaybackCallback {
let timely = playback_at.checked_add(frames_duration(last_offset as u64, self.format.sample_rate)) let timely = playback_at.checked_add(frames_duration(last_offset as u64, self.format.sample_rate))
.is_some_and(|last_at| last_at < block.expires_at); .is_some_and(|last_at| last_at < block.expires_at);
if !timely { if !timely {
self.state.discarded_time_blocks.fetch_add(1, Ordering::Relaxed);
self.current = None; self.current = None;
continue; continue;
} }
@@ -610,6 +630,13 @@ impl PlaybackCallback {
self.current_offset += 1; self.current_offset += 1;
return Some(sample); return Some(sample);
} }
if self.current_offset < block.frames {
if block.epoch != epoch || block.sample_rate != self.format.sample_rate || block.frames > BLOCK_FRAMES {
self.state.discarded_route_blocks.fetch_add(1, Ordering::Relaxed);
} else {
self.state.discarded_time_blocks.fetch_add(1, Ordering::Relaxed);
}
}
self.current = None; self.current = None;
} }
if *scan_budget == 0 { return None; } if *scan_budget == 0 { return None; }
@@ -745,3 +772,66 @@ pub fn start_playback(selected: SelectedDevice, permission: StartPermission, epo
#[cfg(test)] #[cfg(test)]
#[path = "devices_tests.rs"] #[path = "devices_tests.rs"]
mod tests; mod tests;
#[cfg(test)]
mod playback_diagnostics_tests {
use super::*;
fn fixture(now: Instant) -> (PlaybackCallback, Producer<PlaybackBlock>) {
let format = DeviceFormat { sample_rate: 48_000, channels: 2, sample_format: SampleFormat::F32, buffer_size: BufferSize::Default };
let state = Arc::new(StreamState::new(7, now));
assert!(state.resume());
let (producer, consumer) = ring::channel(8);
let (references, _rendered) = ring::channel(8);
(PlaybackCallback { consumer, references, state, clock: Arc::new(ClockAnchor::new(now)),
format, current: None, current_offset: 0, frame_position: 0, expected_at: None }, producer)
}
fn block(now: Instant) -> PlaybackBlock {
let mut block = PlaybackBlock::silence(48_000, 7, now);
block.frames = 1;
block.samples[0] = [0.25; 2];
block
}
#[test]
fn expired_and_old_epoch_blocks_are_counted_once_without_changing_scan_behavior() {
let now = Instant::now();
let (mut callback, mut producer) = fixture(now);
let mut old = block(now);
old.epoch = 6;
producer.try_push(old).unwrap();
let mut expired = block(now);
expired.expires_at = now;
producer.try_push(expired).unwrap();
producer.try_push(block(now)).unwrap();
let mut budget = 8;
let mut checked = false;
assert_eq!(callback.next_frame(7, now, now, 0, &mut checked, &mut budget), Some([0.25; 2]));
assert_eq!(callback.next_frame(7, now, now, 1, &mut checked, &mut budget), None);
let stats = callback.state.stats();
assert_eq!((stats.discarded_route_blocks, stats.discarded_time_blocks), (1, 1));
assert_eq!(stats.fault, StreamFault::None);
}
#[test]
fn hardware_deadline_and_suspended_partial_block_have_distinct_discard_counters() {
let now = Instant::now();
let (mut callback, mut producer) = fixture(now);
let mut late = block(now);
late.expires_at = now + Duration::from_millis(1);
producer.try_push(late).unwrap();
let mut budget = 8;
let mut checked = false;
assert_eq!(callback.next_frame(7, now, now + Duration::from_millis(1), 0, &mut checked, &mut budget), None);
let mut partial = block(now);
partial.frames = 2;
callback.current = Some(partial);
callback.current_offset = 1;
callback.state.suspend();
assert_eq!(callback.next_frame(7, now, now, 0, &mut checked, &mut budget), None);
assert_eq!(callback.next_frame(7, now, now, 0, &mut checked, &mut budget), None);
let stats = callback.state.stats();
assert_eq!((stats.discarded_route_blocks, stats.discarded_time_blocks), (1, 1));
}
}
+99
View File
@@ -0,0 +1,99 @@
//! Sanitized counters and fixed-capacity log gates; never retain media or route identities.
#![cfg_attr(not(any(target_os = "android", test)), allow(dead_code))]
use std::time::{Duration, Instant};
#[cfg(any(target_os = "android", test))]
use std::sync::atomic::{AtomicU64, Ordering};
pub(super) const REPORT_INTERVAL: Duration = Duration::from_secs(5);
#[derive(Default)]
pub(super) struct Counter {
#[cfg(any(target_os = "android", test))]
value: AtomicU64,
}
impl Counter {
pub fn increment(&self) {
#[cfg(any(target_os = "android", test))]
self.value.fetch_add(1, Ordering::Relaxed);
}
pub fn load(&self) -> u64 {
#[cfg(any(target_os = "android", test))]
{ self.value.load(Ordering::Relaxed) }
#[cfg(not(any(target_os = "android", test)))]
{ 0 }
}
pub fn record_max(&self, value: u64) {
#[cfg(any(target_os = "android", test))]
self.value.fetch_max(value, Ordering::Relaxed);
#[cfg(not(any(target_os = "android", test)))]
let _ = value;
}
}
macro_rules! counters {
($($name:ident),+ $(,)?) => {
#[derive(Default)]
pub(super) struct Counters { $(pub $name: Counter),+ }
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Totals { $(pub $name: u64),+ }
impl Counters {
pub fn totals(&self) -> Totals { Totals { $($name: self.$name.load()),+ } }
}
};
}
counters!(binding_received, binding_route_drop, rx_offered, rx_enqueued, rx_queue_drop,
rx_accepted, rx_route_drop, rx_time_drop, rx_mixer_drop,
tx_accepted, tx_frame_drop, tx_permit_revoked, command_logs_suppressed,
voice_nonzero_blocks, voice_peak_bucket_max);
impl Counters {
/// Coarse aggregate only; no sample, exact magnitude, timing or media is retained.
pub fn observe_voice(&self, pcm: &[[f32; 2]]) {
#[cfg(any(target_os = "android", test))]
{
let peak = pcm.iter().flatten().fold(0_f32, |peak, sample| peak.max(sample.abs()));
let bucket = if peak == 0. { 0 } else if peak < 0.001 { 1 }
else if peak < 0.01 { 2 } else if peak < 0.1 { 3 } else { 4 };
if bucket != 0 { self.voice_nonzero_blocks.increment(); }
self.voice_peak_bucket_max.record_max(bucket);
}
#[cfg(not(any(target_os = "android", test)))]
let _ = pcm;
}
}
/// Activation starts a new window; idle time never causes an immediate report.
#[allow(dead_code)]
#[derive(Default)]
pub(super) struct SummaryGate { since: Option<Instant> }
#[allow(dead_code)]
impl SummaryGate {
pub fn due(&mut self, now: Instant, active: bool) -> bool {
if !active { self.since = None; return false; }
let Some(since) = self.since else { self.since = Some(now); return false; };
if now.saturating_duration_since(since) < REPORT_INTERVAL { return false; }
self.since = Some(now);
true
}
}
/// One begin/end pair per command kind per window, including per-frame commands.
/// Fixed labels only, and fixed storage: no strings from commands are retained.
#[allow(dead_code)]
#[derive(Default)]
pub(super) struct CommandGate { last: [Option<Instant>; 26] }
#[allow(dead_code)]
impl CommandGate {
pub fn admit(&mut self, name: &'static str, now: Instant) -> bool {
const NAMES: [&str; 26] = ["enumerate", "pin_host", "select_input", "select_output",
"start_input", "start_output", "stop_input", "stop_output", "bind_permit",
"activate_connection", "connection_enabled", "remove_connection", "stream_gain",
"remove_stream", "playback_dsp", "voice_gain", "transmitting", "typing_enabled",
"typing_hit", "whisper", "configure_notifications", "notify", "begin_microphone_test",
"listen_microphone_test", "stop_microphone_test", "finish_microphone_test"];
let Some(index) = NAMES.iter().position(|candidate| *candidate == name) else { return false; };
if self.last[index].is_some_and(|last| now.saturating_duration_since(last) < REPORT_INTERVAL) { return false; }
self.last[index] = Some(now);
true
}
}
+106 -23
View File
@@ -24,6 +24,8 @@ const TEST_SAMPLES: usize = 480_000;
#[path = "lifecycle.rs"] #[path = "lifecycle.rs"]
mod lifecycle; mod lifecycle;
use lifecycle::{DeviceLease, DeviceOwner, Lifecycle}; use lifecycle::{DeviceLease, DeviceOwner, Lifecycle};
#[path = "diagnostics.rs"]
mod diagnostics;
pub enum AudioCommand { pub enum AudioCommand {
Enumerate, Enumerate,
@@ -205,6 +207,7 @@ struct Shared {
transmission_enabled: AtomicBool, transmission_enabled: AtomicBool,
notification_revision: AtomicU64, notification_revision: AtomicU64,
first_fault: FirstFault, first_fault: FirstFault,
diagnostics: diagnostics::Counters,
} }
impl Shared { impl Shared {
fn new(manager: Arc<ConnectionManager>) -> Self { fn new(manager: Arc<ConnectionManager>) -> Self {
@@ -213,7 +216,8 @@ impl Shared {
playback_state: Mutex::new((false, Instant::now())), input_level: AtomicU32::new(0f32.to_bits()), playback_state: Mutex::new((false, Instant::now())), input_level: AtomicU32::new(0f32.to_bits()),
playback_authorized: AtomicBool::new(false), test_reservation: AtomicU64::new(0), playback_authorized: AtomicBool::new(false), test_reservation: AtomicU64::new(0),
#[cfg(test)] capture_start: Mutex::new(None), #[cfg(test)] capture_start: Mutex::new(None),
transmission_enabled: AtomicBool::new(false), notification_revision: AtomicU64::new(0), first_fault: FirstFault::default() } transmission_enabled: AtomicBool::new(false), notification_revision: AtomicU64::new(0), first_fault: FirstFault::default(),
diagnostics: diagnostics::Counters::default() }
} }
fn revoke(&self) -> u64 { fn revoke(&self) -> u64 {
self.manager.invalidate_audio(); self.manager.invalidate_audio();
@@ -290,6 +294,10 @@ impl AudioHandle {
pub fn terminal_error(&self) -> Option<ServiceError> { self.shared.terminal_error.lock().expect("audio terminal error").clone() } pub fn terminal_error(&self) -> Option<ServiceError> { self.shared.terminal_error.lock().expect("audio terminal error").clone() }
/// First failure remains available after StopOutput, privacy revocation and teardown. /// First failure remains available after StopOutput, privacy revocation and teardown.
pub fn first_fault(&self) -> Option<AudioFirstFault> { self.shared.first_fault.get() } pub fn first_fault(&self) -> Option<AudioFirstFault> { self.shared.first_fault.get() }
/// Binding ingress only: aggregate decoded-frame delivery without retaining session data.
pub fn record_binding_received(&self) { self.shared.diagnostics.binding_received.increment(); }
/// Binding rejected a missing/disabled/old route before offering PCM to the worker.
pub fn record_binding_route_drop(&self) { self.shared.diagnostics.binding_route_drop.increment(); }
/// Allocate a never-reused source ID in the active connection/privacy epoch. /// Allocate a never-reused source ID in the active connection/privacy epoch.
pub fn open_stream(&self, key: &SessionKey, privacy_epoch: u64) -> Result<u64> { pub fn open_stream(&self, key: &SessionKey, privacy_epoch: u64) -> Result<u64> {
if self.shared.stop.load(Ordering::Acquire) { return Err(closed()); } if self.shared.stop.load(Ordering::Acquire) { return Err(closed()); }
@@ -365,13 +373,23 @@ impl AudioHandle {
result result
} }
pub fn push_voice(&self, key: SessionKey, privacy_epoch: u64, pcm: [i16; 960], received_at: Instant) -> Result<()> { pub fn push_voice(&self, key: SessionKey, privacy_epoch: u64, pcm: [i16; 960], received_at: Instant) -> Result<()> {
self.playback.try_send(PlaybackMessage::Voice { key, epoch: privacy_epoch, pcm, received_at }).map_err(queue_error) self.shared.diagnostics.rx_offered.increment();
let result = self.playback.try_send(PlaybackMessage::Voice { key, epoch: privacy_epoch, pcm, received_at }).map_err(queue_error);
if result.is_ok() { self.shared.diagnostics.rx_enqueued.increment(); }
else { self.shared.diagnostics.rx_queue_drop.increment(); }
result
} }
pub fn push_stream(&self, key: SessionKey, privacy_epoch: u64, stream_id: u64, pcm: StereoBlock, received_at: Instant) -> Result<()> { pub fn push_stream(&self, key: SessionKey, privacy_epoch: u64, stream_id: u64, pcm: StereoBlock, received_at: Instant) -> Result<()> {
if self.shared.stop.load(Ordering::Acquire) { return Err(closed()); } self.shared.diagnostics.rx_offered.increment();
if !self.shared.streams.accepts(&key, privacy_epoch, stream_id) { return Err(changed()); } if self.shared.stop.load(Ordering::Acquire) { self.shared.diagnostics.rx_route_drop.increment(); return Err(closed()); }
if self.playback_route(&key).is_none_or(|route| !route.accepts_frame(privacy_epoch, received_at, Instant::now())) { return Err(changed()); } if !self.shared.streams.accepts(&key, privacy_epoch, stream_id) { self.shared.diagnostics.rx_route_drop.increment(); return Err(changed()); }
self.playback.try_send(PlaybackMessage::Stream { key, epoch: privacy_epoch, id: stream_id, pcm, received_at }).map_err(queue_error) if let Some(counter) = playback_rejection(&self.shared.diagnostics, self.playback_route(&key), privacy_epoch, received_at, Instant::now()) {
counter.increment(); return Err(changed());
}
let result = self.playback.try_send(PlaybackMessage::Stream { key, epoch: privacy_epoch, id: stream_id, pcm, received_at }).map_err(queue_error);
if result.is_ok() { self.shared.diagnostics.rx_enqueued.increment(); }
else { self.shared.diagnostics.rx_queue_drop.increment(); }
result
} }
} }
@@ -564,6 +582,7 @@ impl Output {
self.pending.frames += 1; self.pending.frames += 1;
if self.pending.frames == devices::BLOCK_FRAMES { if self.pending.frames == devices::BLOCK_FRAMES {
self.port.samples.try_push(self.pending).map_err(|_| ServiceError::new("audio_playback_overflow", "Output clock queue filled; stale playback was stopped"))?; self.port.samples.try_push(self.pending).map_err(|_| ServiceError::new("audio_playback_overflow", "Output clock queue filled; stale playback was stopped"))?;
self.port.state.record_submission(self.pending.frames);
self.pending.frames = 0; self.pending.frames = 0;
} }
} }
@@ -682,7 +701,9 @@ struct Worker {
pending_events: VecDeque<AudioEvent>, pending_events: VecDeque<AudioEvent>,
current_command: &'static str, current_command: &'static str,
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
ingress_reported: u8, summary_gate: diagnostics::SummaryGate,
#[cfg(target_os = "android")]
command_gate: diagnostics::CommandGate,
#[cfg(test)] #[cfg(test)]
output_reset: Option<Box<dyn FnOnce(&Arc<Shared>) + Send>>, output_reset: Option<Box<dyn FnOnce(&Arc<Shared>) + Send>>,
} }
@@ -697,7 +718,8 @@ impl Worker {
notification_device: NotificationDevice::Voice, notification_level: -23., notification_sink: None, revision: 0, output_epoch: 0, notification_device: NotificationDevice::Voice, notification_level: -23., notification_sink: None, revision: 0, output_epoch: 0,
references: ReferenceTimeline::new(Instant::now()), test: None, test_revision: 0, references: ReferenceTimeline::new(Instant::now()), test: None, test_revision: 0,
pending_events: VecDeque::with_capacity(EVENT_CAPACITY), current_command: "none", pending_events: VecDeque::with_capacity(EVENT_CAPACITY), current_command: "none",
#[cfg(target_os = "android")] ingress_reported: 0, #[cfg(target_os = "android")] summary_gate: diagnostics::SummaryGate::default(),
#[cfg(target_os = "android")] command_gate: diagnostics::CommandGate::default(),
#[cfg(test)] output_reset: None }) #[cfg(test)] output_reset: None })
} }
fn emit(&mut self, event: AudioEvent) { fn emit(&mut self, event: AudioEvent) {
@@ -818,6 +840,8 @@ impl Worker {
self.next_mix += TICK; self.next_mix += TICK;
} }
if self.notifications.idle_close_due(now).is_some() { self.retire_notifications(); } if self.notifications.idle_close_due(now).is_some() { self.retire_notifications(); }
#[cfg(target_os = "android")]
self.report_diagnostics(now);
} }
fn capture_failed(&mut self, error: ServiceError) { fn capture_failed(&mut self, error: ServiceError) {
self.record_fault("capture", Some(Direction::Input), &error, None); self.record_fault("capture", Some(Direction::Input), &error, None);
@@ -833,10 +857,41 @@ impl Worker {
} }
} }
fn devices_active(&self) -> bool { self.input.is_some() || !self.outputs.is_empty() } fn devices_active(&self) -> bool { self.input.is_some() || !self.outputs.is_empty() }
#[cfg(target_os = "android")]
fn report_diagnostics(&mut self, now: Instant) {
let active = self.input.as_ref().is_some_and(|input| input.port.state.enabled())
|| self.outputs.iter().any(|output| output.port.state.enabled());
if !self.summary_gate.due(now, active) { return; }
let totals = self.shared.diagnostics.totals();
eprintln!("audio_summary totals={totals:?} capture_revision={} output_revision={} worker_output_revision={} stream_revision={} notification_revision={} transmitting={} output_authorized={} mixer_streams={} mixer_rejected={}",
self.shared.revision.load(Ordering::Acquire), self.shared.outputs.revision(), self.output_revision,
self.shared.outputs.stream_revision.load(Ordering::Acquire), self.notifications.revision(),
self.shared.transmission_enabled.load(Ordering::Acquire), self.shared.playback_authorized.load(Ordering::Acquire),
self.mixer.stream_count(), self.mixer.rejected());
if let Some(input) = &self.input {
eprintln!("audio_stream direction=Input selection={} format={:?} stats={:?}", selection_kind(&self.input_selection), input._owner.format, input.port.state.stats());
}
for output in &self.outputs {
eprintln!("audio_stream direction=Output selection={} voice={} notification={} format={:?} stats={:?}",
if output.voice { selection_kind(&self.output_selection) } else {
match self.notification_sink.as_ref() { Some(OutputSink::SystemDefault) => "system_default", Some(OutputSink::Explicit(_)) => "exact", None => "none" }
},
output.voice, output.notification, output.owner.format, output.port.state.stats());
}
}
/// Physical generation fencing must never discard an authoritative connection epoch. /// Physical generation fencing must never discard an authoritative connection epoch.
fn consume(&mut self, envelope: Envelope) { fn consume(&mut self, envelope: Envelope) {
self.check_revision(); self.check_revision();
self.current_command = command_name(&envelope.command); self.current_command = command_name(&envelope.command);
#[cfg(target_os = "android")]
let diagnostic_start = Instant::now();
#[cfg(target_os = "android")]
let diagnostic_log = self.command_gate.admit(self.current_command, diagnostic_start);
#[cfg(target_os = "android")]
if diagnostic_log {
eprintln!("audio_command phase=begin command={} capture_revision={} output_revision={} test_revision={} selection={}",
self.current_command, envelope.revision, envelope.output_revision, envelope.test_revision, command_selection_kind(&envelope.command));
} else { self.shared.diagnostics.command_logs_suppressed.increment(); }
let begin = matches!(&envelope.command, AudioCommand::BeginMicrophoneTest { .. }); let begin = matches!(&envelope.command, AudioCommand::BeginMicrophoneTest { .. });
let finish = matches!(&envelope.command, AudioCommand::FinishMicrophoneTest); let finish = matches!(&envelope.command, AudioCommand::FinishMicrophoneTest);
let stop_test = matches!(&envelope.command, AudioCommand::StopMicrophoneTest); let stop_test = matches!(&envelope.command, AudioCommand::StopMicrophoneTest);
@@ -871,6 +926,13 @@ impl Worker {
if let Err(error) = &result { if let Err(error) = &result {
if error.code != "target_changed" { self.record_fault("command", None, error, None); } if error.code != "target_changed" { self.record_fault("command", None, error, None); }
} }
#[cfg(target_os = "android")]
if diagnostic_log {
let code = result.as_ref().err().map_or("ok", |error| fault_code(&error.code));
eprintln!("audio_command phase=end command={} code={} duration_ms={} capture_revision={} output_revision={} worker_output_revision={} notification_revision={}",
self.current_command, code, diagnostic_start.elapsed().as_millis(), self.shared.revision.load(Ordering::Acquire),
self.shared.outputs.revision(), self.output_revision, self.notifications.revision());
}
// Acknowledged callers add their workflow stage; a raw duplicate would race // Acknowledged callers add their workflow stage; a raw duplicate would race
// and overwrite that annotation. Unacknowledged faults still emit normally. // and overwrite that annotation. Unacknowledged faults still emit normally.
if let Some(reply) = envelope.reply { let _ = reply.send(result); } if let Some(reply) = envelope.reply { let _ = reply.send(result); }
@@ -1285,17 +1347,25 @@ impl Worker {
let now = Instant::now(); let now = Instant::now();
let accepted = match message { let accepted = match message {
PlaybackMessage::Voice { key, epoch, pcm, received_at } => { PlaybackMessage::Voice { key, epoch, pcm, received_at } => {
if self.shared.playback_route(&key).is_none_or(|route| !route.accepts_frame(epoch, received_at, now)) { return Err(changed()); } if let Some(counter) = playback_rejection(&self.shared.diagnostics, self.shared.playback_route(&key), epoch, received_at, now) {
let handle = self.mixer.register_voice(&key, epoch)?; counter.increment(); return Err(changed());
}
let handle = self.mixer.register_voice(&key, epoch).inspect_err(|_| self.shared.diagnostics.rx_mixer_drop.increment())?;
self.mixer.push_voice(handle, epoch, &pcm, received_at, now) self.mixer.push_voice(handle, epoch, &pcm, received_at, now)
} }
PlaybackMessage::Stream { key, epoch, id, pcm, received_at } => { PlaybackMessage::Stream { key, epoch, id, pcm, received_at } => {
if self.shared.playback_route(&key).is_none_or(|route| !route.accepts_frame(epoch, received_at, now)) { return Err(changed()); } if let Some(counter) = playback_rejection(&self.shared.diagnostics, self.shared.playback_route(&key), epoch, received_at, now) {
let handle = self.mixer.register_stream(&key, epoch, id)?; counter.increment(); return Err(changed());
}
let handle = self.mixer.register_stream(&key, epoch, id).inspect_err(|_| self.shared.diagnostics.rx_mixer_drop.increment())?;
self.mixer.push_stream(handle, epoch, &pcm, received_at, now) self.mixer.push_stream(handle, epoch, &pcm, received_at, now)
} }
}; };
if !accepted { return Err(ServiceError::new("audio_playback_rejected", "Playback PCM was stale, disabled, or belonged to an old route")); } if !accepted {
self.shared.diagnostics.rx_mixer_drop.increment();
return Err(ServiceError::new("audio_playback_rejected", "Playback PCM was stale, disabled, or belonged to an old route"));
}
self.shared.diagnostics.rx_accepted.increment();
Ok(()) Ok(())
} }
fn render_references(&mut self) -> Result<()> { self.render_references_with_clock(Instant::now) } fn render_references(&mut self) -> Result<()> { self.render_references_with_clock(Instant::now) }
@@ -1389,16 +1459,11 @@ impl Worker {
} }
fn forward_capture_frame(&mut self, permit: &CapturePermit, frame: teamspeach_core::audio::CapturedFrame) -> bool { fn forward_capture_frame(&mut self, permit: &CapturePermit, frame: teamspeach_core::audio::CapturedFrame) -> bool {
if !self.shared.transmission_enabled.load(Ordering::Acquire) { return true; } if !self.shared.transmission_enabled.load(Ordering::Acquire) { return true; }
#[cfg(target_os = "android")]
let age_ns = signed_age_ns(Instant::now(), frame.captured_at);
let outcome = self.shared.manager.push_audio(&permit.key, frame); let outcome = self.shared.manager.push_audio(&permit.key, frame);
#[cfg(target_os = "android")] match outcome {
{ CaptureIngress::Accepted => self.shared.diagnostics.tx_accepted.increment(),
let bit = match outcome { CaptureIngress::Accepted => 0, CaptureIngress::FrameRejected => 1, CaptureIngress::PermitRevoked => 2 }; CaptureIngress::FrameRejected => self.shared.diagnostics.tx_frame_drop.increment(),
if bit != 0 && self.ingress_reported & bit == 0 { CaptureIngress::PermitRevoked => self.shared.diagnostics.tx_permit_revoked.increment(),
self.ingress_reported |= bit;
eprintln!("audio_capture_ingress outcome={outcome:?} age_ns={age_ns} capture_epoch={} generation={}", permit.capture_epoch, permit.key.generation);
}
} }
match outcome { match outcome {
CaptureIngress::Accepted | CaptureIngress::FrameRejected => true, CaptureIngress::Accepted | CaptureIngress::FrameRejected => true,
@@ -1427,6 +1492,7 @@ impl Worker {
} }
let mut voice = [[0.; 2]; 480]; let mut voice = [[0.; 2]; 480];
let voice_expiry = self.mixer.mix_with_deadline(now, &mut voice).unwrap_or(now + MAX_AGE); let voice_expiry = self.mixer.mix_with_deadline(now, &mut voice).unwrap_or(now + MAX_AGE);
self.shared.diagnostics.observe_voice(&voice);
let private_preview = self.test.as_ref().is_some_and(|test| test.listen.is_some()); let private_preview = self.test.as_ref().is_some_and(|test| test.listen.is_some());
let mut finished = None; let mut finished = None;
if let Some(test) = &mut self.test { if let Some(test) = &mut self.test {
@@ -1463,6 +1529,22 @@ fn resolved_voice_sink(selection: &DeviceSelection, active_device: Option<&str>)
fn selection_for_sink(sink: &OutputSink) -> DeviceSelection { fn selection_for_sink(sink: &OutputSink) -> DeviceSelection {
match sink { OutputSink::SystemDefault => DeviceSelection::SystemDefault, OutputSink::Explicit(id) => DeviceSelection::Exact(id.clone()) } match sink { OutputSink::SystemDefault => DeviceSelection::SystemDefault, OutputSink::Explicit(id) => DeviceSelection::Exact(id.clone()) }
} }
/// Preserve the production route predicate; classify its rejected stage without PCM inspection.
fn playback_rejection(counters: &diagnostics::Counters, route: Option<super::mixer::PlaybackRoute>, epoch: u64,
received_at: Instant, now: Instant) -> Option<&diagnostics::Counter> {
let Some(route) = route else { return Some(&counters.rx_route_drop); };
if !route.enabled || route.privacy_epoch != epoch { return Some(&counters.rx_route_drop); }
if !route.accepts_frame(epoch, received_at, now) { return Some(&counters.rx_time_drop); }
None
}
#[cfg(target_os = "android")]
fn selection_kind(selection: &DeviceSelection) -> &'static str {
match selection { DeviceSelection::SystemDefault => "system_default", DeviceSelection::Exact(_) => "exact" }
}
#[cfg(target_os = "android")]
fn command_selection_kind(command: &AudioCommand) -> &'static str {
match command { AudioCommand::SelectInput(selection) | AudioCommand::SelectOutput(selection) => selection_kind(selection), _ => "unchanged" }
}
fn command_name(command: &AudioCommand) -> &'static str { fn command_name(command: &AudioCommand) -> &'static str {
match command { match command {
AudioCommand::Enumerate => "enumerate", AudioCommand::PinHost(_) => "pin_host", AudioCommand::Enumerate => "enumerate", AudioCommand::PinHost(_) => "pin_host",
@@ -1495,7 +1577,8 @@ fn fault_code(code: &str) -> &'static str {
"audio_input_timeout" => "audio_input_timeout", "audio_playback_overflow" => "audio_playback_overflow", "audio_input_timeout" => "audio_input_timeout", "audio_playback_overflow" => "audio_playback_overflow",
"audio_resampler" => "audio_resampler", "audio_format" => "audio_format", "capture_dsp" => "capture_dsp", "audio_resampler" => "audio_resampler", "audio_format" => "audio_format", "capture_dsp" => "capture_dsp",
"audio_buffer" => "audio_buffer", "audio_epoch" => "audio_epoch", "audio_event_overflow" => "audio_event_overflow", "audio_buffer" => "audio_buffer", "audio_epoch" => "audio_epoch", "audio_event_overflow" => "audio_event_overflow",
"audio_worker" => "audio_worker", _ => "audio_other", "audio_worker" => "audio_worker", "target_changed" => "target_changed", "audio_busy" => "audio_busy",
"audio_closed" => "audio_closed", "audio_playback_rejected" => "audio_playback_rejected", _ => "audio_other",
} }
} }
fn changed() -> ServiceError { ServiceError::new("target_changed", "Audio permit, connection, or privacy epoch changed") } fn changed() -> ServiceError { ServiceError::new("target_changed", "Audio permit, connection, or privacy epoch changed") }
+127 -1
View File
@@ -630,7 +630,8 @@ fn acknowledged_errors_are_not_reemitted_but_async_errors_remain_visible() {
fn first_fault_retains_counters_across_cleanup_and_cannot_be_overwritten() { fn first_fault_retains_counters_across_cleanup_and_cannot_be_overwritten() {
let (mut worker, handle, _commands, _events) = command_fixture(); let (mut worker, handle, _commands, _events) = command_fixture();
let stats = StreamStats { epoch: 7, enabled: false, fault: devices::StreamFault::ClockDiscontinuity, let stats = StreamStats { epoch: 7, enabled: false, fault: devices::StreamFault::ClockDiscontinuity,
dropped_blocks: 2, underrun_frames: 96, realtime_denied: false, callbacks: 4, frames: 192, xruns: 1 }; dropped_blocks: 2, underrun_frames: 96, realtime_denied: false, callbacks: 4, frames: 192, xruns: 1,
submitted_frames: 256, discarded_route_blocks: 3, discarded_time_blocks: 4 };
worker.current_command = "start_output"; worker.current_command = "start_output";
worker.record_fault("output_publish", Some(Direction::Output), &ServiceError::new("audio_clock_discontinuity", "must never be retained"), Some(stats)); worker.record_fault("output_publish", Some(Direction::Output), &ServiceError::new("audio_clock_discontinuity", "must never be retained"), Some(stats));
worker.fail_devices("schedule", ServiceError::new("audio_worker_stall", "later failure")); worker.fail_devices("schedule", ServiceError::new("audio_worker_stall", "later failure"));
@@ -642,6 +643,7 @@ fn first_fault_retains_counters_across_cleanup_and_cannot_be_overwritten() {
assert_eq!(first.direction, Some(Direction::Output)); assert_eq!(first.direction, Some(Direction::Output));
let output = first.outputs[0].unwrap(); let output = first.outputs[0].unwrap();
assert_eq!((output.epoch, output.callbacks, output.frames, output.xruns, output.dropped_blocks, output.underrun_frames), (7, 4, 192, 1, 2, 96)); assert_eq!((output.epoch, output.callbacks, output.frames, output.xruns, output.dropped_blocks, output.underrun_frames), (7, 4, 192, 1, 2, 96));
assert_eq!((output.submitted_frames, output.discarded_route_blocks, output.discarded_time_blocks), (256, 3, 4));
assert!(worker.outputs.is_empty()); assert!(worker.outputs.is_empty());
assert_eq!(fault_code("server-or-device-identifier"), "audio_other"); assert_eq!(fault_code("server-or-device-identifier"), "audio_other");
} }
@@ -1195,6 +1197,130 @@ async fn capture_ingress_frame_drop_and_old_permit_cannot_revoke_new_authorizati
worker.command(AudioCommand::BindPermit { permit:replacement.clone(),settings }).unwrap(); worker.command(AudioCommand::BindPermit { permit:replacement.clone(),settings }).unwrap();
shared.transmission_enabled.store(true,Ordering::Release); shared.transmission_enabled.store(true,Ordering::Release);
assert!(worker.forward_capture_frame(&replacement,frame(&replacement,Instant::now()))); assert!(worker.forward_capture_frame(&replacement,frame(&replacement,Instant::now())));
let totals = shared.diagnostics.totals();
assert_eq!((totals.tx_accepted, totals.tx_frame_drop, totals.tx_permit_revoked), (1, 2, 1));
assert_eq!(manager.current_capture_permit(),Some(replacement)); assert_eq!(manager.current_capture_permit(),Some(replacement));
manager.shutdown().await.unwrap(); manager.shutdown().await.unwrap();
} }
#[test]
fn diagnostic_summary_requires_active_five_second_windows_and_resets_on_idle() {
let origin = Instant::now();
let interval = diagnostics::REPORT_INTERVAL;
let mut gate = diagnostics::SummaryGate::default();
assert!(!gate.due(origin, false));
assert!(!gate.due(origin + interval, true));
assert!(!gate.due(origin + interval * 2 - Duration::from_nanos(1), true));
assert!(gate.due(origin + interval * 2, true));
assert!(!gate.due(origin + interval * 2, true));
assert!(gate.due(origin + interval * 8, true), "a long gap emits only one summary");
assert!(!gate.due(origin + interval * 8, true));
assert!(!gate.due(origin + interval * 9, false));
assert!(!gate.due(origin + interval * 20, true), "idle time is not active time");
assert!(gate.due(origin + interval * 21, true));
}
#[test]
fn diagnostic_command_gate_bounds_frame_flood_without_hiding_other_command_kinds() {
let now = Instant::now();
let mut gate = diagnostics::CommandGate::default();
assert!(gate.admit("transmitting", now));
for _ in 0..10_000 { assert!(!gate.admit("transmitting", now)); }
assert!(gate.admit("select_output", now));
assert!(gate.admit("start_output", now));
assert!(!gate.admit("select_output", now));
assert!(!gate.admit("transmitting", now + diagnostics::REPORT_INTERVAL - Duration::from_nanos(1)));
assert!(gate.admit("transmitting", now + diagnostics::REPORT_INTERVAL));
assert!(!gate.admit("arbitrary-session-or-device-value", now));
}
#[test]
fn diagnostic_binding_and_queue_counters_survive_privacy_and_output_revocation() {
let (_worker, mut handle, _commands, _events) = command_fixture();
let (playback, receive) = mpsc::sync_channel(1);
handle.playback = playback;
let key = SessionKey { connection_id: "diagnostic-fixture".into(), session: 1, generation: 1 };
handle.record_binding_received();
handle.record_binding_received();
handle.record_binding_route_drop();
handle.push_voice(key.clone(), 1, [0; 960], Instant::now()).unwrap();
assert_eq!(handle.push_voice(key.clone(), 1, [0; 960], Instant::now()).unwrap_err().code, "audio_busy");
handle.revoke_local_capture();
handle.shared.silence_outputs();
let totals = handle.shared.diagnostics.totals();
assert_eq!((totals.binding_received, totals.binding_route_drop), (2, 1));
assert_eq!((totals.rx_offered, totals.rx_enqueued, totals.rx_queue_drop), (2, 1, 1));
drop(receive);
assert_eq!(handle.push_voice(key, 1, [0; 960], Instant::now()).unwrap_err().code, "audio_closed");
assert_eq!(handle.shared.diagnostics.totals().rx_queue_drop, 2);
}
#[test]
fn diagnostic_route_classification_matches_the_production_acceptance_predicate() {
use super::super::mixer::PlaybackRoute;
let now = Instant::now();
let route = PlaybackRoute { privacy_epoch: 7, enabled: true, boundary: now - Duration::from_secs(1) };
let counters = diagnostics::Counters::default();
for (candidate, epoch, at, expected_route_drop) in [
(None, 7, now, true),
(Some(PlaybackRoute { enabled: false, ..route }), 7, now, true),
(Some(route), 8, now, true),
(Some(PlaybackRoute { boundary: now, ..route }), 7, now - Duration::from_nanos(1), false),
(Some(route), 7, now + Duration::from_nanos(1), false),
(Some(route), 7, now - MAX_AGE - Duration::from_nanos(1), false),
] {
assert!(candidate.is_none_or(|route| !route.accepts_frame(epoch, at, now)));
let counter = playback_rejection(&counters, candidate, epoch, at, now).unwrap();
assert_eq!(std::ptr::eq(counter, &counters.rx_route_drop), expected_route_drop);
counter.increment();
}
for at in [now, now - MAX_AGE] {
assert!(route.accepts_frame(7, at, now));
assert!(playback_rejection(&counters, Some(route), 7, at, now).is_none());
}
let totals = counters.totals();
assert_eq!((totals.rx_route_drop, totals.rx_time_drop), (3, 3));
}
#[test]
fn diagnostic_worker_distinguishes_accepted_voice_from_disabled_mixer_rejection() {
let (mut worker, handle, _commands, _events) = command_fixture();
let key = SessionKey { connection_id: "diagnostic-fixture".into(), session: 1, generation: 1 };
worker.command(AudioCommand::ActivateConnection { key: key.clone(), privacy_epoch: 7 }).unwrap();
*handle.shared.playback_state.lock().unwrap() = (true, Instant::now());
worker.mixer.set_enabled(true);
worker.playback(PlaybackMessage::Voice { key: key.clone(), epoch: 7, pcm: [0; 960], received_at: Instant::now() }).unwrap();
worker.mixer.set_enabled(false);
assert_eq!(worker.playback(PlaybackMessage::Voice { key, epoch: 7, pcm: [0; 960], received_at: Instant::now() }).unwrap_err().code, "audio_playback_rejected");
let totals = handle.shared.diagnostics.totals();
assert_eq!((totals.rx_accepted, totals.rx_mixer_drop, totals.rx_route_drop, totals.rx_time_drop), (1, 1, 0, 0));
}
#[test]
fn diagnostic_submitted_frames_count_only_successful_device_ring_publications() {
let (mut worker, _handle, _commands, _events) = command_fixture();
let mut samples = install_voice_output(&mut worker);
let now = Instant::now();
let mut failed = false;
for _ in 0..40 {
if let Err(error) = worker.outputs[0].write(&[[0.; 2]; 480], now, now + MAX_AGE) {
assert_eq!(error.code, "audio_playback_overflow");
failed = true; break;
}
}
assert!(failed, "bounded ring must fill without a callback consumer");
let mut published = 0;
while let Some(block) = samples.try_pop() { published += block.frames as u64; }
assert!(published > 0);
assert_eq!(worker.outputs[0].port.state.stats().submitted_frames, published);
}
#[test]
fn diagnostic_voice_activity_retains_only_nonzero_count_and_coarse_peak_bucket() {
let counters = diagnostics::Counters::default();
for (level, expected_bucket) in [(0., 0), (0.0005, 1), (0.005, 2), (0.05, 3), (0.5, 4), (0., 4)] {
counters.observe_voice(&[[level; 2]; 480]);
assert_eq!(counters.totals().voice_peak_bucket_max, expected_bucket);
}
assert_eq!(counters.totals().voice_nonzero_blocks, 4);
}
+58 -14
View File
@@ -23,6 +23,30 @@ 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>, 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()));
#[derive(Clone, Copy, Debug)]
pub(crate) enum VoiceRoutePhase { CallStart, CaptureChange, Authorization, Fence, Selection, Settings, Validate, Configuration, StopInput, SelectInput, SelectOutput, StopOutput, StartOutput, OutputAck, CaptureIntent, ResumeCapture, MuteCapture, Enumerate, Complete }
#[derive(Clone, Copy, Debug)]
pub(crate) enum VoiceRouteReason { Queued, Timeout, RouteChanged, FocusGained, FocusLost, CaptureRevoked, Pending, Completed, Failed, OwnerChanged, AudioRevisionChanged, CaptureIntentChanged, PlaybackRevoked, OutputNotGranted, DefaultSelection, BuiltinDefault, ExactSelection }
// Called only by service/control workers, never a PCM callback. No identity-bearing
// keys, endpoint IDs, device descriptions or arbitrary platform error strings.
fn route_log_permit() -> Option<u64> { ROUTE_LOG_BUDGET.lock().expect("Android route log budget").take(std::time::Instant::now()) }
fn log_voice_authorization(token:u64,phase:VoiceRoutePhase,reason:VoiceRouteReason) {
let Some(suppressed)=route_log_permit() else{return};
let state={let slot=VOICE.lock().expect("Android voice");slot.as_ref().filter(|voice|voice.token==token).map(|voice|(voice.audio.allows(false),voice.audio.allows(true),voice.audio.retains_capture(),voice.audio.restart_output(),voice.capture_change.is_some()))};
eprintln!("audio_route platform=native phase={phase:?} reason={reason:?} lease_current={} output_allowed={} capture_allowed={} capture_retained={} restart_pending={} capture_change_pending={} suppressed={suppressed}",state.is_some(),state.is_some_and(|s|s.0),state.is_some_and(|s|s.1),state.is_some_and(|s|s.2),state.is_some_and(|s|s.3),state.is_some_and(|s|s.4));
}
pub(crate) fn log_voice_route(key:&SessionKey,phase:VoiceRoutePhase,reason:VoiceRouteReason,elapsed:std::time::Duration,restart_output:bool,output_active:bool,input_active:bool) {
let Some(suppressed)=route_log_permit() else{return};
let state={let slot=VOICE.lock().expect("Android voice");slot.as_ref().filter(|voice|&voice.key==key).map(|voice|(voice.audio.allows(false),voice.audio.allows(true),voice.audio.retains_capture(),voice.audio.restart_output()))};
eprintln!("audio_route platform=runtime phase={phase:?} reason={reason:?} elapsed_ms={} lease_current={} restart_output={restart_output} output_allowed={} output_active={output_active} capture_allowed={} input_active={input_active} capture_retained={} restart_pending={} suppressed={suppressed}",elapsed.as_millis(),state.is_some(),state.is_some_and(|s|s.0),state.is_some_and(|s|s.1),state.is_some_and(|s|s.2),state.is_some_and(|s|s.3));
}
fn log_voice_selection(reason:VoiceRouteReason) {
if let Some(suppressed)=route_log_permit(){eprintln!("audio_route platform=native phase={:?} reason={reason:?} suppressed={suppressed}",VoiceRoutePhase::Selection);}
}
fn log_voice_request(phase:VoiceRoutePhase,reason:VoiceRouteReason,started:std::time::Instant,capture:bool) {
if let Some(suppressed)=route_log_permit(){eprintln!("audio_route platform=native phase={phase:?} reason={reason:?} elapsed_ms={} capture_requested={capture} suppressed={suppressed}",started.elapsed().as_millis());}
}
#[derive(Clone)] #[derive(Clone)]
struct Action { key: SessionKey, stream: Option<String> } struct Action { key: SessionKey, stream: Option<String> }
static ACTIONS: LazyLock<Mutex<HashMap<u64, Action>>> = LazyLock::new(|| Mutex::new(HashMap::new())); static ACTIONS: LazyLock<Mutex<HashMap<u64, Action>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
@@ -151,12 +175,19 @@ pub async fn start_voice(runtime: Arc<AppRuntime>, key: SessionKey, microphone:
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);
with_env(|env, class| accepted(java(env.call_static_method(class, "startVoice", "(JZ)Z", &[JValue::Long(token as i64), JValue::Bool(microphone as u8)]))?.z().unwrap_or(false)))?; let started=std::time::Instant::now();
match tokio::time::timeout(std::time::Duration::from_secs(15), request.receive()).await { if let Err(error)=with_env(|env, class| accepted(java(env.call_static_method(class, "startVoice", "(JZ)Z", &[JValue::Long(token as i64), JValue::Bool(microphone as u8)]))?.z().unwrap_or(false))){
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(()) }, log_voice_request(VoiceRoutePhase::CallStart,VoiceRouteReason::Failed,started,microphone);return Err(error)
Ok(Err(error)) => Err(error),
_ => Err(error("call_start_failed", "Android did not grant a foreground voice session")),
} }
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 {
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(Err(error)) => (Err(error),VoiceRouteReason::Failed),
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),
};
log_voice_request(VoiceRoutePhase::CallStart,reason,started,microphone);
result
} }
/// Stop/invalidate CPAL capture before disabling. Enable CPAL only after this OS acknowledgment /// Stop/invalidate CPAL capture before disabling. Enable CPAL only after this OS acknowledgment
@@ -173,14 +204,22 @@ pub async fn set_voice_capture(key: &SessionKey, enabled: bool, policy: ActionPo
if cancel{let _=call_void("cancelVoiceCapture","(JJ)V",&[JValue::Long(self.token as i64),JValue::Long(self.id as i64)]);} if cancel{let _=call_void("cancelVoiceCapture","(JJ)V",&[JValue::Long(self.token as i64),JValue::Long(self.id as i64)]);}
}}} }}}
let mut change=CaptureChange{token,id,committed:false}; let mut change=CaptureChange{token,id,committed:false};
with_env(|env,class|accepted(java(env.call_static_method(class,"setVoiceCapture","(JJZ)Z",&[JValue::Long(token as i64),JValue::Long(id as i64),JValue::Bool(enabled as u8)]))?.z().unwrap_or(false)))?; let started=std::time::Instant::now();
match tokio::time::timeout(std::time::Duration::from_secs(15),request.receive()).await { if let Err(error)=with_env(|env,class|accepted(java(env.call_static_method(class,"setVoiceCapture","(JJZ)Z",&[JValue::Long(token as i64),JValue::Long(id as i64),JValue::Bool(enabled as u8)]))?.z().unwrap_or(false))){
Ok(Ok(Response::Voice)) if VOICE.lock().expect("Android voice").as_ref().is_some_and(|voice|voice.token==token&&voice.capture_revision==id&&voice.microphone==enabled)=>{change.committed=true;Ok(())}, log_voice_request(VoiceRoutePhase::CaptureChange,VoiceRouteReason::Failed,started,enabled);return Err(error)
Ok(Err(error))=>Err(error),
_=>Err(error("call_capture_failed","Android did not acknowledge the microphone service transition")),
} }
log_voice_request(VoiceRoutePhase::CaptureChange,VoiceRouteReason::Queued,started,enabled);
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.capture_revision==id&&voice.microphone==enabled)=>{change.committed=true;(Ok(()),VoiceRouteReason::Completed)},
Ok(Err(error))=>(Err(error),VoiceRouteReason::Failed),
Err(_)=>(Err(error("call_capture_failed","Android did not acknowledge the microphone service transition")),VoiceRouteReason::Timeout),
_=>(Err(error("call_capture_failed","Android did not acknowledge the microphone service transition")),VoiceRouteReason::AudioRevisionChanged),
};
log_voice_request(VoiceRoutePhase::CaptureChange,reason,started,enabled);
result
} }
fn voice_audio_changed(token:u64, focused:Option<bool>, restart_output:bool) { fn voice_audio_changed(token:u64, focused:Option<bool>, restart_output:bool) {
let reason=match focused{Some(true)=>VoiceRouteReason::FocusGained,Some(false)=>VoiceRouteReason::FocusLost,None if restart_output=>VoiceRouteReason::RouteChanged,None=>VoiceRouteReason::CaptureRevoked};
let changed={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token).map(|voice|{ let changed={let mut slot=VOICE.lock().expect("Android voice");slot.as_mut().filter(|voice|voice.token==token).map(|voice|{
let route=focused.is_none()&&restart_output; let route=focused.is_none()&&restart_output;
// Only completed consent can survive endpoint replacement. A route may // Only completed consent can survive endpoint replacement. A route may
@@ -194,23 +233,25 @@ fn voice_audio_changed(token:u64, focused:Option<bool>, restart_output:bool) {
if let Some((key,revision,pending,restart_output))=changed { if let Some((key,revision,pending,restart_output))=changed {
if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","Microphone transition was superseded by an Android audio change")));} if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","Microphone transition was superseded by an Android audio change")));}
lifecycle::emit(PlatformEvent::AndroidCallAudio{key,token,revision,restart_output}); lifecycle::emit(PlatformEvent::AndroidCallAudio{key,token,revision,restart_output});
log_voice_authorization(token,VoiceRoutePhase::Authorization,reason);
} }
} }
/// Phone endpoints follow Android's communication route during an active call. /// Phone endpoints follow Android's communication route during an active call.
/// Explicit external and unknown endpoints keep their exact-ID failure behavior. /// Explicit external and unknown endpoints keep their exact-ID failure behavior.
pub(crate) fn voice_device_selection(raw:&str)->Result<crate::media::audio::devices::DeviceSelection>{ pub(crate) fn voice_device_selection(raw:&str)->Result<crate::media::audio::devices::DeviceSelection>{
use crate::media::audio::devices::DeviceSelection; use crate::media::audio::devices::DeviceSelection;
if raw.is_empty(){return Ok(DeviceSelection::SystemDefault)} if raw.is_empty(){log_voice_selection(VoiceRouteReason::DefaultSelection);return Ok(DeviceSelection::SystemDefault)}
if VOICE.lock().expect("Android voice").is_some(){ if VOICE.lock().expect("Android voice").is_some(){
if let Ok(id)=raw.parse::<cpal::DeviceId>(){ if let Ok(id)=raw.parse::<cpal::DeviceId>(){
if id.host()==cpal::HostId::AAudio { if id.host()==cpal::HostId::AAudio {
if let Ok(endpoint)=id.id().parse::<i32>(){ if let Ok(endpoint)=id.id().parse::<i32>(){
let builtin=with_env(|env,class|java(env.call_static_method(class,"voiceDeviceIsBuiltin","(I)Z",&[JValue::Int(endpoint)]))?.z().map_err(|_|error("android_os_error","Invalid audio endpoint metadata")))?; let builtin=with_env(|env,class|java(env.call_static_method(class,"voiceDeviceIsBuiltin","(I)Z",&[JValue::Int(endpoint)]))?.z().map_err(|_|error("android_os_error","Invalid audio endpoint metadata")))?;
if builtin{return Ok(DeviceSelection::SystemDefault)} if builtin{log_voice_selection(VoiceRouteReason::BuiltinDefault);return Ok(DeviceSelection::SystemDefault)}
} }
} }
} }
} }
log_voice_selection(VoiceRouteReason::ExactSelection);
Ok(DeviceSelection::Exact(raw.into())) Ok(DeviceSelection::Exact(raw.into()))
} }
pub(crate) fn voice_audio_allowed(key:&SessionKey,microphone:bool)->bool { pub(crate) fn voice_audio_allowed(key:&SessionKey,microphone:bool)->bool {
@@ -223,7 +264,8 @@ 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 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) {
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);} 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});
} }
fn end_voice(token: u64) -> bool { fn end_voice(token: u64) -> bool {
end_voice_with_shutdown(token,false) end_voice_with_shutdown(token,false)
@@ -399,7 +441,7 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceVali
#[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){voice.microphone=microphone!=0;voice.audio.start(microphone!=0);true}else{false}};
if active{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));}
} }
#[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}
@@ -419,6 +461,7 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceEven
})}; })};
if let Some((runtime,key,authorized,pending))=owner{ if let Some((runtime,key,authorized,pending))=owner{
runtime.fence_android_audio_route(&key,authorized); runtime.fence_android_audio_route(&key,authorized);
log_voice_authorization(token as u64,VoiceRoutePhase::Fence,VoiceRouteReason::Pending);
if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","Microphone transition was superseded by a route change")));} if let Some(id)=pending{complete(id,Err(error("call_capture_revoked","Microphone transition was superseded by a route change")));}
} }
}, },
@@ -436,6 +479,7 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeVoiceCapt
#[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{
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.capture_revision==id as u64&&voice.capture_change==Some(id as u64)){if !voice.audio.change_capture(enabled!=0){false}else{voice.microphone=enabled!=0;voice.capture_change=None;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&&voice.capture_revision==id as u64&&voice.capture_change==Some(id as u64)){if !voice.audio.change_capture(enabled!=0){false}else{voice.microphone=enabled!=0;voice.capture_change=None;true}}else{false}};
log_voice_authorization(token as u64,VoiceRoutePhase::Authorization,if active{VoiceRouteReason::Completed}else{VoiceRouteReason::AudioRevisionChanged});
if active{complete(id as u64,Ok(Response::Voice));}active as u8 if active{complete(id as u64,Ok(Response::Voice));}active as u8
} }
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
+32
View File
@@ -50,10 +50,42 @@ impl CallAudioState {
pub fn is_current(&self, revision: u64) -> bool { self.revision == revision } pub fn is_current(&self, revision: u64) -> bool { self.revision == revision }
} }
/// Control-thread log budget; callback storms cannot flood retained diagnostics.
#[derive(Default)]
pub(super) struct RouteLogBudget {
window: Option<std::time::Instant>,
emitted: u8,
suppressed: u64,
}
impl RouteLogBudget {
pub fn take(&mut self, now: std::time::Instant) -> Option<u64> {
if self.window.is_none_or(|window| now.saturating_duration_since(window) >= std::time::Duration::from_secs(10)) {
self.window = Some(now);
self.emitted = 0;
}
if self.emitted >= 16 {
self.suppressed = self.suppressed.saturating_add(1);
return None;
}
self.emitted += 1;
Some(std::mem::take(&mut self.suppressed))
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::CallAudioState; use super::CallAudioState;
#[test] #[test]
fn route_logs_are_bounded_and_report_suppression_in_next_window() {
let mut budget = super::RouteLogBudget::default();
let now = std::time::Instant::now();
for _ in 0..16 { assert_eq!(budget.take(now), Some(0)); }
assert_eq!(budget.take(now), None);
assert_eq!(budget.take(now + std::time::Duration::from_secs(9)), None);
assert_eq!(budget.take(now + std::time::Duration::from_secs(10)), Some(2));
assert_eq!(budget.take(now + std::time::Duration::from_secs(10)), Some(0));
}
#[test]
fn focus_gain_restores_only_receive_authorization() { fn focus_gain_restores_only_receive_authorization() {
let mut state = CallAudioState::default(); let mut state = CallAudioState::default();
assert!(!state.allows(false)); assert!(!state.allows(false));
@@ -29,6 +29,40 @@ public final class VoiceService extends Service {
private boolean scoRequested; private boolean scoRequested;
private boolean scoConnected; private boolean scoConnected;
private BroadcastReceiver scoReceiver; private BroadcastReceiver scoReceiver;
private enum RoutePhase { REQUEST, PLATFORM_ACCEPTED, PLATFORM_RETURNED, CALLBACK, ACK, FINISH, FOCUS, SCO, RELEASE, CAPTURE }
private enum RouteReason { NONE, ALREADY_CURRENT, DEVICE_CALLBACK, SYNCHRONOUS, SCO_CONNECTED, LEGACY_IMMEDIATE, 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 routeTargetType;
private boolean routeTopologyChanged;
private int routeDeviceCount;
private long routeDeviceTypes;
private int routeAvailableCount;
private long routeAvailableTypes;
private boolean routeRequested;
private boolean routeAccepted;
private boolean routeCaptureRequested;
private int routeFocusChange;
private int routeFocusRequestResult;
private int routeScoState=AudioManager.SCO_AUDIO_STATE_ERROR;
private long routeStartedMs;
private static long routeLogWindowMs;
private static int routeLogCount;
private static long routeLogSuppressed;
// Main-thread lifecycle diagnostics only: no endpoint IDs, names or exception text.
// Bound callback storms across service replacement, not just within one call.
private void routeLog(RoutePhase phase,RouteReason reason) {
long now=SystemClock.elapsedRealtime();
if(now-routeLogWindowMs>=10000){routeLogWindowMs=now;routeLogCount=0;}
if(routeLogCount>=16){if(routeLogSuppressed<Long.MAX_VALUE)++routeLogSuppressed;return;}
++routeLogCount;
android.util.Log.i("TeamsPeachAudioRoute","audio_route platform=android phase="+phase+" reason="+reason
+" topologyChanged="+routeTopologyChanged+" current_type="+routeCurrentType+" target_type="+routeTargetType
+" device_count="+routeDeviceCount+" device_types="+routeDeviceTypes+" available_count="+routeAvailableCount+" available_types="+routeAvailableTypes
+" requested="+routeRequested+" accepted="+routeAccepted+" acknowledged="+(phase==RoutePhase.ACK)+" focused="+focused+" focus_change="+routeFocusChange+" focus_request_result="+routeFocusRequestResult+" pending="+(pendingDeviceId!=0)
+" starting="+starting+" capture="+microphone+" capture_requested="+routeCaptureRequested+" sco_requested="+scoRequested+" sco_connected="+scoConnected+" sco_state="+routeScoState
+" elapsed_ms="+(routeStartedMs==0?0:Math.max(0,now-routeStartedMs))+" suppressed="+routeLogSuppressed);
routeLogSuppressed=0;
}
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();} }
@@ -44,13 +78,16 @@ public final class VoiceService extends Service {
} }
static void changeCapture(long token,long request,boolean enabled) { static void changeCapture(long token,long request,boolean enabled) {
VoiceService service=current.get(); VoiceService service=current.get();
if(service!=null){service.routeCaptureRequested=enabled;service.routeLog(RoutePhase.CAPTURE,RouteReason.CAPTURE_REQUEST);}
if(service==null||service.token!=token||!PlatformBridge.nativeVoiceCaptureValid(token,request)){PlatformBridge.nativeText(request,null,"target_changed");return;} if(service==null||service.token!=token||!PlatformBridge.nativeVoiceCaptureValid(token,request)){PlatformBridge.nativeText(request,null,"target_changed");return;}
if(enabled && (PlatformBridge.visible()==null||!PlatformBridge.granted(0))){service.receiveOnly();PlatformBridge.nativeText(request,null,"Microphone activation requires a visible user action and RECORD_AUDIO grant");return;} if(enabled && (PlatformBridge.visible()==null||!PlatformBridge.granted(0))){service.routeLog(RoutePhase.CAPTURE,RouteReason.PERMISSION_DENIED);service.receiveOnly();PlatformBridge.nativeText(request,null,"Microphone activation requires a visible user action and RECORD_AUDIO grant");return;}
if(enabled && !service.focused){PlatformBridge.nativeText(request,null,"Audio focus is unavailable; wait for the interruption to end");return;} if(enabled && !service.focused){service.routeLog(RoutePhase.CAPTURE,RouteReason.FOCUS_UNAVAILABLE);PlatformBridge.nativeText(request,null,"Audio focus is unavailable; wait for the interruption to end");return;}
if(enabled && service.pendingDeviceId!=0){PlatformBridge.nativeText(request,null,"Audio route is changing; wait for the headset transition to finish");return;} if(enabled && service.pendingDeviceId!=0){service.routeLog(RoutePhase.CAPTURE,RouteReason.ROUTE_PENDING);PlatformBridge.nativeText(request,null,"Audio route is changing; wait for the headset transition to finish");return;}
try { try {
service.foreground(enabled); service.foreground(enabled);
if(!PlatformBridge.nativeVoiceCaptureChanged(token,request,enabled))service.foreground(false); boolean acknowledged=PlatformBridge.nativeVoiceCaptureChanged(token,request,enabled);
service.routeLog(RoutePhase.CAPTURE,acknowledged?RouteReason.CAPTURE_ACK:RouteReason.SUPERSEDED);
if(!acknowledged)service.foreground(false);
}catch(RuntimeException error){service.receiveOnly();PlatformBridge.nativeText(request,null,"Android denied the microphone service transition; call remains receive-only if playback is permitted");} }catch(RuntimeException error){service.receiveOnly();PlatformBridge.nativeText(request,null,"Android denied the microphone service transition; call remains receive-only if playback is permitted");}
} }
static void cancelCapture(long token,long request) { static void cancelCapture(long token,long request) {
@@ -61,11 +98,13 @@ public final class VoiceService extends Service {
} }
private void receiveOnly() { private void receiveOnly() {
PlatformBridge.nativeVoiceCaptureRevoked(token); PlatformBridge.nativeVoiceCaptureRevoked(token);
routeLog(RoutePhase.CAPTURE,RouteReason.CAPTURE_REVOKED);
try{foreground(false);}catch(RuntimeException playbackDenied){PlatformBridge.nativeVoiceStopped(token);stopSelf();} try{foreground(false);}catch(RuntimeException playbackDenied){PlatformBridge.nativeVoiceStopped(token);stopSelf();}
} }
private java.util.Set<Integer> audioDevices(AudioManager audio) { private java.util.Set<Integer> audioDevices(AudioManager audio) {
java.util.Set<Integer> ids = new java.util.HashSet<>(); java.util.Set<Integer> ids = new java.util.HashSet<>();
for(AudioDeviceInfo device : audio.getDevices(AudioManager.GET_DEVICES_ALL)) ids.add(device.getId()); routeDeviceCount=0;routeDeviceTypes=0;
for(AudioDeviceInfo device : audio.getDevices(AudioManager.GET_DEVICES_ALL)){ids.add(device.getId());++routeDeviceCount;int type=device.getType();routeDeviceTypes|=1L<<(type>=0&&type<63?type:63);}
return ids; return ids;
} }
private int communicationDevice(AudioManager audio) { private int communicationDevice(AudioManager audio) {
@@ -76,39 +115,47 @@ public final class VoiceService extends Service {
private AudioDeviceInfo preferredCommunicationDevice(AudioManager audio,boolean rememberPhone) { private AudioDeviceInfo preferredCommunicationDevice(AudioManager audio,boolean rememberPhone) {
Iterable<AudioDeviceInfo> available=Build.VERSION.SDK_INT>=31?audio.getAvailableCommunicationDevices():java.util.Arrays.asList(audio.getDevices(AudioManager.GET_DEVICES_OUTPUTS)); Iterable<AudioDeviceInfo> available=Build.VERSION.SDK_INT>=31?audio.getAvailableCommunicationDevices():java.util.Arrays.asList(audio.getDevices(AudioManager.GET_DEVICES_OUTPUTS));
AudioDeviceInfo best=null;int selected=communicationDevice(audio); AudioDeviceInfo best=null;int selected=communicationDevice(audio);
routeAvailableCount=0;routeAvailableTypes=0;
if(rememberPhone&&!headsetRoute&&(!starting||phoneDeviceId==0)){ if(rememberPhone&&!headsetRoute&&(!starting||phoneDeviceId==0)){
for(AudioDeviceInfo device:available)if(device.getId()==selected&&CommunicationRoutePolicy.isBuiltin(device.getType())){phoneDeviceId=selected;break;} for(AudioDeviceInfo device:available)if(device.getId()==selected&&CommunicationRoutePolicy.isBuiltin(device.getType())){phoneDeviceId=selected;break;}
} }
int preferred=phoneDeviceId!=0?phoneDeviceId:selected; int preferred=phoneDeviceId!=0?phoneDeviceId:selected;
for(AudioDeviceInfo device:available){ for(AudioDeviceInfo device:available){
++routeAvailableCount;int type=device.getType();routeAvailableTypes|=1L<<(type>=0&&type<63?type:63);
if(CommunicationRoutePolicy.prefer(device.getId(),device.getType(),best==null?0:best.getId(),best==null?0:best.getType(),CommunicationRoutePolicy.isBuiltin(device.getType())?preferred:selected))best=device; if(CommunicationRoutePolicy.prefer(device.getId(),device.getType(),best==null?0:best.getId(),best==null?0:best.getType(),CommunicationRoutePolicy.isBuiltin(device.getType())?preferred:selected))best=device;
} }
return best; return best;
} }
private void finishRoute(long owner,long generation,boolean accepted) { private void finishRoute(long owner,long generation,boolean accepted,RouteReason reason) {
if(token!=owner||routeGeneration!=generation||!PlatformBridge.nativeVoiceValid(owner))return; if(token!=owner||routeGeneration!=generation||!PlatformBridge.nativeVoiceValid(owner)){routeLog(RoutePhase.FINISH,RouteReason.SUPERSEDED);return;}
pendingDeviceId=0; pendingDeviceId=0;
if(accepted)headsetRoute=pendingExternalRoute; if(accepted)headsetRoute=pendingExternalRoute;
if(!accepted)receiveOnly(); if(!accepted)receiveOnly();
if(starting){starting=false;if(!focused){PlatformBridge.nativeVoiceStopped(owner);stopSelf();return;}PlatformBridge.nativeVoiceStarted(owner,microphone);} if(starting){starting=false;if(!focused){PlatformBridge.nativeVoiceStopped(owner);stopSelf();return;}PlatformBridge.nativeVoiceStarted(owner,microphone);}
else PlatformBridge.nativeVoiceEvent(owner,3,true); else PlatformBridge.nativeVoiceEvent(owner,3,true);
routeLog(accepted?RoutePhase.ACK:RoutePhase.FINISH,reason);
} }
private void awaitRoute(long owner,long generation) { private void awaitRoute(long owner,long generation) {
// A missing platform acknowledgement becomes receive-only, not a retry loop. // A missing platform acknowledgement becomes receive-only, not a retry loop.
PlatformBridge.MAIN.postDelayed(()->{if(pendingDeviceId!=0)finishRoute(owner,generation,false);},3000); PlatformBridge.MAIN.postDelayed(()->{if(pendingDeviceId!=0)finishRoute(owner,generation,false,RouteReason.TIMEOUT);},3000);
} }
private void routeChanged(long owner) { private void routeChanged(long owner) {
if(token!=owner||!PlatformBridge.nativeVoiceValid(owner))return; if(token!=owner||!PlatformBridge.nativeVoiceValid(owner))return;
AudioManager audio=getSystemService(AudioManager.class); AudioManager audio=getSystemService(AudioManager.class);
java.util.Set<Integer> next=audioDevices(audio); java.util.Set<Integer> next=audioDevices(audio);
int selected=communicationDevice(audio); AudioDeviceInfo selectedDevice=Build.VERSION.SDK_INT>=31?audio.getCommunicationDevice():null;
int selected=selectedDevice==null?0:selectedDevice.getId();
routeCurrentType=selectedDevice==null?AudioDeviceInfo.TYPE_UNKNOWN:selectedDevice.getType();
boolean topologyChanged=!next.equals(deviceIds); boolean topologyChanged=!next.equals(deviceIds);
if(Build.VERSION.SDK_INT>=31&&pendingDeviceId!=0&&!topologyChanged){ if(Build.VERSION.SDK_INT>=31&&pendingDeviceId!=0&&!topologyChanged){
communicationDeviceId=selected; communicationDeviceId=selected;
if(selected==pendingDeviceId)finishRoute(owner,routeGeneration,true); if(selected==pendingDeviceId)finishRoute(owner,routeGeneration,true,RouteReason.DEVICE_CALLBACK);
else routeLog(RoutePhase.CALLBACK,RouteReason.ROUTE_PENDING);
return; return;
} }
if(!starting&&!topologyChanged&&selected==communicationDeviceId)return; if(!starting&&!topologyChanged&&selected==communicationDeviceId)return;
if(pendingDeviceId!=0)routeLog(RoutePhase.FINISH,RouteReason.SUPERSEDED);
routeStartedMs=SystemClock.elapsedRealtime();routeTopologyChanged=topologyChanged;routeRequested=false;routeAccepted=false;
deviceIds=next;communicationDeviceId=selected; deviceIds=next;communicationDeviceId=selected;
if(!starting)PlatformBridge.nativeVoiceEvent(owner,8,true); if(!starting)PlatformBridge.nativeVoiceEvent(owner,8,true);
long generation=++routeGeneration; long generation=++routeGeneration;
@@ -121,27 +168,35 @@ public final class VoiceService extends Service {
} }
pendingExternalRoute=target!=null&&CommunicationRoutePolicy.priority(target.getType())>=20; pendingExternalRoute=target!=null&&CommunicationRoutePolicy.priority(target.getType())>=20;
pendingDeviceId=target==null?-1:target.getId(); pendingDeviceId=target==null?-1:target.getId();
routeTargetType=target==null?AudioDeviceInfo.TYPE_UNKNOWN:target.getType();
routeLog(RoutePhase.REQUEST,RouteReason.NONE);
try { try {
if(Build.VERSION.SDK_INT>=31){ if(Build.VERSION.SDK_INT>=31){
if(target==null){audio.clearCommunicationDevice();finishRoute(owner,generation,false);} if(target==null){audio.clearCommunicationDevice();finishRoute(owner,generation,false,RouteReason.NO_TARGET);}
else if(selected==target.getId()){finishRoute(owner,generation,true);} else if(selected==target.getId()){finishRoute(owner,generation,true,RouteReason.ALREADY_CURRENT);}
else if(!audio.setCommunicationDevice(target)){finishRoute(owner,generation,false);} else {
else if(communicationDevice(audio)==target.getId()){communicationDeviceId=target.getId();finishRoute(owner,generation,true);} routeRequested=true;routeAccepted=audio.setCommunicationDevice(target);
else awaitRoute(owner,generation); routeLog(RoutePhase.PLATFORM_ACCEPTED,routeAccepted?RouteReason.NONE:RouteReason.REQUEST_DENIED);
if(!routeAccepted)finishRoute(owner,generation,false,RouteReason.REQUEST_DENIED);
else if(communicationDevice(audio)==target.getId()){communicationDeviceId=target.getId();routeCurrentType=target.getType();finishRoute(owner,generation,true,RouteReason.SYNCHRONOUS);}
else awaitRoute(owner,generation);
}
}else{ }else{
boolean sco=target!=null&&target.getType()==AudioDeviceInfo.TYPE_BLUETOOTH_SCO; boolean sco=target!=null&&target.getType()==AudioDeviceInfo.TYPE_BLUETOOTH_SCO;
audio.setSpeakerphoneOn(!pendingExternalRoute&&phoneSpeaker); audio.setSpeakerphoneOn(!pendingExternalRoute&&phoneSpeaker);
if(sco){ if(sco){
scoRequested=true;audio.startBluetoothSco();audio.setBluetoothScoOn(true); routeRequested=true;scoRequested=true;audio.startBluetoothSco();audio.setBluetoothScoOn(true);
if(scoConnected)finishRoute(owner,generation,true);else awaitRoute(owner,generation); routeLog(RoutePhase.PLATFORM_RETURNED,RouteReason.NONE);
if(scoConnected)finishRoute(owner,generation,true,RouteReason.SCO_CONNECTED);else awaitRoute(owner,generation);
}else{ }else{
if(scoRequested){audio.stopBluetoothSco();audio.setBluetoothScoOn(false);scoRequested=false;scoConnected=false;} if(scoRequested){audio.stopBluetoothSco();audio.setBluetoothScoOn(false);scoRequested=false;scoConnected=false;}
finishRoute(owner,generation,true); finishRoute(owner,generation,true,RouteReason.LEGACY_IMMEDIATE);
} }
} }
}catch(RuntimeException denied){finishRoute(owner,generation,false);} }catch(RuntimeException denied){finishRoute(owner,generation,false,RouteReason.PLATFORM_DENIED);}
} }
private void releaseCommunicationRoute(AudioManager audio) { private void releaseCommunicationRoute(AudioManager audio) {
routeLog(RoutePhase.RELEASE,RouteReason.NONE);
++routeGeneration;pendingDeviceId=0; ++routeGeneration;pendingDeviceId=0;
if(Build.VERSION.SDK_INT>=31)audio.clearCommunicationDevice(); if(Build.VERSION.SDK_INT>=31)audio.clearCommunicationDevice();
else{if(scoRequested){audio.stopBluetoothSco();audio.setBluetoothScoOn(false);}audio.setSpeakerphoneOn(phoneSpeaker);} else{if(scoRequested){audio.stopBluetoothSco();audio.setBluetoothScoOn(false);}audio.setSpeakerphoneOn(phoneSpeaker);}
@@ -182,12 +237,16 @@ public final class VoiceService extends Service {
boolean gained=change==AudioManager.AUDIOFOCUS_GAIN; boolean gained=change==AudioManager.AUDIOFOCUS_GAIN;
if(focused==gained&&change!=AudioManager.AUDIOFOCUS_LOSS)return; if(focused==gained&&change!=AudioManager.AUDIOFOCUS_LOSS)return;
focused=gained; focused=gained;
routeFocusChange=change;
if(!focused){try{foreground(false);}catch(RuntimeException denied){stopSelf();}} if(!focused){try{foreground(false);}catch(RuntimeException denied){stopSelf();}}
PlatformBridge.nativeVoiceEvent(owner, 2, !focused); PlatformBridge.nativeVoiceEvent(owner, 2, !focused);
routeLog(RoutePhase.FOCUS,gained?RouteReason.FOCUS_GAIN:RouteReason.FOCUS_LOSS);
if (change == AudioManager.AUDIOFOCUS_LOSS) stopSelf(); if (change == AudioManager.AUDIOFOCUS_LOSS) stopSelf();
}, PlatformBridge.MAIN).build(); }, PlatformBridge.MAIN).build();
if (audio.requestAudioFocus(focus) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) throw new IllegalStateException("Audio focus denied"); routeFocusRequestResult=audio.requestAudioFocus(focus);
focused=true; boolean focusGranted=routeFocusRequestResult==AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
focused=focusGranted;routeLog(RoutePhase.FOCUS,focusGranted?RouteReason.FOCUS_GRANTED:RouteReason.FOCUS_DENIED);
if(!focusGranted)throw new IllegalStateException("Audio focus denied");
starting=true;deviceIds=java.util.Collections.emptySet();communicationDeviceId=-1; 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);
@@ -198,14 +257,16 @@ public final class VoiceService extends Service {
if(token!=owner||!PlatformBridge.nativeVoiceValid(owner))return; if(token!=owner||!PlatformBridge.nativeVoiceValid(owner))return;
int state=intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,AudioManager.SCO_AUDIO_STATE_ERROR); int state=intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,AudioManager.SCO_AUDIO_STATE_ERROR);
boolean wasConnected=scoConnected;scoConnected=state==AudioManager.SCO_AUDIO_STATE_CONNECTED; boolean wasConnected=scoConnected;scoConnected=state==AudioManager.SCO_AUDIO_STATE_CONNECTED;
routeScoState=state;
routeLog(RoutePhase.SCO,RouteReason.NONE);
if(scoConnected&&!wasConnected&&scoRequested){ if(scoConnected&&!wasConnected&&scoRequested){
if(pendingDeviceId!=0)finishRoute(owner,routeGeneration,true); if(pendingDeviceId!=0)finishRoute(owner,routeGeneration,true,RouteReason.SCO_CONNECTED);
else{PlatformBridge.nativeVoiceEvent(owner,8,true);finishRoute(owner,++routeGeneration,true);} else{routeStartedMs=SystemClock.elapsedRealtime();PlatformBridge.nativeVoiceEvent(owner,8,true);finishRoute(owner,++routeGeneration,true,RouteReason.SCO_CONNECTED);}
} }
else if(state==AudioManager.SCO_AUDIO_STATE_DISCONNECTED&&wasConnected&&scoRequested){ else if(state==AudioManager.SCO_AUDIO_STATE_DISCONNECTED&&wasConnected&&scoRequested){
scoRequested=false;audio.setBluetoothScoOn(false);audio.setSpeakerphoneOn(phoneSpeaker);pendingExternalRoute=false; scoRequested=false;audio.setBluetoothScoOn(false);audio.setSpeakerphoneOn(phoneSpeaker);pendingExternalRoute=false;
PlatformBridge.nativeVoiceEvent(owner,8,true); PlatformBridge.nativeVoiceEvent(owner,8,true);
finishRoute(owner,++routeGeneration,true); routeStartedMs=SystemClock.elapsedRealtime();finishRoute(owner,++routeGeneration,true,RouteReason.LEGACY_IMMEDIATE);
} }
}}; }};
if(Build.VERSION.SDK_INT>=33)registerReceiver(scoReceiver,new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED),Context.RECEIVER_NOT_EXPORTED); if(Build.VERSION.SDK_INT>=33)registerReceiver(scoReceiver,new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED),Context.RECEIVER_NOT_EXPORTED);
@@ -218,7 +279,7 @@ public final class VoiceService extends Service {
audio.registerAudioDeviceCallback(devices, PlatformBridge.MAIN); audio.registerAudioDeviceCallback(devices, PlatformBridge.MAIN);
} }
routeChanged(token); routeChanged(token);
} catch (RuntimeException error) { PlatformBridge.nativeVoiceStopped(token); stopSelf(); } } catch (RuntimeException error) { routeLog(RoutePhase.FINISH,RouteReason.PLATFORM_DENIED);PlatformBridge.nativeVoiceStopped(token); stopSelf(); }
return START_NOT_STICKY; return START_NOT_STICKY;
} }
@Override public void onTaskRemoved(Intent rootIntent) { @Override public void onTaskRemoved(Intent rootIntent) {