Path: blob/master/platform/android/audio_driver_opensl.cpp
10277 views
/**************************************************************************/1/* audio_driver_opensl.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "audio_driver_opensl.h"3132#define MAX_NUMBER_INTERFACES 333#define MAX_NUMBER_OUTPUT_DEVICES 63435/* Structure for passing information to callback function */3637void AudioDriverOpenSL::_buffer_callback(38SLAndroidSimpleBufferQueueItf queueItf) {39bool mix = true;4041if (pause) {42mix = false;43} else {44mix = mutex.try_lock();45}4647if (mix) {48audio_server_process(buffer_size, mixdown_buffer);49} else {50int32_t *src_buff = mixdown_buffer;51for (unsigned int i = 0; i < buffer_size * 2; i++) {52src_buff[i] = 0;53}54}5556if (mix) {57mutex.unlock();58}5960const int32_t *src_buff = mixdown_buffer;6162int16_t *ptr = (int16_t *)buffers[last_free];63last_free = (last_free + 1) % BUFFER_COUNT;6465for (unsigned int i = 0; i < buffer_size * 2; i++) {66ptr[i] = src_buff[i] >> 16;67}6869(*queueItf)->Enqueue(queueItf, ptr, 4 * buffer_size);70}7172void AudioDriverOpenSL::_buffer_callbacks(73SLAndroidSimpleBufferQueueItf queueItf,74void *pContext) {75AudioDriverOpenSL *ad = static_cast<AudioDriverOpenSL *>(pContext);7677ad->_buffer_callback(queueItf);78}7980Error AudioDriverOpenSL::init() {81SLresult res;82SLEngineOption EngineOption[] = {83{ (SLuint32)SL_ENGINEOPTION_THREADSAFE, (SLuint32)SL_BOOLEAN_TRUE }84};85res = slCreateEngine(&sl, 1, EngineOption, 0, nullptr, nullptr);86ERR_FAIL_COND_V_MSG(res != SL_RESULT_SUCCESS, ERR_INVALID_PARAMETER, "Could not initialize OpenSL.");8788res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);89ERR_FAIL_COND_V_MSG(res != SL_RESULT_SUCCESS, ERR_INVALID_PARAMETER, "Could not realize OpenSL.");9091return OK;92}9394void AudioDriverOpenSL::start() {95active = false;9697SLresult res;9899buffer_size = 1024;100101for (int i = 0; i < BUFFER_COUNT; i++) {102buffers[i] = memnew_arr(int16_t, buffer_size * 2);103memset(buffers[i], 0, buffer_size * 4);104}105106mixdown_buffer = memnew_arr(int32_t, buffer_size * 2);107108/* Callback context for the buffer queue callback function */109110/* Get the SL Engine Interface which is implicit */111res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void *)&EngineItf);112113ERR_FAIL_COND(res != SL_RESULT_SUCCESS);114115{116const SLInterfaceID ids[1] = { SL_IID_ENVIRONMENTALREVERB };117const SLboolean req[1] = { SL_BOOLEAN_FALSE };118res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0, ids, req);119}120121ERR_FAIL_COND(res != SL_RESULT_SUCCESS);122// Realizing the Output Mix object in synchronous mode.123res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);124ERR_FAIL_COND(res != SL_RESULT_SUCCESS);125126SLDataLocator_AndroidSimpleBufferQueue loc_bufq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, BUFFER_COUNT };127/* Setup the format of the content in the buffer queue */128pcm.formatType = SL_DATAFORMAT_PCM;129pcm.numChannels = 2;130pcm.samplesPerSec = SL_SAMPLINGRATE_44_1;131pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;132pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;133pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;134#ifdef BIG_ENDIAN_ENABLED135pcm.endianness = SL_BYTEORDER_BIGENDIAN;136#else137pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;138#endif139audioSource.pFormat = (void *)&pcm;140audioSource.pLocator = (void *)&loc_bufq;141142/* Setup the data sink structure */143locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;144locator_outputmix.outputMix = OutputMix;145audioSink.pLocator = (void *)&locator_outputmix;146audioSink.pFormat = nullptr;147148/* Create the music player */149{150const SLInterfaceID ids[2] = { SL_IID_BUFFERQUEUE, SL_IID_EFFECTSEND };151const SLboolean req[2] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };152153res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink, 1, ids, req);154ERR_FAIL_COND(res != SL_RESULT_SUCCESS);155}156/* Realizing the player in synchronous mode. */157res = (*player)->Realize(player, SL_BOOLEAN_FALSE);158ERR_FAIL_COND(res != SL_RESULT_SUCCESS);159/* Get seek and play interfaces */160res = (*player)->GetInterface(player, SL_IID_PLAY, (void *)&playItf);161ERR_FAIL_COND(res != SL_RESULT_SUCCESS);162res = (*player)->GetInterface(player, SL_IID_BUFFERQUEUE,163(void *)&bufferQueueItf);164ERR_FAIL_COND(res != SL_RESULT_SUCCESS);165/* Setup to receive buffer queue event callbacks */166res = (*bufferQueueItf)->RegisterCallback(bufferQueueItf, _buffer_callbacks, this);167ERR_FAIL_COND(res != SL_RESULT_SUCCESS);168169last_free = 0;170171//fill up buffers172for (int i = 0; i < BUFFER_COUNT; i++) {173/* Enqueue a few buffers to get the ball rolling */174res = (*bufferQueueItf)->Enqueue(bufferQueueItf, buffers[i], 4 * buffer_size); /* Size given in */175}176177res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING);178ERR_FAIL_COND(res != SL_RESULT_SUCCESS);179180active = true;181}182183void AudioDriverOpenSL::_record_buffer_callback(SLAndroidSimpleBufferQueueItf queueItf) {184for (int i = 0; i < rec_buffer.size(); i++) {185int32_t sample = rec_buffer[i] << 16;186input_buffer_write(sample);187input_buffer_write(sample); // call twice to convert to Stereo188}189190SLresult res = (*recordBufferQueueItf)->Enqueue(recordBufferQueueItf, rec_buffer.ptrw(), rec_buffer.size() * sizeof(int16_t));191ERR_FAIL_COND(res != SL_RESULT_SUCCESS);192}193194void AudioDriverOpenSL::_record_buffer_callbacks(SLAndroidSimpleBufferQueueItf queueItf, void *pContext) {195AudioDriverOpenSL *ad = static_cast<AudioDriverOpenSL *>(pContext);196197ad->_record_buffer_callback(queueItf);198}199200Error AudioDriverOpenSL::init_input_device() {201SLDataLocator_IODevice loc_dev = {202SL_DATALOCATOR_IODEVICE,203SL_IODEVICE_AUDIOINPUT,204SL_DEFAULTDEVICEID_AUDIOINPUT,205nullptr206};207SLDataSource recSource = { &loc_dev, nullptr };208209SLDataLocator_AndroidSimpleBufferQueue loc_bq = {210SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,2112212};213SLDataFormat_PCM format_pcm = {214SL_DATAFORMAT_PCM,2151,216SL_SAMPLINGRATE_44_1,217SL_PCMSAMPLEFORMAT_FIXED_16,218SL_PCMSAMPLEFORMAT_FIXED_16,219SL_SPEAKER_FRONT_CENTER,220SL_BYTEORDER_LITTLEENDIAN221};222SLDataSink recSnk = { &loc_bq, &format_pcm };223224const SLInterfaceID ids[2] = { SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION };225const SLboolean req[2] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };226227SLresult res = (*EngineItf)->CreateAudioRecorder(EngineItf, &recorder, &recSource, &recSnk, 2, ids, req);228ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);229230res = (*recorder)->Realize(recorder, SL_BOOLEAN_FALSE);231ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);232233res = (*recorder)->GetInterface(recorder, SL_IID_RECORD, (void *)&recordItf);234ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);235236res = (*recorder)->GetInterface(recorder, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, (void *)&recordBufferQueueItf);237ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);238239res = (*recordBufferQueueItf)->RegisterCallback(recordBufferQueueItf, _record_buffer_callbacks, this);240ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);241242SLuint32 state;243res = (*recordItf)->GetRecordState(recordItf, &state);244ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);245246if (state != SL_RECORDSTATE_STOPPED) {247res = (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_STOPPED);248ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);249250res = (*recordBufferQueueItf)->Clear(recordBufferQueueItf);251ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);252}253254const int rec_buffer_frames = 2048;255rec_buffer.resize(rec_buffer_frames);256input_buffer_init(rec_buffer_frames);257258res = (*recordBufferQueueItf)->Enqueue(recordBufferQueueItf, rec_buffer.ptrw(), rec_buffer.size() * sizeof(int16_t));259ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);260261res = (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_RECORDING);262ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);263264return OK;265}266267Error AudioDriverOpenSL::input_start() {268if (recordItf || recordBufferQueueItf) {269return ERR_ALREADY_IN_USE;270}271272if (OS::get_singleton()->request_permission("RECORD_AUDIO")) {273return init_input_device();274}275276WARN_PRINT("Unable to start audio capture - No RECORD_AUDIO permission");277return ERR_UNAUTHORIZED;278}279280Error AudioDriverOpenSL::input_stop() {281if (!recordItf || !recordBufferQueueItf) {282return ERR_CANT_OPEN;283}284285SLuint32 state;286SLresult res = (*recordItf)->GetRecordState(recordItf, &state);287ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);288289if (state != SL_RECORDSTATE_STOPPED) {290res = (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_STOPPED);291ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);292293res = (*recordBufferQueueItf)->Clear(recordBufferQueueItf);294ERR_FAIL_COND_V(res != SL_RESULT_SUCCESS, ERR_CANT_OPEN);295}296297return OK;298}299300int AudioDriverOpenSL::get_mix_rate() const {301return 44100; // hardcoded for Android, as selected by SL_SAMPLINGRATE_44_1302}303304AudioDriver::SpeakerMode AudioDriverOpenSL::get_speaker_mode() const {305return SPEAKER_MODE_STEREO;306}307308void AudioDriverOpenSL::lock() {309if (active) {310mutex.lock();311}312}313314void AudioDriverOpenSL::unlock() {315if (active) {316mutex.unlock();317}318}319320void AudioDriverOpenSL::finish() {321if (recordItf) {322(*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_STOPPED);323recordItf = nullptr;324}325if (recorder) {326(*recorder)->Destroy(recorder);327recorder = nullptr;328}329if (playItf) {330(*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);331playItf = nullptr;332}333if (player) {334(*player)->Destroy(player);335player = nullptr;336}337if (OutputMix) {338(*OutputMix)->Destroy(OutputMix);339OutputMix = nullptr;340}341if (sl) {342(*sl)->Destroy(sl);343sl = nullptr;344}345}346347void AudioDriverOpenSL::set_pause(bool p_pause) {348pause = p_pause;349350if (active && playItf) {351if (pause) {352(*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PAUSED);353} else {354(*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING);355}356}357}358359AudioDriverOpenSL::AudioDriverOpenSL() {360}361362363