henrika | b261989 | 2015-05-18 16:49:16 +0200 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | |
| 11 | #include "webrtc/modules/audio_device/android/opensles_player.h" |
| 12 | |
| 13 | #include <android/log.h> |
| 14 | |
| 15 | #include "webrtc/base/arraysize.h" |
| 16 | #include "webrtc/base/checks.h" |
| 17 | #include "webrtc/modules/audio_device/android/audio_manager.h" |
| 18 | #include "webrtc/modules/audio_device/android/fine_audio_buffer.h" |
| 19 | |
| 20 | #define TAG "OpenSLESPlayer" |
| 21 | #define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__) |
| 22 | #define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__) |
| 23 | #define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__) |
| 24 | #define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__) |
| 25 | #define ALOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__) |
| 26 | |
| 27 | #define RETURN_ON_ERROR(op, ...) \ |
| 28 | do { \ |
| 29 | SLresult err = (op); \ |
| 30 | if (err != SL_RESULT_SUCCESS) { \ |
| 31 | ALOGE("%s failed: %d", #op, err); \ |
| 32 | return __VA_ARGS__; \ |
| 33 | } \ |
| 34 | } while (0) |
| 35 | |
| 36 | namespace webrtc { |
| 37 | |
| 38 | OpenSLESPlayer::OpenSLESPlayer(AudioManager* audio_manager) |
| 39 | : audio_parameters_(audio_manager->GetPlayoutAudioParameters()), |
| 40 | audio_device_buffer_(NULL), |
| 41 | initialized_(false), |
| 42 | playing_(false), |
| 43 | bytes_per_buffer_(0), |
| 44 | buffer_index_(0), |
| 45 | engine_(nullptr), |
| 46 | player_(nullptr), |
| 47 | simple_buffer_queue_(nullptr), |
| 48 | volume_(nullptr) { |
| 49 | ALOGD("ctor%s", GetThreadInfo().c_str()); |
| 50 | // Use native audio output parameters provided by the audio manager and |
| 51 | // define the PCM format structure. |
| 52 | pcm_format_ = CreatePCMConfiguration(audio_parameters_.channels(), |
| 53 | audio_parameters_.sample_rate(), |
| 54 | audio_parameters_.bits_per_sample()); |
| 55 | // Detach from this thread since we want to use the checker to verify calls |
| 56 | // from the internal audio thread. |
| 57 | thread_checker_opensles_.DetachFromThread(); |
| 58 | } |
| 59 | |
| 60 | OpenSLESPlayer::~OpenSLESPlayer() { |
| 61 | ALOGD("dtor%s", GetThreadInfo().c_str()); |
| 62 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 63 | Terminate(); |
| 64 | DestroyAudioPlayer(); |
| 65 | DestroyMix(); |
| 66 | DestroyEngine(); |
| 67 | DCHECK(!engine_object_.Get()); |
| 68 | DCHECK(!engine_); |
| 69 | DCHECK(!output_mix_.Get()); |
| 70 | DCHECK(!player_); |
| 71 | DCHECK(!simple_buffer_queue_); |
| 72 | DCHECK(!volume_); |
| 73 | } |
| 74 | |
| 75 | int OpenSLESPlayer::Init() { |
| 76 | ALOGD("Init%s", GetThreadInfo().c_str()); |
| 77 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 78 | return 0; |
| 79 | } |
| 80 | |
| 81 | int OpenSLESPlayer::Terminate() { |
| 82 | ALOGD("Terminate%s", GetThreadInfo().c_str()); |
| 83 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 84 | StopPlayout(); |
| 85 | return 0; |
| 86 | } |
| 87 | |
| 88 | int OpenSLESPlayer::InitPlayout() { |
| 89 | ALOGD("InitPlayout%s", GetThreadInfo().c_str()); |
| 90 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 91 | DCHECK(!initialized_); |
| 92 | DCHECK(!playing_); |
| 93 | CreateEngine(); |
| 94 | CreateMix(); |
| 95 | initialized_ = true; |
| 96 | buffer_index_ = 0; |
| 97 | return 0; |
| 98 | } |
| 99 | |
| 100 | int OpenSLESPlayer::StartPlayout() { |
| 101 | ALOGD("StartPlayout%s", GetThreadInfo().c_str()); |
| 102 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 103 | DCHECK(initialized_); |
| 104 | DCHECK(!playing_); |
| 105 | // The number of lower latency audio players is limited, hence we create the |
| 106 | // audio player in Start() and destroy it in Stop(). |
| 107 | CreateAudioPlayer(); |
| 108 | // Fill up audio buffers to avoid initial glitch and to ensure that playback |
| 109 | // starts when mode is later changed to SL_PLAYSTATE_PLAYING. |
| 110 | // TODO(henrika): we can save some delay by only making one call to |
| 111 | // EnqueuePlayoutData. Most likely not worth the risk of adding a glitch. |
| 112 | for (int i = 0; i < kNumOfOpenSLESBuffers; ++i) { |
| 113 | EnqueuePlayoutData(); |
| 114 | } |
| 115 | // Start streaming data by setting the play state to SL_PLAYSTATE_PLAYING. |
| 116 | // For a player object, when the object is in the SL_PLAYSTATE_PLAYING |
| 117 | // state, adding buffers will implicitly start playback. |
| 118 | RETURN_ON_ERROR((*player_)->SetPlayState(player_, SL_PLAYSTATE_PLAYING), -1); |
| 119 | playing_ = (GetPlayState() == SL_PLAYSTATE_PLAYING); |
| 120 | DCHECK(playing_); |
| 121 | return 0; |
| 122 | } |
| 123 | |
| 124 | int OpenSLESPlayer::StopPlayout() { |
| 125 | ALOGD("StopPlayout%s", GetThreadInfo().c_str()); |
| 126 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 127 | if (!initialized_ || !playing_) { |
| 128 | return 0; |
| 129 | } |
| 130 | // Stop playing by setting the play state to SL_PLAYSTATE_STOPPED. |
| 131 | RETURN_ON_ERROR((*player_)->SetPlayState(player_, SL_PLAYSTATE_STOPPED), -1); |
| 132 | // Clear the buffer queue to flush out any remaining data. |
| 133 | RETURN_ON_ERROR((*simple_buffer_queue_)->Clear(simple_buffer_queue_), -1); |
| 134 | #ifndef NDEBUG |
| 135 | // Verify that the buffer queue is in fact cleared as it should. |
| 136 | SLAndroidSimpleBufferQueueState buffer_queue_state; |
| 137 | (*simple_buffer_queue_)->GetState(simple_buffer_queue_, &buffer_queue_state); |
| 138 | DCHECK_EQ(0u, buffer_queue_state.count); |
| 139 | DCHECK_EQ(0u, buffer_queue_state.index); |
| 140 | #endif |
| 141 | // The number of lower latency audio players is limited, hence we create the |
| 142 | // audio player in Start() and destroy it in Stop(). |
| 143 | DestroyAudioPlayer(); |
| 144 | thread_checker_opensles_.DetachFromThread(); |
| 145 | initialized_ = false; |
| 146 | playing_ = false; |
| 147 | return 0; |
| 148 | } |
| 149 | |
| 150 | int OpenSLESPlayer::SpeakerVolumeIsAvailable(bool& available) { |
| 151 | available = false; |
| 152 | return 0; |
| 153 | } |
| 154 | |
| 155 | int OpenSLESPlayer::MaxSpeakerVolume(uint32_t& maxVolume) const { |
| 156 | return -1; |
| 157 | } |
| 158 | |
| 159 | int OpenSLESPlayer::MinSpeakerVolume(uint32_t& minVolume) const { |
| 160 | return -1; |
| 161 | } |
| 162 | |
| 163 | int OpenSLESPlayer::SetSpeakerVolume(uint32_t volume) { |
| 164 | return -1; |
| 165 | } |
| 166 | |
| 167 | int OpenSLESPlayer::SpeakerVolume(uint32_t& volume) const { |
| 168 | return -1; |
| 169 | } |
| 170 | |
| 171 | void OpenSLESPlayer::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) { |
| 172 | ALOGD("AttachAudioBuffer"); |
| 173 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 174 | audio_device_buffer_ = audioBuffer; |
| 175 | const int sample_rate_hz = audio_parameters_.sample_rate(); |
| 176 | ALOGD("SetPlayoutSampleRate(%d)", sample_rate_hz); |
| 177 | audio_device_buffer_->SetPlayoutSampleRate(sample_rate_hz); |
| 178 | const int channels = audio_parameters_.channels(); |
| 179 | ALOGD("SetPlayoutChannels(%d)", channels); |
| 180 | audio_device_buffer_->SetPlayoutChannels(channels); |
| 181 | CHECK(audio_device_buffer_); |
| 182 | AllocateDataBuffers(); |
| 183 | } |
| 184 | |
| 185 | SLDataFormat_PCM OpenSLESPlayer::CreatePCMConfiguration(int channels, |
| 186 | int sample_rate, |
| 187 | int bits_per_sample) { |
| 188 | ALOGD("CreatePCMConfiguration"); |
| 189 | CHECK_EQ(bits_per_sample, SL_PCMSAMPLEFORMAT_FIXED_16); |
| 190 | SLDataFormat_PCM format; |
| 191 | format.formatType = SL_DATAFORMAT_PCM; |
| 192 | format.numChannels = static_cast<SLuint32>(channels); |
| 193 | // Note that, the unit of sample rate is actually in milliHertz and not Hertz. |
| 194 | switch (sample_rate) { |
| 195 | case 8000: |
| 196 | format.samplesPerSec = SL_SAMPLINGRATE_8; |
| 197 | break; |
| 198 | case 16000: |
| 199 | format.samplesPerSec = SL_SAMPLINGRATE_16; |
| 200 | break; |
| 201 | case 22050: |
| 202 | format.samplesPerSec = SL_SAMPLINGRATE_22_05; |
| 203 | break; |
| 204 | case 32000: |
| 205 | format.samplesPerSec = SL_SAMPLINGRATE_32; |
| 206 | break; |
| 207 | case 44100: |
| 208 | format.samplesPerSec = SL_SAMPLINGRATE_44_1; |
| 209 | break; |
| 210 | case 48000: |
| 211 | format.samplesPerSec = SL_SAMPLINGRATE_48; |
| 212 | break; |
| 213 | default: |
| 214 | CHECK(false) << "Unsupported sample rate: " << sample_rate; |
| 215 | } |
| 216 | format.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; |
| 217 | format.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; |
| 218 | format.endianness = SL_BYTEORDER_LITTLEENDIAN; |
| 219 | if (format.numChannels == 1) |
| 220 | format.channelMask = SL_SPEAKER_FRONT_CENTER; |
| 221 | else if (format.numChannels == 2) |
| 222 | format.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; |
| 223 | else |
| 224 | CHECK(false) << "Unsupported number of channels: " << format.numChannels; |
| 225 | return format; |
| 226 | } |
| 227 | |
| 228 | void OpenSLESPlayer::AllocateDataBuffers() { |
| 229 | ALOGD("AllocateDataBuffers"); |
| 230 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 231 | DCHECK(!simple_buffer_queue_); |
| 232 | CHECK(audio_device_buffer_); |
| 233 | bytes_per_buffer_ = audio_parameters_.GetBytesPerBuffer(); |
| 234 | ALOGD("native buffer size: %d", bytes_per_buffer_); |
| 235 | // Create a modified audio buffer class which allows us to ask for any number |
| 236 | // of samples (and not only multiple of 10ms) to match the native OpenSL ES |
| 237 | // buffer size. |
| 238 | fine_buffer_.reset(new FineAudioBuffer(audio_device_buffer_, |
| 239 | bytes_per_buffer_, |
| 240 | audio_parameters_.sample_rate())); |
| 241 | // Each buffer must be of this size to avoid unnecessary memcpy while caching |
| 242 | // data between successive callbacks. |
| 243 | const int required_buffer_size = fine_buffer_->RequiredBufferSizeBytes(); |
| 244 | ALOGD("required buffer size: %d", required_buffer_size); |
| 245 | for (int i = 0; i < kNumOfOpenSLESBuffers; ++i) { |
| 246 | audio_buffers_[i].reset(new SLint8[required_buffer_size]); |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | bool OpenSLESPlayer::CreateEngine() { |
| 251 | ALOGD("CreateEngine"); |
| 252 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 253 | if (engine_object_.Get()) |
| 254 | return true; |
| 255 | DCHECK(!engine_); |
| 256 | const SLEngineOption option[] = { |
| 257 | {SL_ENGINEOPTION_THREADSAFE, static_cast<SLuint32>(SL_BOOLEAN_TRUE)}}; |
| 258 | RETURN_ON_ERROR( |
| 259 | slCreateEngine(engine_object_.Receive(), 1, option, 0, NULL, NULL), |
| 260 | false); |
| 261 | RETURN_ON_ERROR( |
| 262 | engine_object_->Realize(engine_object_.Get(), SL_BOOLEAN_FALSE), false); |
| 263 | RETURN_ON_ERROR(engine_object_->GetInterface(engine_object_.Get(), |
| 264 | SL_IID_ENGINE, &engine_), |
| 265 | false); |
| 266 | return true; |
| 267 | } |
| 268 | |
| 269 | void OpenSLESPlayer::DestroyEngine() { |
| 270 | ALOGD("DestroyEngine"); |
| 271 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 272 | if (!engine_object_.Get()) |
| 273 | return; |
| 274 | engine_ = nullptr; |
| 275 | engine_object_.Reset(); |
| 276 | } |
| 277 | |
| 278 | bool OpenSLESPlayer::CreateMix() { |
| 279 | ALOGD("CreateMix"); |
| 280 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 281 | DCHECK(engine_); |
| 282 | if (output_mix_.Get()) |
| 283 | return true; |
| 284 | |
| 285 | // Create the ouput mix on the engine object. No interfaces will be used. |
| 286 | RETURN_ON_ERROR((*engine_)->CreateOutputMix(engine_, output_mix_.Receive(), 0, |
| 287 | NULL, NULL), |
| 288 | false); |
| 289 | RETURN_ON_ERROR(output_mix_->Realize(output_mix_.Get(), SL_BOOLEAN_FALSE), |
| 290 | false); |
| 291 | return true; |
| 292 | } |
| 293 | |
| 294 | void OpenSLESPlayer::DestroyMix() { |
| 295 | ALOGD("DestroyMix"); |
| 296 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 297 | if (!output_mix_.Get()) |
| 298 | return; |
| 299 | output_mix_.Reset(); |
| 300 | } |
| 301 | |
| 302 | bool OpenSLESPlayer::CreateAudioPlayer() { |
| 303 | ALOGD("CreateAudioPlayer"); |
| 304 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 305 | DCHECK(engine_object_.Get()); |
| 306 | DCHECK(output_mix_.Get()); |
| 307 | if (player_object_.Get()) |
| 308 | return true; |
| 309 | DCHECK(!player_); |
| 310 | DCHECK(!simple_buffer_queue_); |
| 311 | DCHECK(!volume_); |
| 312 | |
| 313 | // source: Android Simple Buffer Queue Data Locator is source. |
| 314 | SLDataLocator_AndroidSimpleBufferQueue simple_buffer_queue = { |
| 315 | SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, |
| 316 | static_cast<SLuint32>(kNumOfOpenSLESBuffers)}; |
| 317 | SLDataSource audio_source = {&simple_buffer_queue, &pcm_format_}; |
| 318 | |
| 319 | // sink: OutputMix-based data is sink. |
| 320 | SLDataLocator_OutputMix locator_output_mix = {SL_DATALOCATOR_OUTPUTMIX, |
| 321 | output_mix_.Get()}; |
| 322 | SLDataSink audio_sink = {&locator_output_mix, NULL}; |
| 323 | |
| 324 | // Define interfaces that we indend to use and realize. |
| 325 | const SLInterfaceID interface_ids[] = { |
| 326 | SL_IID_ANDROIDCONFIGURATION, SL_IID_BUFFERQUEUE, SL_IID_VOLUME}; |
| 327 | const SLboolean interface_required[] = { |
| 328 | SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; |
| 329 | |
| 330 | // Create the audio player on the engine interface. |
| 331 | RETURN_ON_ERROR( |
| 332 | (*engine_)->CreateAudioPlayer( |
| 333 | engine_, player_object_.Receive(), &audio_source, &audio_sink, |
| 334 | arraysize(interface_ids), interface_ids, interface_required), |
| 335 | false); |
| 336 | |
| 337 | // Use the Android configuration interface to set platform-specific |
| 338 | // parameters. Should be done before player is realized. |
| 339 | SLAndroidConfigurationItf player_config; |
| 340 | RETURN_ON_ERROR( |
| 341 | player_object_->GetInterface(player_object_.Get(), |
| 342 | SL_IID_ANDROIDCONFIGURATION, &player_config), |
| 343 | false); |
| 344 | // Set audio player configuration to SL_ANDROID_STREAM_VOICE which |
| 345 | // corresponds to android.media.AudioManager.STREAM_VOICE_CALL. |
| 346 | SLint32 stream_type = SL_ANDROID_STREAM_VOICE; |
| 347 | RETURN_ON_ERROR( |
| 348 | (*player_config) |
| 349 | ->SetConfiguration(player_config, SL_ANDROID_KEY_STREAM_TYPE, |
| 350 | &stream_type, sizeof(SLint32)), |
| 351 | false); |
| 352 | |
| 353 | // Realize the audio player object after configuration has been set. |
| 354 | RETURN_ON_ERROR( |
| 355 | player_object_->Realize(player_object_.Get(), SL_BOOLEAN_FALSE), false); |
| 356 | |
| 357 | // Get the SLPlayItf interface on the audio player. |
| 358 | RETURN_ON_ERROR( |
| 359 | player_object_->GetInterface(player_object_.Get(), SL_IID_PLAY, &player_), |
| 360 | false); |
| 361 | |
| 362 | // Get the SLAndroidSimpleBufferQueueItf interface on the audio player. |
| 363 | RETURN_ON_ERROR( |
| 364 | player_object_->GetInterface(player_object_.Get(), SL_IID_BUFFERQUEUE, |
| 365 | &simple_buffer_queue_), |
| 366 | false); |
| 367 | |
| 368 | // Register callback method for the Android Simple Buffer Queue interface. |
| 369 | // This method will be called when the native audio layer needs audio data. |
| 370 | RETURN_ON_ERROR((*simple_buffer_queue_) |
| 371 | ->RegisterCallback(simple_buffer_queue_, |
| 372 | SimpleBufferQueueCallback, this), |
| 373 | false); |
| 374 | |
| 375 | // Get the SLVolumeItf interface on the audio player. |
| 376 | RETURN_ON_ERROR(player_object_->GetInterface(player_object_.Get(), |
| 377 | SL_IID_VOLUME, &volume_), |
| 378 | false); |
| 379 | |
| 380 | // TODO(henrika): might not be required to set volume to max here since it |
| 381 | // seems to be default on most devices. Might be required for unit tests. |
| 382 | // RETURN_ON_ERROR((*volume_)->SetVolumeLevel(volume_, 0), false); |
| 383 | |
| 384 | return true; |
| 385 | } |
| 386 | |
| 387 | void OpenSLESPlayer::DestroyAudioPlayer() { |
| 388 | ALOGD("DestroyAudioPlayer"); |
| 389 | DCHECK(thread_checker_.CalledOnValidThread()); |
| 390 | if (!player_object_.Get()) |
| 391 | return; |
| 392 | player_object_.Reset(); |
| 393 | player_ = nullptr; |
| 394 | simple_buffer_queue_ = nullptr; |
| 395 | volume_ = nullptr; |
| 396 | } |
| 397 | |
| 398 | // static |
| 399 | void OpenSLESPlayer::SimpleBufferQueueCallback( |
| 400 | SLAndroidSimpleBufferQueueItf caller, |
| 401 | void* context) { |
| 402 | OpenSLESPlayer* stream = reinterpret_cast<OpenSLESPlayer*>(context); |
| 403 | stream->FillBufferQueue(); |
| 404 | } |
| 405 | |
| 406 | void OpenSLESPlayer::FillBufferQueue() { |
| 407 | DCHECK(thread_checker_opensles_.CalledOnValidThread()); |
| 408 | SLuint32 state = GetPlayState(); |
| 409 | if (state != SL_PLAYSTATE_PLAYING) { |
| 410 | ALOGW("Buffer callback in non-playing state!"); |
| 411 | return; |
| 412 | } |
| 413 | EnqueuePlayoutData(); |
| 414 | } |
| 415 | |
| 416 | void OpenSLESPlayer::EnqueuePlayoutData() { |
| 417 | // Read audio data from the WebRTC source using the FineAudioBuffer object |
| 418 | // to adjust for differences in buffer size between WebRTC (10ms) and native |
| 419 | // OpenSL ES. |
| 420 | SLint8* audio_ptr = audio_buffers_[buffer_index_].get(); |
| 421 | fine_buffer_->GetBufferData(audio_ptr); |
| 422 | // Enqueue the decoded audio buffer for playback. |
| 423 | SLresult err = |
| 424 | (*simple_buffer_queue_) |
| 425 | ->Enqueue(simple_buffer_queue_, audio_ptr, bytes_per_buffer_); |
| 426 | if (SL_RESULT_SUCCESS != err) { |
| 427 | ALOGE("Enqueue failed: %d", err); |
| 428 | } |
| 429 | buffer_index_ = (buffer_index_ + 1) % kNumOfOpenSLESBuffers; |
| 430 | } |
| 431 | |
| 432 | SLuint32 OpenSLESPlayer::GetPlayState() const { |
| 433 | DCHECK(player_); |
| 434 | SLuint32 state; |
| 435 | SLresult err = (*player_)->GetPlayState(player_, &state); |
| 436 | if (SL_RESULT_SUCCESS != err) { |
| 437 | ALOGE("GetPlayState failed: %d", err); |
| 438 | } |
| 439 | return state; |
| 440 | } |
| 441 | |
| 442 | } // namespace webrtc |