Verify fresh voice playback after releasing the native UI attachment

This commit is contained in:
omar committed 2026-11-28 00:33:43 +03:00
1 parent 00643532a3
commit a47bebf922
7 files changed
+418 -13

No files matched your search

+2
View File
@@ -2,6 +2,8 @@
## Current Windows account-free checkpoint (2026-11-26) ## Current Windows account-free checkpoint (2026-11-26)
**Voice playback after UI detach (Windows beta14):** A receiver with a synthetic output rendered a tone from a second disposable core. The first burst drained to silence, the receiver released its UI attachment, and a fresh burst produced new non-silent output blocks without reattaching or replacing either session. Notifications and comfort noise were disabled. Separate mixer tests checked gain and isolation when closing a connection. No physical speaker or microphone was opened.
**Playback authorization:** On Windows, generated PCM stayed silent when the initial roster lacked a local client ID. An explicit boolean output_muted=false admitted the samples; a missing flag or the string "false" closed the route again. Separate mixer tests checked volume and the surviving connection's samples after another route retired. No physical speaker was opened. **Playback authorization:** On Windows, generated PCM stayed silent when the initial roster lacked a local client ID. An explicit boolean output_muted=false admitted the samples; a missing flag or the string "false" closed the route again. Separate mixer tests checked volume and the surviving connection's samples after another route retired. No physical speaker was opened.
**Native capture ingress on Windows:** The synthetic 48 kHz input passed through the capture worker, DSP and embedded core to another beta14 client. Separate tests checked the full 960-sample frame against the timestamp of its first half (200 ms inclusive), discarded stale frames without retiring a valid permit, and discarded partial frames on mute or rebind. During input handoff the old permit was unusable before the new core's acknowledgement; viewing a third tab did not transfer ownership. Generation changes invalidated the old capture epoch. These checks do not measure a physical microphone or speaker. **Native capture ingress on Windows:** The synthetic 48 kHz input passed through the capture worker, DSP and embedded core to another beta14 client. Separate tests checked the full 960-sample frame against the timestamp of its first half (200 ms inclusive), discarded stale frames without retiring a valid permit, and discarded partial frames on mute or rebind. During input handoff the old permit was unusable before the new core's acknowledgement; viewing a third tab did not transfer ownership. Generation changes invalidated the old capture epoch. These checks do not measure a physical microphone or speaker.
+2
View File
@@ -4,6 +4,8 @@
## Возврат к разработке на ПК, 2026-11-26 ## Возврат к разработке на ПК, 2026-11-26
Windows, база `0064353`: закрыт preload:onAudio. После первого сигнала и паузы до тишины получатель отсоединил UI; второй сигнал через beta14 дал новые ненулевые блоки на тестовом выходе без повторного подключения. Прошли четыре адресных нативных теста, включая усиление голоса и изоляцию вкладок. Физические устройства не открывались, стенд остановлен.
Windows, база `a1bf10f`: исправлено разрешение воспроизведения по неполному снимку и audio_state. Проверка отсчётов микшера различает тишину, явное снятие заглушения и повторное закрытие маршрута. Прошли четыре проверки микшера и три интеграционных теста привязки звука. Отсоединение UI в этот прогон не входило. Windows, база `a1bf10f`: исправлено разрешение воспроизведения по неполному снимку и audio_state. Проверка отсчётов микшера различает тишину, явное снятие заглушения и повторное закрытие маршрута. Прошли четыре проверки микшера и три интеграционных теста привязки звука. Отсоединение UI в этот прогон не входило.
Windows, база `aab5a34`: закрыт preload:sendAudioFrame для нативного тракта. На beta14 проверена передача синтетического сигнала через DSP и ядро. Отдельно проверены возраст всего кадра, сброс половины кадра при смене разрешения и отзыв предыдущего владельца до подтверждения нового. Прошли пять нативных тестов и три теста ядра. Физический микрофон не использовался; стенд остановлен. Windows, база `aab5a34`: закрыт preload:sendAudioFrame для нативного тракта. На beta14 проверена передача синтетического сигнала через DSP и ядро. Отдельно проверены возраст всего кадра, сброс половины кадра при смене разрешения и отзыв предыдущего владельца до подтверждения нового. Прошли пять нативных тестов и три теста ядра. Физический микрофон не использовался; стенд остановлен.
+20 -6
View File
@@ -516,6 +516,14 @@ struct PlaybackCallback {
format: DeviceFormat, current: Option<PlaybackBlock>, current_offset: usize, frame_position: u64, expected_at: Option<Instant>, format: DeviceFormat, current: Option<PlaybackBlock>, current_offset: usize, frame_position: u64, expected_at: Option<Instant>,
} }
impl PlaybackCallback { impl PlaybackCallback {
fn new(format: DeviceFormat, state: Arc<StreamState>, clock: Arc<ClockAnchor>) -> (Self, PlaybackPort) {
let capacity = queue_capacity(format.sample_rate);
let (samples, consumer) = ring::channel(capacity);
let (references, rendered) = ring::channel(capacity);
let port = PlaybackPort { samples, rendered, state: state.clone() };
(Self { consumer, references, state, clock, format, current: None, current_offset: 0, frame_position: 0, expected_at: None }, port)
}
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) { self.current = None; return None; }
loop { loop {
@@ -662,17 +670,23 @@ pub(super) fn start_playback(selected: SelectedDevice, permission: StartPermissi
let origin = Instant::now(); let origin = Instant::now();
let state = Arc::new(StreamState::new(epoch, origin)); let state = Arc::new(StreamState::new(epoch, origin));
let clock = Arc::new(ClockAnchor::new(origin)); let clock = Arc::new(ClockAnchor::new(origin));
let capacity = queue_capacity(selected.format.sample_rate); let (callback, port) = PlaybackCallback::new(selected.format, state.clone(), clock.clone());
let (samples, consumer) = ring::channel(capacity);
let (references, rendered) = ring::channel(capacity);
let callback = PlaybackCallback { consumer, references, state: state.clone(), clock: clock.clone(), format: selected.format, current: None, current_offset: 0, frame_position: 0, expected_at: None };
let stream = dispatch_pcm!(selected.format.sample_format, build_playback, &selected.device, callback, state.clone())?; let stream = dispatch_pcm!(selected.format.sample_format, build_playback, &selected.device, callback, state.clone())?;
clock.calibrate(&stream); clock.calibrate(&stream);
before_play()?; before_play()?;
// The engine, not backend construction, grants the playback generation. // The engine, not backend construction, grants the playback generation.
stream.play().map_err(audio_error)?; stream.play().map_err(audio_error)?;
let owner = StreamOwner { stream: Some(stream), state: state.clone(), device_id: selected.id, format: selected.format, _owner_thread: PhantomData }; let owner = StreamOwner { stream: Some(stream), state, device_id: selected.id, format: selected.format, _owner_thread: PhantomData };
Ok((owner, PlaybackPort { samples, rendered, state })) Ok((owner, port))
}
#[cfg(test)]
pub(super) fn test_playback(format: DeviceFormat, state: Arc<StreamState>, origin: Instant) -> (PlaybackPort, impl FnMut(&mut [f32], u64, Instant)) {
let (mut callback, port) = PlaybackCallback::new(format, state, Arc::new(ClockAnchor::new(origin)));
(port, move |data, elapsed_ms, now| {
let at = StreamInstant::from_millis(elapsed_ms);
callback.process(data, cpal::OutputStreamTimestamp { callback: at, playback: at }, now);
})
} }
#[cfg(test)] #[cfg(test)]
+32 -7
View File
@@ -28,6 +28,10 @@ use self::lifecycle::{DeviceLease, DeviceOwner, Lifecycle};
#[path = "test_tone_input.rs"] #[path = "test_tone_input.rs"]
mod test_tone_input; mod test_tone_input;
#[cfg(test)]
#[path = "test_pcm_output.rs"]
mod test_pcm_output;
const COMMAND_CAPACITY: usize = 64; const COMMAND_CAPACITY: usize = 64;
const PCM_CAPACITY: usize = 32; const PCM_CAPACITY: usize = 32;
const EVENT_CAPACITY: usize = 128; const EVENT_CAPACITY: usize = 128;
@@ -150,6 +154,10 @@ struct Shared {
test_tone_input: AtomicBool, test_tone_input: AtomicBool,
#[cfg(test)] #[cfg(test)]
test_tone_blocks: AtomicU64, test_tone_blocks: AtomicU64,
#[cfg(test)]
test_pcm_output: Mutex<test_pcm_output::Backend>,
#[cfg(test)]
test_pcm_voiced_blocks: AtomicU64,
input_level: AtomicU32, input_level: AtomicU32,
transmission_enabled: AtomicBool, transmission_enabled: AtomicBool,
notification_revision: AtomicU64, notification_revision: AtomicU64,
@@ -163,6 +171,8 @@ impl Shared {
#[cfg(test)] capture_start: Mutex::new(None), #[cfg(test)] capture_start: Mutex::new(None),
#[cfg(test)] test_tone_input: AtomicBool::new(false), #[cfg(test)] test_tone_input: AtomicBool::new(false),
#[cfg(test)] test_tone_blocks: AtomicU64::new(0), #[cfg(test)] test_tone_blocks: AtomicU64::new(0),
#[cfg(test)] test_pcm_output: Mutex::default(),
#[cfg(test)] test_pcm_voiced_blocks: AtomicU64::new(0),
transmission_enabled: AtomicBool::new(false), notification_revision: AtomicU64::new(0) } transmission_enabled: AtomicBool::new(false), notification_revision: AtomicU64::new(0) }
} }
fn revoke(&self) -> u64 { fn revoke(&self) -> u64 {
@@ -245,6 +255,16 @@ impl AudioHandle {
/// Successful synthetic callback writes, cumulative across capture leases. /// Successful synthetic callback writes, cumulative across capture leases.
#[cfg(test)] #[cfg(test)]
pub(crate) fn test_tone_blocks(&self) -> u64 { self.shared.test_tone_blocks.load(Ordering::Acquire) } pub(crate) fn test_tone_blocks(&self) -> u64 { self.shared.test_tone_blocks.load(Ordering::Acquire) }
/// Install before the first output open. Starting voice output still requires explicit permission.
#[cfg(test)]
pub(crate) fn install_test_pcm_output(&self) -> Result<()> {
if self.shared.stop.load(Ordering::Acquire) { return Err(closed()); }
self.shared.test_pcm_output.lock().expect("test playback backend").install()
}
/// Non-silent callbacks on the authorized synthetic voice output, cumulative across leases.
/// Isolate the input to this mix (no streams, private playback, or comfort noise) to prove received voice.
#[cfg(test)]
pub(crate) fn test_pcm_voiced_blocks(&self) -> u64 { self.shared.test_pcm_voiced_blocks.load(Ordering::Acquire) }
/// This synchronous boundary remains effective even when the worker command queue is full. /// This synchronous boundary remains effective even when the worker command queue is full.
pub fn revoke_capture(&self) { self.shared.revoke(); } pub fn revoke_capture(&self) { self.shared.revoke(); }
/// Fresh capture-worker RMS in [0,1], reset synchronously at privacy boundaries. /// Fresh capture-worker RMS in [0,1], reset synchronously at privacy boundaries.
@@ -892,18 +912,23 @@ impl Worker {
let opened = self.lifecycle(move |owner| -> Result<_> { let opened = self.lifecycle(move |owner| -> Result<_> {
let authorize = || shared.check_output_start(revision, stream_revision); let authorize = || shared.check_output_start(revision, stream_revision);
authorize()?; authorize()?;
let selected = owner.host()?.select(Direction::Output, &selection, None, permission)?; let before_play = || {
if known.contains(&selected.id) { return Ok(OpenedOutput::Existing(selected.id)); }
if known.len() == 2 { return Err(ServiceError::new("audio_output_limit", "Voice and notification routes already own two devices")); }
let prepared = PreparedOutput::new(selected.format.sample_rate)?;
authorize()?;
let (stream, port) = devices::start_playback(selected, permission, epoch, || {
authorize()?; authorize()?;
// Change acoustic topology only after successful construction and before play. // Change acoustic topology only after successful construction and before play.
let capture_active = shared.input.lock().expect("audio input state").is_some(); let capture_active = shared.input.lock().expect("audio input state").is_some();
if capture_active { shared.revoke(); } if capture_active { shared.revoke(); }
authorize() authorize()
})?; };
#[cfg(test)]
if shared.test_pcm_output.lock().expect("test playback backend").select_synthetic() {
return test_pcm_output::open(shared.clone(), epoch, voice, before_play);
}
let selected = owner.host()?.select(Direction::Output, &selection, None, permission)?;
if known.contains(&selected.id) { return Ok(OpenedOutput::Existing(selected.id)); }
if known.len() == 2 { return Err(ServiceError::new("audio_output_limit", "Voice and notification routes already own two devices")); }
let prepared = PreparedOutput::new(selected.format.sample_rate)?;
authorize()?;
let (stream, port) = devices::start_playback(selected, permission, epoch, before_play)?;
Ok(OpenedOutput::New(owner.lease(stream), port, prepared)) Ok(OpenedOutput::New(owner.lease(stream), port, prepared))
})??; })??;
self.shared.check_output_start(revision, stream_revision)?; self.shared.check_output_start(revision, stream_revision)?;
+71
View File
@@ -0,0 +1,71 @@
use std::{
sync::{Arc, atomic::Ordering},
thread,
time::Instant,
};
use super::{DeviceLease, OpenedOutput, PreparedOutput, Result, ServiceError, Shared, TICK, devices};
use super::super::resample::{BLOCK_FRAMES, MIX_RATE};
#[derive(Default)]
pub(super) enum Backend {
#[default]
Unselected,
Physical,
Synthetic,
}
impl Backend {
pub(super) fn install(&mut self) -> Result<()> {
if matches!(self, Self::Physical) {
return Err(ServiceError::new("audio_output_active", "Install the synthetic playback backend before opening any output"));
}
*self = Self::Synthetic;
Ok(())
}
pub(super) fn select_synthetic(&mut self) -> bool {
if matches!(self, Self::Unselected) { *self = Self::Physical; }
matches!(self, Self::Synthetic)
}
}
pub(super) fn open(shared: Arc<Shared>, epoch: u64, voice: bool, before_play: impl FnOnce() -> Result<()>) -> Result<OpenedOutput> {
let format = devices::DeviceFormat {
sample_rate: MIX_RATE, channels: 2, sample_format: cpal::SampleFormat::F32, buffer_size: cpal::BufferSize::Default,
};
let prepared = PreparedOutput::new(format.sample_rate)?;
let origin = Instant::now();
let mut lease = DeviceLease::test(format, epoch, origin);
lease.state.suspend();
// Keep notification PCM off the measured output, including voice-follow notifications.
lease.device_id = if voice { "test-pcm-voice" } else { "test-pcm-notification" }.into();
let state = lease.state.clone();
let retired = lease.retirement();
let (port, mut callback) = devices::test_playback(format, state.clone(), origin);
before_play()?;
lease.test_thread = Some(thread::Builder::new().name("teamspeach-test-playback".into()).spawn(move || {
let live = || !retired.load(Ordering::Acquire) && !shared.stop.load(Ordering::Acquire);
let mut data = [0.0_f32; BLOCK_FRAMES * 2];
let mut elapsed_ms = TICK.as_millis() as u64;
let mut due = origin + TICK;
while live() {
let now = Instant::now();
if now < due {
thread::park_timeout(due - now);
continue;
}
// Serialize counting with route revocation; the callback also rejects stale and old-epoch PCM.
let _states = shared.outputs.states.lock().expect("audio output states");
if !live() { break; }
callback(&mut data, elapsed_ms, Instant::now());
if voice && live() && shared.playback_authorized.load(Ordering::Acquire) && state.stats().enabled
&& data.iter().any(|&sample| sample != 0.0) {
shared.test_pcm_voiced_blocks.fetch_add(1, Ordering::Release);
}
elapsed_ms += TICK.as_millis() as u64;
due += TICK;
}
}).map_err(|error| ServiceError::new("audio_worker", error.to_string()))?);
Ok(OpenedOutput::New(lease, port, prepared))
}
+1
View File
@@ -12,6 +12,7 @@ mod focus;
#[cfg(all(test, windows))] mod owned_folder_dialog; #[cfg(all(test, windows))] mod owned_folder_dialog;
#[cfg(all(test, windows))] mod download_folder; #[cfg(all(test, windows))] mod download_folder;
#[cfg(all(test, windows))] mod contact_edit; #[cfg(all(test, windows))] mod contact_edit;
#[cfg(all(test, windows))] mod detached_voice;
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod theme_selection; #[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod theme_selection;
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod channel_commander; #[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod channel_commander;
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod speaker_gain; #[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod speaker_gain;
+290
View File
@@ -0,0 +1,290 @@
//! Real beta14 receive path with a synthetic output device and no Slint window.
use std::{sync::atomic::Ordering, time::{Duration, Instant}};
use serde_json::{Value, json};
use teamspeach_core::{
audio::CapturedFrame,
protocol::{Command, ConnectArgs, FRAME_SAMPLES},
runtime::{self, CoreConfig, CoreEvents, CoreHandle},
};
use tokio::sync::mpsc::error::TryRecvError;
use tokio::time::{sleep, timeout};
use super::SmokeResult;
use crate::{
AppConfig, AppRuntime,
app::{connections::{ConnectionSnapshot, SessionKey}, runtime::{context::RuntimeServices, model::BootstrapState}},
media::audio::{devices::StartPermission, engine::AudioCommand, mixer::PlaybackDsp},
services::{profile::ProfileServices, profile_import::initialize_native_root},
};
const ENDPOINT: &str = "127.0.0.1:19987";
const RECEIVER: &str = "Detached Voice Receiver";
const SENDER: &str = "Detached Voice Sender";
const POLL: Duration = Duration::from_millis(10);
const SETTLE: Duration = Duration::from_secs(5);
const QUIET: Duration = Duration::from_millis(500);
const FRAME: Duration = Duration::from_millis(20);
const MIN_VOICED_BLOCKS: u64 = 3;
#[tokio::test(flavor = "current_thread")]
#[ignore = "requires exclusive use of private beta14 at 127.0.0.1:19987 with guest voice enabled"]
async fn received_voice_reaches_output_after_ui_detach() {
let temp = tempfile::tempdir().expect("create disposable voice profiles");
let receiver_root = temp.path().join("receiver");
initialize_native_root(&receiver_root).expect("initialize disposable receiver profile");
let receiver_identity = {
let mut profile = ProfileServices::open(&receiver_root).expect("open disposable receiver profile");
profile.prefs.set(json!({"notificationDeviceId": "none"})).expect("disable notification audio");
let identity = profile.identities.onboard(RECEIVER).expect("create disposable receiver identity");
identity["uid"].as_str().expect("receiver identity has no UID").to_owned()
};
let (sender, mut events) = runtime::spawn(CoreConfig {
data_dir: temp.path().join("sender"),
connection_dir: temp.path().join("sender-connection"),
}).expect("start isolated sender core");
let app = AppRuntime::start(AppConfig::isolated(receiver_root)).expect("start isolated receiver runtime");
let result = timeout(Duration::from_secs(40), verify(&app, &sender, &mut events, &receiver_identity)).await;
sender.end_audio();
let (sender_stop, receiver_stop) = tokio::join!(
timeout(SETTLE, sender.shutdown()),
timeout(SETTLE, app.shutdown()),
);
sender_stop.expect("sender shutdown timed out").expect("sender shutdown failed");
receiver_stop.expect("receiver shutdown timed out").expect("receiver shutdown failed");
let final_state = app.snapshot();
assert!(!final_state.audio_input_active && !final_state.audio_output_active, "receiver audio still active after shutdown");
assert_eq!(final_state.audio_input_starts, 0, "receiver started a capture device");
drop(app);
temp.close().expect("remove disposable voice profiles");
result.expect("detached voice workflow timed out").unwrap();
}
async fn wait_for(label: &str, mut ready: impl FnMut() -> SmokeResult<bool>) -> SmokeResult<()> {
let deadline = Instant::now() + SETTLE;
loop {
if ready()? { return Ok(()); }
if Instant::now() >= deadline { return Err(format!("timed out waiting for {label}")); }
sleep(POLL).await;
}
}
fn connect(identity: &str) -> Command {
Command::Connect(ConnectArgs {
address: ENDPOINT.into(), identity_id: Some(identity.into()), nickname: None,
channel: None, server_password: None, channel_password: None,
})
}
fn audio(input_muted: bool, output_muted: bool) -> Command {
Command::SetAudio { input_muted: Some(input_muted), output_muted: Some(output_muted) }
}
fn check_mutes(reply: Value, input_muted: bool, output_muted: bool) -> SmokeResult<()> {
if reply["input_muted"] != input_muted || reply["output_muted"] != output_muted || reply["transmitting"] != false {
return Err("guest did not acknowledge the requested mute flags".into());
}
Ok(())
}
fn client_id(reply: &Value) -> SmokeResult<u16> {
reply["own_client_id"].as_u64().and_then(|id| u16::try_from(id).ok()).filter(|id| *id != 0)
.ok_or_else(|| "connected guest has no client ID".into())
}
struct Guest<'a> { id: u16, profile: &'a str, uid: String, name: &'static str }
fn roster(server: &Value, [receiver, sender]: [&Guest<'_>; 2], muted: bool) -> bool {
let Some(channel) = server["own_channel_id"].as_u64().filter(|id| *id != 0) else { return false };
server["server"]["version"].as_str().is_some_and(|v| v.starts_with("6.") && v.contains("beta14"))
&& server["own_client_id"] == receiver.id
&& server["clients"].as_array().is_some_and(|rows| rows.len() == 2
&& [receiver, sender].into_iter().all(|guest| rows.iter().any(|row| {
row["id"] == guest.id && row["uid"] == guest.uid && row["nickname"] == guest.name
&& row["client_type"] == "normal" && row["channel_id"] == channel
&& (!muted || (row["input_muted"] == true && row["output_muted"] == true))
})))
}
struct Trial<'a> {
app: &'a AppRuntime,
owner: &'a RuntimeServices,
sender: &'a CoreHandle,
events: &'a mut CoreEvents,
receiver_key: SessionKey,
receiver_guest: Guest<'a>,
sender_guest: Guest<'a>,
sender_generation: u64,
sender_connected: bool,
sender_transmitting: bool,
}
impl Trial<'_> {
fn receiver_tab<'a>(&self, tabs: &'a crate::app::connections::ConnectionsSnapshot) -> SmokeResult<&'a ConnectionSnapshot> {
tabs.get(&self.receiver_key.connection_id).filter(|tab| {
tab.key == self.receiver_key && tab.is_connected() && tab.address == ENDPOINT
&& tab.identity_id.as_deref() == Some(self.receiver_guest.profile)
}).ok_or_else(|| "receiver session changed during the voice trial".into())
}
fn observe(&mut self, ui: Option<u64>) -> SmokeResult<bool> {
loop {
let event = match self.events.control.try_recv() {
Ok(event) => event,
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => return Err("sender control stream closed".into()),
};
if event["generation"] != self.sender_generation { continue; }
match event["event"].as_str() {
Some("state") => self.sender_connected = event["state"] == "connected"
&& event["identity_id"] == self.sender_guest.profile && event["address"] == ENDPOINT,
Some("audio_state") => self.sender_transmitting = event["transmitting"] == true,
Some("error") => return Err("sender reported a voice-path error".into()),
_ => {}
}
}
if !self.sender_connected || self.sender.connection_generation() != self.sender_generation {
return Err("sender session changed during the voice trial".into());
}
let state = self.app.snapshot();
let tabs = self.owner.connected.connections.snapshot();
let receiver = self.receiver_tab(&tabs)?;
if !receiver.server.as_deref().is_some_and(|server| roster(server, [&self.receiver_guest, &self.sender_guest], false)) {
return Err("the original two guests no longer share the beta14 channel".into());
}
if self.app.current_ui_generation() != ui || state.bootstrap == BootstrapState::Failed
|| !state.audio_output_active || state.audio_output_starts != 1 || state.audio_input_active
|| state.audio_input_starts != 0 || self.owner.microphone_granted.load(Ordering::Acquire)
|| tabs.capture.is_some() || !receiver.audio.input_muted || receiver.audio.output_muted || receiver.audio.transmitting
{
return Err("receiver lost its expected attachment or receive-only audio state".into());
}
Ok(self.sender_transmitting || receiver.talking.contains(&self.sender_guest.id))
}
async fn quiet(&mut self, ui: Option<u64>, label: &str) -> SmokeResult<u64> {
let mut blocks = self.owner.audio.test_pcm_voiced_blocks();
let mut quiet_since = Instant::now();
wait_for(label, || {
let talking = self.observe(ui)?;
let current = self.owner.audio.test_pcm_voiced_blocks();
if talking || current != blocks {
quiet_since = Instant::now();
blocks = current;
}
Ok(quiet_since.elapsed() >= QUIET)
}).await?;
Ok(blocks)
}
async fn burst(&mut self, ui: Option<u64>, hz: f32, baseline: u64, label: &str) -> SmokeResult<()> {
// Integral cycles per 20 ms frame keep the tone phase continuous.
let pcm = std::array::from_fn::<_, FRAME_SAMPLES, _>(|i| {
(12_000.0 * (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin()) as i16
});
let capture_epoch = self.sender.audio_epoch();
for _ in 0..20 {
self.observe(ui)?;
if !self.sender.push_audio(CapturedFrame {
pcm, captured_at: Instant::now(), connection_generation: self.sender_generation,
capture_epoch, whisper: None,
}) { return Err(format!("{label}: sender rejected fresh PCM")); }
sleep(FRAME).await;
}
self.sender.end_audio();
wait_for(label, || {
self.observe(ui)?;
Ok(self.owner.audio.test_pcm_voiced_blocks().saturating_sub(baseline) >= MIN_VOICED_BLOCKS)
}).await
}
}
async fn verify(app: &AppRuntime, sender: &CoreHandle, events: &mut CoreEvents, receiver_identity: &str) -> SmokeResult<()> {
// Use the real attachment token, without creating a window or enabling OS actions.
let ui = app.next_ui_generation();
wait_for("receiver profile and idle tab", || {
let state = app.snapshot();
if state.bootstrap == BootstrapState::Failed { return Err("receiver bootstrap failed".into()); }
Ok(state.settings.loaded && state.connections.get("c1").is_some())
}).await?;
let owner = app.services.lock().unwrap().upgrade().ok_or("receiver runtime closed")?;
owner.audio.install_test_pcm_output().map_err(|err| format!("install test output: {}", err.code))?;
owner.audio.request(AudioCommand::SetPlaybackDsp(PlaybackDsp { comfort_noise: false, ..PlaybackDsp::default() })).await
.map_err(|err| format!("disable output comfort noise: {}", err.code))?;
let sender_profile = sender.request(Command::ProfileCreate { nickname: SENDER.into() }).await
.map_err(|err| format!("create sender profile: {:?}", err.code))?;
let sender_identity = sender_profile["uid"].as_str().filter(|uid| !uid.is_empty() && *uid != receiver_identity)
.ok_or("sender did not create a distinct identity")?;
let manager = &owner.connected.connections;
let idle = manager.key("c1").await.map_err(|_| "get receiver tab")?;
check_mutes(manager.request(&idle, audio(true, true)).await.map_err(|_| "mute idle receiver")?, true, true)?;
check_mutes(sender.request(audio(true, true)).await.map_err(|err| format!("mute idle sender: {:?}", err.code))?, true, true)?;
// As in the download fixture, only these explicit requests use the network;
// the isolated AppConfig keeps updates, asset fetches, and discovery disabled.
let receiver = manager.request(&idle, connect(receiver_identity)).await.map_err(|_| "connect receiver to beta14")?;
let receiver_id = client_id(&receiver)?;
let receiver_key = manager.key(&idle.connection_id).await.map_err(|_| "get connected receiver key")?;
// Both logins use the private server's shared loopback command budget.
sleep(SETTLE).await;
let sender_id = client_id(&sender.request(connect(sender_identity)).await
.map_err(|err| format!("connect sender to beta14: {:?}", err.code))?)?;
if receiver_id == sender_id { return Err("beta14 did not assign distinct client IDs".into()); }
let mut trial = Trial {
app, owner: &owner, sender, events, receiver_key,
receiver_guest: Guest { id: receiver_id, profile: receiver_identity, uid: String::new(), name: RECEIVER },
sender_guest: Guest { id: sender_id, profile: sender_identity, uid: String::new(), name: SENDER },
sender_generation: sender.connection_generation(), sender_connected: false, sender_transmitting: false,
};
let mut sender_roster = Value::Null;
wait_for("two muted guests in the same private beta14 Opus channel", || {
while let Ok(event) = trial.events.control.try_recv() {
if event["generation"] != trial.sender_generation { continue; }
match event["event"].as_str() {
Some("snapshot") => sender_roster = event,
Some("state") => trial.sender_connected = event["state"] == "connected" && event["identity_id"] == sender_identity && event["address"] == ENDPOINT,
Some("error") => return Err("sender reported an error during setup".into()),
_ => (),
}
}
if !trial.sender_connected { return Ok(false); }
for guest in [&mut trial.receiver_guest, &mut trial.sender_guest] {
let uid = sender_roster["clients"].as_array().and_then(|rows| rows.iter().find(|row|row["id"]==guest.id && row["nickname"]==guest.name))
.and_then(|row|row["uid"].as_str()).filter(|uid|!uid.is_empty());
let Some(uid) = uid else {return Ok(false)};
guest.uid.clear();guest.uid.push_str(uid);
}
if trial.receiver_guest.uid == trial.sender_guest.uid || !roster(&sender_roster,[&trial.sender_guest,&trial.receiver_guest],true) {return Ok(false)}
let tabs = manager.snapshot();
let tab = trial.receiver_tab(&tabs)?;
Ok(tab.audio.input_muted && tab.audio.output_muted && !tab.audio.transmitting
&& matches!(tab.joined_channel_codec(), Some("opus_voice" | "opus_music"))
&& tab.server.as_deref().is_some_and(|server| roster(server, [&trial.receiver_guest, &trial.sender_guest], true)))
}).await?;
owner.audio.request(AudioCommand::StartOutput(StartPermission::Granted)).await
.map_err(|err| format!("start synthetic receiver output: {}", err.code))?;
wait_for("only the synthetic receiver output to start", || {
let state = app.snapshot();
Ok(!state.audio_input_active && state.audio_input_starts == 0 && state.audio_output_active && state.audio_output_starts == 1)
}).await?;
check_mutes(manager.request(&trial.receiver_key, audio(true, false)).await.map_err(|_| "unmute receiver wire output")?, true, false)?;
// This core owns no devices. The wire requires both flags open to transmit.
sender.request(Command::SetTransmit { vad: None }).await.map_err(|err| format!("set direct transmission: {:?}", err.code))?;
check_mutes(sender.request(audio(false, false)).await.map_err(|err| format!("unmute sender wire voice: {:?}", err.code))?, false, false)?;
let attached = trial.quiet(Some(ui), "quiet before attached tone").await?;
if attached != 0 { return Err("output rendered non-silent PCM before the first tone".into()); }
trial.burst(Some(ui), 1_000.0, attached, "rendered PCM with UI attached").await?;
let drained = trial.quiet(Some(ui), "attached tone to drain").await?;
let revision = app.snapshot().revision;
app.release_ui(ui);
wait_for("receiver runtime to publish after UI release", || Ok(app.snapshot().revision > revision)).await?;
let detached = trial.quiet(None, "quiet output after UI release").await?;
if detached != drained { return Err("output rendered non-silent PCM after release before a fresh tone".into()); }
trial.burst(None, 1_500.0, detached, "fresh rendered PCM with UI detached").await?;
trial.quiet(None, "detached tone to drain").await?;
Ok(())
}