tesselode / kira

Library for expressive game audio.
https://crates.io/crates/kira
Apache License 2.0
836 stars 42 forks source link

Possible memory leak? #82

Closed Icemic closed 2 months ago

Icemic commented 2 months ago

I found that loaded audio resources will not be released after it stops, here is a quick example:

use anyhow::Result;
use kira::{
    manager::{backend::DefaultBackend, AudioManager, AudioManagerSettings},
    sound::static_sound::{StaticSoundData, StaticSoundSettings},
    tween::Tween,
};

fn main() {
    play().unwrap();
}

fn play() -> Result<()> {
    // Create an audio manager. This plays sounds and manages resources.
    let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;

    let path = std::env::current_dir()
        .unwrap()
        .join("assets/audio/test.ogg");

    let file = std::fs::File::open(path)?;

    let sound_data = StaticSoundData::from_media_source(file, StaticSoundSettings::new())?;

    let mut handle = manager.play(sound_data)?;

    let mut i = 0;

    loop {
        std::thread::sleep(std::time::Duration::from_secs(1));
        i += 1;

        if i == 10 {
            handle.stop(Tween::default())?;
        }
    }
}

The music will play for 10 seconds and then stop, seeing that no memory usage drop in task manager.

I think it is just because a missing implement of removing it here: https://github.com/tesselode/kira/blob/4c047c3cc60d4f778416e09bc910960d1b482cba/crates/kira/src/manager/backend/resources/sounds.rs#L35-L48

Stopped sound is moved to unused_sound_producer but no next steps, while simply comment out line 40~45 will fix the problem.

Not sure if the problem exist in other backends or wasm.

tesselode commented 2 months ago

Hello!

All finished sounds are unloaded whenever you play a new sound - you can see the code that does that here:

https://github.com/tesselode/kira/blob/4c047c3cc60d4f778416e09bc910960d1b482cba/crates/kira/src/manager.rs#L162-L169

Other resources work this way as well.

While removing the lines you mentioned would cause sounds to be unloaded as soon as they finish, it would also mean memory is deallocated on the audio thread, which in rare causes could cause undesirable audio stutters. So this mechanism of sending finished sounds through an SPSC to the gameplay thread to be deallocated later is intentional.