From 6ed426614a7b1b2968c169c9e11166c0f86fa08a Mon Sep 17 00:00:00 2001 From: Dickless <37750743+Dicklessgreat@users.noreply.github.com> Date: Wed, 15 Mar 2023 23:10:38 +0900 Subject: [PATCH] Fixed wasapi thread panics involving the main(or other) thread(when Stream drops). (#756) when main(or other) thread(s) try to drop the Stream object, they would panic at host/wasapi/stream.rs Stream::drop() if the wasapi thread is dead. this occurs when the user wants to do something after all the cpal objects have been dropped. --- src/host/wasapi/stream.rs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/host/wasapi/stream.rs b/src/host/wasapi/stream.rs index c775114..5a04695 100644 --- a/src/host/wasapi/stream.rs +++ b/src/host/wasapi/stream.rs @@ -6,7 +6,7 @@ use crate::{ }; use std::mem; use std::ptr; -use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::mpsc::{channel, Receiver, SendError, Sender}; use std::thread::{self, JoinHandle}; use windows::Win32::Foundation; use windows::Win32::Foundation::WAIT_OBJECT_0; @@ -147,34 +147,37 @@ impl Stream { } #[inline] - fn push_command(&self, command: Command) { - // Sender generally outlives receiver, unless the device gets unplugged. - let _ = self.commands.send(command); + fn push_command(&self, command: Command) -> Result<(), SendError> { + self.commands.send(command)?; unsafe { let result = Threading::SetEvent(self.pending_scheduled_event); assert_ne!(result, false); } + Ok(()) } } impl Drop for Stream { #[inline] fn drop(&mut self) { - self.push_command(Command::Terminate); - self.thread.take().unwrap().join().unwrap(); - unsafe { - Foundation::CloseHandle(self.pending_scheduled_event); + if let Ok(_) = self.push_command(Command::Terminate) { + self.thread.take().unwrap().join().unwrap(); + unsafe { + Foundation::CloseHandle(self.pending_scheduled_event); + } } } } impl StreamTrait for Stream { fn play(&self) -> Result<(), PlayStreamError> { - self.push_command(Command::PlayStream); + self.push_command(Command::PlayStream) + .map_err(|_| crate::error::PlayStreamError::DeviceNotAvailable)?; Ok(()) } fn pause(&self) -> Result<(), PauseStreamError> { - self.push_command(Command::PauseStream); + self.push_command(Command::PauseStream) + .map_err(|_| crate::error::PauseStreamError::DeviceNotAvailable)?; Ok(()) } }