[big refactoring] Audio latency fix for Android. Support to preload effects on Android now. (#15875)
* Audio latency fix for Android. Support preload effects on Android now.
Squashed commits:
[b6d80fe] log fix
[a0a918e] Fixes assetFd didn't be released while PcmData is returned from cache.
[4b956ba] Potential crash fix for PcmAudioPlayer while pause / resume.
[398ab8c] Updates LOG_TAG position in AudioEngine-inl.cpp
[e3634e7] include stdlib.h for posix_memalign
[9004074] fixes setVolume logical error.
[c96df46] Don't use another thread for mixing, enqueue is in a seperated thread, therefore doing mixing in another thread will waste more time.
[0a4c1a8] Adds setLoop, setVolume, setPostion support for Track
[c35fb20] Fixed include.
[cdd9d32] Do mixing by ourself. (TO BE POLISHED)
[6447025] µ -> u since µ could not be shown on some android devices.
[97be0c6] Don't send a silence clip.
[c1607ed] Make linter.py happy.
[0898b54] Puts enqueue & SetPlayState in PcmAudioPlayer::play to thread pool.
[b79fc01] Adds getDuration, getPosition support for PcmAudioPlayer
[80fa2ab] minor fix of the code position of resetting state to State::INITIALIZED
[d9c62f1] underrun fix for PcmAudioPlayer.
[9c2212a] UrlAudioPlayer, playOverMutex should be static, and should be used in update method.
[1519d2e] static variables
[19da936] _pcmAudioPlayer Null pointer check in AudioPlayerProvider.
[e6b0d14] Updates audio performance test.
[fc01dd4] Registers foreground & background event in AudioEngine-inl.cpp(android), the callback should invoke `provider`'s pause & resume method.
[e00a886] TBD: Pause & resume support for PcmAudioPlayerPool.
Since OpenSLES audio resources are expensive and device shared, we should delete all unused PcmAudioPlayers in pool while pause and re-create them while resume.
But this commit isn't finished yet, I don't find a better way to register pause&resume event in AudioEngine module.
[9e42ea3] Interleave mono audio to stereo audio. PcmAudioPlayerPool only contains PcmAudioPlayers with 2 channels.
[3f18d05] Adds a strategy for checking small size of different file formats.
[753ff49] Adds performance test for AudioEngine.
[09d3045] Releases an extra PcmAudioPlayer for UrlAudioPlayer while allocating PcmAudioPlayer fails.
[9dd4477] Using std::move for PcmData move constructor & move assignment.
[6ca3bcb] some fixes:
1) new -> new (std::nothrow)
2) break if allocate PcmAudioPlayer fails
3) renames 'initForPlayPcmData' to 'init'
4) PcmAudioPlayer destructor deadlock if 'init' failed
[54675b6] include path fix.
[a1903ca] More refactorings.
[19b9498] Makes linter.py happy. :)
[923c530] Fixes:
1) Avoid getFileInfo to be invoked twice
2) A critical bug fix for UrlAudioPlayer and adds detailed comments
3) __clang__ compiler option fix for AudioResamplerSinc.cpp.
[5ec4faf] minor fix.
[faaa0f3] output a log in the destructor of UrlAudioPlayer.
[9c20355] NewAudioEngineTest,TestControll crash fix.
[f114464] fixes an unused import.
[1dc5dab] Better algorithm for allocating PcmAudioPlayer.
[331a213] minor fix.
[e54084a] null -> nullptr
[f9a0389] Support uncache.
[89a364f] Removes unused update, and TODO uncache functionality.
[1732bf9] Supports AudioEngineImpl::setFinishCallback for android.
[43d1596] UrlAudioPlayer::stop fix.
[e2ee941] Test case fix in NewAudioEngineTest/AudioIssue11143Test
[5c5ba01] More fixes for making cpp-tests/New Audio Engine Test happy.
[8b554a3] Adds log while remove player from map.
[ed71322] If original file is larger than 30k bytes, consider it's a large audio file.
[fb1845a] Updates project.properties
[6f3839f] minor log output fix in AudioEngine-inl.cpp
[c68bc6c] Don't resample if the sample rate of the decoded pcm data matchs the device's.
[43ca45f] PcmAudioPlayers also need to be removed while they play over, but should not be deleted since their lifecycle is managed by PcmAudioPlayerPool.
[f5e63c9] Audio latency fix for Android. Support preload effects on Android now.
* Supports to loading audio files asynchronously.
* Crash fix for stop audio right after play2d.
* Minor fix for logic in AudioMixerController.cpp
* Adds missing files (CCThreadPool.h/.cpp).
* Minor fix for including.
* Minor fix for missing include <functional> in Track.h
* update license information in audio.h
* Don't use std::future/std::promise anymore since ndk counldn't support it well in armeabi arch.
* isSmallFile postion updated, fixes large audio file goto the checking logic of cache.
* std::atomic<int> isn't supported by ndk-r10e while compiling with `armeabi` arch, using a int with a mutex instead.
* fixes __isnanf & posix_memalign doesn't exist on low api (<=16) devices.
* namespace updated: cocos2d -> cocos2d::experimental
* Removes commented code in AudioMixerController.h/.cpp
* Removes unused code again, and fixes a memory leak of `Track` instance.
* Oops, namespace changed.
* Only outputs log in debug mode.
* Uses ALOGV for outputing logs in AudioEngine-inl.cpp
* const PcmData& -> PcmData for Track
* Fixes a protential crash in NewAudioEngineTest
* Adds `COCOS` prefix in header #ifndef COCOS_BALABALA #define COCOS_BALABALA
* Uses _ prefix for cocos code style instead of `m` prefix.
* Deletes AudioResamplerSinc related files.
* Bug fix from @minggo's reply on github.
* Don't need to invoke pause after in UrlAudioPlayer::prepare.
* Updates ThreadPool class, uses enum class and adds const keyword.
2016-07-18 10:22:40 +08:00
|
|
|
/****************************************************************************
|
|
|
|
Copyright (c) 2016 Chukong Technologies Inc.
|
|
|
|
|
|
|
|
http://www.cocos2d-x.org
|
|
|
|
|
|
|
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
|
|
of this software and associated documentation files (the "Software"), to deal
|
|
|
|
in the Software without restriction, including without limitation the rights
|
|
|
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
|
|
copies of the Software, and to permit persons to whom the Software is
|
|
|
|
furnished to do so, subject to the following conditions:
|
|
|
|
|
|
|
|
The above copyright notice and this permission notice shall be included in
|
|
|
|
all copies or substantial portions of the Software.
|
|
|
|
|
|
|
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
|
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
|
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
|
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
|
|
THE SOFTWARE.
|
|
|
|
****************************************************************************/
|
|
|
|
|
|
|
|
#define LOG_TAG "AudioPlayerProvider"
|
|
|
|
|
|
|
|
#include "audio/android/AudioPlayerProvider.h"
|
|
|
|
#include "audio/android/UrlAudioPlayer.h"
|
|
|
|
#include "audio/android/PcmAudioPlayer.h"
|
|
|
|
#include "audio/android/AudioDecoder.h"
|
|
|
|
#include "audio/android/AudioMixerController.h"
|
|
|
|
#include "audio/android/PcmAudioService.h"
|
|
|
|
#include "audio/android/CCThreadPool.h"
|
|
|
|
#include "audio/android/ICallerThreadUtils.h"
|
|
|
|
|
|
|
|
#include <sys/system_properties.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <algorithm> // for std::find_if
|
|
|
|
|
|
|
|
namespace cocos2d { namespace experimental {
|
|
|
|
|
|
|
|
static int getSystemAPILevel()
|
|
|
|
{
|
|
|
|
static int __systemApiLevel = -1;
|
|
|
|
if (__systemApiLevel > 0)
|
|
|
|
{
|
|
|
|
return __systemApiLevel;
|
|
|
|
}
|
|
|
|
|
|
|
|
int apiLevel = -1;
|
|
|
|
char sdk_ver_str[PROP_VALUE_MAX] = {0};
|
|
|
|
auto len = __system_property_get("ro.build.version.sdk", sdk_ver_str);
|
|
|
|
if (len > 0)
|
|
|
|
{
|
|
|
|
apiLevel = atoi(sdk_ver_str);
|
|
|
|
ALOGD("Android API level: %d", apiLevel);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
ALOGE("Fail to get Android API level!");
|
|
|
|
}
|
|
|
|
__systemApiLevel = apiLevel;
|
|
|
|
return apiLevel;
|
|
|
|
}
|
|
|
|
|
|
|
|
struct AudioFileIndicator
|
|
|
|
{
|
|
|
|
std::string extension;
|
|
|
|
int smallSizeIndicator;
|
|
|
|
};
|
|
|
|
|
|
|
|
static AudioFileIndicator __audioFileIndicator[] = {
|
|
|
|
{"default", 128000}, // If we could not handle the audio format, return default value, the position should be first.
|
|
|
|
{".wav", 1024000},
|
|
|
|
{".ogg", 128000},
|
|
|
|
{".mp3", 160000}
|
|
|
|
};
|
|
|
|
|
|
|
|
AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outputMixObject,
|
|
|
|
int deviceSampleRate, int bufferSizeInFrames,
|
|
|
|
const FdGetterCallback &fdGetterCallback,
|
|
|
|
ICallerThreadUtils* callerThreadUtils)
|
|
|
|
: _engineItf(engineItf), _outputMixObject(outputMixObject),
|
|
|
|
_deviceSampleRate(deviceSampleRate), _bufferSizeInFrames(bufferSizeInFrames),
|
|
|
|
_fdGetterCallback(fdGetterCallback), _callerThreadUtils(callerThreadUtils),
|
|
|
|
_pcmAudioService(nullptr), _mixController(nullptr),
|
|
|
|
_threadPool(ThreadPool::newCachedThreadPool(1, 8, 5, 2, 2))
|
|
|
|
{
|
|
|
|
ALOGI("deviceSampleRate: %d, bufferSizeInFrames: %d", _deviceSampleRate, _bufferSizeInFrames);
|
|
|
|
if (getSystemAPILevel() >= 17)
|
|
|
|
{
|
|
|
|
_mixController = new (std::nothrow) AudioMixerController(_bufferSizeInFrames, _deviceSampleRate, 2);
|
|
|
|
_mixController->init();
|
|
|
|
_pcmAudioService = new (std::nothrow) PcmAudioService(engineItf, outputMixObject);
|
|
|
|
_pcmAudioService->init(_mixController, 2, deviceSampleRate, bufferSizeInFrames * 2);
|
|
|
|
}
|
|
|
|
|
|
|
|
ALOG_ASSERT(callerThreadUtils != nullptr, "Caller thread utils parameter should not be nullptr!");
|
|
|
|
}
|
|
|
|
|
|
|
|
AudioPlayerProvider::~AudioPlayerProvider()
|
|
|
|
{
|
|
|
|
ALOGV("~AudioPlayerProvider()");
|
|
|
|
UrlAudioPlayer::stopAll();
|
|
|
|
|
|
|
|
SL_SAFE_DELETE(_pcmAudioService);
|
|
|
|
SL_SAFE_DELETE(_mixController);
|
|
|
|
SL_SAFE_DELETE(_threadPool);
|
|
|
|
}
|
|
|
|
|
|
|
|
IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const std::string &audioFilePath)
|
|
|
|
{
|
|
|
|
// Pcm data decoding by OpenSLES API only supports in API level 17 and later.
|
|
|
|
if (getSystemAPILevel() < 17)
|
|
|
|
{
|
|
|
|
AudioFileInfo info = getFileInfo(audioFilePath);
|
|
|
|
if (info.isValid())
|
|
|
|
{
|
|
|
|
return createUrlAudioPlayer(info);
|
|
|
|
}
|
|
|
|
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
IAudioPlayer *player = nullptr;
|
|
|
|
|
|
|
|
_pcmCacheMutex.lock();
|
|
|
|
auto iter = _pcmCache.find(audioFilePath);
|
|
|
|
if (iter != _pcmCache.end())
|
|
|
|
{// Found pcm cache means it was used to be a PcmAudioService
|
|
|
|
PcmData pcmData = iter->second;
|
|
|
|
_pcmCacheMutex.unlock();
|
|
|
|
player = obtainPcmAudioPlayer(audioFilePath, pcmData);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
_pcmCacheMutex.unlock();
|
|
|
|
// Check audio file size to determine to use a PcmAudioService or UrlAudioPlayer,
|
|
|
|
// generally PcmAudioService is used for playing short audio like game effects while
|
|
|
|
// playing background music uses UrlAudioPlayer
|
|
|
|
AudioFileInfo info = getFileInfo(audioFilePath);
|
|
|
|
if (info.isValid())
|
|
|
|
{
|
|
|
|
if (isSmallFile(info))
|
|
|
|
{
|
|
|
|
// Put an empty lambda to preloadEffect since we only want the future object to get PcmData
|
|
|
|
auto pcmData = std::make_shared<PcmData>();
|
|
|
|
auto isSucceed = std::make_shared<bool>(false);
|
|
|
|
auto isReturnFromCache = std::make_shared<bool>(false);
|
|
|
|
|
|
|
|
std::thread::id threadId = std::this_thread::get_id();
|
|
|
|
|
|
|
|
preloadEffect(info, [threadId, pcmData, isSucceed, isReturnFromCache](bool succeed, PcmData data){
|
|
|
|
// If the callback is in the same thread as caller's, it means that we found it
|
|
|
|
// in the cache
|
|
|
|
*isReturnFromCache = std::this_thread::get_id() == threadId;
|
|
|
|
*pcmData = data;
|
|
|
|
*isSucceed = succeed;
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!*isReturnFromCache)
|
|
|
|
{
|
|
|
|
std::unique_lock<std::mutex> lk(_preloadWaitMutex);
|
|
|
|
// Wait for 2 seconds for the decoding in sub thread finishes.
|
|
|
|
ALOGV("Waiting preload (%s) to finish ...", audioFilePath.c_str());
|
|
|
|
_preloadWaitCond.wait_for(lk, std::chrono::seconds(2));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (*isSucceed)
|
|
|
|
{
|
|
|
|
if (pcmData->isValid())
|
|
|
|
{
|
|
|
|
player = obtainPcmAudioPlayer(info.url, *pcmData);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
player = createUrlAudioPlayer(info);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return player;
|
|
|
|
}
|
|
|
|
|
|
|
|
void AudioPlayerProvider::preloadEffect(const std::string &audioFilePath, const PreloadCallback& cb)
|
|
|
|
{
|
|
|
|
// Pcm data decoding by OpenSLES API only supports in API level 17 and later.
|
|
|
|
if (getSystemAPILevel() < 17)
|
|
|
|
{
|
|
|
|
PcmData data;
|
|
|
|
cb(true, data);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lk(_pcmCacheMutex);
|
|
|
|
auto&& iter = _pcmCache.find(audioFilePath);
|
|
|
|
if (iter != _pcmCache.end())
|
|
|
|
{
|
|
|
|
ALOGV("preload return from cache: (%s)", audioFilePath.c_str());
|
|
|
|
cb(true, iter->second);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
auto info = getFileInfo(audioFilePath);
|
|
|
|
preloadEffect(info, [this, cb, audioFilePath](bool succeed, PcmData data){
|
|
|
|
|
|
|
|
_callerThreadUtils->performFunctionInCallerThread([this, succeed, data, cb](){
|
|
|
|
cb(succeed, data);
|
|
|
|
});
|
|
|
|
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Used internally
|
|
|
|
void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const PreloadCallback& cb)
|
|
|
|
{
|
|
|
|
PcmData pcmData;
|
|
|
|
|
|
|
|
if (!info.isValid())
|
|
|
|
{
|
|
|
|
cb(false, pcmData);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isSmallFile(info))
|
|
|
|
{
|
|
|
|
std::string audioFilePath = info.url;
|
|
|
|
|
|
|
|
{
|
|
|
|
// 1. First time check, if it wasn't in the cache, goto 2 step
|
|
|
|
std::lock_guard<std::mutex> lk(_pcmCacheMutex);
|
|
|
|
auto&& iter = _pcmCache.find(audioFilePath);
|
|
|
|
if (iter != _pcmCache.end())
|
|
|
|
{
|
|
|
|
ALOGV("1. Return pcm data from cache, url: %s", info.url.c_str());
|
|
|
|
cb(true, iter->second);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
{
|
|
|
|
// 2. Check whether the audio file is being preloaded, if it has been removed from map just now,
|
|
|
|
// goto step 3
|
|
|
|
std::lock_guard<std::mutex> lk(_preloadCallbackMutex);
|
|
|
|
|
|
|
|
auto&& preloadIter = _preloadCallbackMap.find(audioFilePath);
|
|
|
|
if (preloadIter != _preloadCallbackMap.end())
|
|
|
|
{
|
|
|
|
ALOGV("audio (%s) is being preloaded, add to callback vector!", audioFilePath.c_str());
|
|
|
|
PreloadCallbackParam param;
|
|
|
|
param.callback = cb;
|
|
|
|
preloadIter->second.push_back(std::move(param));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
{ // 3. Check it in cache again. If it has been removed from map just now, the file is in
|
|
|
|
// the cache absolutely.
|
|
|
|
std::lock_guard<std::mutex> lk2(_pcmCacheMutex);
|
|
|
|
auto&& iter = _pcmCache.find(audioFilePath);
|
|
|
|
if (iter != _pcmCache.end())
|
|
|
|
{
|
|
|
|
ALOGV("2. Return pcm data from cache, url: %s", info.url.c_str());
|
|
|
|
cb(true, iter->second);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
PreloadCallbackParam param;
|
|
|
|
param.callback = cb;
|
|
|
|
std::vector<PreloadCallbackParam> callbacks;
|
|
|
|
callbacks.push_back(std::move(param));
|
|
|
|
_preloadCallbackMap.insert(std::make_pair(audioFilePath, std::move(callbacks)));
|
|
|
|
}
|
|
|
|
|
|
|
|
_threadPool->pushTask([this, audioFilePath](int tid) {
|
|
|
|
ALOGV("AudioPlayerProvider::preloadEffect: (%s)", audioFilePath.c_str());
|
|
|
|
PcmData d;
|
2016-07-27 13:54:39 +08:00
|
|
|
AudioDecoder decoder(_engineItf, audioFilePath, _bufferSizeInFrames, _deviceSampleRate, _fdGetterCallback);
|
|
|
|
bool ret = decoder.start();
|
[big refactoring] Audio latency fix for Android. Support to preload effects on Android now. (#15875)
* Audio latency fix for Android. Support preload effects on Android now.
Squashed commits:
[b6d80fe] log fix
[a0a918e] Fixes assetFd didn't be released while PcmData is returned from cache.
[4b956ba] Potential crash fix for PcmAudioPlayer while pause / resume.
[398ab8c] Updates LOG_TAG position in AudioEngine-inl.cpp
[e3634e7] include stdlib.h for posix_memalign
[9004074] fixes setVolume logical error.
[c96df46] Don't use another thread for mixing, enqueue is in a seperated thread, therefore doing mixing in another thread will waste more time.
[0a4c1a8] Adds setLoop, setVolume, setPostion support for Track
[c35fb20] Fixed include.
[cdd9d32] Do mixing by ourself. (TO BE POLISHED)
[6447025] µ -> u since µ could not be shown on some android devices.
[97be0c6] Don't send a silence clip.
[c1607ed] Make linter.py happy.
[0898b54] Puts enqueue & SetPlayState in PcmAudioPlayer::play to thread pool.
[b79fc01] Adds getDuration, getPosition support for PcmAudioPlayer
[80fa2ab] minor fix of the code position of resetting state to State::INITIALIZED
[d9c62f1] underrun fix for PcmAudioPlayer.
[9c2212a] UrlAudioPlayer, playOverMutex should be static, and should be used in update method.
[1519d2e] static variables
[19da936] _pcmAudioPlayer Null pointer check in AudioPlayerProvider.
[e6b0d14] Updates audio performance test.
[fc01dd4] Registers foreground & background event in AudioEngine-inl.cpp(android), the callback should invoke `provider`'s pause & resume method.
[e00a886] TBD: Pause & resume support for PcmAudioPlayerPool.
Since OpenSLES audio resources are expensive and device shared, we should delete all unused PcmAudioPlayers in pool while pause and re-create them while resume.
But this commit isn't finished yet, I don't find a better way to register pause&resume event in AudioEngine module.
[9e42ea3] Interleave mono audio to stereo audio. PcmAudioPlayerPool only contains PcmAudioPlayers with 2 channels.
[3f18d05] Adds a strategy for checking small size of different file formats.
[753ff49] Adds performance test for AudioEngine.
[09d3045] Releases an extra PcmAudioPlayer for UrlAudioPlayer while allocating PcmAudioPlayer fails.
[9dd4477] Using std::move for PcmData move constructor & move assignment.
[6ca3bcb] some fixes:
1) new -> new (std::nothrow)
2) break if allocate PcmAudioPlayer fails
3) renames 'initForPlayPcmData' to 'init'
4) PcmAudioPlayer destructor deadlock if 'init' failed
[54675b6] include path fix.
[a1903ca] More refactorings.
[19b9498] Makes linter.py happy. :)
[923c530] Fixes:
1) Avoid getFileInfo to be invoked twice
2) A critical bug fix for UrlAudioPlayer and adds detailed comments
3) __clang__ compiler option fix for AudioResamplerSinc.cpp.
[5ec4faf] minor fix.
[faaa0f3] output a log in the destructor of UrlAudioPlayer.
[9c20355] NewAudioEngineTest,TestControll crash fix.
[f114464] fixes an unused import.
[1dc5dab] Better algorithm for allocating PcmAudioPlayer.
[331a213] minor fix.
[e54084a] null -> nullptr
[f9a0389] Support uncache.
[89a364f] Removes unused update, and TODO uncache functionality.
[1732bf9] Supports AudioEngineImpl::setFinishCallback for android.
[43d1596] UrlAudioPlayer::stop fix.
[e2ee941] Test case fix in NewAudioEngineTest/AudioIssue11143Test
[5c5ba01] More fixes for making cpp-tests/New Audio Engine Test happy.
[8b554a3] Adds log while remove player from map.
[ed71322] If original file is larger than 30k bytes, consider it's a large audio file.
[fb1845a] Updates project.properties
[6f3839f] minor log output fix in AudioEngine-inl.cpp
[c68bc6c] Don't resample if the sample rate of the decoded pcm data matchs the device's.
[43ca45f] PcmAudioPlayers also need to be removed while they play over, but should not be deleted since their lifecycle is managed by PcmAudioPlayerPool.
[f5e63c9] Audio latency fix for Android. Support preload effects on Android now.
* Supports to loading audio files asynchronously.
* Crash fix for stop audio right after play2d.
* Minor fix for logic in AudioMixerController.cpp
* Adds missing files (CCThreadPool.h/.cpp).
* Minor fix for including.
* Minor fix for missing include <functional> in Track.h
* update license information in audio.h
* Don't use std::future/std::promise anymore since ndk counldn't support it well in armeabi arch.
* isSmallFile postion updated, fixes large audio file goto the checking logic of cache.
* std::atomic<int> isn't supported by ndk-r10e while compiling with `armeabi` arch, using a int with a mutex instead.
* fixes __isnanf & posix_memalign doesn't exist on low api (<=16) devices.
* namespace updated: cocos2d -> cocos2d::experimental
* Removes commented code in AudioMixerController.h/.cpp
* Removes unused code again, and fixes a memory leak of `Track` instance.
* Oops, namespace changed.
* Only outputs log in debug mode.
* Uses ALOGV for outputing logs in AudioEngine-inl.cpp
* const PcmData& -> PcmData for Track
* Fixes a protential crash in NewAudioEngineTest
* Adds `COCOS` prefix in header #ifndef COCOS_BALABALA #define COCOS_BALABALA
* Uses _ prefix for cocos code style instead of `m` prefix.
* Deletes AudioResamplerSinc related files.
* Bug fix from @minggo's reply on github.
* Don't need to invoke pause after in UrlAudioPlayer::prepare.
* Updates ThreadPool class, uses enum class and adds const keyword.
2016-07-18 10:22:40 +08:00
|
|
|
if (ret)
|
|
|
|
{
|
|
|
|
d = decoder.getResult();
|
|
|
|
std::lock_guard<std::mutex> lk(_pcmCacheMutex);
|
|
|
|
_pcmCache.insert(std::make_pair(audioFilePath, d));
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
ALOGE("decode (%s) failed!", audioFilePath.c_str());
|
|
|
|
}
|
|
|
|
|
|
|
|
ALOGV("decode succeed.");
|
|
|
|
std::lock_guard<std::mutex> lk(_preloadCallbackMutex);
|
|
|
|
auto&& preloadIter = _preloadCallbackMap.find(audioFilePath);
|
|
|
|
if (preloadIter != _preloadCallbackMap.end())
|
|
|
|
{
|
|
|
|
auto&& params = preloadIter->second;
|
|
|
|
ALOGV("preload (%s) callback count: %d", audioFilePath.c_str(), params.size());
|
|
|
|
PcmData result = decoder.getResult();
|
|
|
|
for (auto&& param : params)
|
|
|
|
{
|
|
|
|
param.callback(ret, result);
|
|
|
|
}
|
|
|
|
_preloadCallbackMap.erase(preloadIter);
|
|
|
|
|
|
|
|
_preloadWaitCond.notify_one();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
ALOGV("File (%s) is too large, ignore preload!", info.url.c_str());
|
|
|
|
cb(true, pcmData);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(
|
|
|
|
const std::string &audioFilePath)
|
|
|
|
{
|
|
|
|
AudioFileInfo info;
|
|
|
|
long fileSize = 0;
|
|
|
|
off_t start = 0, length = 0;
|
|
|
|
int assetFd = 0;
|
|
|
|
|
|
|
|
if (audioFilePath[0] != '/')
|
|
|
|
{
|
|
|
|
std::string relativePath;
|
|
|
|
size_t position = audioFilePath.find("assets/");
|
|
|
|
|
|
|
|
if (0 == position)
|
|
|
|
{
|
|
|
|
// "assets/" is at the beginning of the path and we don't want it
|
|
|
|
relativePath = audioFilePath.substr(strlen("assets/"));
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
relativePath = audioFilePath;
|
|
|
|
}
|
|
|
|
|
|
|
|
assetFd = _fdGetterCallback(relativePath, &start, &length);
|
|
|
|
|
|
|
|
if (assetFd <= 0)
|
|
|
|
{
|
|
|
|
ALOGE("Failed to open file descriptor for '%s'", audioFilePath.c_str());
|
|
|
|
return info;
|
|
|
|
}
|
|
|
|
|
|
|
|
fileSize = length;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
FILE *fp = fopen(audioFilePath.c_str(), "rb");
|
|
|
|
if (fp != nullptr)
|
|
|
|
{
|
|
|
|
fseek(fp, 0, SEEK_END);
|
|
|
|
fileSize = ftell(fp);
|
|
|
|
fclose(fp);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
return info;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
info.url = audioFilePath;
|
|
|
|
info.assetFd = std::make_shared<AssetFd>(assetFd);
|
|
|
|
info.start = start;
|
|
|
|
info.length = fileSize;
|
|
|
|
|
|
|
|
ALOGV("(%s) file size: %ld", audioFilePath.c_str(), fileSize);
|
|
|
|
|
|
|
|
return info;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info)
|
|
|
|
{
|
|
|
|
//TODO: If file size is smaller than 100k, we think it's a small file. This value should be set by developers.
|
|
|
|
AudioFileInfo &audioFileInfo = const_cast<AudioFileInfo &>(info);
|
|
|
|
size_t judgeCount = sizeof(__audioFileIndicator) / sizeof(__audioFileIndicator[0]);
|
|
|
|
size_t pos = audioFileInfo.url.rfind(".");
|
|
|
|
std::string extension;
|
|
|
|
if (pos != std::string::npos)
|
|
|
|
{
|
|
|
|
extension = audioFileInfo.url.substr(pos);
|
|
|
|
}
|
|
|
|
auto iter = std::find_if(std::begin(__audioFileIndicator), std::end(__audioFileIndicator),
|
|
|
|
[&extension](const AudioFileIndicator &judge) -> bool {
|
|
|
|
return judge.extension == extension;
|
|
|
|
});
|
|
|
|
|
|
|
|
if (iter != std::end(__audioFileIndicator))
|
|
|
|
{
|
|
|
|
// ALOGV("isSmallFile: found: %s: ", iter->extension.c_str());
|
|
|
|
return info.length < iter->smallSizeIndicator;
|
|
|
|
}
|
|
|
|
|
|
|
|
// ALOGV("isSmallFile: not found return default value");
|
|
|
|
return info.length < __audioFileIndicator[0].smallSizeIndicator;
|
|
|
|
}
|
|
|
|
|
|
|
|
void AudioPlayerProvider::clearPcmCache(const std::string &audioFilePath)
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lk(_pcmCacheMutex);
|
|
|
|
auto iter = _pcmCache.find(audioFilePath);
|
|
|
|
if (iter != _pcmCache.end())
|
|
|
|
{
|
|
|
|
ALOGV("clear pcm cache: (%s)", audioFilePath.c_str());
|
|
|
|
_pcmCache.erase(iter);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
ALOGW("Couldn't find the pcm cache: (%s)", audioFilePath.c_str());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void AudioPlayerProvider::clearAllPcmCaches()
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> lk(_pcmCacheMutex);
|
|
|
|
_pcmCache.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
PcmAudioPlayer *AudioPlayerProvider::obtainPcmAudioPlayer(const std::string &url,
|
|
|
|
const PcmData &pcmData)
|
|
|
|
{
|
|
|
|
PcmAudioPlayer *pcmPlayer = nullptr;
|
|
|
|
if (pcmData.isValid())
|
|
|
|
{
|
|
|
|
pcmPlayer = new(std::nothrow) PcmAudioPlayer(_mixController, _callerThreadUtils);
|
|
|
|
if (pcmPlayer != nullptr)
|
|
|
|
{
|
|
|
|
pcmPlayer->prepare(url, pcmData);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
ALOGE("obtainPcmAudioPlayer failed, pcmData isn't valid!");
|
|
|
|
}
|
|
|
|
return pcmPlayer;
|
|
|
|
}
|
|
|
|
|
|
|
|
UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer(
|
|
|
|
const AudioPlayerProvider::AudioFileInfo &info)
|
|
|
|
{
|
|
|
|
if (info.url.empty())
|
|
|
|
{
|
|
|
|
ALOGE("createUrlAudioPlayer failed, url is empty!");
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
SLuint32 locatorType = info.assetFd > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI;
|
|
|
|
auto urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils);
|
|
|
|
bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length);
|
|
|
|
if (!ret)
|
|
|
|
{
|
|
|
|
SL_SAFE_DELETE(urlPlayer);
|
|
|
|
}
|
|
|
|
return urlPlayer;
|
|
|
|
}
|
|
|
|
|
|
|
|
void AudioPlayerProvider::pause()
|
|
|
|
{
|
|
|
|
if (_mixController != nullptr)
|
|
|
|
{
|
|
|
|
_mixController->pause();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (_pcmAudioService != nullptr)
|
|
|
|
{
|
|
|
|
_pcmAudioService->pause();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void AudioPlayerProvider::resume()
|
|
|
|
{
|
|
|
|
if (_mixController != nullptr)
|
|
|
|
{
|
|
|
|
_mixController->resume();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (_pcmAudioService != nullptr)
|
|
|
|
{
|
|
|
|
_pcmAudioService->resume();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}} // namespace cocos2d { namespace experimental {
|