1- use crate :: context:: AudioNodeId ;
1+ use crate :: context:: { AudioContextState , AudioNodeId } ;
22use crate :: { AudioBuffer , AudioRenderCapacityEvent } ;
33
44use std:: any:: Any ;
@@ -55,6 +55,7 @@ pub(crate) enum EventPayload {
5555 ProcessorError ( ErrorEvent ) ,
5656 Diagnostics ( Vec < u8 > ) ,
5757 Message ( Box < dyn Any + Send + ' static > ) ,
58+ AudioContextState ( AudioContextState ) ,
5859}
5960
6061#[ derive( Debug ) ]
@@ -78,10 +79,10 @@ impl EventDispatch {
7879 }
7980 }
8081
81- pub fn state_change ( ) -> Self {
82+ pub fn state_change ( state : AudioContextState ) -> Self {
8283 EventDispatch {
8384 type_ : EventType :: StateChange ,
84- payload : EventPayload :: None ,
85+ payload : EventPayload :: AudioContextState ( state ) ,
8586 }
8687 }
8788
@@ -130,11 +131,22 @@ impl EventLoop {
130131 }
131132
132133 pub fn run ( & self , event_channel : Receiver < EventDispatch > ) {
134+ log:: debug!( "Entering event loop" ) ;
133135 let self_clone = self . clone ( ) ;
134136
135- std:: thread:: spawn ( move || loop {
136- // this thread is dedicated to event handling so we can block
137- for event in event_channel. iter ( ) {
137+ std:: thread:: spawn ( move || {
138+ // This thread is dedicated to event handling so we can block
139+ for mut event in event_channel. iter ( ) {
140+ // Terminate the event loop when the audio context is closing
141+ let mut terminate = false ;
142+ if matches ! (
143+ event. payload,
144+ EventPayload :: AudioContextState ( AudioContextState :: Closed )
145+ ) {
146+ event. payload = EventPayload :: None ; // the statechange handler takes no argument
147+ terminate = true ;
148+ }
149+
138150 let mut event_handler_lock = self_clone. event_handlers . lock ( ) . unwrap ( ) ;
139151 let callback_option = event_handler_lock. remove ( & event. type_ ) ;
140152 drop ( event_handler_lock) ; // release Mutex while running callback
@@ -152,7 +164,13 @@ impl EventLoop {
152164 }
153165 } ;
154166 }
167+
168+ if terminate {
169+ break ;
170+ }
155171 }
172+
173+ log:: debug!( "Event loop has terminated" ) ;
156174 } ) ;
157175 }
158176
0 commit comments