From 0616a948efbab95d1820443aad82e55f0540db1b Mon Sep 17 00:00:00 2001 From: yangchao <1162485779@qq.com> Date: Thu, 24 Sep 2026 11:25:09 +0800 Subject: [PATCH] =?UTF-8?q?fix(audio):=20iterator=20invalidation=E3=80=81e?= =?UTF-8?q?xit=20crash=20issue=E3=80=82=20(#360)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(audio): iterator invalidation when call stopall in finish callback * fix(audio): prevent callback crashes and cache teardown hangs on Apple platforms --------- Co-authored-by: yangchao <1162486779@qq.com> --- native/cocos/audio/apple/AudioCache.h | 13 ++++--- native/cocos/audio/apple/AudioCache.mm | 36 +++++++++++-------- native/cocos/audio/apple/AudioEngine-inl.mm | 8 +++++ .../cocos/audio/oalsoft/AudioEngine-soft.cpp | 12 ++++++- 4 files changed, 50 insertions(+), 19 deletions(-) diff --git a/native/cocos/audio/apple/AudioCache.h b/native/cocos/audio/apple/AudioCache.h index a2d3fd9aeb..80cdba85fe 100644 --- a/native/cocos/audio/apple/AudioCache.h +++ b/native/cocos/audio/apple/AudioCache.h @@ -27,7 +27,9 @@ #import +#include #include +#include #include #include "base/std/container/string.h" @@ -40,6 +42,7 @@ namespace cc { class AudioEngineImpl; class AudioPlayer; +class Scheduler; class AudioCache { public: @@ -96,13 +99,15 @@ protected: std::mutex _readDataTaskMutex; - State _state{State::INITIAL}; + std::atomic _state{State::INITIAL}; - std::shared_ptr _isDestroyed; + // Assigned before the read task is submitted; workers must not look up the current application. + std::weak_ptr _scheduler; + std::shared_ptr _isDestroyed; ccstd::string _fileFullPath; unsigned int _id; - bool _isLoadingFinished{false}; - bool _isSkipReadDataTask{false}; + std::atomic_bool _isLoadingFinished{false}; + std::atomic_bool _isSkipReadDataTask{false}; friend class AudioEngineImpl; friend class AudioPlayer; diff --git a/native/cocos/audio/apple/AudioCache.mm b/native/cocos/audio/apple/AudioCache.mm index 9f594410c7..e60ee8584f 100644 --- a/native/cocos/audio/apple/AudioCache.mm +++ b/native/cocos/audio/apple/AudioCache.mm @@ -31,7 +31,6 @@ #import #import #include -#include "application/ApplicationManager.h" #include "base/Scheduler.h" #include "base/memory/Memory.h" @@ -85,7 +84,7 @@ unsigned int __idIndex = 0; using namespace cc; AudioCache::AudioCache() -: _isDestroyed(std::make_shared(false)), _id(++__idIndex){ +: _isDestroyed(std::make_shared(false)), _id(++__idIndex){ ALOGVV("AudioCache() %p, id=%u", this, _id); for (int i = 0; i < QUEUEBUFFER_NUM; ++i) { _queBuffers[i] = nullptr; @@ -114,7 +113,7 @@ AudioCache::~AudioCache() { _alBufferId = INVALID_AL_BUFFER_ID; } } else { - ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, _state); + ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, static_cast(_state.load())); } if (_queBufferFrames > 0) { @@ -267,7 +266,6 @@ void AudioCache::readDataTask(unsigned int selfId) { invokingPlayCallbacks(); invokingLoadCallbacks(); - _isLoadingFinished = true; if (_state != State::READY) { _state = State::FAILED; if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId)) { @@ -277,12 +275,13 @@ void AudioCache::readDataTask(unsigned int selfId) { } } + _isLoadingFinished = true; _readDataTaskMutex.unlock(); } void AudioCache::addPlayCallback(const std::function &callback) { std::lock_guard lk(_playCallbackMutex); - switch (_state) { + switch (_state.load()) { case State::INITIAL: case State::LOADING: _playCallbacks.push_back(callback); @@ -296,7 +295,7 @@ void AudioCache::addPlayCallback(const std::function &callback) { break; default: - ALOGE("Invalid state: %d", _state); + ALOGE("Invalid state: %d", static_cast(_state.load())); break; } } @@ -312,7 +311,7 @@ void AudioCache::invokingPlayCallbacks() { } void AudioCache::addLoadCallback(const std::function &callback) { - switch (_state) { + switch (_state.load()) { case State::INITIAL: case State::LOADING: _loadCallbacks.push_back(callback); @@ -326,7 +325,7 @@ void AudioCache::addLoadCallback(const std::function &callback) { break; default: - ALOGE("Invalid state: %d", _state); + ALOGE("Invalid state: %d", static_cast(_state.load())); break; } } @@ -337,18 +336,27 @@ void AudioCache::invokingLoadCallbacks() { return; } + auto scheduler = _scheduler.lock(); + if (!scheduler) { + return; + } + auto isDestroyed = _isDestroyed; - auto scheduler = CC_CURRENT_ENGINE()->getScheduler(); - scheduler->performFunctionInCocosThread([&, isDestroyed]() { + const bool isReady = _state.load() == State::READY; + scheduler->performFunctionInCocosThread([this, isDestroyed, isReady]() { if (*isDestroyed) { ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this); return; } - for (auto &&cb : _loadCallbacks) { - cb(_state == State::READY); + // A callback may uncache this file or end the audio engine. Do not access the + // cache again after invoking user code, and cancel any remaining callbacks. + auto callbacks = std::move(_loadCallbacks); + for (auto &&cb : callbacks) { + if (*isDestroyed) { + break; + } + cb(isReady); } - - _loadCallbacks.clear(); }); } diff --git a/native/cocos/audio/apple/AudioEngine-inl.mm b/native/cocos/audio/apple/AudioEngine-inl.mm index 159f3dccf5..eb01a579bd 100644 --- a/native/cocos/audio/apple/AudioEngine-inl.mm +++ b/native/cocos/audio/apple/AudioEngine-inl.mm @@ -167,6 +167,13 @@ AudioEngineImpl::~AudioEngineImpl() { sche->unschedule("AudioEngine", this); } + // AudioEngine::end() has joined the worker pool before deleting this backend. + // Queued tasks are discarded by the pool, so their caches will never receive + // a read/skip notification from a worker. Unblock those cache destructors. + for (auto &entry : _audioCaches) { + entry.second.setSkipReadDataTask(true); + } + if (s_ALContext) { alDeleteSources(MAX_AUDIOINSTANCES, _alSources); @@ -286,6 +293,7 @@ AudioCache *AudioEngineImpl::preload(const ccstd::string &filePath, std::functio auto it = _audioCaches.find(filePath); if (it == _audioCaches.end()) { audioCache = &_audioCaches[filePath]; + audioCache->_scheduler = _scheduler; audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); unsigned int cacheId = audioCache->_id; auto isCacheDestroyed = audioCache->_isDestroyed; diff --git a/native/cocos/audio/oalsoft/AudioEngine-soft.cpp b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp index d1d1b9868d..ba598ba5d7 100644 --- a/native/cocos/audio/oalsoft/AudioEngine-soft.cpp +++ b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include "audio/common/decoder/AudioDecoder.h" #include "base/Log.h" #include "base/Utils.h" @@ -500,6 +501,7 @@ void AudioEngineImpl::setFinishCallback(int audioID, const std::function> finishCallbacks; ALint sourceState; int audioID; AudioPlayer *player; @@ -534,7 +536,9 @@ void AudioEngineImpl::update(float /*dt*/) { _threadMutex.unlock(); if (player->_finishCallbak) { - player->_finishCallbak(audioID, filePath); //IDEA: callback will delay 50ms + finishCallbacks.emplace_back([callback = std::move(player->_finishCallbak), audioID, filePath]() { + callback(audioID, filePath); + }); } delete player; _alSourceUsed[alSource] = false; @@ -549,6 +553,12 @@ void AudioEngineImpl::update(float /*dt*/) { sche->unschedule("AudioEngine", this); } } + + // Callbacks may play/stop audio or destroy the engine. Finish all access to + // player state before invoking them, and keep the callbacks in local storage. + for (const auto &callback : finishCallbacks) { + callback(); + } } void AudioEngineImpl::uncache(const ccstd::string &filePath) {