Compare commits

..

10 commits

Author SHA1 Message Date
RustDesk
96d4da121b
Merge pull request #7 from fufesou/fix/remove-non-exist-test-file
Some checks failed
cpal / clippy-test (push) Failing after 11s
cpal / rustfmt-check (push) Failing after 14s
cpal / cargo-publish (push) Has been skipped
cpal / ubuntu-test (push) Failing after 6s
cpal / linux-check-and-test-armv7 (push) Failing after 9s
cpal / asmjs-wasm32-test (wasm32-unknown-emscripten) (push) Failing after 8s
cpal / wasm32-bindgen-test (wasm32-unknown-unknown) (push) Failing after 14s
cpal / wasm32-wasi-test (wasm32-wasi) (push) Failing after 3s
cpal / android-check (push) Failing after 9s
cpal / android-apk-build (push) Failing after 18s
cpal / wasm-beep-build (push) Failing after 11s
cpal / windows-test (i686) (push) Has been cancelled
cpal / windows-test (x86_64) (push) Has been cancelled
cpal / macos-test (push) Has been cancelled
cpal / ios-build (push) Has been cancelled
fix: remove non exist test mod
2026-09-15 15:34:39 +08:00
fufesou
199c8c7c8b fix: remove non exist test mod
Signed-off-by: fufesou <linlong1266@gmail.com>
2026-09-15 15:21:56 +08:00
RustDesk
1816e3269e
Merge pull request #6 from fufesou/fix/wasapi-stream-cleanup
fix(wasapi): release command events after worker exit
2026-09-15 14:05:50 +08:00
fufesou
5aacdf3983 refact: Remove tests of little value.
Signed-off-by: fufesou <linlong1266@gmail.com>
2026-09-15 13:57:37 +08:00
fufesou
0bf4a78ec5 Explain WASAPI self-join handling and shared event lifetime 2026-09-13 10:30:12 +08:00
fufesou
b8ad274267 Follow upstream WASAPI teardown without stderr diagnostics 2026-09-12 23:16:49 +08:00
fufesou
8aa24a369b docs(wasapi): explain fallible teardown diagnostics 2026-09-12 22:49:41 +08:00
fufesou
949c287769 fix(wasapi): make teardown diagnostic writes fallible
A closed stderr pipe must not interrupt worker joining or event cleanup. Add one isolated native child-process regression that confirms BrokenPipe before exercising worker-exits-first destruction and handle accounting.
2026-09-12 22:32:35 +08:00
fufesou
f967589db3 test(wasapi): keep only native cleanup regressions
Preserve the original import layout and remove synthetic stream fixtures covered by the native lifecycle regressions.
2026-09-12 22:14:56 +08:00
fufesou
a9fae8fac6 fix(wasapi): align worker teardown with upstream lifetime handling
Adapt the self-join check and worker event lifetime from RustAudio/cpal#1187 (dccd6b464dc49267fa214ee168eb2b3c17a1ebf6). Keep shared OwnedHandle ownership so command submission also retains a valid event. Verify callback-thread destruction with a real WASAPI regression.
2026-09-12 22:11:39 +08:00
2 changed files with 22 additions and 182 deletions

View file

@ -4,23 +4,18 @@ use crate::{
BackendSpecificError, Data, InputCallbackInfo, OutputCallbackInfo, PauseStreamError,
PlayStreamError, SampleFormat, StreamError,
};
use std::{
mem,
os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle},
ptr,
sync::mpsc::{channel, Receiver, Sender},
thread::{self, JoinHandle},
};
use std::mem;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::ptr;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use windows::Win32::Foundation;
use windows::Win32::Foundation::WAIT_OBJECT_0;
use windows::Win32::Media::Audio;
use windows::Win32::System::SystemServices;
use windows::Win32::System::Threading;
#[cfg(test)]
#[path = "stream_lifecycle_tests.rs"]
mod lifecycle_tests;
pub struct Stream {
/// The high-priority audio processing thread calling callbacks.
/// Option used for moving out in destructor.
@ -33,7 +28,7 @@ pub struct Stream {
// This event is signalled after a new entry is added to `commands`, so that the `run()`
// method can be notified.
pending_scheduled_event: OwnedHandle,
pending_scheduled_event: Arc<OwnedHandle>,
}
struct RunContext {
@ -45,6 +40,9 @@ struct RunContext {
handles: Vec<Foundation::HANDLE>,
commands: Receiver<Command>,
// Keep the event alive if Stream is dropped inside its own callback.
_pending_scheduled_event: Arc<OwnedHandle>,
}
// Once we start running the eventloop, the RunContext will not be moved.
@ -97,13 +95,15 @@ impl Stream {
Threading::CreateEventA(None, false, false, windows::core::PCSTR(ptr::null()))
}
.expect("cpal: could not create input stream event");
let owned_event = unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) };
let owned_event =
Arc::new(unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) });
let (tx, rx) = channel();
let run_context = RunContext {
handles: vec![pending_scheduled_event, stream_inner.event],
stream: stream_inner,
commands: rx,
_pending_scheduled_event: Arc::clone(&owned_event),
};
let thread = thread::Builder::new()
@ -131,13 +131,15 @@ impl Stream {
Threading::CreateEventA(None, false, false, windows::core::PCSTR(ptr::null()))
}
.expect("cpal: could not create output stream event");
let owned_event = unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) };
let owned_event =
Arc::new(unsafe { OwnedHandle::from_raw_handle(pending_scheduled_event.0 as _) });
let (tx, rx) = channel();
let run_context = RunContext {
handles: vec![pending_scheduled_event, stream_inner.event],
stream: stream_inner,
commands: rx,
_pending_scheduled_event: Arc::clone(&owned_event),
};
let thread = thread::Builder::new()
@ -169,12 +171,13 @@ impl Stream {
impl Drop for Stream {
#[inline]
fn drop(&mut self) {
if let Err(error) = self.push_command(Command::Terminate) {
eprintln!("cpal: WASAPI termination notification failed: {error}");
}
let _ = self.push_command(Command::Terminate);
if let Some(thread) = self.thread.take() {
if thread.join().is_err() {
eprintln!("cpal: WASAPI worker panicked during stream processing");
// Prevent self-join: Terminate was sent; the thread exits after the current callback
// returns. Shared event ownership keeps the handle alive until both Stream and
// RunContext release it.
if thread.thread().id() != thread::current().id() {
let _ = thread.join();
}
}
}

View file

@ -1,163 +0,0 @@
use super::*;
use crate::traits::{DeviceTrait, HostTrait};
use std::{
ffi::CString,
time::{Duration, Instant},
};
const WORKER_DEADLINE: Duration = Duration::from_secs(2);
#[derive(Debug)]
enum WorkerExit {
Termination,
Finished,
Panicked,
}
fn stream(exit: WorkerExit) -> (Stream, CString) {
let name = CString::new(format!(
"Local\\cpal-lifecycle-{}-{exit:?}",
std::process::id()
))
.unwrap();
let event = unsafe {
Threading::CreateEventA(None, false, false, windows::core::PCSTR(name.as_ptr() as _))
}
.unwrap();
let (tx, rx) = channel();
let wait_for_exit = !matches!(exit, WorkerExit::Termination);
let worker = thread::spawn(move || match exit {
WorkerExit::Termination => assert!(matches!(rx.recv().unwrap(), Command::Terminate)),
WorkerExit::Finished => drop(rx),
WorkerExit::Panicked => {
drop(rx);
panic!("Injected worker failure");
}
});
if wait_for_exit {
let deadline = Instant::now() + WORKER_DEADLINE;
while !worker.is_finished() {
assert!(Instant::now() < deadline, "Worker failed to exit");
thread::yield_now();
}
}
let owned_event = unsafe { OwnedHandle::from_raw_handle(event.0 as _) };
(
Stream {
thread: Some(worker),
commands: tx,
pending_scheduled_event: owned_event,
},
name,
)
}
fn assert_event_closed(exit: WorkerExit) {
let (stream, name) = stream(exit);
drop(stream);
// Another test can reuse a closed handle value; check the event's identity instead.
match unsafe {
Threading::OpenEventA(
Threading::EVENT_MODIFY_STATE,
false,
windows::core::PCSTR(name.as_ptr() as _),
)
} {
Ok(event) => {
let _event = unsafe { OwnedHandle::from_raw_handle(event.0 as _) };
panic!("Stream destruction leaked its command event");
}
Err(error) => assert_eq!(
error.code(),
windows::core::HRESULT::from_win32(Foundation::ERROR_FILE_NOT_FOUND.0),
),
}
}
#[test]
fn normal_shutdown_closes_command_event() {
assert_event_closed(WorkerExit::Termination);
}
#[test]
fn completed_worker_still_closes_command_event() {
assert_event_closed(WorkerExit::Finished);
}
#[test]
fn panicked_worker_does_not_panic_in_drop_or_leak_event() {
assert_event_closed(WorkerExit::Panicked);
}
const WARMUP_CYCLES: usize = 4;
const MEASURED_CYCLES: usize = 16;
const CALLBACK_TIMEOUT: Duration = Duration::from_secs(3);
const POLL_INTERVAL: Duration = Duration::from_millis(10);
const SETTLE_TIME: Duration = Duration::from_millis(100);
fn handle_count() -> u32 {
let mut count = 0;
unsafe { Threading::GetProcessHandleCount(Threading::GetCurrentProcess(), &mut count) }
.unwrap();
count
}
fn native_cycle(worker_exits_first: bool) {
let host = crate::default_host();
let device = host.default_output_device().unwrap();
let supported = device.default_output_config().unwrap();
assert_eq!(supported.sample_format(), SampleFormat::F32);
let (tx, rx) = channel();
let output = device
.build_output_stream(
&supported.into(),
move |data: &mut [f32], _| {
data.fill(0.0);
tx.send(()).unwrap();
// Test-only fault injection exits the real WASAPI worker before Drop.
assert!(!worker_exits_first, "Injected native worker exit");
},
|error| eprintln!("Native callback error: {error}"),
None,
)
.unwrap();
output.play().unwrap();
rx.recv_timeout(CALLBACK_TIMEOUT).unwrap();
if worker_exits_first {
let deadline = Instant::now() + CALLBACK_TIMEOUT;
while output.play().is_ok() {
assert!(Instant::now() < deadline, "Worker receiver did not close");
thread::sleep(POLL_INTERVAL);
}
}
drop(output);
thread::sleep(SETTLE_TIME);
}
fn measured_cycles(worker_exits_first: bool) -> Vec<u32> {
let mut counts = vec![handle_count()];
for _ in 0..MEASURED_CYCLES {
native_cycle(worker_exits_first);
counts.push(handle_count());
}
counts
}
#[test]
#[ignore = "Requires a native F32 output device; run alone with a 60-second process deadline"]
fn native_worker_exit_does_not_leak_process_handles() {
for _ in 0..WARMUP_CYCLES {
native_cycle(false);
}
let normal_before = measured_cycles(false);
let exited_first = measured_cycles(true);
let normal_after = measured_cycles(false);
eprintln!("normal_before={normal_before:?} worker_exits_first={exited_first:?} normal_after={normal_after:?}");
assert_eq!(normal_before.first(), normal_before.last());
assert_eq!(normal_after.first(), normal_after.last());
assert_eq!(
exited_first.first(),
exited_first.last(),
"Worker-exit-before-drop leaked native process handles"
);
}