Skip to content

Commit bf670df

Browse files
committed
Clean up audio clips of not downloaded songs after fading out
1 parent f3070d9 commit bf670df

File tree

1 file changed

+36
-28
lines changed

1 file changed

+36
-28
lines changed

src/UI/ViewControllers/SongList.cpp

Lines changed: 36 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
#include "PluginConfig.hpp"
3434
#include "songcore/shared/SongCore.hpp"
3535
#include "songcore/shared/SongLoader/RuntimeSongLoader.hpp"
36+
#include "System/Action.hpp"
3637
#include "System/Nullable_1.hpp"
3738
#include "UI/FlowCoordinators/BetterSongSearchFlowCoordinator.hpp"
3839
#include "UI/Manager.hpp"
@@ -691,36 +692,43 @@ void ViewControllers::SongListController::UpdateDetails() {
691692
return;
692693
}
693694

694-
auto ssp = songPreviewPlayer;
695-
696695
std::string newUrl = fmt::format("{}/{}.mp3", BeatSaverRegionManager::coverDownloadUrl, toLower(song->hash()));
697696

698-
coro(GetPreview(newUrl, [ssp](UnityW<UnityEngine::AudioClip> clip) {
699-
if (!clip) {
700-
return;
701-
}
702-
// TODO: Fix audio clip cleanup for non downloaded songs (this is a memory leak)
703-
// This does not compile and is possibly very unsafe
704-
// {
705-
// auto clipPtr = clip.ptr();
706-
707-
// // Audio clip fade out
708-
// std::function<void()> onFadeOutLambda = [clipPtr]() {
709-
// DEBUG("Crossfade to song preview, clearing the clip");
710-
// try {
711-
// if (clipPtr != nullptr && clipPtr->m_CachedPtr.m_value != nullptr) {
712-
// UnityEngine::Object::Destroy(clipPtr);
713-
// }
714-
// } catch (...) {
715-
// ERROR("Error destroying clip: {}");
716-
// }
717-
// };
718-
// auto onFadeOut = BSML::MakeDelegate<System::Action*>(onFadeOutLambda);
719-
720-
// ssp->CrossfadeTo(clip, -5, 0, clip->get_length(), onFadeOut);
721-
// }
722-
ssp->CrossfadeTo(clip, -5, 0, clip->get_length(), nullptr);
723-
}));
697+
coro(GetPreview(
698+
newUrl,
699+
700+
std::function<void(UnityW<UnityEngine::AudioClip>)>([this, song](UnityW<UnityEngine::AudioClip> clip) {
701+
if (!clip) {
702+
return;
703+
}
704+
// Get current song
705+
auto currentSong = GetCurrentSong();
706+
// Return if the song has changed somehow
707+
if (currentSong == nullptr) {
708+
UnityEngine::Object::Destroy(clip);
709+
return;
710+
}
711+
if (song->hash() != currentSong->hash()) {
712+
DEBUG("Song hash changed, returning");
713+
UnityEngine::Object::Destroy(clip);
714+
return;
715+
}
716+
717+
// Audio clip cleanup
718+
std::function<void()> onFadeOutLambda = [clip]() {
719+
try {
720+
if (clip) {
721+
UnityEngine::Object::Destroy(clip);
722+
}
723+
} catch (...) {
724+
ERROR("Error destroying clip");
725+
}
726+
};
727+
auto onFadeOut = BSML::MakeDelegate<System::Action*>(onFadeOutLambda);
728+
729+
songPreviewPlayer->CrossfadeTo(clip, -5, 0, clip->get_length(), onFadeOut);
730+
})
731+
));
724732
}
725733
}
726734

0 commit comments

Comments
 (0)