RandyGaul / cute_headers

Collection of cross-platform one-file C/C++ libraries with no dependencies, primarily used for games
4.28k stars 267 forks source link

[cute_sound] Error when freeing a sound that is playing even after stopping it #328

Closed roig closed 1 year ago

roig commented 1 year ago

When I'm closing my application and I free my cs_audio_source that is currently playing I receive an error that can't free it if it's playing. That's good.

But how you can really stop it playing? I'm doing this to force cute_sound to release the current playing cs_sound_source:

  log.trace("Sound component free", .{}, @src());
  _ = cute_sound.cs_music_stop(0);
  _ = cute_sound.cs_update(0);
  const err = cute_sound.cs_free_audio_source(source_ptr);
  if (err != 0) {
      log.warning("Error freeing cute_sound audio source with error: {}", .{err}, @src());
  }

But I'm getting the same error that you can't free it because is currently playing. (But I have stopped it :D)

RandyGaul commented 1 year ago

The core issue is that the mixing thread has a linked list of playing sound instances, of which reference your audio. I can change this behavior to e.g. queue up the destruction of the audio in-memory and let cute_sound figure out when the reference count hits zero.

But, if you set a sound active to false with cs_sound_is_active, or cs_music_stop(0) the playing instance will immediately stop playing, despite the audio source (the audio samples in memory) still hanging around in memory. They have to hang around in memory at least until the audio source reference count hits zero.

Ultimately the quirk you saw is a thread sync'ing thing that's getting leaked through the abstraction. I'm sort of thinking this through myself, but queue'ing up delayed destruction of the audio source seems like a great solution.

RandyGaul commented 1 year ago

Fixed https://github.com/RandyGaul/cute_headers/commit/2a23339c72335b44e4f49e61bc904d30c96ddc78