From 615eab0701a61441a8adf14d06203405f56cb8ba Mon Sep 17 00:00:00 2001 From: Jonatino Date: Sun, 25 Oct 2026 01:44:14 -0400 Subject: [PATCH] Stop a streaming sound's decode thread when the sound is dropped The decode scheduler's thread only ends once the sound is stopped or reaches its end. A sound refused by the sound limit, or dropped with the audio manager while playing, is never stopped, so its thread waited on a full frame buffer forever, waking every millisecond. Each refused play leaked one thread. --- crates/kira/src/sound/streaming/sound.rs | 11 +++++++++++ crates/kira/src/sound/streaming/sound/test.rs | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/crates/kira/src/sound/streaming/sound.rs b/crates/kira/src/sound/streaming/sound.rs index 966abf19..8fc09430 100644 --- a/crates/kira/src/sound/streaming/sound.rs +++ b/crates/kira/src/sound/streaming/sound.rs @@ -204,6 +204,17 @@ impl StreamingSound { } } +impl Drop for StreamingSound { + fn drop(&mut self) { + // the decode scheduler's thread only ends once the sound is stopped or + // reaches its end. a sound can be dropped without either happening, for + // example when it's refused because the sound limit was reached, or when + // the audio manager is dropped while it's playing, so mark it stopped here + // to end the thread. + self.shared.set_state(PlaybackState::Stopped); + } +} + impl Sound for StreamingSound { fn on_start_processing(&mut self) { self.update_current_frame(); diff --git a/crates/kira/src/sound/streaming/sound/test.rs b/crates/kira/src/sound/streaming/sound/test.rs index 44254919..8eefe8bd 100644 --- a/crates/kira/src/sound/streaming/sound/test.rs +++ b/crates/kira/src/sound/streaming/sound/test.rs @@ -56,6 +56,22 @@ fn plays_all_samples() { ); } +/// Tests that dropping a `StreamingSound` that was never stopped ends its +/// decode scheduler, as happens when the sound limit refuses the sound or the +/// audio manager is dropped while it's playing. +#[test] +fn dropping_sound_ends_decode_scheduler() { + let data = StreamingSoundData { + decoder: Box::new(MockDecoder::new(vec![Frame::from_mono(1.0); 100])), + settings: StreamingSoundSettings::new(), + slice: None, + }; + let (sound, _, mut scheduler) = data.split().unwrap(); + assert!(matches!(scheduler.run().unwrap(), NextStep::Continue)); + drop(sound); + assert!(matches!(scheduler.run().unwrap(), NextStep::End)); +} + /// Tests that a `StreamingSound` will pause playback while waiting /// for samples from the decoder. #[test]