diff --git a/native/cocos/audio/android/Android.mk b/native/cocos/audio/android/Android.mk index b2884cb277..d5a4133ea1 100644 --- a/native/cocos/audio/android/Android.mk +++ b/native/cocos/audio/android/Android.mk @@ -12,6 +12,10 @@ LOCAL_SRC_FILES := AudioEngine-inl.cpp \ CCThreadPool.cpp \ AssetFd.cpp \ AudioDecoder.cpp \ + AudioDecoderProvider.cpp \ + AudioDecoderSLES.cpp \ + AudioDecoderOgg.cpp \ + AudioDecoderMp3.cpp \ AudioPlayerProvider.cpp \ AudioResampler.cpp \ AudioResamplerCubic.cpp \ @@ -26,7 +30,8 @@ LOCAL_SRC_FILES := AudioEngine-inl.cpp \ audio_utils/format.c \ audio_utils/minifloat.cpp \ audio_utils/primitives.c \ - utils/Utils.cpp + utils/Utils.cpp \ + mp3reader.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include @@ -35,8 +40,11 @@ LOCAL_EXPORT_LDLIBS := -lOpenSLES LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \ $(LOCAL_PATH)/../.. \ - $(LOCAL_PATH)/../../platform/android + $(LOCAL_PATH)/../../platform/android \ + $(LOCAL_PATH)/../../../external \ + $(LOCAL_PATH)/../../../external/sources +LOCAL_STATIC_LIBRARIES += libvorbisidec libpvmp3dec include $(BUILD_STATIC_LIBRARY) #SimpleAudioEngine @@ -58,3 +66,6 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \ $(LOCAL_PATH)/../../platform/android include $(BUILD_STATIC_LIBRARY) + +$(call import-module,sources/tremolo) +$(call import-module,sources/pvmp3dec) diff --git a/native/cocos/audio/android/AudioDecoder.cpp b/native/cocos/audio/android/AudioDecoder.cpp index 2343c09d41..e8e2bc96a1 100644 --- a/native/cocos/audio/android/AudioDecoder.cpp +++ b/native/cocos/audio/android/AudioDecoder.cpp @@ -27,86 +27,52 @@ THE SOFTWARE. #include "audio/android/AudioDecoder.h" #include "audio/android/AudioResampler.h" #include "audio/android/PcmBufferProvider.h" +#include "audio/android/AudioResampler.h" #include #include namespace cocos2d { namespace experimental { -/* Explicitly requesting SL_IID_ANDROIDSIMPLEBUFFERQUEUE and SL_IID_PREFETCHSTATUS -* on the UrlAudioPlayer object for decoding, SL_IID_METADATAEXTRACTION for retrieving the -* format of the decoded audio */ -#define NUM_EXPLICIT_INTERFACES_FOR_PLAYER 3 - -/* Size of the decode buffer queue */ -#define NB_BUFFERS_IN_QUEUE 4 - -/* size of the struct to retrieve the PCM format metadata values: the values we're interested in - * are SLuint32, but it is saved in the data field of a SLMetadataInfo, hence the larger size. - * Nate that this size is queried and displayed at l.452 for demonstration/test purposes. - * */ -#define PCM_METADATA_VALUE_SIZE 32 - -/* used to detect errors likely to have occurred when the OpenSL ES framework fails to open - * a resource, for instance because a file URI is invalid, or an HTTP server doesn't respond. - */ -#define PREFETCHEVENT_ERROR_CANDIDATE (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE) - -//----------------------------------------------------------------- - -static int toBufferSizeInBytes(int bufferSizeInFrames, int sampleSize, int channelCount) +size_t AudioDecoder::fileRead(void* ptr, size_t size, size_t nmemb, void* datasource) { - return bufferSizeInFrames * sampleSize * channelCount; + AudioDecoder* thiz = (AudioDecoder*)datasource; + ssize_t toReadBytes = std::min((ssize_t)(thiz->_fileData.getSize() - thiz->_fileCurrPos), (ssize_t)(nmemb * size)); + if (toReadBytes > 0) + { + memcpy(ptr, (unsigned char*) thiz->_fileData.getBytes() + thiz->_fileCurrPos, toReadBytes); + thiz->_fileCurrPos += toReadBytes; + } + // ALOGD("File size: %d, After fileRead _fileCurrPos %d", (int)thiz->_fileData.getSize(), thiz->_fileCurrPos); + return toReadBytes; } -static int BUFFER_SIZE_IN_BYTES = 0; - -static void checkMetaData(int index, const char *key) +int AudioDecoder::fileSeek(void* datasource, int64_t offset, int whence) { - if (index != -1) - { - ALOGV("Key %s is at index %d", key, index); - } - else - { - ALOGE("Unable to find key %s", key); - } + AudioDecoder* thiz = (AudioDecoder*)datasource; + if (whence == SEEK_SET) + thiz->_fileCurrPos = offset; + else if (whence == SEEK_CUR) + thiz->_fileCurrPos = thiz->_fileCurrPos + offset; + else if (whence == SEEK_END) + thiz->_fileCurrPos = thiz->_fileData.getSize(); + return 0; } -class SLAudioDecoderCallbackProxy +int AudioDecoder::fileClose(void* datasource) { -public: - //----------------------------------------------------------------- - /* Callback for "prefetch" events, here used to detect audio resource opening errors */ - static void prefetchEventCallback(SLPrefetchStatusItf caller, void *context, SLuint32 event) - { - AudioDecoder *thiz = reinterpret_cast(context); - thiz->prefetchCallback(caller, event); - } + return 0; +} - static void decPlayCallback(SLAndroidSimpleBufferQueueItf queueItf, void *context) - { - AudioDecoder *thiz = reinterpret_cast(context); - thiz->decodeToPcmCallback(queueItf); - } - - static void decProgressCallback(SLPlayItf caller, void *context, SLuint32 event) - { - AudioDecoder *thiz = reinterpret_cast(context); - thiz->decodeProgressCallback(caller, event); - } -}; - -AudioDecoder::AudioDecoder(SLEngineItf engineItf, const std::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback) - : _engineItf(engineItf), _url(url), _playObj(nullptr), _formatQueried(false), - _prefetchError(false), _counter(0), _numChannelsKeyIndex(-1), _sampleRateKeyIndex(-1), - _bitsPerSampleKeyIndex(-1), _containerSizeKeyIndex(-1), _channelMaskKeyIndex(-1), - _endiannessKeyIndex(-1), _eos(false), _bufferSizeInFrames(bufferSizeInFrames), - _sampleRate(sampleRate), _assetFd(0), _fdGetterCallback(fdGetterCallback), _isDecodingCallbackInvoked(false) +long AudioDecoder::fileTell(void* datasource) +{ + AudioDecoder* thiz = (AudioDecoder*)datasource; + return (long) thiz->_fileCurrPos; +} + +AudioDecoder::AudioDecoder() + : _fileCurrPos(0), _sampleRate(-1) { - BUFFER_SIZE_IN_BYTES = toBufferSizeInBytes(bufferSizeInFrames, 2, 2); - _pcmData = (char*) malloc(NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES); - memset(_pcmData, 0x00, NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES); auto pcmBuffer = std::make_shared>(); pcmBuffer->reserve(4096); _result.pcmBuffer = pcmBuffer; @@ -115,15 +81,13 @@ AudioDecoder::AudioDecoder(SLEngineItf engineItf, const std::string &url, int bu AudioDecoder::~AudioDecoder() { ALOGV("~AudioDecoder() %p", this); - SL_DESTROY_OBJ(_playObj); - ALOGV("After destroying SL play object"); - if (_assetFd > 0) - { - ALOGV("Closing assetFd: %d", _assetFd); - ::close(_assetFd); - _assetFd = 0; - } - free(_pcmData); +} + +bool AudioDecoder::init(const std::string &url, int sampleRate) +{ + _url = url; + _sampleRate = sampleRate; + return true; } bool AudioDecoder::start() @@ -163,324 +127,6 @@ bool AudioDecoder::start() return ret; } -bool AudioDecoder::decodeToPcm() -{ - SLresult result; - - /* Objects this application uses: one audio player */ - SLObjectItf player; - - /* Interfaces for the audio player */ - SLAndroidSimpleBufferQueueItf decBuffQueueItf; - SLPrefetchStatusItf prefetchItf; - SLPlayItf playItf; - SLMetadataExtractionItf mdExtrItf; - - /* Source of audio data for the decoding */ - SLDataSource decSource; - - // decUri & locFd should be defined here - SLDataLocator_URI decUri; - SLDataLocator_AndroidFD locFd; - - /* Data sink for decoded audio */ - SLDataSink decDest; - SLDataLocator_AndroidSimpleBufferQueue decBuffQueue; - SLDataFormat_PCM pcm; - - SLboolean required[NUM_EXPLICIT_INTERFACES_FOR_PLAYER]; - SLInterfaceID iidArray[NUM_EXPLICIT_INTERFACES_FOR_PLAYER]; - - /* Initialize arrays required[] and iidArray[] */ - for (int i = 0; i < NUM_EXPLICIT_INTERFACES_FOR_PLAYER; i++) - { - required[i] = SL_BOOLEAN_FALSE; - iidArray[i] = SL_IID_NULL; - } - - /* ------------------------------------------------------ */ - /* Configuration of the player */ - - /* Request the AndroidSimpleBufferQueue interface */ - required[0] = SL_BOOLEAN_TRUE; - iidArray[0] = SL_IID_ANDROIDSIMPLEBUFFERQUEUE; - /* Request the PrefetchStatus interface */ - required[1] = SL_BOOLEAN_TRUE; - iidArray[1] = SL_IID_PREFETCHSTATUS; - /* Request the PrefetchStatus interface */ - required[2] = SL_BOOLEAN_TRUE; - iidArray[2] = SL_IID_METADATAEXTRACTION; - - SLDataFormat_MIME formatMime = {SL_DATAFORMAT_MIME, nullptr, SL_CONTAINERTYPE_UNSPECIFIED}; - decSource.pFormat = &formatMime; - - if (_url[0] != '/') - { - off_t start = 0, length = 0; - std::string relativePath; - size_t position = _url.find("assets/"); - - if (0 == position) - { - // "assets/" is at the beginning of the path and we don't want it - relativePath = _url.substr(strlen("assets/")); - } else - { - relativePath = _url; - } - - _assetFd = _fdGetterCallback(relativePath, &start, &length); - - if (_assetFd <= 0) - { - ALOGE("Failed to open file descriptor for '%s'", _url.c_str()); - return false; - } - - // configure audio source - locFd = {SL_DATALOCATOR_ANDROIDFD, _assetFd, start, length}; - - decSource.pLocator = &locFd; - } - else - { - decUri = {SL_DATALOCATOR_URI, (SLchar *) _url.c_str()}; - decSource.pLocator = &decUri; - } - - /* Setup the data sink */ - decBuffQueue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; - decBuffQueue.numBuffers = NB_BUFFERS_IN_QUEUE; - /* set up the format of the data in the buffer queue */ - pcm.formatType = SL_DATAFORMAT_PCM; - // FIXME valid value required but currently ignored - pcm.numChannels = 2; - pcm.samplesPerSec = SL_SAMPLINGRATE_44_1; - pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; - pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; - pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; - pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; - - decDest.pLocator = (void *) &decBuffQueue; - decDest.pFormat = (void *) &pcm; - - /* Create the audio player */ - result = (*_engineItf)->CreateAudioPlayer(_engineItf, &player, &decSource, &decDest, - NUM_EXPLICIT_INTERFACES_FOR_PLAYER, iidArray, - required); - SL_RETURN_VAL_IF_FAILED(result, false, "CreateAudioPlayer failed"); - - _playObj = player; - /* Realize the player in synchronous mode. */ - result = (*player)->Realize(player, SL_BOOLEAN_FALSE); - SL_RETURN_VAL_IF_FAILED(result, false, "Realize failed"); - - /* Get the play interface which is implicit */ - result = (*player)->GetInterface(player, SL_IID_PLAY, (void *) &playItf); - SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_PLAY failed"); - - /* Set up the player callback to get events during the decoding */ - // FIXME currently ignored - result = (*playItf)->SetMarkerPosition(playItf, 2000); - SL_RETURN_VAL_IF_FAILED(result, false, "SetMarkerPosition failed"); - - result = (*playItf)->SetPositionUpdatePeriod(playItf, 500); - SL_RETURN_VAL_IF_FAILED(result, false, "SetPositionUpdatePeriod failed"); - result = (*playItf)->SetCallbackEventsMask(playItf, - SL_PLAYEVENT_HEADATMARKER | - SL_PLAYEVENT_HEADATNEWPOS | SL_PLAYEVENT_HEADATEND); - SL_RETURN_VAL_IF_FAILED(result, false, "SetCallbackEventsMask failed"); - result = (*playItf)->RegisterCallback(playItf, SLAudioDecoderCallbackProxy::decProgressCallback, - this); - SL_RETURN_VAL_IF_FAILED(result, false, "RegisterCallback failed"); - ALOGV("Play callback registered"); - - - /* Get the buffer queue interface which was explicitly requested */ - result = (*player)->GetInterface(player, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, - (void *) &decBuffQueueItf); - SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_ANDROIDSIMPLEBUFFERQUEUE failed"); - - /* Get the prefetch status interface which was explicitly requested */ - result = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void *) &prefetchItf); - SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_PREFETCHSTATUS failed"); - - /* Get the metadata extraction interface which was explicitly requested */ - result = (*player)->GetInterface(player, SL_IID_METADATAEXTRACTION, (void *) &mdExtrItf); - SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_METADATAEXTRACTION failed"); - - /* ------------------------------------------------------ */ - /* Initialize the callback and its context for the decoding buffer queue */ - _decContext.playItf = playItf; - _decContext.metaItf = mdExtrItf; - _decContext.pDataBase = (int8_t *) _pcmData; - _decContext.pData = _decContext.pDataBase; - _decContext.size = NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES; - - result = (*decBuffQueueItf)->RegisterCallback(decBuffQueueItf, - SLAudioDecoderCallbackProxy::decPlayCallback, - this); - SL_RETURN_VAL_IF_FAILED(result, false, "decBuffQueueItf RegisterCallback failed"); - - /* Enqueue buffers to map the region of memory allocated to store the decoded data */ -// ALOGV("Enqueueing buffer "); - for (int i = 0; i < NB_BUFFERS_IN_QUEUE; i++) - { - result = (*decBuffQueueItf)->Enqueue(decBuffQueueItf, _decContext.pData, - BUFFER_SIZE_IN_BYTES); - SL_RETURN_VAL_IF_FAILED(result, false, "Enqueue failed"); - _decContext.pData += BUFFER_SIZE_IN_BYTES; - } - - _decContext.pData = _decContext.pDataBase; - - /* ------------------------------------------------------ */ - /* Initialize the callback for prefetch errors, if we can't open the resource to decode */ - result = (*prefetchItf)->RegisterCallback(prefetchItf, - SLAudioDecoderCallbackProxy::prefetchEventCallback, - this); - SL_RETURN_VAL_IF_FAILED(result, false, "prefetchItf RegisterCallback failed"); - - result = (*prefetchItf)->SetCallbackEventsMask(prefetchItf, PREFETCHEVENT_ERROR_CANDIDATE); - SL_RETURN_VAL_IF_FAILED(result, false, "prefetchItf SetCallbackEventsMask failed"); - - /* ------------------------------------------------------ */ - /* Prefetch the data so we can get information about the format before starting to decode */ - /* 1/ cause the player to prefetch the data */ - result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PAUSED); - SL_RETURN_VAL_IF_FAILED(result, false, "SetPlayState SL_PLAYSTATE_PAUSED failed"); - - /* 2/ block until data has been prefetched */ - SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW; - SLuint32 timeOutIndex = 1000; //cjh time out prefetching after 2s - while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0) && - !_prefetchError) - { - std::this_thread::sleep_for(std::chrono::milliseconds(2)); - (*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus); - timeOutIndex--; - } - if (timeOutIndex == 0 || _prefetchError) - { - ALOGE("Failure to prefetch data in time, exiting"); - SL_RETURN_VAL_IF_FAILED(SL_RESULT_CONTENT_NOT_FOUND, false, - "Failure to prefetch data in time"); - } - - /* ------------------------------------------------------ */ - /* Display duration */ - SLmillisecond durationInMsec = SL_TIME_UNKNOWN; - result = (*playItf)->GetDuration(playItf, &durationInMsec); - SL_RETURN_VAL_IF_FAILED(result, false, "GetDuration failed"); - - if (durationInMsec == SL_TIME_UNKNOWN) - { - ALOGV("Content duration is unknown"); - } else - { - ALOGV("Content duration is %dms", (int)durationInMsec); - } - - /* ------------------------------------------------------ */ - /* Display the metadata obtained from the decoder */ - // This is for test / demonstration purposes only where we discover the key and value sizes - // of a PCM decoder. An application that would want to directly get access to those values - // can make assumptions about the size of the keys and their matching values (all SLuint32) - SLuint32 itemCount; - result = (*mdExtrItf)->GetItemCount(mdExtrItf, &itemCount); - SLuint32 i, keySize, valueSize; - SLMetadataInfo *keyInfo, *value; - for (i = 0; i < itemCount; i++) - { - keyInfo = nullptr; - keySize = 0; - value = nullptr; - valueSize = 0; - result = (*mdExtrItf)->GetKeySize(mdExtrItf, i, &keySize); - SL_RETURN_VAL_IF_FAILED(result, false, "GetKeySize(%d) failed", (int)i); - - result = (*mdExtrItf)->GetValueSize(mdExtrItf, i, &valueSize); - SL_RETURN_VAL_IF_FAILED(result, false, "GetValueSize(%d) failed", (int)i); - - keyInfo = (SLMetadataInfo *) malloc(keySize); - if (nullptr != keyInfo) - { - result = (*mdExtrItf)->GetKey(mdExtrItf, i, keySize, keyInfo); - - SL_RETURN_VAL_IF_FAILED(result, false, "GetKey(%d) failed", (int)i); - - ALOGV("key[%d] size=%d, name=%s, value size=%d", - (int)i, (int)keyInfo->size, keyInfo->data, (int)valueSize); - /* find out the key index of the metadata we're interested in */ - if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_NUMCHANNELS)) - { - _numChannelsKeyIndex = i; - } else if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_SAMPLERATE)) - { - _sampleRateKeyIndex = i; - } else if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_BITSPERSAMPLE)) - { - _bitsPerSampleKeyIndex = i; - } else if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_CONTAINERSIZE)) - { - _containerSizeKeyIndex = i; - } else if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_CHANNELMASK)) - { - _channelMaskKeyIndex = i; - } else if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_ENDIANNESS)) - { - _endiannessKeyIndex = i; - } - free(keyInfo); - } - } - - checkMetaData(_numChannelsKeyIndex, ANDROID_KEY_PCMFORMAT_NUMCHANNELS); - checkMetaData(_sampleRateKeyIndex, ANDROID_KEY_PCMFORMAT_SAMPLERATE); - checkMetaData(_bitsPerSampleKeyIndex, ANDROID_KEY_PCMFORMAT_BITSPERSAMPLE); - checkMetaData(_containerSizeKeyIndex, ANDROID_KEY_PCMFORMAT_CONTAINERSIZE); - checkMetaData(_channelMaskKeyIndex, ANDROID_KEY_PCMFORMAT_CHANNELMASK); - checkMetaData(_endiannessKeyIndex, ANDROID_KEY_PCMFORMAT_ENDIANNESS); - - /* ------------------------------------------------------ */ - /* Start decoding */ - result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); - SL_RETURN_VAL_IF_FAILED(result, false, "SetPlayState SL_PLAYSTATE_PLAYING failed"); - - ALOGV("Starting to decode"); - - /* Decode until the end of the stream is reached */ - { - std::unique_lock autoLock(_eosLock); - while (!_eos) - { - _eosCondition.wait(autoLock); - } - } - ALOGV("EOS signaled"); - - /* ------------------------------------------------------ */ - /* End of decoding */ - - /* Stop decoding */ - result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED); - SL_RETURN_VAL_IF_FAILED(result, false, "SetPlayState SL_PLAYSTATE_STOPPED failed"); - - ALOGV("Stopped decoding"); - - /* Destroy the UrlAudioPlayer object */ - SL_DESTROY_OBJ(_playObj); - - ALOGV("After destroy player ..."); - - _result.numFrames = - _result.pcmBuffer->size() / _result.numChannels / (_result.bitsPerSample / 8); - - std::string info = _result.toString(); - ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size()); - return true; -} - bool AudioDecoder::resample() { if (_result.sampleRate == _sampleRate) @@ -597,185 +243,6 @@ bool AudioDecoder::resample() } //----------------------------------------------------------------- -void AudioDecoder::signalEos() -{ - std::unique_lock autoLock(_eosLock); - _eos = true; - _eosCondition.notify_one(); -} - -void AudioDecoder::queryAudioInfo() -{ - if (_formatQueried) - { - return; - } - - SLresult result; - /* Get duration in callback where we use the callback context for the SLPlayItf*/ - SLmillisecond durationInMsec = SL_TIME_UNKNOWN; - result = (*_decContext.playItf)->GetDuration(_decContext.playItf, &durationInMsec); - SL_RETURN_IF_FAILED(result, "decodeProgressCallback,GetDuration failed"); - - if (durationInMsec == SL_TIME_UNKNOWN) - { - ALOGV("Content duration is unknown (in dec callback)"); - } else - { - ALOGV("Content duration is %dms (in dec callback)", (int)durationInMsec); - _result.duration = durationInMsec / 1000.0f; - } - - /* used to query metadata values */ - SLMetadataInfo pcmMetaData; - - result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _sampleRateKeyIndex, - PCM_METADATA_VALUE_SIZE, &pcmMetaData); - - SL_RETURN_IF_FAILED(result, "%s GetValue _sampleRateKeyIndex failed", __FUNCTION__); - // Note: here we could verify the following: - // pcmMetaData->encoding == SL_CHARACTERENCODING_BINARY - // pcmMetaData->size == sizeof(SLuint32) - // but the call was successful for the PCM format keys, so those conditions are implied - - _result.sampleRate = *((SLuint32 *) pcmMetaData.data); - result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _numChannelsKeyIndex, - PCM_METADATA_VALUE_SIZE, &pcmMetaData); - SL_RETURN_IF_FAILED(result, "%s GetValue _numChannelsKeyIndex failed", __FUNCTION__); - - _result.numChannels = *((SLuint32 *) pcmMetaData.data); - - result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _bitsPerSampleKeyIndex, - PCM_METADATA_VALUE_SIZE, &pcmMetaData); - SL_RETURN_IF_FAILED(result, "%s GetValue _bitsPerSampleKeyIndex failed", __FUNCTION__) - _result.bitsPerSample = *((SLuint32 *) pcmMetaData.data); - - result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _containerSizeKeyIndex, - PCM_METADATA_VALUE_SIZE, &pcmMetaData); - SL_RETURN_IF_FAILED(result, "%s GetValue _containerSizeKeyIndex failed", __FUNCTION__) - _result.containerSize = *((SLuint32 *) pcmMetaData.data); - - result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _channelMaskKeyIndex, - PCM_METADATA_VALUE_SIZE, &pcmMetaData); - SL_RETURN_IF_FAILED(result, "%s GetValue _channelMaskKeyIndex failed", __FUNCTION__) - _result.channelMask = *((SLuint32 *) pcmMetaData.data); - - result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _endiannessKeyIndex, - PCM_METADATA_VALUE_SIZE, &pcmMetaData); - SL_RETURN_IF_FAILED(result, "%s GetValue _endiannessKeyIndex failed", __FUNCTION__) - _result.endianness = *((SLuint32 *) pcmMetaData.data); - - _formatQueried = true; -} - -void AudioDecoder::prefetchCallback(SLPrefetchStatusItf caller, SLuint32 event) -{ - SLpermille level = 0; - SLresult result; - result = (*caller)->GetFillLevel(caller, &level); - SL_RETURN_IF_FAILED(result, "GetFillLevel failed"); - - SLuint32 status; - //ALOGV("PrefetchEventCallback: received event %u", event); - result = (*caller)->GetPrefetchStatus(caller, &status); - - SL_RETURN_IF_FAILED(result, "GetPrefetchStatus failed"); - - if ((PREFETCHEVENT_ERROR_CANDIDATE == (event & PREFETCHEVENT_ERROR_CANDIDATE)) - && (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) - { - ALOGV("PrefetchEventCallback: Error while prefetching data, exiting"); - _prefetchError = true; - signalEos(); - } -} - -/* Callback for "playback" events, i.e. event happening during decoding */ -void AudioDecoder::decodeProgressCallback(SLPlayItf caller, SLuint32 event) -{ - if (SL_PLAYEVENT_HEADATEND & event) - { - ALOGV("SL_PLAYEVENT_HEADATEND"); - if (!_isDecodingCallbackInvoked) - { - queryAudioInfo(); - - for (int i = 0; i < NB_BUFFERS_IN_QUEUE; ++i) - { - _result.pcmBuffer->insert(_result.pcmBuffer->end(), _decContext.pData, - _decContext.pData + BUFFER_SIZE_IN_BYTES); - - /* Increase data pointer by buffer size */ - _decContext.pData += BUFFER_SIZE_IN_BYTES; - } - } - signalEos(); - } -} - -//----------------------------------------------------------------- -/* Callback for decoding buffer queue events */ -void AudioDecoder::decodeToPcmCallback(SLAndroidSimpleBufferQueueItf queueItf) -{ - _isDecodingCallbackInvoked = true; - ALOGV("%s ...", __FUNCTION__); - _counter++; - SLresult result; - // FIXME: ?? - if (_counter % 1000 == 0) - { - SLmillisecond msec; - result = (*_decContext.playItf)->GetPosition(_decContext.playItf, &msec); - SL_RETURN_IF_FAILED(result, "%s, GetPosition failed", __FUNCTION__); - ALOGV("%s called (iteration %d): current position=%d ms", __FUNCTION__, _counter, (int)msec); - } - - _result.pcmBuffer->insert(_result.pcmBuffer->end(), _decContext.pData, - _decContext.pData + BUFFER_SIZE_IN_BYTES); - - result = (*queueItf)->Enqueue(queueItf, _decContext.pData, BUFFER_SIZE_IN_BYTES); - SL_RETURN_IF_FAILED(result, "%s, Enqueue failed", __FUNCTION__); - - /* Increase data pointer by buffer size */ - _decContext.pData += BUFFER_SIZE_IN_BYTES; - - if (_decContext.pData >= _decContext.pDataBase + (NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES)) - { - _decContext.pData = _decContext.pDataBase; - } - - // Note: adding a sleep here or any sync point is a way to slow down the decoding, or - // synchronize it with some other event, as the OpenSL ES framework will block until the - // buffer queue callback return to proceed with the decoding. - -#if 0 - /* Example: buffer queue state display */ - SLAndroidSimpleBufferQueueState decQueueState; - result =(*queueItf)->GetState(queueItf, &decQueueState); - SL_RETURN_IF_FAILED(result, "decQueueState.GetState failed"); - - ALOGV("DecBufferQueueCallback now has _decContext.pData=%p, _decContext.pDataBase=%p, queue: " - "count=%u playIndex=%u, count: %d", - _decContext.pData, _decContext.pDataBase, decQueueState.count, decQueueState.index, _counter); -#endif - -#if 0 - /* Example: display position in callback where we use the callback context for the SLPlayItf*/ - SLmillisecond posMsec = SL_TIME_UNKNOWN; - result = (*_decContext.playItf)->GetPosition(_decContext.playItf, &posMsec); - SL_RETURN_IF_FAILED(result, "decodeToPcmCallback,GetPosition2 failed"); - - if (posMsec == SL_TIME_UNKNOWN) { - ALOGV("Content position is unknown (in dec callback)"); - } else { - ALOGV("Content position is %ums (in dec callback)", - posMsec); - } -#endif - - queryAudioInfo(); -} - bool AudioDecoder::interleave() { if (_result.numChannels == 2) diff --git a/native/cocos/audio/android/AudioDecoder.h b/native/cocos/audio/android/AudioDecoder.h index 72eb0b5a04..d0024bf33b 100644 --- a/native/cocos/audio/android/AudioDecoder.h +++ b/native/cocos/audio/android/AudioDecoder.h @@ -26,83 +26,38 @@ THE SOFTWARE. #include "audio/android/OpenSLHelper.h" #include "audio/android/PcmData.h" - -#include -#include +#include "base/CCData.h" namespace cocos2d { namespace experimental { class AudioDecoder { public: - AudioDecoder(SLEngineItf engineItf, const std::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback); - + AudioDecoder(); virtual ~AudioDecoder(); + virtual bool init(const std::string &url, int sampleRate); + bool start(); inline PcmData getResult() { return _result; }; -private: - bool decodeToPcm(); +protected: + virtual bool decodeToPcm() = 0; bool resample(); bool interleave(); - void queryAudioInfo(); - void signalEos(); - void decodeToPcmCallback(SLAndroidSimpleBufferQueueItf queueItf); - void prefetchCallback(SLPrefetchStatusItf caller, SLuint32 event); - void decodeProgressCallback(SLPlayItf caller, SLuint32 event); + static size_t fileRead(void* ptr, size_t size, size_t nmemb, void* datasource); + static int fileSeek(void* datasource, int64_t offset, int whence); + static int fileClose(void* datasource); + static long fileTell(void* datasource); -private: - SLEngineItf _engineItf; std::string _url; PcmData _result; - - SLObjectItf _playObj; - /* Local storage for decoded audio data */ - char* _pcmData; - - /* we only want to query / display the PCM format once */ - bool _formatQueried; - /* Used to signal prefetching failures */ - bool _prefetchError; - - /* to display the number of decode iterations */ - int _counter; - - /* metadata key index for the PCM format information we want to retrieve */ - int _numChannelsKeyIndex; - int _sampleRateKeyIndex; - int _bitsPerSampleKeyIndex; - int _containerSizeKeyIndex; - int _channelMaskKeyIndex; - int _endiannessKeyIndex; - - /* to signal to the test app the end of the stream to decode has been reached */ - bool _eos; - std::mutex _eosLock; - std::condition_variable _eosCondition; - - /* Structure for passing information to callback function */ - typedef struct CallbackCntxt_ - { - SLPlayItf playItf; - SLMetadataExtractionItf metaItf; - SLuint32 size; - SLint8 *pDataBase; // Base address of local audio data storage - SLint8 *pData; // Current address of local audio data storage - } CallbackCntxt; - - CallbackCntxt _decContext; - int _bufferSizeInFrames; int _sampleRate; - int _assetFd; - FdGetterCallback _fdGetterCallback; - bool _isDecodingCallbackInvoked; - - friend class SLAudioDecoderCallbackProxy; + Data _fileData; + size_t _fileCurrPos; }; }} // namespace cocos2d { namespace experimental { diff --git a/native/cocos/audio/android/AudioDecoderMp3.cpp b/native/cocos/audio/android/AudioDecoderMp3.cpp new file mode 100644 index 0000000000..6ac384f7fc --- /dev/null +++ b/native/cocos/audio/android/AudioDecoderMp3.cpp @@ -0,0 +1,52 @@ +#define LOG_TAG "AudioDecoderMp3" + +#include "audio/android/AudioDecoderMp3.h" +#include "audio/android/mp3reader.h" +#include "platform/CCFileUtils.h" + +namespace cocos2d { namespace experimental { + +AudioDecoderMp3::AudioDecoderMp3() +{ + ALOGV("Create AudioDecoderMp3"); +} + +AudioDecoderMp3::~AudioDecoderMp3() +{ + +} + +bool AudioDecoderMp3::decodeToPcm() +{ + _fileData = FileUtils::getInstance()->getDataFromFile(_url); + if (_fileData.isNull()) + { + return false; + } + + mp3_callbacks callbacks; + callbacks.read = AudioDecoder::fileRead; + callbacks.seek = AudioDecoder::fileSeek; + callbacks.close = AudioDecoder::fileClose; + callbacks.tell = AudioDecoder::fileTell; + + int numChannels = 0; + int sampleRate = 0; + int numFrames = 0; + decodeMP3(&callbacks, this, *_result.pcmBuffer, &numChannels, &sampleRate, &numFrames); + + _result.numChannels = numChannels; + _result.sampleRate = sampleRate; + _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.channelMask = numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); + _result.endianness = SL_BYTEORDER_LITTLEENDIAN; + _result.numFrames = numFrames; + _result.duration = 1.0f * numFrames / sampleRate; + + std::string info = _result.toString(); + ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size()); + return true; +} + +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderMp3.h b/native/cocos/audio/android/AudioDecoderMp3.h new file mode 100644 index 0000000000..67562b1f14 --- /dev/null +++ b/native/cocos/audio/android/AudioDecoderMp3.h @@ -0,0 +1,42 @@ +/**************************************************************************** +Copyright (c) 2017 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. +****************************************************************************/ + +#pragma once + +#include "audio/android/AudioDecoder.h" + +namespace cocos2d { namespace experimental { + +class AudioDecoderMp3 : public AudioDecoder +{ +protected: + AudioDecoderMp3(); + virtual ~AudioDecoderMp3(); + + virtual bool decodeToPcm() override; + + friend class AudioDecoderProvider; +}; + +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderOgg.cpp b/native/cocos/audio/android/AudioDecoderOgg.cpp new file mode 100644 index 0000000000..8e4e406372 --- /dev/null +++ b/native/cocos/audio/android/AudioDecoderOgg.cpp @@ -0,0 +1,80 @@ +#define LOG_TAG "AudioDecoderOgg" + +#include "audio/android/AudioDecoderOgg.h" +#include "platform/CCFileUtils.h" + +namespace cocos2d { namespace experimental { + +AudioDecoderOgg::AudioDecoderOgg() +{ + ALOGV("Create AudioDecoderOgg"); +} + +AudioDecoderOgg::~AudioDecoderOgg() +{ + +} + +int AudioDecoderOgg::fseek64Wrap(void* datasource, ogg_int64_t off, int whence) +{ + return AudioDecoder::fileSeek(datasource, (long)off, whence); +} + +bool AudioDecoderOgg::decodeToPcm() +{ + _fileData = FileUtils::getInstance()->getDataFromFile(_url); + if (_fileData.isNull()) + { + return false; + } + + ov_callbacks callbacks; + callbacks.read_func = AudioDecoder::fileRead; + callbacks.seek_func = AudioDecoderOgg::fseek64Wrap; + callbacks.close_func = AudioDecoder::fileClose; + callbacks.tell_func = AudioDecoder::fileTell; + + _fileCurrPos = 0; + + OggVorbis_File vf; + int ret = ov_open_callbacks(this, &vf, NULL, 0, callbacks); + if (ret != 0) + { + ALOGE("Open file error, file: %s, ov_open_callbacks return %d", _url.c_str(), ret); + return false; + } + // header + auto vi = ov_info(&vf, -1); + + uint32_t uiPCMSamples = (uint32_t) ov_pcm_total(&vf, -1); + + uint32_t bufferSize = uiPCMSamples * vi->channels * sizeof(short); + char* pvPCMBuffer = (char*)malloc(bufferSize); + memset(pvPCMBuffer, 0, bufferSize); + + int current_section = 0; + int uiCurrPos = 0; + long iRead = 0; + // decode + do { + iRead = ov_read(&vf, pvPCMBuffer + uiCurrPos, 4096, ¤t_section); + uiCurrPos += (unsigned int) iRead; + } while (iRead != 0); + + _result.pcmBuffer->insert(_result.pcmBuffer->end(), pvPCMBuffer, pvPCMBuffer + bufferSize); + _result.numChannels = vi->channels; + _result.sampleRate = vi->rate; + _result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; + _result.channelMask = vi->channels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT); + _result.endianness = SL_BYTEORDER_LITTLEENDIAN; + _result.numFrames = uiPCMSamples; + _result.duration = 1.0f * uiPCMSamples / vi->rate; + + ov_clear(&vf); + free(pvPCMBuffer); + + return true; +} + +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderOgg.h b/native/cocos/audio/android/AudioDecoderOgg.h new file mode 100644 index 0000000000..99573d3631 --- /dev/null +++ b/native/cocos/audio/android/AudioDecoderOgg.h @@ -0,0 +1,45 @@ +/**************************************************************************** +Copyright (c) 2017 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. +****************************************************************************/ + +#pragma once + +#include "audio/android/AudioDecoder.h" + +#include "tremolo/Tremolo/ivorbisfile.h" + +namespace cocos2d { namespace experimental { + +class AudioDecoderOgg : public AudioDecoder +{ +protected: + AudioDecoderOgg(); + virtual ~AudioDecoderOgg(); + + static int fseek64Wrap(void* datasource, ogg_int64_t off, int whence); + virtual bool decodeToPcm() override; + + friend class AudioDecoderProvider; +}; + +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderProvider.cpp b/native/cocos/audio/android/AudioDecoderProvider.cpp new file mode 100644 index 0000000000..3a355e2850 --- /dev/null +++ b/native/cocos/audio/android/AudioDecoderProvider.cpp @@ -0,0 +1,57 @@ +#include "audio/android/AudioDecoderProvider.h" +#include "audio/android/AudioDecoderSLES.h" +#include "audio/android/AudioDecoderOgg.h" +#include "audio/android/AudioDecoderMp3.h" +#include "platform/CCFileUtils.h" + +namespace cocos2d { namespace experimental { + +AudioDecoder* AudioDecoderProvider::createAudioDecoder(SLEngineItf engineItf, const std::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback) +{ + AudioDecoder* decoder = nullptr; + std::string extension = FileUtils::getInstance()->getFileExtension(url); + + if (extension == ".ogg") + { + decoder = new AudioDecoderOgg(); + if (!decoder->init(url, sampleRate)) + { + delete decoder; + decoder = nullptr; + } + } + else if (extension == ".mp3") + { + decoder = new AudioDecoderMp3(); + if (!decoder->init(url, sampleRate)) + { + delete decoder; + decoder = nullptr; + } + } + else + { + auto slesDecoder = new AudioDecoderSLES(); + if (slesDecoder->init(engineItf, url, bufferSizeInFrames, sampleRate, fdGetterCallback)) + { + decoder = slesDecoder; + } + else + { + delete slesDecoder; + } + } + + return decoder; +} + +void AudioDecoderProvider::destroyAudioDecoder(AudioDecoder** decoder) +{ + if (decoder != nullptr && *decoder != nullptr) + { + delete (*decoder); + (*decoder) = nullptr; + } +} + +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderProvider.h b/native/cocos/audio/android/AudioDecoderProvider.h new file mode 100644 index 0000000000..27073e3786 --- /dev/null +++ b/native/cocos/audio/android/AudioDecoderProvider.h @@ -0,0 +1,40 @@ +/**************************************************************************** +Copyright (c) 2017 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. +****************************************************************************/ + +#pragma once + +#include "audio/android/OpenSLHelper.h" + +namespace cocos2d { namespace experimental { + +class AudioDecoder; + +class AudioDecoderProvider +{ +public: + static AudioDecoder* createAudioDecoder(SLEngineItf engineItf, const std::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback); + static void destroyAudioDecoder(AudioDecoder** decoder); +}; + +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderSLES.cpp b/native/cocos/audio/android/AudioDecoderSLES.cpp new file mode 100644 index 0000000000..fcf8dd800d --- /dev/null +++ b/native/cocos/audio/android/AudioDecoderSLES.cpp @@ -0,0 +1,621 @@ +#define LOG_TAG "AudioDecoderSLES" + +#include "audio/android/AudioDecoderSLES.h" +#include "platform/CCFileUtils.h" + +namespace cocos2d { namespace experimental { + +/* Explicitly requesting SL_IID_ANDROIDSIMPLEBUFFERQUEUE and SL_IID_PREFETCHSTATUS +* on the UrlAudioPlayer object for decoding, SL_IID_METADATAEXTRACTION for retrieving the +* format of the decoded audio */ +#define NUM_EXPLICIT_INTERFACES_FOR_PLAYER 3 + +/* Size of the decode buffer queue */ +#define NB_BUFFERS_IN_QUEUE 4 + +/* size of the struct to retrieve the PCM format metadata values: the values we're interested in + * are SLuint32, but it is saved in the data field of a SLMetadataInfo, hence the larger size. + * Nate that this size is queried and displayed at l.452 for demonstration/test purposes. + * */ +#define PCM_METADATA_VALUE_SIZE 32 + +/* used to detect errors likely to have occurred when the OpenSL ES framework fails to open + * a resource, for instance because a file URI is invalid, or an HTTP server doesn't respond. + */ +#define PREFETCHEVENT_ERROR_CANDIDATE (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE) + +//----------------------------------------------------------------- + +static std::mutex __SLPlayerMutex; + +static int toBufferSizeInBytes(int bufferSizeInFrames, int sampleSize, int channelCount) +{ + return bufferSizeInFrames * sampleSize * channelCount; +} + +static int BUFFER_SIZE_IN_BYTES = 0; + +static void checkMetaData(int index, const char *key) +{ + if (index != -1) + { + ALOGV("Key %s is at index %d", key, index); + } + else + { + ALOGE("Unable to find key %s", key); + } +} + +class SLAudioDecoderCallbackProxy +{ +public: + //----------------------------------------------------------------- + /* Callback for "prefetch" events, here used to detect audio resource opening errors */ + static void prefetchEventCallback(SLPrefetchStatusItf caller, void *context, SLuint32 event) + { + AudioDecoderSLES *thiz = reinterpret_cast(context); + thiz->prefetchCallback(caller, event); + } + + static void decPlayCallback(SLAndroidSimpleBufferQueueItf queueItf, void *context) + { + AudioDecoderSLES *thiz = reinterpret_cast(context); + thiz->decodeToPcmCallback(queueItf); + } + + static void decProgressCallback(SLPlayItf caller, void *context, SLuint32 event) + { + AudioDecoderSLES *thiz = reinterpret_cast(context); + thiz->decodeProgressCallback(caller, event); + } +}; + +AudioDecoderSLES::AudioDecoderSLES() + : _engineItf(nullptr), _playObj(nullptr), _formatQueried(false), + _prefetchError(false), _counter(0), _numChannelsKeyIndex(-1), _sampleRateKeyIndex(-1), + _bitsPerSampleKeyIndex(-1), _containerSizeKeyIndex(-1), _channelMaskKeyIndex(-1), + _endiannessKeyIndex(-1), _eos(false), _bufferSizeInFrames(-1), + _assetFd(0), _fdGetterCallback(nullptr), _isDecodingCallbackInvoked(false) +{ + ALOGV("Create AudioDecoderSLES"); +} + +AudioDecoderSLES::~AudioDecoderSLES() +{ + { + std::lock_guard lk(__SLPlayerMutex); + SL_DESTROY_OBJ(_playObj); + } + ALOGV("After destroying SL play object"); + if (_assetFd > 0) + { + ALOGV("Closing assetFd: %d", _assetFd); + ::close(_assetFd); + _assetFd = 0; + } + free(_pcmData); +} + +bool AudioDecoderSLES::init(SLEngineItf engineItf, const std::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback) +{ + if (AudioDecoder::init(url, sampleRate)) + { + _engineItf = engineItf; + _bufferSizeInFrames = bufferSizeInFrames; + _fdGetterCallback = fdGetterCallback; + + BUFFER_SIZE_IN_BYTES = toBufferSizeInBytes(bufferSizeInFrames, 2, 2); + _pcmData = (char*) malloc(NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES); + memset(_pcmData, 0x00, NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES); + return true; + } + + return false; +} + +bool AudioDecoderSLES::decodeToPcm() +{ + SLresult result; + + /* Objects this application uses: one audio player */ + SLObjectItf player; + + /* Interfaces for the audio player */ + SLAndroidSimpleBufferQueueItf decBuffQueueItf; + SLPrefetchStatusItf prefetchItf; + SLPlayItf playItf; + SLMetadataExtractionItf mdExtrItf; + + /* Source of audio data for the decoding */ + SLDataSource decSource; + + // decUri & locFd should be defined here + SLDataLocator_URI decUri; + SLDataLocator_AndroidFD locFd; + + /* Data sink for decoded audio */ + SLDataSink decDest; + SLDataLocator_AndroidSimpleBufferQueue decBuffQueue; + SLDataFormat_PCM pcm; + + SLboolean required[NUM_EXPLICIT_INTERFACES_FOR_PLAYER]; + SLInterfaceID iidArray[NUM_EXPLICIT_INTERFACES_FOR_PLAYER]; + + /* Initialize arrays required[] and iidArray[] */ + for (int i = 0; i < NUM_EXPLICIT_INTERFACES_FOR_PLAYER; i++) + { + required[i] = SL_BOOLEAN_FALSE; + iidArray[i] = SL_IID_NULL; + } + + /* ------------------------------------------------------ */ + /* Configuration of the player */ + + /* Request the AndroidSimpleBufferQueue interface */ + required[0] = SL_BOOLEAN_TRUE; + iidArray[0] = SL_IID_ANDROIDSIMPLEBUFFERQUEUE; + /* Request the PrefetchStatus interface */ + required[1] = SL_BOOLEAN_TRUE; + iidArray[1] = SL_IID_PREFETCHSTATUS; + /* Request the PrefetchStatus interface */ + required[2] = SL_BOOLEAN_TRUE; + iidArray[2] = SL_IID_METADATAEXTRACTION; + + SLDataFormat_MIME formatMime = {SL_DATAFORMAT_MIME, nullptr, SL_CONTAINERTYPE_UNSPECIFIED}; + decSource.pFormat = &formatMime; + + if (_url[0] != '/') + { + off_t start = 0, length = 0; + std::string relativePath; + size_t position = _url.find("assets/"); + + if (0 == position) + { + // "assets/" is at the beginning of the path and we don't want it + relativePath = _url.substr(strlen("assets/")); + } else + { + relativePath = _url; + } + + _assetFd = _fdGetterCallback(relativePath, &start, &length); + + if (_assetFd <= 0) + { + ALOGE("Failed to open file descriptor for '%s'", _url.c_str()); + return false; + } + + // configure audio source + locFd = {SL_DATALOCATOR_ANDROIDFD, _assetFd, start, length}; + + decSource.pLocator = &locFd; + } + else + { + decUri = {SL_DATALOCATOR_URI, (SLchar *) _url.c_str()}; + decSource.pLocator = &decUri; + } + + /* Setup the data sink */ + decBuffQueue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; + decBuffQueue.numBuffers = NB_BUFFERS_IN_QUEUE; + /* set up the format of the data in the buffer queue */ + pcm.formatType = SL_DATAFORMAT_PCM; + // FIXME valid value required but currently ignored + pcm.numChannels = 2; + pcm.samplesPerSec = SL_SAMPLINGRATE_44_1; + pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; + pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; + pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; + pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; + + decDest.pLocator = (void *) &decBuffQueue; + decDest.pFormat = (void *) &pcm; + + { + std::lock_guard lk(__SLPlayerMutex); + /* Create the audio player */ + result = (*_engineItf)->CreateAudioPlayer(_engineItf, &player, &decSource, &decDest, + NUM_EXPLICIT_INTERFACES_FOR_PLAYER, iidArray, + required); + SL_RETURN_VAL_IF_FAILED(result, false, "CreateAudioPlayer failed"); + + _playObj = player; + /* Realize the player in synchronous mode. */ + result = (*player)->Realize(player, SL_BOOLEAN_FALSE); + SL_RETURN_VAL_IF_FAILED(result, false, "Realize failed"); + } + + /* Get the play interface which is implicit */ + result = (*player)->GetInterface(player, SL_IID_PLAY, (void *) &playItf); + SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_PLAY failed"); + + /* Set up the player callback to get events during the decoding */ + // FIXME currently ignored + result = (*playItf)->SetMarkerPosition(playItf, 2000); + SL_RETURN_VAL_IF_FAILED(result, false, "SetMarkerPosition failed"); + + result = (*playItf)->SetPositionUpdatePeriod(playItf, 500); + SL_RETURN_VAL_IF_FAILED(result, false, "SetPositionUpdatePeriod failed"); + result = (*playItf)->SetCallbackEventsMask(playItf, + SL_PLAYEVENT_HEADATMARKER | + SL_PLAYEVENT_HEADATNEWPOS | SL_PLAYEVENT_HEADATEND); + SL_RETURN_VAL_IF_FAILED(result, false, "SetCallbackEventsMask failed"); + result = (*playItf)->RegisterCallback(playItf, SLAudioDecoderCallbackProxy::decProgressCallback, + this); + SL_RETURN_VAL_IF_FAILED(result, false, "RegisterCallback failed"); + ALOGV("Play callback registered"); + + + /* Get the buffer queue interface which was explicitly requested */ + result = (*player)->GetInterface(player, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, + (void *) &decBuffQueueItf); + SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_ANDROIDSIMPLEBUFFERQUEUE failed"); + + /* Get the prefetch status interface which was explicitly requested */ + result = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void *) &prefetchItf); + SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_PREFETCHSTATUS failed"); + + /* Get the metadata extraction interface which was explicitly requested */ + result = (*player)->GetInterface(player, SL_IID_METADATAEXTRACTION, (void *) &mdExtrItf); + SL_RETURN_VAL_IF_FAILED(result, false, "GetInterface SL_IID_METADATAEXTRACTION failed"); + + /* ------------------------------------------------------ */ + /* Initialize the callback and its context for the decoding buffer queue */ + _decContext.playItf = playItf; + _decContext.metaItf = mdExtrItf; + _decContext.pDataBase = (int8_t *) _pcmData; + _decContext.pData = _decContext.pDataBase; + _decContext.size = NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES; + + result = (*decBuffQueueItf)->RegisterCallback(decBuffQueueItf, + SLAudioDecoderCallbackProxy::decPlayCallback, + this); + SL_RETURN_VAL_IF_FAILED(result, false, "decBuffQueueItf RegisterCallback failed"); + + /* Enqueue buffers to map the region of memory allocated to store the decoded data */ +// ALOGV("Enqueueing buffer "); + for (int i = 0; i < NB_BUFFERS_IN_QUEUE; i++) + { + result = (*decBuffQueueItf)->Enqueue(decBuffQueueItf, _decContext.pData, + BUFFER_SIZE_IN_BYTES); + SL_RETURN_VAL_IF_FAILED(result, false, "Enqueue failed"); + _decContext.pData += BUFFER_SIZE_IN_BYTES; + } + + _decContext.pData = _decContext.pDataBase; + + /* ------------------------------------------------------ */ + /* Initialize the callback for prefetch errors, if we can't open the resource to decode */ + result = (*prefetchItf)->RegisterCallback(prefetchItf, + SLAudioDecoderCallbackProxy::prefetchEventCallback, + this); + SL_RETURN_VAL_IF_FAILED(result, false, "prefetchItf RegisterCallback failed"); + + result = (*prefetchItf)->SetCallbackEventsMask(prefetchItf, PREFETCHEVENT_ERROR_CANDIDATE); + SL_RETURN_VAL_IF_FAILED(result, false, "prefetchItf SetCallbackEventsMask failed"); + + /* ------------------------------------------------------ */ + /* Prefetch the data so we can get information about the format before starting to decode */ + /* 1/ cause the player to prefetch the data */ + result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PAUSED); + SL_RETURN_VAL_IF_FAILED(result, false, "SetPlayState SL_PLAYSTATE_PAUSED failed"); + + /* 2/ block until data has been prefetched */ + SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW; + SLuint32 timeOutIndex = 1000; //cjh time out prefetching after 2s + while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0) && + !_prefetchError) + { + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + (*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus); + timeOutIndex--; + } + if (timeOutIndex == 0 || _prefetchError) + { + ALOGE("Failure to prefetch data in time, exiting"); + SL_RETURN_VAL_IF_FAILED(SL_RESULT_CONTENT_NOT_FOUND, false, + "Failure to prefetch data in time"); + } + + /* ------------------------------------------------------ */ + /* Display duration */ + SLmillisecond durationInMsec = SL_TIME_UNKNOWN; + result = (*playItf)->GetDuration(playItf, &durationInMsec); + SL_RETURN_VAL_IF_FAILED(result, false, "GetDuration failed"); + + if (durationInMsec == SL_TIME_UNKNOWN) + { + ALOGV("Content duration is unknown"); + } else + { + ALOGV("Content duration is %dms", (int)durationInMsec); + } + + /* ------------------------------------------------------ */ + /* Display the metadata obtained from the decoder */ + // This is for test / demonstration purposes only where we discover the key and value sizes + // of a PCM decoder. An application that would want to directly get access to those values + // can make assumptions about the size of the keys and their matching values (all SLuint32) + SLuint32 itemCount; + result = (*mdExtrItf)->GetItemCount(mdExtrItf, &itemCount); + SLuint32 i, keySize, valueSize; + SLMetadataInfo *keyInfo, *value; + for (i = 0; i < itemCount; i++) + { + keyInfo = nullptr; + keySize = 0; + value = nullptr; + valueSize = 0; + result = (*mdExtrItf)->GetKeySize(mdExtrItf, i, &keySize); + SL_RETURN_VAL_IF_FAILED(result, false, "GetKeySize(%d) failed", (int)i); + + result = (*mdExtrItf)->GetValueSize(mdExtrItf, i, &valueSize); + SL_RETURN_VAL_IF_FAILED(result, false, "GetValueSize(%d) failed", (int)i); + + keyInfo = (SLMetadataInfo *) malloc(keySize); + if (nullptr != keyInfo) + { + result = (*mdExtrItf)->GetKey(mdExtrItf, i, keySize, keyInfo); + + SL_RETURN_VAL_IF_FAILED(result, false, "GetKey(%d) failed", (int)i); + + ALOGV("key[%d] size=%d, name=%s, value size=%d", + (int)i, (int)keyInfo->size, keyInfo->data, (int)valueSize); + /* find out the key index of the metadata we're interested in */ + if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_NUMCHANNELS)) + { + _numChannelsKeyIndex = i; + } else if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_SAMPLERATE)) + { + _sampleRateKeyIndex = i; + } else if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_BITSPERSAMPLE)) + { + _bitsPerSampleKeyIndex = i; + } else if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_CONTAINERSIZE)) + { + _containerSizeKeyIndex = i; + } else if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_CHANNELMASK)) + { + _channelMaskKeyIndex = i; + } else if (!strcmp((char *) keyInfo->data, ANDROID_KEY_PCMFORMAT_ENDIANNESS)) + { + _endiannessKeyIndex = i; + } + free(keyInfo); + } + } + + checkMetaData(_numChannelsKeyIndex, ANDROID_KEY_PCMFORMAT_NUMCHANNELS); + checkMetaData(_sampleRateKeyIndex, ANDROID_KEY_PCMFORMAT_SAMPLERATE); + checkMetaData(_bitsPerSampleKeyIndex, ANDROID_KEY_PCMFORMAT_BITSPERSAMPLE); + checkMetaData(_containerSizeKeyIndex, ANDROID_KEY_PCMFORMAT_CONTAINERSIZE); + checkMetaData(_channelMaskKeyIndex, ANDROID_KEY_PCMFORMAT_CHANNELMASK); + checkMetaData(_endiannessKeyIndex, ANDROID_KEY_PCMFORMAT_ENDIANNESS); + + /* ------------------------------------------------------ */ + /* Start decoding */ + result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); + SL_RETURN_VAL_IF_FAILED(result, false, "SetPlayState SL_PLAYSTATE_PLAYING failed"); + + ALOGV("Starting to decode"); + + /* Decode until the end of the stream is reached */ + { + std::unique_lock autoLock(_eosLock); + while (!_eos) + { + _eosCondition.wait(autoLock); + } + } + ALOGV("EOS signaled"); + + /* ------------------------------------------------------ */ + /* End of decoding */ + + /* Stop decoding */ + result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED); + SL_RETURN_VAL_IF_FAILED(result, false, "SetPlayState SL_PLAYSTATE_STOPPED failed"); + + ALOGV("Stopped decoding"); + + /* Destroy the UrlAudioPlayer object */ + { + std::lock_guard lk(__SLPlayerMutex); + SL_DESTROY_OBJ(_playObj); + } + + ALOGV("After destroy player ..."); + + _result.numFrames = + _result.pcmBuffer->size() / _result.numChannels / (_result.bitsPerSample / 8); + + std::string info = _result.toString(); + ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size()); + return true; +} + +//----------------------------------------------------------------- +void AudioDecoderSLES::signalEos() +{ + std::unique_lock autoLock(_eosLock); + _eos = true; + _eosCondition.notify_one(); +} + +void AudioDecoderSLES::queryAudioInfo() +{ + if (_formatQueried) + { + return; + } + + SLresult result; + /* Get duration in callback where we use the callback context for the SLPlayItf*/ + SLmillisecond durationInMsec = SL_TIME_UNKNOWN; + result = (*_decContext.playItf)->GetDuration(_decContext.playItf, &durationInMsec); + SL_RETURN_IF_FAILED(result, "decodeProgressCallback,GetDuration failed"); + + if (durationInMsec == SL_TIME_UNKNOWN) + { + ALOGV("Content duration is unknown (in dec callback)"); + } else + { + ALOGV("Content duration is %dms (in dec callback)", (int)durationInMsec); + _result.duration = durationInMsec / 1000.0f; + } + + /* used to query metadata values */ + SLMetadataInfo pcmMetaData; + + result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _sampleRateKeyIndex, + PCM_METADATA_VALUE_SIZE, &pcmMetaData); + + SL_RETURN_IF_FAILED(result, "%s GetValue _sampleRateKeyIndex failed", __FUNCTION__); + // Note: here we could verify the following: + // pcmMetaData->encoding == SL_CHARACTERENCODING_BINARY + // pcmMetaData->size == sizeof(SLuint32) + // but the call was successful for the PCM format keys, so those conditions are implied + + _result.sampleRate = *((SLuint32 *) pcmMetaData.data); + result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _numChannelsKeyIndex, + PCM_METADATA_VALUE_SIZE, &pcmMetaData); + SL_RETURN_IF_FAILED(result, "%s GetValue _numChannelsKeyIndex failed", __FUNCTION__); + + _result.numChannels = *((SLuint32 *) pcmMetaData.data); + + result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _bitsPerSampleKeyIndex, + PCM_METADATA_VALUE_SIZE, &pcmMetaData); + SL_RETURN_IF_FAILED(result, "%s GetValue _bitsPerSampleKeyIndex failed", __FUNCTION__) + _result.bitsPerSample = *((SLuint32 *) pcmMetaData.data); + + result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _containerSizeKeyIndex, + PCM_METADATA_VALUE_SIZE, &pcmMetaData); + SL_RETURN_IF_FAILED(result, "%s GetValue _containerSizeKeyIndex failed", __FUNCTION__) + _result.containerSize = *((SLuint32 *) pcmMetaData.data); + + result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _channelMaskKeyIndex, + PCM_METADATA_VALUE_SIZE, &pcmMetaData); + SL_RETURN_IF_FAILED(result, "%s GetValue _channelMaskKeyIndex failed", __FUNCTION__) + _result.channelMask = *((SLuint32 *) pcmMetaData.data); + + result = (*_decContext.metaItf)->GetValue(_decContext.metaItf, _endiannessKeyIndex, + PCM_METADATA_VALUE_SIZE, &pcmMetaData); + SL_RETURN_IF_FAILED(result, "%s GetValue _endiannessKeyIndex failed", __FUNCTION__) + _result.endianness = *((SLuint32 *) pcmMetaData.data); + + _formatQueried = true; +} + +void AudioDecoderSLES::prefetchCallback(SLPrefetchStatusItf caller, SLuint32 event) +{ + SLpermille level = 0; + SLresult result; + result = (*caller)->GetFillLevel(caller, &level); + SL_RETURN_IF_FAILED(result, "GetFillLevel failed"); + + SLuint32 status; + //ALOGV("PrefetchEventCallback: received event %u", event); + result = (*caller)->GetPrefetchStatus(caller, &status); + + SL_RETURN_IF_FAILED(result, "GetPrefetchStatus failed"); + + if ((PREFETCHEVENT_ERROR_CANDIDATE == (event & PREFETCHEVENT_ERROR_CANDIDATE)) + && (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) + { + ALOGV("PrefetchEventCallback: Error while prefetching data, exiting"); + _prefetchError = true; + signalEos(); + } +} + +/* Callback for "playback" events, i.e. event happening during decoding */ +void AudioDecoderSLES::decodeProgressCallback(SLPlayItf caller, SLuint32 event) +{ + if (SL_PLAYEVENT_HEADATEND & event) + { + ALOGV("SL_PLAYEVENT_HEADATEND"); + if (!_isDecodingCallbackInvoked) + { + queryAudioInfo(); + + for (int i = 0; i < NB_BUFFERS_IN_QUEUE; ++i) + { + _result.pcmBuffer->insert(_result.pcmBuffer->end(), _decContext.pData, + _decContext.pData + BUFFER_SIZE_IN_BYTES); + + /* Increase data pointer by buffer size */ + _decContext.pData += BUFFER_SIZE_IN_BYTES; + } + } + signalEos(); + } +} + +//----------------------------------------------------------------- +/* Callback for decoding buffer queue events */ +void AudioDecoderSLES::decodeToPcmCallback(SLAndroidSimpleBufferQueueItf queueItf) +{ + _isDecodingCallbackInvoked = true; + ALOGV("%s ...", __FUNCTION__); + _counter++; + SLresult result; + // FIXME: ?? + if (_counter % 1000 == 0) + { + SLmillisecond msec; + result = (*_decContext.playItf)->GetPosition(_decContext.playItf, &msec); + SL_RETURN_IF_FAILED(result, "%s, GetPosition failed", __FUNCTION__); + ALOGV("%s called (iteration %d): current position=%d ms", __FUNCTION__, _counter, (int)msec); + } + + _result.pcmBuffer->insert(_result.pcmBuffer->end(), _decContext.pData, + _decContext.pData + BUFFER_SIZE_IN_BYTES); + + result = (*queueItf)->Enqueue(queueItf, _decContext.pData, BUFFER_SIZE_IN_BYTES); + SL_RETURN_IF_FAILED(result, "%s, Enqueue failed", __FUNCTION__); + + /* Increase data pointer by buffer size */ + _decContext.pData += BUFFER_SIZE_IN_BYTES; + + if (_decContext.pData >= _decContext.pDataBase + (NB_BUFFERS_IN_QUEUE * BUFFER_SIZE_IN_BYTES)) + { + _decContext.pData = _decContext.pDataBase; + } + + // Note: adding a sleep here or any sync point is a way to slow down the decoding, or + // synchronize it with some other event, as the OpenSL ES framework will block until the + // buffer queue callback return to proceed with the decoding. + +#if 0 + /* Example: buffer queue state display */ + SLAndroidSimpleBufferQueueState decQueueState; + result =(*queueItf)->GetState(queueItf, &decQueueState); + SL_RETURN_IF_FAILED(result, "decQueueState.GetState failed"); + + ALOGV("DecBufferQueueCallback now has _decContext.pData=%p, _decContext.pDataBase=%p, queue: " + "count=%u playIndex=%u, count: %d", + _decContext.pData, _decContext.pDataBase, decQueueState.count, decQueueState.index, _counter); +#endif + +#if 0 + /* Example: display position in callback where we use the callback context for the SLPlayItf*/ + SLmillisecond posMsec = SL_TIME_UNKNOWN; + result = (*_decContext.playItf)->GetPosition(_decContext.playItf, &posMsec); + SL_RETURN_IF_FAILED(result, "decodeToPcmCallback,GetPosition2 failed"); + + if (posMsec == SL_TIME_UNKNOWN) { + ALOGV("Content position is unknown (in dec callback)"); + } else { + ALOGV("Content position is %ums (in dec callback)", + posMsec); + } +#endif + + queryAudioInfo(); +} + +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioDecoderSLES.h b/native/cocos/audio/android/AudioDecoderSLES.h new file mode 100644 index 0000000000..39d5bf0440 --- /dev/null +++ b/native/cocos/audio/android/AudioDecoderSLES.h @@ -0,0 +1,96 @@ +/**************************************************************************** +Copyright (c) 2017 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. +****************************************************************************/ + +#pragma once + +#include "audio/android/AudioDecoder.h" +#include +#include + +namespace cocos2d { namespace experimental { + +class AudioDecoderSLES : public AudioDecoder +{ +protected: + AudioDecoderSLES(); + virtual ~AudioDecoderSLES(); + + bool init(SLEngineItf engineItf, const std::string &url, int bufferSizeInFrames, int sampleRate, const FdGetterCallback &fdGetterCallback); + virtual bool decodeToPcm() override; + +private: + void queryAudioInfo(); + + void signalEos(); + void decodeToPcmCallback(SLAndroidSimpleBufferQueueItf queueItf); + void prefetchCallback(SLPrefetchStatusItf caller, SLuint32 event); + void decodeProgressCallback(SLPlayItf caller, SLuint32 event); + + SLEngineItf _engineItf; + SLObjectItf _playObj; + /* Local storage for decoded audio data */ + char* _pcmData; + + /* we only want to query / display the PCM format once */ + bool _formatQueried; + /* Used to signal prefetching failures */ + bool _prefetchError; + + /* to display the number of decode iterations */ + int _counter; + + /* metadata key index for the PCM format information we want to retrieve */ + int _numChannelsKeyIndex; + int _sampleRateKeyIndex; + int _bitsPerSampleKeyIndex; + int _containerSizeKeyIndex; + int _channelMaskKeyIndex; + int _endiannessKeyIndex; + + /* to signal to the test app the end of the stream to decode has been reached */ + bool _eos; + std::mutex _eosLock; + std::condition_variable _eosCondition; + + /* Structure for passing information to callback function */ + typedef struct CallbackCntxt_ + { + SLPlayItf playItf; + SLMetadataExtractionItf metaItf; + SLuint32 size; + SLint8 *pDataBase; // Base address of local audio data storage + SLint8 *pData; // Current address of local audio data storage + } CallbackCntxt; + + CallbackCntxt _decContext; + int _bufferSizeInFrames; + int _assetFd; + FdGetterCallback _fdGetterCallback; + bool _isDecodingCallbackInvoked; + + friend class SLAudioDecoderCallbackProxy; + friend class AudioDecoderProvider; +}; + +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/AudioPlayerProvider.cpp b/native/cocos/audio/android/AudioPlayerProvider.cpp index 8727eb209e..5a750594eb 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.cpp +++ b/native/cocos/audio/android/AudioPlayerProvider.cpp @@ -28,6 +28,7 @@ THE SOFTWARE. #include "audio/android/UrlAudioPlayer.h" #include "audio/android/PcmAudioPlayer.h" #include "audio/android/AudioDecoder.h" +#include "audio/android/AudioDecoderProvider.h" #include "audio/android/AudioMixerController.h" #include "audio/android/PcmAudioService.h" #include "audio/android/CCThreadPool.h" @@ -149,13 +150,15 @@ IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const std::string &audioFilePa std::thread::id threadId = std::this_thread::get_id(); - preloadEffect(info, [&info, threadId, pcmData, isSucceed, isReturnFromCache](bool succeed, PcmData data){ + void* infoPtr = &info; + std::string url = info.url; + preloadEffect(info, [infoPtr, url, 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; - ALOGV("FileInfo (%p), Set isSucceed flag: %d, path: %s", &info, succeed, info.url.c_str()); + ALOGV("FileInfo (%p), Set isSucceed flag: %d, path: %s", infoPtr, succeed, url.c_str()); }, true); if (!*isReturnFromCache) @@ -297,11 +300,11 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload _threadPool->pushTask([this, audioFilePath, isPreloadInPlay2d](int tid) { ALOGV("AudioPlayerProvider::preloadEffect: (%s)", audioFilePath.c_str()); PcmData d; - AudioDecoder decoder(_engineItf, audioFilePath, _bufferSizeInFrames, _deviceSampleRate, _fdGetterCallback); - bool ret = decoder.start(); + AudioDecoder* decoder = AudioDecoderProvider::createAudioDecoder(_engineItf, audioFilePath, _bufferSizeInFrames, _deviceSampleRate, _fdGetterCallback); + bool ret = decoder != nullptr && decoder->start(); if (ret) { - d = decoder.getResult(); + d = decoder->getResult(); std::lock_guard lk(_pcmCacheMutex); _pcmCache.insert(std::make_pair(audioFilePath, d)); } @@ -310,14 +313,15 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload ALOGE("decode (%s) failed!", audioFilePath.c_str()); } - ALOGV("decode succeed."); + ALOGV("decode %s", (ret ? "succeed" : "failed")); + std::lock_guard 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(); + ALOGV("preload (%s) callback count: %d", audioFilePath.c_str(), (int)params.size()); + PcmData result = decoder->getResult(); for (auto&& param : params) { param.callback(ret, result); @@ -329,6 +333,8 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload _preloadWaitCond.notify_one(); } } + + AudioDecoderProvider::destroyAudioDecoder(&decoder); }); } else diff --git a/native/cocos/audio/android/Track.cpp b/native/cocos/audio/android/Track.cpp index 29ace2a50b..da06da5df9 100644 --- a/native/cocos/audio/android/Track.cpp +++ b/native/cocos/audio/android/Track.cpp @@ -94,4 +94,4 @@ void Track::setState(State state) } }; -}} // namespace cocos2d { namespace experimental { +}} // namespace cocos2d { namespace experimental { \ No newline at end of file diff --git a/native/cocos/audio/android/mp3reader.cpp b/native/cocos/audio/android/mp3reader.cpp new file mode 100644 index 0000000000..eacee02c17 --- /dev/null +++ b/native/cocos/audio/android/mp3reader.cpp @@ -0,0 +1,526 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include "audio/android/cutils/log.h" + +#include "pvmp3decoder_api.h" +#include "mp3reader.h" + +using namespace std; + +static uint32_t U32_AT(const uint8_t *ptr) { + return ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3]; +} + +static bool parseHeader( + uint32_t header, size_t *frame_size, + uint32_t *out_sampling_rate = NULL, uint32_t *out_channels = NULL , + uint32_t *out_bitrate = NULL, uint32_t *out_num_samples = NULL) { + *frame_size = 0; + + if (out_sampling_rate) { + *out_sampling_rate = 0; + } + + if (out_channels) { + *out_channels = 0; + } + + if (out_bitrate) { + *out_bitrate = 0; + } + + if (out_num_samples) { + *out_num_samples = 1152; + } + + if ((header & 0xffe00000) != 0xffe00000) { + return false; + } + + unsigned version = (header >> 19) & 3; + + if (version == 0x01) { + return false; + } + + unsigned layer = (header >> 17) & 3; + + if (layer == 0x00) { + return false; + } + + unsigned bitrate_index = (header >> 12) & 0x0f; + + if (bitrate_index == 0 || bitrate_index == 0x0f) { + // Disallow "free" bitrate. + return false; + } + + unsigned sampling_rate_index = (header >> 10) & 3; + + if (sampling_rate_index == 3) { + return false; + } + + static const int kSamplingRateV1[] = { 44100, 48000, 32000 }; + int sampling_rate = kSamplingRateV1[sampling_rate_index]; + if (version == 2 /* V2 */) { + sampling_rate /= 2; + } else if (version == 0 /* V2.5 */) { + sampling_rate /= 4; + } + + unsigned padding = (header >> 9) & 1; + + if (layer == 3) { + // layer I + + static const int kBitrateV1[] = { + 32, 64, 96, 128, 160, 192, 224, 256, + 288, 320, 352, 384, 416, 448 + }; + + static const int kBitrateV2[] = { + 32, 48, 56, 64, 80, 96, 112, 128, + 144, 160, 176, 192, 224, 256 + }; + + int bitrate = + (version == 3 /* V1 */) + ? kBitrateV1[bitrate_index - 1] + : kBitrateV2[bitrate_index - 1]; + + if (out_bitrate) { + *out_bitrate = bitrate; + } + + *frame_size = (12000 * bitrate / sampling_rate + padding) * 4; + + if (out_num_samples) { + *out_num_samples = 384; + } + } else { + // layer II or III + + static const int kBitrateV1L2[] = { + 32, 48, 56, 64, 80, 96, 112, 128, + 160, 192, 224, 256, 320, 384 + }; + + static const int kBitrateV1L3[] = { + 32, 40, 48, 56, 64, 80, 96, 112, + 128, 160, 192, 224, 256, 320 + }; + + static const int kBitrateV2[] = { + 8, 16, 24, 32, 40, 48, 56, 64, + 80, 96, 112, 128, 144, 160 + }; + + int bitrate; + if (version == 3 /* V1 */) { + bitrate = (layer == 2 /* L2 */) + ? kBitrateV1L2[bitrate_index - 1] + : kBitrateV1L3[bitrate_index - 1]; + + if (out_num_samples) { + *out_num_samples = 1152; + } + } else { + // V2 (or 2.5) + + bitrate = kBitrateV2[bitrate_index - 1]; + if (out_num_samples) { + *out_num_samples = (layer == 1 /* L3 */) ? 576 : 1152; + } + } + + if (out_bitrate) { + *out_bitrate = bitrate; + } + + if (version == 3 /* V1 */) { + *frame_size = 144000 * bitrate / sampling_rate + padding; + } else { + // V2 or V2.5 + size_t tmp = (layer == 1 /* L3 */) ? 72000 : 144000; + *frame_size = tmp * bitrate / sampling_rate + padding; + } + } + + if (out_sampling_rate) { + *out_sampling_rate = sampling_rate; + } + + if (out_channels) { + int channel_mode = (header >> 6) & 3; + + *out_channels = (channel_mode == 3) ? 1 : 2; + } + + return true; +} + +// Mask to extract the version, layer, sampling rate parts of the MP3 header, +// which should be same for all MP3 frames. +static const uint32_t kMask = 0xfffe0c00; + +static ssize_t sourceReadAt(mp3_callbacks *callback, void* source, off64_t offset, void *data, size_t size) { + int retVal = callback->seek(source, offset, SEEK_SET); + if (retVal != EXIT_SUCCESS) { + return 0; + } else { + return callback->read(data, 1, size, source); + } +} + +// Resync to next valid MP3 frame in the file. +static bool resync( + mp3_callbacks *callback, void* source, uint32_t match_header, + off64_t *inout_pos, uint32_t *out_header) { + + if (*inout_pos == 0) { + // Skip an optional ID3 header if syncing at the very beginning + // of the datasource. + + for (;;) { + uint8_t id3header[10]; + int retVal = sourceReadAt(callback, source, *inout_pos, id3header, + sizeof(id3header)); + if (retVal < (ssize_t)sizeof(id3header)) { + // If we can't even read these 10 bytes, we might as well bail + // out, even if there _were_ 10 bytes of valid mp3 audio data... + return false; + } + + if (memcmp("ID3", id3header, 3)) { + break; + } + + // Skip the ID3v2 header. + + size_t len = + ((id3header[6] & 0x7f) << 21) + | ((id3header[7] & 0x7f) << 14) + | ((id3header[8] & 0x7f) << 7) + | (id3header[9] & 0x7f); + + len += 10; + + *inout_pos += len; + } + + } + + off64_t pos = *inout_pos; + bool valid = false; + + const int32_t kMaxReadBytes = 1024; + const int32_t kMaxBytesChecked = 128 * 1024; + uint8_t buf[kMaxReadBytes]; + ssize_t bytesToRead = kMaxReadBytes; + ssize_t totalBytesRead = 0; + ssize_t remainingBytes = 0; + bool reachEOS = false; + uint8_t *tmp = buf; + + do { + if (pos >= *inout_pos + kMaxBytesChecked) { + // Don't scan forever. + break; + } + + if (remainingBytes < 4) { + if (reachEOS) { + break; + } else { + memcpy(buf, tmp, remainingBytes); + bytesToRead = kMaxReadBytes - remainingBytes; + + /* + * The next read position should start from the end of + * the last buffer, and thus should include the remaining + * bytes in the buffer. + */ + totalBytesRead = sourceReadAt(callback, source, pos + remainingBytes, + buf + remainingBytes, bytesToRead); + + if (totalBytesRead <= 0) { + break; + } + reachEOS = (totalBytesRead != bytesToRead); + remainingBytes += totalBytesRead; + tmp = buf; + continue; + } + } + + uint32_t header = U32_AT(tmp); + + if (match_header != 0 && (header & kMask) != (match_header & kMask)) { + ++pos; + ++tmp; + --remainingBytes; + continue; + } + + size_t frame_size; + uint32_t sample_rate, num_channels, bitrate; + if (!parseHeader( + header, &frame_size, + &sample_rate, &num_channels, &bitrate)) { + ++pos; + ++tmp; + --remainingBytes; + continue; + } + + // We found what looks like a valid frame, + // now find its successors. + + off64_t test_pos = pos + frame_size; + + valid = true; + const int FRAME_MATCH_REQUIRED = 3; + for (int j = 0; j < FRAME_MATCH_REQUIRED; ++j) { + uint8_t tmp[4]; + ssize_t retval = sourceReadAt(callback, source, test_pos, tmp, sizeof(tmp)); + if (retval < (ssize_t)sizeof(tmp)) { + valid = false; + break; + } + + uint32_t test_header = U32_AT(tmp); + + if ((test_header & kMask) != (header & kMask)) { + valid = false; + break; + } + + size_t test_frame_size; + if (!parseHeader(test_header, &test_frame_size)) { + valid = false; + break; + } + + test_pos += test_frame_size; + } + + if (valid) { + *inout_pos = pos; + + if (out_header != NULL) { + *out_header = header; + } + } + + ++pos; + ++tmp; + --remainingBytes; + } while (!valid); + + return valid; +} + +Mp3Reader::Mp3Reader() : mSource(NULL), mCallback(NULL) { +} + +// Initialize the MP3 reader. +bool Mp3Reader::init(mp3_callbacks *callback, void* source) { + + mSource = source; + mCallback = callback; + // Open the file. + // mFp = fopen(file, "rb"); + // if (mFp == NULL) return false; + + // Sync to the first valid frame. + off64_t pos = 0; + uint32_t header; + bool success = resync(callback, source, 0 /*match_header*/, &pos, &header); + if (success == false) return false; + + mCurrentPos = pos; + mFixedHeader = header; + + size_t frame_size; + return parseHeader(header, &frame_size, &mSampleRate, + &mNumChannels, &mBitrate); +} + +// Get the next valid MP3 frame. +bool Mp3Reader::getFrame(void *buffer, uint32_t *size) { + + size_t frame_size; + uint32_t bitrate; + uint32_t num_samples; + uint32_t sample_rate; + for (;;) { + ssize_t n = sourceReadAt(mCallback, mSource, mCurrentPos, buffer, 4); + if (n < 4) { + return false; + } + + uint32_t header = U32_AT((const uint8_t *)buffer); + + if ((header & kMask) == (mFixedHeader & kMask) + && parseHeader( + header, &frame_size, &sample_rate, NULL /*out_channels*/, + &bitrate, &num_samples)) { + break; + } + + // Lost sync. + off64_t pos = mCurrentPos; + if (!resync(mCallback, mSource, mFixedHeader, &pos, NULL /*out_header*/)) { + // Unable to resync. Signalling end of stream. + return false; + } + + mCurrentPos = pos; + + // Try again with the new position. + } + ssize_t n = sourceReadAt(mCallback, mSource, mCurrentPos, buffer, frame_size); + if (n < (ssize_t)frame_size) { + return false; + } + + *size = frame_size; + mCurrentPos += frame_size; + return true; +} + +// Close the MP3 reader. +void Mp3Reader::close() { + assert(mCallback != NULL); + mCallback->close(mSource); +} + +Mp3Reader::~Mp3Reader() { +} + +enum { + kInputBufferSize = 10 * 1024, + kOutputBufferSize = 4608 * 2, +}; + +int decodeMP3(mp3_callbacks* cb, void* source, std::vector& pcmBuffer, int* numChannels, int* sampleRate, int* numFrames) +{ + // Initialize the config. + tPVMP3DecoderExternal config; + config.equalizerType = flat; + config.crcEnabled = false; + + // Allocate the decoder memory. + uint32_t memRequirements = pvmp3_decoderMemRequirements(); + void *decoderBuf = malloc(memRequirements); + assert(decoderBuf != NULL); + + // Initialize the decoder. + pvmp3_InitDecoder(&config, decoderBuf); + + // Open the input file. + Mp3Reader mp3Reader; + bool success = mp3Reader.init(cb, source); + if (!success) { + fprintf(stderr, "Encountered error reading\n"); + free(decoderBuf); + return EXIT_FAILURE; + } + + // Open the output file. + // SF_INFO sfInfo; + // memset(&sfInfo, 0, sizeof(SF_INFO)); + // sfInfo.channels = mp3Reader.getNumChannels(); + // sfInfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; + // sfInfo.samplerate = mp3Reader.getSampleRate(); + // SNDFILE *handle = sf_open(argv[2], SFM_WRITE, &sfInfo); + // if (handle == NULL) { + // fprintf(stderr, "Encountered error writing %s\n", argv[2]); + // mp3Reader.close(); + // free(decoderBuf); + // return EXIT_FAILURE; + // } + + // Allocate input buffer. + uint8_t *inputBuf = static_cast(malloc(kInputBufferSize)); + assert(inputBuf != NULL); + + // Allocate output buffer. + int16_t *outputBuf = static_cast(malloc(kOutputBufferSize)); + assert(outputBuf != NULL); + + // Decode loop. + int retVal = EXIT_SUCCESS; + while (1) { + // Read input from the file. + uint32_t bytesRead; + bool success = mp3Reader.getFrame(inputBuf, &bytesRead); + if (!success) break; + + *numChannels = mp3Reader.getNumChannels(); + *sampleRate = mp3Reader.getSampleRate(); + + // Set the input config. + config.inputBufferCurrentLength = bytesRead; + config.inputBufferMaxLength = 0; + config.inputBufferUsedLength = 0; + config.pInputBuffer = inputBuf; + config.pOutputBuffer = outputBuf; + config.outputFrameSize = kOutputBufferSize / sizeof(int16_t); + + ERROR_CODE decoderErr; + decoderErr = pvmp3_framedecoder(&config, decoderBuf); + if (decoderErr != NO_DECODING_ERROR) { + fprintf(stderr, "Decoder encountered error\n"); + retVal = EXIT_FAILURE; + break; + } + + pcmBuffer.insert(pcmBuffer.end(), (char*)outputBuf, ((char*)outputBuf) + config.outputFrameSize * 2); + *numFrames += config.outputFrameSize / mp3Reader.getNumChannels(); + } + + // Close input reader and output writer. + mp3Reader.close(); + // sf_close(handle); + + // Free allocated memory. + free(inputBuf); + free(outputBuf); + free(decoderBuf); + + return retVal; +} diff --git a/native/cocos/audio/android/mp3reader.h b/native/cocos/audio/android/mp3reader.h new file mode 100644 index 0000000000..7c9e0a7a59 --- /dev/null +++ b/native/cocos/audio/android/mp3reader.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#ifndef MP3READER_H_ +#define MP3READER_H_ + +typedef struct { + size_t (*read) (void *ptr, size_t size, size_t nmemb, void *datasource); + int (*seek) (void *datasource, int64_t offset, int whence); + int (*close) (void *datasource); + long (*tell) (void *datasource); +} mp3_callbacks; + +class Mp3Reader { +public: + Mp3Reader(); + bool init(mp3_callbacks *callback, void* source); + bool getFrame(void *buffer, uint32_t *size); + uint32_t getSampleRate() { return mSampleRate;} + uint32_t getNumChannels() { return mNumChannels;} + void close(); + ~Mp3Reader(); +private: + void *mSource; + mp3_callbacks* mCallback; + uint32_t mFixedHeader; + off64_t mCurrentPos; + uint32_t mSampleRate; + uint32_t mNumChannels; + uint32_t mBitrate; +}; + +int decodeMP3(mp3_callbacks* cb, void* source, std::vector& pcmBuffer, int* numChannels, int* sampleRate, int* numFrames); + + +#endif /* MP3READER_H_ */ diff --git a/native/external/config.json b/native/external/config.json index defcebe34e..fa12146643 100644 --- a/native/external/config.json +++ b/native/external/config.json @@ -1,5 +1,5 @@ { - "version":"v3-deps-20", + "version":"v3-deps-21", "zip_file_size":"62588953", "repo_name":"cocos2d-x-lite-external", "repo_parent":"https://github.com/cocos-creator/"