AudioPlayer_to_android.cpp revision f4b45a37248899ae2d27bb172f8387fbf1edff8e
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include "sles_allinclusive.h" 18#include "android_prompts.h" 19#include "android/android_AudioToCbRenderer.h" 20#include "android/android_StreamPlayer.h" 21#include "android/android_LocAVPlayer.h" 22#include "android/include/AacBqToPcmCbRenderer.h" 23 24#include <fcntl.h> 25#include <sys/stat.h> 26 27#include <system/audio.h> 28 29template class android::KeyedVector<SLuint32, android::AudioEffect* > ; 30 31#define KEY_STREAM_TYPE_PARAMSIZE sizeof(SLint32) 32 33#define AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE 500 34#define AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE 2000 35 36//----------------------------------------------------------------------------- 37// FIXME this method will be absorbed into android_audioPlayer_setPlayState() once 38// bufferqueue and uri/fd playback are moved under the GenericPlayer C++ object 39SLresult aplayer_setPlayState(const android::sp<android::GenericPlayer> &ap, SLuint32 playState, 40 AndroidObjectState* pObjState) { 41 SLresult result = SL_RESULT_SUCCESS; 42 AndroidObjectState objState = *pObjState; 43 44 switch (playState) { 45 case SL_PLAYSTATE_STOPPED: 46 SL_LOGV("setting GenericPlayer to SL_PLAYSTATE_STOPPED"); 47 ap->stop(); 48 break; 49 case SL_PLAYSTATE_PAUSED: 50 SL_LOGV("setting GenericPlayer to SL_PLAYSTATE_PAUSED"); 51 switch(objState) { 52 case ANDROID_UNINITIALIZED: 53 *pObjState = ANDROID_PREPARING; 54 ap->prepare(); 55 break; 56 case ANDROID_PREPARING: 57 break; 58 case ANDROID_READY: 59 ap->pause(); 60 break; 61 default: 62 SL_LOGE(ERROR_PLAYERSETPLAYSTATE_INVALID_OBJECT_STATE_D, playState); 63 result = SL_RESULT_INTERNAL_ERROR; 64 break; 65 } 66 break; 67 case SL_PLAYSTATE_PLAYING: { 68 SL_LOGV("setting GenericPlayer to SL_PLAYSTATE_PLAYING"); 69 switch(objState) { 70 case ANDROID_UNINITIALIZED: 71 *pObjState = ANDROID_PREPARING; 72 ap->prepare(); 73 // intended fall through 74 case ANDROID_PREPARING: 75 // intended fall through 76 case ANDROID_READY: 77 ap->play(); 78 break; 79 default: 80 SL_LOGE(ERROR_PLAYERSETPLAYSTATE_INVALID_OBJECT_STATE_D, playState); 81 result = SL_RESULT_INTERNAL_ERROR; 82 break; 83 } 84 } 85 break; 86 default: 87 // checked by caller, should not happen 88 SL_LOGE(ERROR_SHOULDNT_BE_HERE_S, "aplayer_setPlayState"); 89 result = SL_RESULT_INTERNAL_ERROR; 90 break; 91 } 92 93 return result; 94} 95 96 97//----------------------------------------------------------------------------- 98// Callback associated with a AudioToCbRenderer of an SL ES AudioPlayer that gets its data 99// from a URI or FD, to write the decoded audio data to a buffer queue 100static size_t adecoder_writeToBufferQueue(const uint8_t *data, size_t size, CAudioPlayer* ap) { 101 if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) { 102 // it is not safe to enter the callback (the player is about to go away) 103 return 0; 104 } 105 size_t sizeConsumed = 0; 106 SL_LOGD("received %d bytes from decoder", size); 107 slBufferQueueCallback callback = NULL; 108 void * callbackPContext = NULL; 109 110 // push decoded data to the buffer queue 111 object_lock_exclusive(&ap->mObject); 112 113 if (ap->mBufferQueue.mState.count != 0) { 114 assert(ap->mBufferQueue.mFront != ap->mBufferQueue.mRear); 115 116 BufferHeader *oldFront = ap->mBufferQueue.mFront; 117 BufferHeader *newFront = &oldFront[1]; 118 119 uint8_t *pDest = (uint8_t *)oldFront->mBuffer + ap->mBufferQueue.mSizeConsumed; 120 if (ap->mBufferQueue.mSizeConsumed + size < oldFront->mSize) { 121 // room to consume the whole or rest of the decoded data in one shot 122 ap->mBufferQueue.mSizeConsumed += size; 123 // consume data but no callback to the BufferQueue interface here 124 memcpy (pDest, data, size); 125 sizeConsumed = size; 126 } else { 127 // push as much as possible of the decoded data into the buffer queue 128 sizeConsumed = oldFront->mSize - ap->mBufferQueue.mSizeConsumed; 129 130 // the buffer at the head of the buffer queue is full, update the state 131 ap->mBufferQueue.mSizeConsumed = 0; 132 if (newFront == &ap->mBufferQueue.mArray[ap->mBufferQueue.mNumBuffers + 1]) { 133 newFront = ap->mBufferQueue.mArray; 134 } 135 ap->mBufferQueue.mFront = newFront; 136 137 ap->mBufferQueue.mState.count--; 138 ap->mBufferQueue.mState.playIndex++; 139 // consume data 140 memcpy (pDest, data, sizeConsumed); 141 // data has been copied to the buffer, and the buffer queue state has been updated 142 // we will notify the client if applicable 143 callback = ap->mBufferQueue.mCallback; 144 // save callback data 145 callbackPContext = ap->mBufferQueue.mContext; 146 } 147 148 } else { 149 // no available buffers in the queue to write the decoded data 150 sizeConsumed = 0; 151 } 152 153 object_unlock_exclusive(&ap->mObject); 154 // notify client 155 if (NULL != callback) { 156 (*callback)(&ap->mBufferQueue.mItf, callbackPContext); 157 } 158 159 ap->mCallbackProtector->exitCb(); 160 return sizeConsumed; 161} 162 163//----------------------------------------------------------------------------- 164int android_getMinFrameCount(uint32_t sampleRate) { 165 int afSampleRate; 166 if (android::AudioSystem::getOutputSamplingRate(&afSampleRate, 167 ANDROID_DEFAULT_OUTPUT_STREAM_TYPE) != android::NO_ERROR) { 168 return ANDROID_DEFAULT_AUDIOTRACK_BUFFER_SIZE; 169 } 170 int afFrameCount; 171 if (android::AudioSystem::getOutputFrameCount(&afFrameCount, 172 ANDROID_DEFAULT_OUTPUT_STREAM_TYPE) != android::NO_ERROR) { 173 return ANDROID_DEFAULT_AUDIOTRACK_BUFFER_SIZE; 174 } 175 uint32_t afLatency; 176 if (android::AudioSystem::getOutputLatency(&afLatency, 177 ANDROID_DEFAULT_OUTPUT_STREAM_TYPE) != android::NO_ERROR) { 178 return ANDROID_DEFAULT_AUDIOTRACK_BUFFER_SIZE; 179 } 180 // minimum nb of buffers to cover output latency, given the size of each hardware audio buffer 181 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate); 182 if (minBufCount < 2) minBufCount = 2; 183 // minimum number of frames to cover output latency at the sample rate of the content 184 return (afFrameCount*sampleRate*minBufCount)/afSampleRate; 185} 186 187 188//----------------------------------------------------------------------------- 189#define LEFT_CHANNEL_MASK 0x1 << 0 190#define RIGHT_CHANNEL_MASK 0x1 << 1 191 192void android_audioPlayer_volumeUpdate(CAudioPlayer* ap) 193{ 194 assert(ap != NULL); 195 196 // the source's channel count, where zero means unknown 197 SLuint8 channelCount = ap->mNumChannels; 198 199 // whether each channel is audible 200 bool leftAudibilityFactor, rightAudibilityFactor; 201 202 // mute has priority over solo 203 if (channelCount >= STEREO_CHANNELS) { 204 if (ap->mMuteMask & LEFT_CHANNEL_MASK) { 205 // left muted 206 leftAudibilityFactor = false; 207 } else { 208 // left not muted 209 if (ap->mSoloMask & LEFT_CHANNEL_MASK) { 210 // left soloed 211 leftAudibilityFactor = true; 212 } else { 213 // left not soloed 214 if (ap->mSoloMask & RIGHT_CHANNEL_MASK) { 215 // right solo silences left 216 leftAudibilityFactor = false; 217 } else { 218 // left and right are not soloed, and left is not muted 219 leftAudibilityFactor = true; 220 } 221 } 222 } 223 224 if (ap->mMuteMask & RIGHT_CHANNEL_MASK) { 225 // right muted 226 rightAudibilityFactor = false; 227 } else { 228 // right not muted 229 if (ap->mSoloMask & RIGHT_CHANNEL_MASK) { 230 // right soloed 231 rightAudibilityFactor = true; 232 } else { 233 // right not soloed 234 if (ap->mSoloMask & LEFT_CHANNEL_MASK) { 235 // left solo silences right 236 rightAudibilityFactor = false; 237 } else { 238 // left and right are not soloed, and right is not muted 239 rightAudibilityFactor = true; 240 } 241 } 242 } 243 244 // channel mute and solo are ignored for mono and unknown channel count sources 245 } else { 246 leftAudibilityFactor = true; 247 rightAudibilityFactor = true; 248 } 249 250 // compute volumes without setting 251 const bool audibilityFactors[2] = {leftAudibilityFactor, rightAudibilityFactor}; 252 float volumes[2]; 253 android_player_volumeUpdate(volumes, &ap->mVolume, channelCount, ap->mAmplFromDirectLevel, 254 audibilityFactors); 255 float leftVol = volumes[0], rightVol = volumes[1]; 256 257 // set volume on the underlying media player or audio track 258 if (ap->mAPlayer != 0) { 259 ap->mAPlayer->setVolume(leftVol, rightVol); 260 } else if (ap->mAudioTrack != 0) { 261 ap->mAudioTrack->setVolume(leftVol, rightVol); 262 } 263 264 // changes in the AudioPlayer volume must be reflected in the send level: 265 // in SLEffectSendItf or in SLAndroidEffectSendItf? 266 // FIXME replace interface test by an internal API once we have one. 267 if (NULL != ap->mEffectSend.mItf) { 268 for (unsigned int i=0 ; i<AUX_MAX ; i++) { 269 if (ap->mEffectSend.mEnableLevels[i].mEnable) { 270 android_fxSend_setSendLevel(ap, 271 ap->mEffectSend.mEnableLevels[i].mSendLevel + ap->mVolume.mLevel); 272 // there's a single aux bus on Android, so we can stop looking once the first 273 // aux effect is found. 274 break; 275 } 276 } 277 } else if (NULL != ap->mAndroidEffectSend.mItf) { 278 android_fxSend_setSendLevel(ap, ap->mAndroidEffectSend.mSendLevel + ap->mVolume.mLevel); 279 } 280} 281 282// Called by android_audioPlayer_volumeUpdate and android_mediaPlayer_volumeUpdate to compute 283// volumes, but setting volumes is handled by the caller. 284 285void android_player_volumeUpdate(float *pVolumes /*[2]*/, const IVolume *volumeItf, unsigned 286channelCount, float amplFromDirectLevel, const bool *audibilityFactors /*[2]*/) 287{ 288 assert(pVolumes != NULL); 289 assert(volumeItf != NULL); 290 // OK for audibilityFactors to be NULL 291 292 bool leftAudibilityFactor, rightAudibilityFactor; 293 294 // apply player mute factor 295 // note that AudioTrack has mute() but not MediaPlayer, so it's easier to use volume 296 // to mute for both rather than calling mute() for AudioTrack 297 298 // player is muted 299 if (volumeItf->mMute) { 300 leftAudibilityFactor = false; 301 rightAudibilityFactor = false; 302 // player isn't muted, and channel mute/solo audibility factors are available (AudioPlayer) 303 } else if (audibilityFactors != NULL) { 304 leftAudibilityFactor = audibilityFactors[0]; 305 rightAudibilityFactor = audibilityFactors[1]; 306 // player isn't muted, and channel mute/solo audibility factors aren't available (MediaPlayer) 307 } else { 308 leftAudibilityFactor = true; 309 rightAudibilityFactor = true; 310 } 311 312 // compute amplification as the combination of volume level and stereo position 313 // amplification (or attenuation) from volume level 314 float amplFromVolLevel = sles_to_android_amplification(volumeItf->mLevel); 315 // amplification from direct level (changed in SLEffectSendtItf and SLAndroidEffectSendItf) 316 float leftVol = amplFromVolLevel * amplFromDirectLevel; 317 float rightVol = leftVol; 318 319 // amplification from stereo position 320 if (volumeItf->mEnableStereoPosition) { 321 // Left/right amplification (can be attenuations) factors derived for the StereoPosition 322 float amplFromStereoPos[STEREO_CHANNELS]; 323 // panning law depends on content channel count: mono to stereo panning vs stereo balance 324 if (1 == channelCount) { 325 // mono to stereo panning 326 double theta = (1000+volumeItf->mStereoPosition)*M_PI_4/1000.0f; // 0 <= theta <= Pi/2 327 amplFromStereoPos[0] = cos(theta); 328 amplFromStereoPos[1] = sin(theta); 329 // channel count is 0 (unknown), 2 (stereo), or > 2 (multi-channel) 330 } else { 331 // stereo balance 332 if (volumeItf->mStereoPosition > 0) { 333 amplFromStereoPos[0] = (1000-volumeItf->mStereoPosition)/1000.0f; 334 amplFromStereoPos[1] = 1.0f; 335 } else { 336 amplFromStereoPos[0] = 1.0f; 337 amplFromStereoPos[1] = (1000+volumeItf->mStereoPosition)/1000.0f; 338 } 339 } 340 leftVol *= amplFromStereoPos[0]; 341 rightVol *= amplFromStereoPos[1]; 342 } 343 344 // apply audibility factors 345 if (!leftAudibilityFactor) { 346 leftVol = 0.0; 347 } 348 if (!rightAudibilityFactor) { 349 rightVol = 0.0; 350 } 351 352 // return the computed volumes 353 pVolumes[0] = leftVol; 354 pVolumes[1] = rightVol; 355} 356 357//----------------------------------------------------------------------------- 358void audioTrack_handleMarker_lockPlay(CAudioPlayer* ap) { 359 //SL_LOGV("received event EVENT_MARKER from AudioTrack"); 360 slPlayCallback callback = NULL; 361 void* callbackPContext = NULL; 362 363 interface_lock_shared(&ap->mPlay); 364 callback = ap->mPlay.mCallback; 365 callbackPContext = ap->mPlay.mContext; 366 interface_unlock_shared(&ap->mPlay); 367 368 if (NULL != callback) { 369 // getting this event implies SL_PLAYEVENT_HEADATMARKER was set in the event mask 370 (*callback)(&ap->mPlay.mItf, callbackPContext, SL_PLAYEVENT_HEADATMARKER); 371 } 372} 373 374//----------------------------------------------------------------------------- 375void audioTrack_handleNewPos_lockPlay(CAudioPlayer* ap) { 376 //SL_LOGV("received event EVENT_NEW_POS from AudioTrack"); 377 slPlayCallback callback = NULL; 378 void* callbackPContext = NULL; 379 380 interface_lock_shared(&ap->mPlay); 381 callback = ap->mPlay.mCallback; 382 callbackPContext = ap->mPlay.mContext; 383 interface_unlock_shared(&ap->mPlay); 384 385 if (NULL != callback) { 386 // getting this event implies SL_PLAYEVENT_HEADATNEWPOS was set in the event mask 387 (*callback)(&ap->mPlay.mItf, callbackPContext, SL_PLAYEVENT_HEADATNEWPOS); 388 } 389} 390 391 392//----------------------------------------------------------------------------- 393void audioTrack_handleUnderrun_lockPlay(CAudioPlayer* ap) { 394 slPlayCallback callback = NULL; 395 void* callbackPContext = NULL; 396 397 interface_lock_shared(&ap->mPlay); 398 callback = ap->mPlay.mCallback; 399 callbackPContext = ap->mPlay.mContext; 400 bool headStalled = (ap->mPlay.mEventFlags & SL_PLAYEVENT_HEADSTALLED) != 0; 401 interface_unlock_shared(&ap->mPlay); 402 403 if ((NULL != callback) && headStalled) { 404 (*callback)(&ap->mPlay.mItf, callbackPContext, SL_PLAYEVENT_HEADSTALLED); 405 } 406} 407 408 409//----------------------------------------------------------------------------- 410/** 411 * post-condition: play state of AudioPlayer is SL_PLAYSTATE_PAUSED if setPlayStateToPaused is true 412 * 413 * note: a conditional flag, setPlayStateToPaused, is used here to specify whether the play state 414 * needs to be changed when the player reaches the end of the content to play. This is 415 * relative to what the specification describes for buffer queues vs the 416 * SL_PLAYEVENT_HEADATEND event. In the OpenSL ES specification 1.0.1: 417 * - section 8.12 SLBufferQueueItf states "In the case of starvation due to insufficient 418 * buffers in the queue, the playing of audio data stops. The player remains in the 419 * SL_PLAYSTATE_PLAYING state." 420 * - section 9.2.31 SL_PLAYEVENT states "SL_PLAYEVENT_HEADATEND Playback head is at the end 421 * of the current content and the player has paused." 422 */ 423void audioPlayer_dispatch_headAtEnd_lockPlay(CAudioPlayer *ap, bool setPlayStateToPaused, 424 bool needToLock) { 425 //SL_LOGV("ap=%p, setPlayStateToPaused=%d, needToLock=%d", ap, setPlayStateToPaused, 426 // needToLock); 427 slPlayCallback playCallback = NULL; 428 void * playContext = NULL; 429 // SLPlayItf callback or no callback? 430 if (needToLock) { 431 interface_lock_exclusive(&ap->mPlay); 432 } 433 if (ap->mPlay.mEventFlags & SL_PLAYEVENT_HEADATEND) { 434 playCallback = ap->mPlay.mCallback; 435 playContext = ap->mPlay.mContext; 436 } 437 if (setPlayStateToPaused) { 438 ap->mPlay.mState = SL_PLAYSTATE_PAUSED; 439 } 440 if (needToLock) { 441 interface_unlock_exclusive(&ap->mPlay); 442 } 443 // enqueue callback with no lock held 444 if (NULL != playCallback) { 445#ifndef USE_ASYNCHRONOUS_PLAY_CALLBACK 446 (*playCallback)(&ap->mPlay.mItf, playContext, SL_PLAYEVENT_HEADATEND); 447#else 448 SLresult result = EnqueueAsyncCallback_ppi(ap, playCallback, &ap->mPlay.mItf, playContext, 449 SL_PLAYEVENT_HEADATEND); 450 if (SL_RESULT_SUCCESS != result) { 451 LOGW("Callback %p(%p, %p, SL_PLAYEVENT_HEADATEND) dropped", playCallback, 452 &ap->mPlay.mItf, playContext); 453 } 454#endif 455 } 456 457} 458 459 460//----------------------------------------------------------------------------- 461/** 462 * pre-condition: AudioPlayer has SLPrefetchStatusItf initialized 463 * post-condition: 464 * - ap->mPrefetchStatus.mStatus == status 465 * - the prefetch status callback, if any, has been notified if a change occurred 466 * 467 */ 468void audioPlayer_dispatch_prefetchStatus_lockPrefetch(CAudioPlayer *ap, SLuint32 status, 469 bool needToLock) { 470 slPrefetchCallback prefetchCallback = NULL; 471 void * prefetchContext = NULL; 472 473 if (needToLock) { 474 interface_lock_exclusive(&ap->mPrefetchStatus); 475 } 476 // status change? 477 if (ap->mPrefetchStatus.mStatus != status) { 478 ap->mPrefetchStatus.mStatus = status; 479 // callback or no callback? 480 if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE) { 481 prefetchCallback = ap->mPrefetchStatus.mCallback; 482 prefetchContext = ap->mPrefetchStatus.mContext; 483 } 484 } 485 if (needToLock) { 486 interface_unlock_exclusive(&ap->mPrefetchStatus); 487 } 488 489 // callback with no lock held 490 if (NULL != prefetchCallback) { 491 (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext, status); 492 } 493} 494 495 496//----------------------------------------------------------------------------- 497SLresult audioPlayer_setStreamType(CAudioPlayer* ap, SLint32 type) { 498 SLresult result = SL_RESULT_SUCCESS; 499 SL_LOGV("type %d", type); 500 501 int newStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE; 502 switch(type) { 503 case SL_ANDROID_STREAM_VOICE: 504 newStreamType = AUDIO_STREAM_VOICE_CALL; 505 break; 506 case SL_ANDROID_STREAM_SYSTEM: 507 newStreamType = AUDIO_STREAM_SYSTEM; 508 break; 509 case SL_ANDROID_STREAM_RING: 510 newStreamType = AUDIO_STREAM_RING; 511 break; 512 case SL_ANDROID_STREAM_MEDIA: 513 newStreamType = AUDIO_STREAM_MUSIC; 514 break; 515 case SL_ANDROID_STREAM_ALARM: 516 newStreamType = AUDIO_STREAM_ALARM; 517 break; 518 case SL_ANDROID_STREAM_NOTIFICATION: 519 newStreamType = AUDIO_STREAM_NOTIFICATION; 520 break; 521 default: 522 SL_LOGE(ERROR_PLAYERSTREAMTYPE_SET_UNKNOWN_TYPE); 523 result = SL_RESULT_PARAMETER_INVALID; 524 break; 525 } 526 527 // stream type needs to be set before the object is realized 528 // (ap->mAudioTrack is supposed to be NULL until then) 529 if (SL_OBJECT_STATE_UNREALIZED != ap->mObject.mState) { 530 SL_LOGE(ERROR_PLAYERSTREAMTYPE_REALIZED); 531 result = SL_RESULT_PRECONDITIONS_VIOLATED; 532 } else { 533 ap->mStreamType = newStreamType; 534 } 535 536 return result; 537} 538 539 540//----------------------------------------------------------------------------- 541SLresult audioPlayer_getStreamType(CAudioPlayer* ap, SLint32 *pType) { 542 SLresult result = SL_RESULT_SUCCESS; 543 544 switch(ap->mStreamType) { 545 case AUDIO_STREAM_VOICE_CALL: 546 *pType = SL_ANDROID_STREAM_VOICE; 547 break; 548 case AUDIO_STREAM_SYSTEM: 549 *pType = SL_ANDROID_STREAM_SYSTEM; 550 break; 551 case AUDIO_STREAM_RING: 552 *pType = SL_ANDROID_STREAM_RING; 553 break; 554 case AUDIO_STREAM_DEFAULT: 555 case AUDIO_STREAM_MUSIC: 556 *pType = SL_ANDROID_STREAM_MEDIA; 557 break; 558 case AUDIO_STREAM_ALARM: 559 *pType = SL_ANDROID_STREAM_ALARM; 560 break; 561 case AUDIO_STREAM_NOTIFICATION: 562 *pType = SL_ANDROID_STREAM_NOTIFICATION; 563 break; 564 default: 565 result = SL_RESULT_INTERNAL_ERROR; 566 *pType = SL_ANDROID_STREAM_MEDIA; 567 break; 568 } 569 570 return result; 571} 572 573 574//----------------------------------------------------------------------------- 575void audioPlayer_auxEffectUpdate(CAudioPlayer* ap) { 576 if ((ap->mAudioTrack != 0) && (ap->mAuxEffect != 0)) { 577 android_fxSend_attach(ap, true, ap->mAuxEffect, ap->mVolume.mLevel + ap->mAuxSendLevel); 578 } 579} 580 581 582//----------------------------------------------------------------------------- 583void audioPlayer_setInvalid(CAudioPlayer* ap) { 584 ap->mAndroidObjType = INVALID_TYPE; 585 ap->mpLock = NULL; 586} 587 588 589//----------------------------------------------------------------------------- 590/* 591 * returns true if the given data sink is supported by AudioPlayer that doesn't 592 * play to an OutputMix object, false otherwise 593 * 594 * pre-condition: the locator of the audio sink is not SL_DATALOCATOR_OUTPUTMIX 595 */ 596bool audioPlayer_isSupportedNonOutputMixSink(const SLDataSink* pAudioSink) { 597 bool result = true; 598 const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSink->pLocator; 599 const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSink->pFormat; 600 601 switch (sinkLocatorType) { 602 603 case SL_DATALOCATOR_BUFFERQUEUE: 604 case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE: 605 if (SL_DATAFORMAT_PCM != sinkFormatType) { 606 SL_LOGE("Unsupported sink format 0x%x, expected SL_DATAFORMAT_PCM", 607 (unsigned)sinkFormatType); 608 result = false; 609 } 610 // it's no use checking the PCM format fields because additional characteristics 611 // such as the number of channels, or sample size are unknown to the player at this stage 612 break; 613 614 default: 615 SL_LOGE("Unsupported sink locator type 0x%x", (unsigned)sinkLocatorType); 616 result = false; 617 break; 618 } 619 620 return result; 621} 622 623 624//----------------------------------------------------------------------------- 625/* 626 * returns the Android object type if the locator type combinations for the source and sinks 627 * are supported by this implementation, INVALID_TYPE otherwise 628 */ 629AndroidObjectType audioPlayer_getAndroidObjectTypeForSourceSink(CAudioPlayer *ap) { 630 631 const SLDataSource *pAudioSrc = &ap->mDataSource.u.mSource; 632 const SLDataSink *pAudioSnk = &ap->mDataSink.u.mSink; 633 const SLuint32 sourceLocatorType = *(SLuint32 *)pAudioSrc->pLocator; 634 const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator; 635 AndroidObjectType type = INVALID_TYPE; 636 637 //-------------------------------------- 638 // Sink / source matching check: 639 // the following source / sink combinations are supported 640 // SL_DATALOCATOR_BUFFERQUEUE / SL_DATALOCATOR_OUTPUTMIX 641 // SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE / SL_DATALOCATOR_OUTPUTMIX 642 // SL_DATALOCATOR_URI / SL_DATALOCATOR_OUTPUTMIX 643 // SL_DATALOCATOR_ANDROIDFD / SL_DATALOCATOR_OUTPUTMIX 644 // SL_DATALOCATOR_ANDROIDBUFFERQUEUE / SL_DATALOCATOR_OUTPUTMIX 645 // SL_DATALOCATOR_ANDROIDBUFFERQUEUE / SL_DATALOCATOR_BUFFERQUEUE 646 // SL_DATALOCATOR_URI / SL_DATALOCATOR_BUFFERQUEUE 647 // SL_DATALOCATOR_ANDROIDFD / SL_DATALOCATOR_BUFFERQUEUE 648 // SL_DATALOCATOR_URI / SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE 649 // SL_DATALOCATOR_ANDROIDFD / SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE 650 switch (sinkLocatorType) { 651 652 case SL_DATALOCATOR_OUTPUTMIX: { 653 switch (sourceLocatorType) { 654 655 // Buffer Queue to AudioTrack 656 case SL_DATALOCATOR_BUFFERQUEUE: 657 case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE: 658 type = AUDIOPLAYER_FROM_PCM_BUFFERQUEUE; 659 break; 660 661 // URI or FD to MediaPlayer 662 case SL_DATALOCATOR_URI: 663 case SL_DATALOCATOR_ANDROIDFD: 664 type = AUDIOPLAYER_FROM_URIFD; 665 break; 666 667 // Android BufferQueue to MediaPlayer (shared memory streaming) 668 case SL_DATALOCATOR_ANDROIDBUFFERQUEUE: 669 type = AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE; 670 break; 671 672 default: 673 SL_LOGE("Source data locator 0x%x not supported with SL_DATALOCATOR_OUTPUTMIX sink", 674 (unsigned)sourceLocatorType); 675 break; 676 } 677 } 678 break; 679 680 case SL_DATALOCATOR_BUFFERQUEUE: 681 case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE: 682 switch (sourceLocatorType) { 683 684 // URI or FD decoded to PCM in a buffer queue 685 case SL_DATALOCATOR_URI: 686 case SL_DATALOCATOR_ANDROIDFD: 687 type = AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE; 688 break; 689 690 // AAC ADTS Android buffer queue decoded to PCM in a buffer queue 691 case SL_DATALOCATOR_ANDROIDBUFFERQUEUE: 692 type = AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE; 693 break; 694 695 default: 696 SL_LOGE("Source data locator 0x%x not supported with SL_DATALOCATOR_BUFFERQUEUE sink", 697 (unsigned)sourceLocatorType); 698 break; 699 } 700 break; 701 702 default: 703 SL_LOGE("Sink data locator 0x%x not supported", (unsigned)sinkLocatorType); 704 break; 705 } 706 707 return type; 708} 709 710 711//----------------------------------------------------------------------------- 712/* 713 * Callback associated with an SfPlayer of an SL ES AudioPlayer that gets its data 714 * from a URI or FD, for prepare, prefetch, and play events 715 */ 716static void sfplayer_handlePrefetchEvent(int event, int data1, int data2, void* user) { 717 718 // FIXME see similar code and comment in player_handleMediaPlayerEventNotifications 719 720 if (NULL == user) { 721 return; 722 } 723 724 CAudioPlayer *ap = (CAudioPlayer *)user; 725 if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) { 726 // it is not safe to enter the callback (the track is about to go away) 727 return; 728 } 729 union { 730 char c[sizeof(int)]; 731 int i; 732 } u; 733 u.i = event; 734 SL_LOGV("sfplayer_handlePrefetchEvent(event='%c%c%c%c' (%d), data1=%d, data2=%d, user=%p) from " 735 "SfAudioPlayer", u.c[3], u.c[2], u.c[1], u.c[0], event, data1, data2, user); 736 switch(event) { 737 738 case android::GenericPlayer::kEventPrepared: { 739 740 if (PLAYER_SUCCESS != data1) { 741 object_lock_exclusive(&ap->mObject); 742 743 // already initialized at object creation, and can only prepare once so never reset 744 assert(ap->mAudioTrack == 0); 745 assert(ap->mNumChannels == UNKNOWN_NUMCHANNELS); 746 assert(ap->mSampleRateMilliHz == UNKNOWN_SAMPLERATE); 747 assert(ap->mAndroidObjState == ANDROID_PREPARING); 748 ap->mAndroidObjState = ANDROID_READY; 749 750 object_unlock_exclusive(&ap->mObject); 751 752 // SfPlayer prepare() failed prefetching, there is no event in SLPrefetchStatus to 753 // indicate a prefetch error, so we signal it by sending simulataneously two events: 754 // - SL_PREFETCHEVENT_FILLLEVELCHANGE with a level of 0 755 // - SL_PREFETCHEVENT_STATUSCHANGE with a status of SL_PREFETCHSTATUS_UNDERFLOW 756 SL_LOGE(ERROR_PLAYER_PREFETCH_d, data1); 757 if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) { 758 break; 759 } 760 761 slPrefetchCallback callback = NULL; 762 void* callbackPContext = NULL; 763 764 interface_lock_exclusive(&ap->mPrefetchStatus); 765 ap->mPrefetchStatus.mLevel = 0; 766 ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW; 767 if ((ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_FILLLEVELCHANGE) 768 && (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE)) { 769 callback = ap->mPrefetchStatus.mCallback; 770 callbackPContext = ap->mPrefetchStatus.mContext; 771 } 772 interface_unlock_exclusive(&ap->mPrefetchStatus); 773 774 // callback with no lock held 775 if (NULL != callback) { 776 (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext, 777 SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE); 778 } 779 780 781 } else { 782 783 object_lock_exclusive(&ap->mObject); 784 785 if (AUDIOPLAYER_FROM_URIFD == ap->mAndroidObjType) { 786 //************************************** 787 // FIXME move under GenericMediaPlayer 788#if 0 789 ap->mAudioTrack = ap->mSfPlayer->getAudioTrack(); 790 ap->mNumChannels = ap->mSfPlayer->getNumChannels(); 791 ap->mSampleRateMilliHz = 792 android_to_sles_sampleRate(ap->mSfPlayer->getSampleRateHz()); 793 ap->mSfPlayer->startPrefetch_async(); 794 // update the new track with the current settings 795 audioPlayer_auxEffectUpdate(ap); 796 android_audioPlayer_useEventMask(ap); 797 android_audioPlayer_volumeUpdate(ap); 798 android_audioPlayer_setPlayRate(ap, ap->mPlaybackRate.mRate, false /*lockAP*/); 799#endif 800 } else if (AUDIOPLAYER_FROM_PCM_BUFFERQUEUE == ap->mAndroidObjType) { 801 if (ap->mAPlayer != 0) { 802 ((android::AudioToCbRenderer*)ap->mAPlayer.get())->startPrefetch_async(); 803 } 804 } else if (AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE == ap->mAndroidObjType) { 805 SL_LOGD("Received SfPlayer::kEventPrepared from AVPlayer for CAudioPlayer %p", ap); 806 } 807 808 ap->mAndroidObjState = ANDROID_READY; 809 810 object_unlock_exclusive(&ap->mObject); 811 } 812 813 } 814 break; 815 816 case android::GenericPlayer::kEventPrefetchFillLevelUpdate : { 817 if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) { 818 break; 819 } 820 slPrefetchCallback callback = NULL; 821 void* callbackPContext = NULL; 822 823 // SLPrefetchStatusItf callback or no callback? 824 interface_lock_exclusive(&ap->mPrefetchStatus); 825 if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_FILLLEVELCHANGE) { 826 callback = ap->mPrefetchStatus.mCallback; 827 callbackPContext = ap->mPrefetchStatus.mContext; 828 } 829 ap->mPrefetchStatus.mLevel = (SLpermille)data1; 830 interface_unlock_exclusive(&ap->mPrefetchStatus); 831 832 // callback with no lock held 833 if (NULL != callback) { 834 (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext, 835 SL_PREFETCHEVENT_FILLLEVELCHANGE); 836 } 837 } 838 break; 839 840 case android::GenericPlayer::kEventPrefetchStatusChange: { 841 if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) { 842 break; 843 } 844 slPrefetchCallback callback = NULL; 845 void* callbackPContext = NULL; 846 847 // SLPrefetchStatusItf callback or no callback? 848 object_lock_exclusive(&ap->mObject); 849 if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE) { 850 callback = ap->mPrefetchStatus.mCallback; 851 callbackPContext = ap->mPrefetchStatus.mContext; 852 } 853 if (data1 >= android::kStatusIntermediate) { 854 ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA; 855 } else if (data1 < android::kStatusIntermediate) { 856 ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW; 857 } 858 object_unlock_exclusive(&ap->mObject); 859 860 // callback with no lock held 861 if (NULL != callback) { 862 (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext, SL_PREFETCHEVENT_STATUSCHANGE); 863 } 864 } 865 break; 866 867 case android::GenericPlayer::kEventEndOfStream: { 868 audioPlayer_dispatch_headAtEnd_lockPlay(ap, true /*set state to paused?*/, true); 869 if ((ap->mAudioTrack != 0) && (!ap->mSeek.mLoopEnabled)) { 870 ap->mAudioTrack->stop(); 871 } 872 } 873 break; 874 875 case android::GenericPlayer::kEventChannelCount: { 876 object_lock_exclusive(&ap->mObject); 877 if (UNKNOWN_NUMCHANNELS == ap->mNumChannels && UNKNOWN_NUMCHANNELS != data1) { 878 ap->mNumChannels = data1; 879 android_audioPlayer_volumeUpdate(ap); 880 } 881 object_unlock_exclusive(&ap->mObject); 882 } 883 break; 884 885 case android::GenericPlayer::kEventPlay: { 886 slPlayCallback callback = NULL; 887 void* callbackPContext = NULL; 888 889 interface_lock_shared(&ap->mPlay); 890 callback = ap->mPlay.mCallback; 891 callbackPContext = ap->mPlay.mContext; 892 interface_unlock_shared(&ap->mPlay); 893 894 if (NULL != callback) { 895 SLuint32 event = (SLuint32) data1; // SL_PLAYEVENT_HEAD* 896#ifndef USE_ASYNCHRONOUS_PLAY_CALLBACK 897 // synchronous callback requires a synchronous GetPosition implementation 898 (*callback)(&ap->mPlay.mItf, callbackPContext, event); 899#else 900 // asynchronous callback works with any GetPosition implementation 901 SLresult result = EnqueueAsyncCallback_ppi(ap, callback, &ap->mPlay.mItf, 902 callbackPContext, event); 903 if (SL_RESULT_SUCCESS != result) { 904 LOGW("Callback %p(%p, %p, 0x%x) dropped", callback, 905 &ap->mPlay.mItf, callbackPContext, event); 906 } 907#endif 908 } 909 } 910 break; 911 912 default: 913 break; 914 } 915 916 ap->mCallbackProtector->exitCb(); 917} 918 919 920//----------------------------------------------------------------------------- 921SLresult android_audioPlayer_checkSourceSink(CAudioPlayer *pAudioPlayer) 922{ 923 // verify that the locator types for the source / sink combination is supported 924 pAudioPlayer->mAndroidObjType = audioPlayer_getAndroidObjectTypeForSourceSink(pAudioPlayer); 925 if (INVALID_TYPE == pAudioPlayer->mAndroidObjType) { 926 return SL_RESULT_PARAMETER_INVALID; 927 } 928 929 const SLDataSource *pAudioSrc = &pAudioPlayer->mDataSource.u.mSource; 930 const SLDataSink *pAudioSnk = &pAudioPlayer->mDataSink.u.mSink; 931 932 // format check: 933 const SLuint32 sourceLocatorType = *(SLuint32 *)pAudioSrc->pLocator; 934 const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator; 935 const SLuint32 sourceFormatType = *(SLuint32 *)pAudioSrc->pFormat; 936 const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSnk->pFormat; 937 938 switch (sourceLocatorType) { 939 //------------------ 940 // Buffer Queues 941 case SL_DATALOCATOR_BUFFERQUEUE: 942 case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE: 943 { 944 SLDataLocator_BufferQueue *dl_bq = (SLDataLocator_BufferQueue *) pAudioSrc->pLocator; 945 946 // Buffer format 947 switch (sourceFormatType) { 948 // currently only PCM buffer queues are supported, 949 case SL_DATAFORMAT_PCM: { 950 SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *) pAudioSrc->pFormat; 951 switch (df_pcm->numChannels) { 952 case 1: 953 case 2: 954 break; 955 default: 956 // this should have already been rejected by checkDataFormat 957 SL_LOGE("Cannot create audio player: unsupported " \ 958 "PCM data source with %u channels", (unsigned) df_pcm->numChannels); 959 return SL_RESULT_CONTENT_UNSUPPORTED; 960 } 961 switch (df_pcm->samplesPerSec) { 962 case SL_SAMPLINGRATE_8: 963 case SL_SAMPLINGRATE_11_025: 964 case SL_SAMPLINGRATE_12: 965 case SL_SAMPLINGRATE_16: 966 case SL_SAMPLINGRATE_22_05: 967 case SL_SAMPLINGRATE_24: 968 case SL_SAMPLINGRATE_32: 969 case SL_SAMPLINGRATE_44_1: 970 case SL_SAMPLINGRATE_48: 971 break; 972 case SL_SAMPLINGRATE_64: 973 case SL_SAMPLINGRATE_88_2: 974 case SL_SAMPLINGRATE_96: 975 case SL_SAMPLINGRATE_192: 976 default: 977 SL_LOGE("Cannot create audio player: unsupported sample rate %u milliHz", 978 (unsigned) df_pcm->samplesPerSec); 979 return SL_RESULT_CONTENT_UNSUPPORTED; 980 } 981 switch (df_pcm->bitsPerSample) { 982 case SL_PCMSAMPLEFORMAT_FIXED_8: 983 case SL_PCMSAMPLEFORMAT_FIXED_16: 984 break; 985 // others 986 default: 987 // this should have already been rejected by checkDataFormat 988 SL_LOGE("Cannot create audio player: unsupported sample bit depth %u", 989 (SLuint32)df_pcm->bitsPerSample); 990 return SL_RESULT_CONTENT_UNSUPPORTED; 991 } 992 switch (df_pcm->containerSize) { 993 case 8: 994 case 16: 995 break; 996 // others 997 default: 998 SL_LOGE("Cannot create audio player: unsupported container size %u", 999 (unsigned) df_pcm->containerSize); 1000 return SL_RESULT_CONTENT_UNSUPPORTED; 1001 } 1002 // df_pcm->channelMask: the earlier platform-independent check and the 1003 // upcoming check by sles_to_android_channelMaskOut are sufficient 1004 switch (df_pcm->endianness) { 1005 case SL_BYTEORDER_LITTLEENDIAN: 1006 break; 1007 case SL_BYTEORDER_BIGENDIAN: 1008 SL_LOGE("Cannot create audio player: unsupported big-endian byte order"); 1009 return SL_RESULT_CONTENT_UNSUPPORTED; 1010 // native is proposed but not yet in spec 1011 default: 1012 SL_LOGE("Cannot create audio player: unsupported byte order %u", 1013 (unsigned) df_pcm->endianness); 1014 return SL_RESULT_CONTENT_UNSUPPORTED; 1015 } 1016 } //case SL_DATAFORMAT_PCM 1017 break; 1018 case SL_DATAFORMAT_MIME: 1019 case XA_DATAFORMAT_RAWIMAGE: 1020 SL_LOGE("Cannot create audio player with buffer queue data source " 1021 "without SL_DATAFORMAT_PCM format"); 1022 return SL_RESULT_CONTENT_UNSUPPORTED; 1023 default: 1024 // invalid data format is detected earlier 1025 assert(false); 1026 return SL_RESULT_INTERNAL_ERROR; 1027 } // switch (sourceFormatType) 1028 } // case SL_DATALOCATOR_BUFFERQUEUE or SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE 1029 break; 1030 //------------------ 1031 // URI 1032 case SL_DATALOCATOR_URI: 1033 { 1034 SLDataLocator_URI *dl_uri = (SLDataLocator_URI *) pAudioSrc->pLocator; 1035 if (NULL == dl_uri->URI) { 1036 return SL_RESULT_PARAMETER_INVALID; 1037 } 1038 // URI format 1039 switch (sourceFormatType) { 1040 case SL_DATAFORMAT_MIME: 1041 break; 1042 case SL_DATAFORMAT_PCM: 1043 case XA_DATAFORMAT_RAWIMAGE: 1044 SL_LOGE("Cannot create audio player with SL_DATALOCATOR_URI data source without " 1045 "SL_DATAFORMAT_MIME format"); 1046 return SL_RESULT_CONTENT_UNSUPPORTED; 1047 } // switch (sourceFormatType) 1048 // decoding format check 1049 if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) && 1050 !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) { 1051 return SL_RESULT_CONTENT_UNSUPPORTED; 1052 } 1053 } // case SL_DATALOCATOR_URI 1054 break; 1055 //------------------ 1056 // File Descriptor 1057 case SL_DATALOCATOR_ANDROIDFD: 1058 { 1059 // fd is already non null 1060 switch (sourceFormatType) { 1061 case SL_DATAFORMAT_MIME: 1062 break; 1063 case SL_DATAFORMAT_PCM: 1064 // FIXME implement 1065 SL_LOGD("[ FIXME implement PCM FD data sources ]"); 1066 break; 1067 case XA_DATAFORMAT_RAWIMAGE: 1068 SL_LOGE("Cannot create audio player with SL_DATALOCATOR_ANDROIDFD data source " 1069 "without SL_DATAFORMAT_MIME or SL_DATAFORMAT_PCM format"); 1070 return SL_RESULT_CONTENT_UNSUPPORTED; 1071 default: 1072 // invalid data format is detected earlier 1073 assert(false); 1074 return SL_RESULT_INTERNAL_ERROR; 1075 } // switch (sourceFormatType) 1076 if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) && 1077 !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) { 1078 return SL_RESULT_CONTENT_UNSUPPORTED; 1079 } 1080 } // case SL_DATALOCATOR_ANDROIDFD 1081 break; 1082 //------------------ 1083 // Stream 1084 case SL_DATALOCATOR_ANDROIDBUFFERQUEUE: 1085 { 1086 switch (sourceFormatType) { 1087 case SL_DATAFORMAT_MIME: 1088 { 1089 SLDataFormat_MIME *df_mime = (SLDataFormat_MIME *) pAudioSrc->pFormat; 1090 if (NULL == df_mime) { 1091 SL_LOGE("MIME type null invalid"); 1092 return SL_RESULT_CONTENT_UNSUPPORTED; 1093 } 1094 SL_LOGD("source MIME is %s", (char*)df_mime->mimeType); 1095 switch(df_mime->containerType) { 1096 case SL_CONTAINERTYPE_MPEG_TS: 1097 if (strcasecmp((char*)df_mime->mimeType, ANDROID_MIME_MP2TS)) { 1098 SL_LOGE("Invalid MIME (%s) for container SL_CONTAINERTYPE_MPEG_TS, expects %s", 1099 (char*)df_mime->mimeType, ANDROID_MIME_MP2TS); 1100 return SL_RESULT_CONTENT_UNSUPPORTED; 1101 } 1102 break; 1103 case SL_CONTAINERTYPE_RAW: 1104 case SL_CONTAINERTYPE_AAC: 1105 if (strcasecmp((char*)df_mime->mimeType, ANDROID_MIME_AACADTS) && 1106 strcasecmp((char*)df_mime->mimeType, 1107 ANDROID_MIME_AACADTS_ANDROID_FRAMEWORK)) { 1108 SL_LOGE("Invalid MIME (%s) for container type %d, expects %s", 1109 (char*)df_mime->mimeType, df_mime->containerType, 1110 ANDROID_MIME_AACADTS); 1111 return SL_RESULT_CONTENT_UNSUPPORTED; 1112 } 1113 break; 1114 default: 1115 SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source " 1116 "that is not fed MPEG-2 TS data or AAC ADTS data"); 1117 return SL_RESULT_CONTENT_UNSUPPORTED; 1118 } 1119 } 1120 break; 1121 default: 1122 SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source " 1123 "without SL_DATAFORMAT_MIME format"); 1124 return SL_RESULT_CONTENT_UNSUPPORTED; 1125 } 1126 } 1127 break; // case SL_DATALOCATOR_ANDROIDBUFFERQUEUE 1128 //------------------ 1129 // Address 1130 case SL_DATALOCATOR_ADDRESS: 1131 case SL_DATALOCATOR_IODEVICE: 1132 case SL_DATALOCATOR_OUTPUTMIX: 1133 case XA_DATALOCATOR_NATIVEDISPLAY: 1134 case SL_DATALOCATOR_MIDIBUFFERQUEUE: 1135 SL_LOGE("Cannot create audio player with data locator type 0x%x", 1136 (unsigned) sourceLocatorType); 1137 return SL_RESULT_CONTENT_UNSUPPORTED; 1138 default: 1139 SL_LOGE("Cannot create audio player with invalid data locator type 0x%x", 1140 (unsigned) sourceLocatorType); 1141 return SL_RESULT_PARAMETER_INVALID; 1142 }// switch (locatorType) 1143 1144 return SL_RESULT_SUCCESS; 1145} 1146 1147 1148 1149//----------------------------------------------------------------------------- 1150static void audioTrack_callBack_uri(int event, void* user, void *info) { 1151 // EVENT_MORE_DATA needs to be handled with priority over the other events 1152 // because it will be called the most often during playback 1153 1154 if (event == android::AudioTrack::EVENT_MORE_DATA) { 1155 //SL_LOGV("received event EVENT_MORE_DATA from AudioTrack"); 1156 // set size to 0 to signal we're not using the callback to write more data 1157 android::AudioTrack::Buffer* pBuff = (android::AudioTrack::Buffer*)info; 1158 pBuff->size = 0; 1159 } else if (NULL != user) { 1160 CAudioPlayer *ap = (CAudioPlayer *)user; 1161 if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) { 1162 // it is not safe to enter the callback (the track is about to go away) 1163 return; 1164 } 1165 switch (event) { 1166 case android::AudioTrack::EVENT_MARKER : 1167 audioTrack_handleMarker_lockPlay(ap); 1168 break; 1169 case android::AudioTrack::EVENT_NEW_POS : 1170 audioTrack_handleNewPos_lockPlay(ap); 1171 break; 1172 case android::AudioTrack::EVENT_UNDERRUN : 1173 audioTrack_handleUnderrun_lockPlay(ap); 1174 break; 1175 case android::AudioTrack::EVENT_BUFFER_END : 1176 case android::AudioTrack::EVENT_LOOP_END : 1177 break; 1178 default: 1179 SL_LOGE("Encountered unknown AudioTrack event %d for CAudioPlayer %p", event, 1180 ap); 1181 break; 1182 } 1183 ap->mCallbackProtector->exitCb(); 1184 } 1185} 1186 1187//----------------------------------------------------------------------------- 1188// Callback associated with an AudioTrack of an SL ES AudioPlayer that gets its data 1189// from a buffer queue. This will not be called once the AudioTrack has been destroyed. 1190static void audioTrack_callBack_pullFromBuffQueue(int event, void* user, void *info) { 1191 CAudioPlayer *ap = (CAudioPlayer *)user; 1192 1193 if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) { 1194 // it is not safe to enter the callback (the track is about to go away) 1195 return; 1196 } 1197 1198 void * callbackPContext = NULL; 1199 switch(event) { 1200 1201 case android::AudioTrack::EVENT_MORE_DATA: { 1202 //SL_LOGV("received event EVENT_MORE_DATA from AudioTrack TID=%d", gettid()); 1203 slBufferQueueCallback callback = NULL; 1204 slPrefetchCallback prefetchCallback = NULL; 1205 void *prefetchContext = NULL; 1206 SLuint32 prefetchEvents = SL_PREFETCHEVENT_NONE; 1207 android::AudioTrack::Buffer* pBuff = (android::AudioTrack::Buffer*)info; 1208 1209 // retrieve data from the buffer queue 1210 interface_lock_exclusive(&ap->mBufferQueue); 1211 1212 if (ap->mBufferQueue.mState.count != 0) { 1213 //SL_LOGV("nbBuffers in queue = %u",ap->mBufferQueue.mState.count); 1214 assert(ap->mBufferQueue.mFront != ap->mBufferQueue.mRear); 1215 1216 BufferHeader *oldFront = ap->mBufferQueue.mFront; 1217 BufferHeader *newFront = &oldFront[1]; 1218 1219 // declared as void * because this code supports both 8-bit and 16-bit PCM data 1220 void *pSrc = (char *)oldFront->mBuffer + ap->mBufferQueue.mSizeConsumed; 1221 if (ap->mBufferQueue.mSizeConsumed + pBuff->size < oldFront->mSize) { 1222 // can't consume the whole or rest of the buffer in one shot 1223 ap->mBufferQueue.mSizeConsumed += pBuff->size; 1224 // leave pBuff->size untouched 1225 // consume data 1226 // FIXME can we avoid holding the lock during the copy? 1227 memcpy (pBuff->raw, pSrc, pBuff->size); 1228 } else { 1229 // finish consuming the buffer or consume the buffer in one shot 1230 pBuff->size = oldFront->mSize - ap->mBufferQueue.mSizeConsumed; 1231 ap->mBufferQueue.mSizeConsumed = 0; 1232 1233 if (newFront == 1234 &ap->mBufferQueue.mArray 1235 [ap->mBufferQueue.mNumBuffers + 1]) 1236 { 1237 newFront = ap->mBufferQueue.mArray; 1238 } 1239 ap->mBufferQueue.mFront = newFront; 1240 1241 ap->mBufferQueue.mState.count--; 1242 ap->mBufferQueue.mState.playIndex++; 1243 1244 // consume data 1245 // FIXME can we avoid holding the lock during the copy? 1246 memcpy (pBuff->raw, pSrc, pBuff->size); 1247 1248 // data has been consumed, and the buffer queue state has been updated 1249 // we will notify the client if applicable 1250 callback = ap->mBufferQueue.mCallback; 1251 // save callback data 1252 callbackPContext = ap->mBufferQueue.mContext; 1253 } 1254 } else { // empty queue 1255 // signal no data available 1256 pBuff->size = 0; 1257 1258 // signal we're at the end of the content, but don't pause (see note in function) 1259 audioPlayer_dispatch_headAtEnd_lockPlay(ap, false /*set state to paused?*/, false); 1260 1261 // signal underflow to prefetch status itf 1262 if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) { 1263 ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW; 1264 ap->mPrefetchStatus.mLevel = 0; 1265 // callback or no callback? 1266 prefetchEvents = ap->mPrefetchStatus.mCallbackEventsMask & 1267 (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE); 1268 if (SL_PREFETCHEVENT_NONE != prefetchEvents) { 1269 prefetchCallback = ap->mPrefetchStatus.mCallback; 1270 prefetchContext = ap->mPrefetchStatus.mContext; 1271 } 1272 } 1273 1274 // stop the track so it restarts playing faster when new data is enqueued 1275 ap->mAudioTrack->stop(); 1276 } 1277 interface_unlock_exclusive(&ap->mBufferQueue); 1278 1279 // notify client 1280 if (NULL != prefetchCallback) { 1281 assert(SL_PREFETCHEVENT_NONE != prefetchEvents); 1282 // spec requires separate callbacks for each event 1283 if (prefetchEvents & SL_PREFETCHEVENT_STATUSCHANGE) { 1284 (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext, 1285 SL_PREFETCHEVENT_STATUSCHANGE); 1286 } 1287 if (prefetchEvents & SL_PREFETCHEVENT_FILLLEVELCHANGE) { 1288 (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext, 1289 SL_PREFETCHEVENT_FILLLEVELCHANGE); 1290 } 1291 } 1292 if (NULL != callback) { 1293 (*callback)(&ap->mBufferQueue.mItf, callbackPContext); 1294 } 1295 } 1296 break; 1297 1298 case android::AudioTrack::EVENT_MARKER: 1299 //SL_LOGI("received event EVENT_MARKER from AudioTrack"); 1300 audioTrack_handleMarker_lockPlay(ap); 1301 break; 1302 1303 case android::AudioTrack::EVENT_NEW_POS: 1304 //SL_LOGI("received event EVENT_NEW_POS from AudioTrack"); 1305 audioTrack_handleNewPos_lockPlay(ap); 1306 break; 1307 1308 case android::AudioTrack::EVENT_UNDERRUN: 1309 //SL_LOGI("received event EVENT_UNDERRUN from AudioTrack"); 1310 audioTrack_handleUnderrun_lockPlay(ap); 1311 break; 1312 1313 default: 1314 // FIXME where does the notification of SL_PLAYEVENT_HEADMOVING fit? 1315 SL_LOGE("Encountered unknown AudioTrack event %d for CAudioPlayer %p", event, 1316 (CAudioPlayer *)user); 1317 break; 1318 } 1319 1320 ap->mCallbackProtector->exitCb(); 1321} 1322 1323 1324//----------------------------------------------------------------------------- 1325SLresult android_audioPlayer_create(CAudioPlayer *pAudioPlayer) { 1326 1327 SLresult result = SL_RESULT_SUCCESS; 1328 // pAudioPlayer->mAndroidObjType has been set in audioPlayer_getAndroidObjectTypeForSourceSink() 1329 if (INVALID_TYPE == pAudioPlayer->mAndroidObjType) { 1330 audioPlayer_setInvalid(pAudioPlayer); 1331 result = SL_RESULT_PARAMETER_INVALID; 1332 } else { 1333 1334 // These initializations are in the same order as the field declarations in classes.h 1335 1336 // FIXME Consolidate initializations (many of these already in IEngine_CreateAudioPlayer) 1337 pAudioPlayer->mpLock = new android::Mutex(); 1338 // mAndroidObjType: see above comment 1339 pAudioPlayer->mAndroidObjState = ANDROID_UNINITIALIZED; 1340 pAudioPlayer->mSessionId = android::AudioSystem::newAudioSessionId(); 1341 pAudioPlayer->mStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE; 1342 1343 // mAudioTrack 1344 pAudioPlayer->mCallbackProtector = new android::CallbackProtector(); 1345 // mAPLayer 1346 // mAuxEffect 1347 1348 pAudioPlayer->mAuxSendLevel = 0; 1349 pAudioPlayer->mAmplFromDirectLevel = 1.0f; // matches initial mDirectLevel value 1350 pAudioPlayer->mDeferredStart = false; 1351 1352 // Already initialized in IEngine_CreateAudioPlayer, to be consolidated 1353 pAudioPlayer->mDirectLevel = 0; // no attenuation 1354 1355 // This section re-initializes interface-specific fields that 1356 // can be set or used regardless of whether the interface is 1357 // exposed on the AudioPlayer or not 1358 1359 // Only AudioTrack supports a non-trivial playback rate 1360 switch (pAudioPlayer->mAndroidObjType) { 1361 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 1362 pAudioPlayer->mPlaybackRate.mMinRate = AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE; 1363 pAudioPlayer->mPlaybackRate.mMaxRate = AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE; 1364 break; 1365 default: 1366 // use the default range 1367 break; 1368 } 1369 1370 } 1371 1372 return result; 1373} 1374 1375 1376//----------------------------------------------------------------------------- 1377SLresult android_audioPlayer_setConfig(CAudioPlayer *ap, const SLchar *configKey, 1378 const void *pConfigValue, SLuint32 valueSize) { 1379 1380 SLresult result; 1381 1382 assert(NULL != ap && NULL != configKey && NULL != pConfigValue); 1383 if(strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) { 1384 1385 // stream type 1386 if (KEY_STREAM_TYPE_PARAMSIZE > valueSize) { 1387 SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW); 1388 result = SL_RESULT_BUFFER_INSUFFICIENT; 1389 } else { 1390 result = audioPlayer_setStreamType(ap, *(SLuint32*)pConfigValue); 1391 } 1392 1393 } else { 1394 SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY); 1395 result = SL_RESULT_PARAMETER_INVALID; 1396 } 1397 1398 return result; 1399} 1400 1401 1402//----------------------------------------------------------------------------- 1403SLresult android_audioPlayer_getConfig(CAudioPlayer* ap, const SLchar *configKey, 1404 SLuint32* pValueSize, void *pConfigValue) { 1405 1406 SLresult result; 1407 1408 assert(NULL != ap && NULL != configKey && NULL != pValueSize); 1409 if(strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) { 1410 1411 // stream type 1412 if (NULL == pConfigValue) { 1413 result = SL_RESULT_SUCCESS; 1414 } else if (KEY_STREAM_TYPE_PARAMSIZE > *pValueSize) { 1415 SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW); 1416 result = SL_RESULT_BUFFER_INSUFFICIENT; 1417 } else { 1418 result = audioPlayer_getStreamType(ap, (SLint32*)pConfigValue); 1419 } 1420 *pValueSize = KEY_STREAM_TYPE_PARAMSIZE; 1421 1422 } else { 1423 SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY); 1424 result = SL_RESULT_PARAMETER_INVALID; 1425 } 1426 1427 return result; 1428} 1429 1430 1431//----------------------------------------------------------------------------- 1432// FIXME abstract out the diff between CMediaPlayer and CAudioPlayer 1433SLresult android_audioPlayer_realize(CAudioPlayer *pAudioPlayer, SLboolean async) { 1434 1435 SLresult result = SL_RESULT_SUCCESS; 1436 SL_LOGV("Realize pAudioPlayer=%p", pAudioPlayer); 1437 1438 switch (pAudioPlayer->mAndroidObjType) { 1439 //----------------------------------- 1440 // AudioTrack 1441 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 1442 { 1443 // initialize platform-specific CAudioPlayer fields 1444 1445 SLDataLocator_BufferQueue *dl_bq = (SLDataLocator_BufferQueue *) 1446 pAudioPlayer->mDynamicSource.mDataSource; 1447 SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *) 1448 pAudioPlayer->mDynamicSource.mDataSource->pFormat; 1449 1450 uint32_t sampleRate = sles_to_android_sampleRate(df_pcm->samplesPerSec); 1451 1452 pAudioPlayer->mAudioTrack = new android::AudioTrackProxy(new android::AudioTrack( 1453 pAudioPlayer->mStreamType, // streamType 1454 sampleRate, // sampleRate 1455 sles_to_android_sampleFormat(df_pcm->bitsPerSample), // format 1456 sles_to_android_channelMaskOut(df_pcm->numChannels, df_pcm->channelMask), 1457 //channel mask 1458 0, // frameCount (here min) 1459 0, // flags 1460 audioTrack_callBack_pullFromBuffQueue, // callback 1461 (void *) pAudioPlayer, // user 1462 0 // FIXME find appropriate frame count // notificationFrame 1463 , pAudioPlayer->mSessionId 1464 )); 1465 android::status_t status = pAudioPlayer->mAudioTrack->initCheck(); 1466 if (status != android::NO_ERROR) { 1467 SL_LOGE("AudioTrack::initCheck status %u", status); 1468 result = SL_RESULT_CONTENT_UNSUPPORTED; 1469 pAudioPlayer->mAudioTrack.clear(); 1470 return result; 1471 } 1472 1473 // initialize platform-independent CAudioPlayer fields 1474 1475 pAudioPlayer->mNumChannels = df_pcm->numChannels; 1476 pAudioPlayer->mSampleRateMilliHz = df_pcm->samplesPerSec; // Note: bad field name in SL ES 1477 1478 // This use case does not have a separate "prepare" step 1479 pAudioPlayer->mAndroidObjState = ANDROID_READY; 1480 } 1481 break; 1482 //----------------------------------- 1483 // MediaPlayer 1484 case AUDIOPLAYER_FROM_URIFD: { 1485 assert(pAudioPlayer->mAndroidObjState == ANDROID_UNINITIALIZED); 1486 assert(pAudioPlayer->mNumChannels == UNKNOWN_NUMCHANNELS); 1487 assert(pAudioPlayer->mSampleRateMilliHz == UNKNOWN_SAMPLERATE); 1488 assert(pAudioPlayer->mAudioTrack == 0); 1489 1490 AudioPlayback_Parameters app; 1491 app.sessionId = pAudioPlayer->mSessionId; 1492 app.streamType = pAudioPlayer->mStreamType; 1493 app.trackcb = audioTrack_callBack_uri; 1494 app.trackcbUser = (void *) pAudioPlayer; 1495 1496 pAudioPlayer->mAPlayer = new android::LocAVPlayer(&app, false /*hasVideo*/); 1497 pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent, 1498 (void*)pAudioPlayer /*notifUSer*/); 1499 1500 switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) { 1501 case SL_DATALOCATOR_URI: { 1502 // The legacy implementation ran Stagefright within the application process, and 1503 // so allowed local pathnames specified by URI that were openable by 1504 // the application but were not openable by mediaserver. 1505 // The current implementation runs Stagefright (mostly) within mediaserver, 1506 // which runs as a different UID and likely a different current working directory. 1507 // For backwards compatibility with any applications which may have relied on the 1508 // previous behavior, we convert an openable file URI into an FD. 1509 // Note that unlike SL_DATALOCATOR_ANDROIDFD, this FD is owned by us 1510 // and so we close it as soon as we've passed it (via Binder dup) to mediaserver. 1511 const char *uri = (const char *)pAudioPlayer->mDataSource.mLocator.mURI.URI; 1512 if (!isDistantProtocol(uri)) { 1513 // don't touch the original uri, we may need it later 1514 const char *pathname = uri; 1515 // skip over an optional leading file:// prefix 1516 if (!strncasecmp(pathname, "file://", 7)) { 1517 pathname += 7; 1518 } 1519 // attempt to open it as a file using the application's credentials 1520 int fd = ::open(pathname, O_RDONLY); 1521 if (fd >= 0) { 1522 // if open is successful, then check to see if it's a regular file 1523 struct stat statbuf; 1524 if (!::fstat(fd, &statbuf) && S_ISREG(statbuf.st_mode)) { 1525 // treat similarly to an FD data locator, but 1526 // let setDataSource take responsibility for closing fd 1527 pAudioPlayer->mAPlayer->setDataSource(fd, 0, statbuf.st_size, true); 1528 break; 1529 } 1530 // we were able to open it, but it's not a file, so let mediaserver try 1531 (void) ::close(fd); 1532 } 1533 } 1534 // if either the URI didn't look like a file, or open failed, or not a file 1535 pAudioPlayer->mAPlayer->setDataSource(uri); 1536 } break; 1537 case SL_DATALOCATOR_ANDROIDFD: { 1538 int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset; 1539 pAudioPlayer->mAPlayer->setDataSource( 1540 (int)pAudioPlayer->mDataSource.mLocator.mFD.fd, 1541 offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ? 1542 (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset, 1543 (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length); 1544 } 1545 break; 1546 default: 1547 SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR); 1548 break; 1549 } 1550 1551 } 1552 break; 1553 //----------------------------------- 1554 // StreamPlayer 1555 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: { 1556 object_lock_exclusive(&pAudioPlayer->mObject); 1557 AudioPlayback_Parameters ap_params; 1558 ap_params.sessionId = pAudioPlayer->mSessionId; 1559 ap_params.streamType = pAudioPlayer->mStreamType; 1560 ap_params.trackcb = NULL; 1561 ap_params.trackcbUser = NULL; 1562 android::StreamPlayer* splr = new android::StreamPlayer(&ap_params, false /*hasVideo*/, 1563 &pAudioPlayer->mAndroidBufferQueue, pAudioPlayer->mCallbackProtector); 1564 pAudioPlayer->mAPlayer = splr; 1565 splr->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer); 1566 object_unlock_exclusive(&pAudioPlayer->mObject); 1567 } 1568 break; 1569 //----------------------------------- 1570 // AudioToCbRenderer 1571 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: { 1572 AudioPlayback_Parameters app; 1573 app.sessionId = pAudioPlayer->mSessionId; 1574 app.streamType = pAudioPlayer->mStreamType; 1575 1576 android::AudioToCbRenderer* decoder = new android::AudioToCbRenderer(&app); 1577 pAudioPlayer->mAPlayer = decoder; 1578 // configures the callback for the sink buffer queue 1579 decoder->setDataPushListener(adecoder_writeToBufferQueue, pAudioPlayer); 1580 // configures the callback for the notifications coming from the SF code 1581 decoder->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer); 1582 1583 switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) { 1584 case SL_DATALOCATOR_URI: 1585 decoder->setDataSource( 1586 (const char*)pAudioPlayer->mDataSource.mLocator.mURI.URI); 1587 break; 1588 case SL_DATALOCATOR_ANDROIDFD: { 1589 int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset; 1590 decoder->setDataSource( 1591 (int)pAudioPlayer->mDataSource.mLocator.mFD.fd, 1592 offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ? 1593 (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset, 1594 (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length); 1595 } 1596 break; 1597 default: 1598 SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR); 1599 break; 1600 } 1601 1602 } 1603 break; 1604 //----------------------------------- 1605 // AacBqToPcmCbRenderer 1606 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: { 1607 AudioPlayback_Parameters app; 1608 app.sessionId = pAudioPlayer->mSessionId; 1609 app.streamType = pAudioPlayer->mStreamType; 1610 app.trackcb = NULL; 1611 app.trackcbUser = NULL; 1612 android::AacBqToPcmCbRenderer* bqtobq = new android::AacBqToPcmCbRenderer(&app); 1613 // configures the callback for the sink buffer queue 1614 bqtobq->setDataPushListener(adecoder_writeToBufferQueue, pAudioPlayer); 1615 pAudioPlayer->mAPlayer = bqtobq; 1616 // configures the callback for the notifications coming from the SF code, 1617 // but also implicitly configures the AndroidBufferQueue from which ADTS data is read 1618 pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer); 1619 } 1620 break; 1621 //----------------------------------- 1622 default: 1623 SL_LOGE(ERROR_PLAYERREALIZE_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType); 1624 result = SL_RESULT_INTERNAL_ERROR; 1625 break; 1626 } 1627 1628 1629 // proceed with effect initialization 1630 // initialize EQ 1631 // FIXME use a table of effect descriptors when adding support for more effects 1632 if (memcmp(SL_IID_EQUALIZER, &pAudioPlayer->mEqualizer.mEqDescriptor.type, 1633 sizeof(effect_uuid_t)) == 0) { 1634 SL_LOGV("Need to initialize EQ for AudioPlayer=%p", pAudioPlayer); 1635 android_eq_init(pAudioPlayer->mSessionId, &pAudioPlayer->mEqualizer); 1636 } 1637 // initialize BassBoost 1638 if (memcmp(SL_IID_BASSBOOST, &pAudioPlayer->mBassBoost.mBassBoostDescriptor.type, 1639 sizeof(effect_uuid_t)) == 0) { 1640 SL_LOGV("Need to initialize BassBoost for AudioPlayer=%p", pAudioPlayer); 1641 android_bb_init(pAudioPlayer->mSessionId, &pAudioPlayer->mBassBoost); 1642 } 1643 // initialize Virtualizer 1644 if (memcmp(SL_IID_VIRTUALIZER, &pAudioPlayer->mVirtualizer.mVirtualizerDescriptor.type, 1645 sizeof(effect_uuid_t)) == 0) { 1646 SL_LOGV("Need to initialize Virtualizer for AudioPlayer=%p", pAudioPlayer); 1647 android_virt_init(pAudioPlayer->mSessionId, &pAudioPlayer->mVirtualizer); 1648 } 1649 1650 // initialize EffectSend 1651 // FIXME initialize EffectSend 1652 1653 return result; 1654} 1655 1656 1657//----------------------------------------------------------------------------- 1658/** 1659 * Called with a lock on AudioPlayer, and blocks until safe to destroy 1660 */ 1661SLresult android_audioPlayer_preDestroy(CAudioPlayer *pAudioPlayer) { 1662 SL_LOGD("android_audioPlayer_preDestroy(%p)", pAudioPlayer); 1663 SLresult result = SL_RESULT_SUCCESS; 1664 1665 bool disableCallbacksBeforePreDestroy; 1666 switch (pAudioPlayer->mAndroidObjType) { 1667 // Not yet clear why this order is important, but it reduces detected deadlocks 1668 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1669 disableCallbacksBeforePreDestroy = true; 1670 break; 1671 // Use the old behavior for all other use cases until proven 1672 // case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 1673 default: 1674 disableCallbacksBeforePreDestroy = false; 1675 break; 1676 } 1677 1678 if (disableCallbacksBeforePreDestroy) { 1679 object_unlock_exclusive(&pAudioPlayer->mObject); 1680 if (pAudioPlayer->mCallbackProtector != 0) { 1681 pAudioPlayer->mCallbackProtector->requestCbExitAndWait(); 1682 } 1683 object_lock_exclusive(&pAudioPlayer->mObject); 1684 } 1685 1686 if (pAudioPlayer->mAPlayer != 0) { 1687 pAudioPlayer->mAPlayer->preDestroy(); 1688 } 1689 SL_LOGD("android_audioPlayer_preDestroy(%p) after mAPlayer->preDestroy()", pAudioPlayer); 1690 1691 if (!disableCallbacksBeforePreDestroy) { 1692 object_unlock_exclusive(&pAudioPlayer->mObject); 1693 if (pAudioPlayer->mCallbackProtector != 0) { 1694 pAudioPlayer->mCallbackProtector->requestCbExitAndWait(); 1695 } 1696 object_lock_exclusive(&pAudioPlayer->mObject); 1697 } 1698 1699 return result; 1700} 1701 1702 1703//----------------------------------------------------------------------------- 1704SLresult android_audioPlayer_destroy(CAudioPlayer *pAudioPlayer) { 1705 SLresult result = SL_RESULT_SUCCESS; 1706 SL_LOGV("android_audioPlayer_destroy(%p)", pAudioPlayer); 1707 switch (pAudioPlayer->mAndroidObjType) { 1708 1709 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 1710 // We own the audio track for PCM buffer queue players 1711 if (pAudioPlayer->mAudioTrack != 0) { 1712 pAudioPlayer->mAudioTrack->stop(); 1713 // Note that there may still be another reference in post-unlock phase of SetPlayState 1714 pAudioPlayer->mAudioTrack.clear(); 1715 } 1716 break; 1717 1718 case AUDIOPLAYER_FROM_URIFD: // intended fall-through 1719 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through 1720 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: // intended fall-through 1721 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 1722 pAudioPlayer->mAPlayer.clear(); 1723 break; 1724 //----------------------------------- 1725 default: 1726 SL_LOGE(ERROR_PLAYERDESTROY_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType); 1727 result = SL_RESULT_INTERNAL_ERROR; 1728 break; 1729 } 1730 1731 pAudioPlayer->mCallbackProtector.clear(); 1732 1733 // FIXME might not be needed 1734 pAudioPlayer->mAndroidObjType = INVALID_TYPE; 1735 1736 // explicit destructor 1737 pAudioPlayer->mAudioTrack.~sp(); 1738 // note that SetPlayState(PLAYING) may still hold a reference 1739 pAudioPlayer->mCallbackProtector.~sp(); 1740 pAudioPlayer->mAuxEffect.~sp(); 1741 pAudioPlayer->mAPlayer.~sp(); 1742 1743 if (pAudioPlayer->mpLock != NULL) { 1744 delete pAudioPlayer->mpLock; 1745 pAudioPlayer->mpLock = NULL; 1746 } 1747 1748 return result; 1749} 1750 1751 1752//----------------------------------------------------------------------------- 1753SLresult android_audioPlayer_setPlaybackRateAndConstraints(CAudioPlayer *ap, SLpermille rate, 1754 SLuint32 constraints) { 1755 SLresult result = SL_RESULT_SUCCESS; 1756 switch(ap->mAndroidObjType) { 1757 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: { 1758 // these asserts were already checked by the platform-independent layer 1759 assert((AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE <= rate) && 1760 (rate <= AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE)); 1761 assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO); 1762 // get the content sample rate 1763 uint32_t contentRate = sles_to_android_sampleRate(ap->mSampleRateMilliHz); 1764 // apply the SL ES playback rate on the AudioTrack as a factor of its content sample rate 1765 if (ap->mAudioTrack != 0) { 1766 ap->mAudioTrack->setSampleRate(contentRate * (rate/1000.0f)); 1767 } 1768 } 1769 break; 1770 case AUDIOPLAYER_FROM_URIFD: 1771 assert(rate == 1000); 1772 assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO); 1773 // that was easy 1774 break; 1775 1776 default: 1777 SL_LOGE("Unexpected object type %d", ap->mAndroidObjType); 1778 result = SL_RESULT_FEATURE_UNSUPPORTED; 1779 break; 1780 } 1781 return result; 1782} 1783 1784 1785//----------------------------------------------------------------------------- 1786// precondition 1787// called with no lock held 1788// ap != NULL 1789// pItemCount != NULL 1790SLresult android_audioPlayer_metadata_getItemCount(CAudioPlayer *ap, SLuint32 *pItemCount) { 1791 if (ap->mAPlayer == 0) { 1792 return SL_RESULT_PARAMETER_INVALID; 1793 } 1794 switch(ap->mAndroidObjType) { 1795 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1796 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 1797 { 1798 android::AudioSfDecoder* decoder = 1799 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get()); 1800 *pItemCount = decoder->getPcmFormatKeyCount(); 1801 } 1802 break; 1803 default: 1804 *pItemCount = 0; 1805 break; 1806 } 1807 return SL_RESULT_SUCCESS; 1808} 1809 1810 1811//----------------------------------------------------------------------------- 1812// precondition 1813// called with no lock held 1814// ap != NULL 1815// pKeySize != NULL 1816SLresult android_audioPlayer_metadata_getKeySize(CAudioPlayer *ap, 1817 SLuint32 index, SLuint32 *pKeySize) { 1818 if (ap->mAPlayer == 0) { 1819 return SL_RESULT_PARAMETER_INVALID; 1820 } 1821 SLresult res = SL_RESULT_SUCCESS; 1822 switch(ap->mAndroidObjType) { 1823 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1824 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 1825 { 1826 android::AudioSfDecoder* decoder = 1827 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get()); 1828 SLuint32 keyNameSize = 0; 1829 if (!decoder->getPcmFormatKeySize(index, &keyNameSize)) { 1830 res = SL_RESULT_PARAMETER_INVALID; 1831 } else { 1832 // *pKeySize is the size of the region used to store the key name AND 1833 // the information about the key (size, lang, encoding) 1834 *pKeySize = keyNameSize + sizeof(SLMetadataInfo); 1835 } 1836 } 1837 break; 1838 default: 1839 *pKeySize = 0; 1840 res = SL_RESULT_PARAMETER_INVALID; 1841 break; 1842 } 1843 return res; 1844} 1845 1846 1847//----------------------------------------------------------------------------- 1848// precondition 1849// called with no lock held 1850// ap != NULL 1851// pKey != NULL 1852SLresult android_audioPlayer_metadata_getKey(CAudioPlayer *ap, 1853 SLuint32 index, SLuint32 size, SLMetadataInfo *pKey) { 1854 if (ap->mAPlayer == 0) { 1855 return SL_RESULT_PARAMETER_INVALID; 1856 } 1857 SLresult res = SL_RESULT_SUCCESS; 1858 switch(ap->mAndroidObjType) { 1859 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1860 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 1861 { 1862 android::AudioSfDecoder* decoder = 1863 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get()); 1864 if ((size < sizeof(SLMetadataInfo) || 1865 (!decoder->getPcmFormatKeyName(index, size - sizeof(SLMetadataInfo), 1866 (char*)pKey->data)))) { 1867 res = SL_RESULT_PARAMETER_INVALID; 1868 } else { 1869 // successfully retrieved the key value, update the other fields 1870 pKey->encoding = SL_CHARACTERENCODING_UTF8; 1871 memcpy((char *) pKey->langCountry, "en", 3); 1872 pKey->size = strlen((char*)pKey->data) + 1; 1873 } 1874 } 1875 break; 1876 default: 1877 res = SL_RESULT_PARAMETER_INVALID; 1878 break; 1879 } 1880 return res; 1881} 1882 1883 1884//----------------------------------------------------------------------------- 1885// precondition 1886// called with no lock held 1887// ap != NULL 1888// pValueSize != NULL 1889SLresult android_audioPlayer_metadata_getValueSize(CAudioPlayer *ap, 1890 SLuint32 index, SLuint32 *pValueSize) { 1891 if (ap->mAPlayer == 0) { 1892 return SL_RESULT_PARAMETER_INVALID; 1893 } 1894 SLresult res = SL_RESULT_SUCCESS; 1895 switch(ap->mAndroidObjType) { 1896 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1897 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 1898 { 1899 android::AudioSfDecoder* decoder = 1900 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get()); 1901 SLuint32 valueSize = 0; 1902 if (!decoder->getPcmFormatValueSize(index, &valueSize)) { 1903 res = SL_RESULT_PARAMETER_INVALID; 1904 } else { 1905 // *pValueSize is the size of the region used to store the key value AND 1906 // the information about the value (size, lang, encoding) 1907 *pValueSize = valueSize + sizeof(SLMetadataInfo); 1908 } 1909 } 1910 break; 1911 default: 1912 *pValueSize = 0; 1913 res = SL_RESULT_PARAMETER_INVALID; 1914 break; 1915 } 1916 return res; 1917} 1918 1919 1920//----------------------------------------------------------------------------- 1921// precondition 1922// called with no lock held 1923// ap != NULL 1924// pValue != NULL 1925SLresult android_audioPlayer_metadata_getValue(CAudioPlayer *ap, 1926 SLuint32 index, SLuint32 size, SLMetadataInfo *pValue) { 1927 if (ap->mAPlayer == 0) { 1928 return SL_RESULT_PARAMETER_INVALID; 1929 } 1930 SLresult res = SL_RESULT_SUCCESS; 1931 switch(ap->mAndroidObjType) { 1932 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1933 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 1934 { 1935 android::AudioSfDecoder* decoder = 1936 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get()); 1937 pValue->encoding = SL_CHARACTERENCODING_BINARY; 1938 memcpy((char *) pValue->langCountry, "en", 3); // applicable here? 1939 SLuint32 valueSize = 0; 1940 if ((size < sizeof(SLMetadataInfo) 1941 || (!decoder->getPcmFormatValueSize(index, &valueSize)) 1942 || (!decoder->getPcmFormatKeyValue(index, size - sizeof(SLMetadataInfo), 1943 (SLuint32*)pValue->data)))) { 1944 res = SL_RESULT_PARAMETER_INVALID; 1945 } else { 1946 pValue->size = valueSize; 1947 } 1948 } 1949 break; 1950 default: 1951 res = SL_RESULT_PARAMETER_INVALID; 1952 break; 1953 } 1954 return res; 1955} 1956 1957//----------------------------------------------------------------------------- 1958// preconditions 1959// ap != NULL 1960// mutex is locked 1961// play state has changed 1962void android_audioPlayer_setPlayState(CAudioPlayer *ap) { 1963 1964 SLuint32 playState = ap->mPlay.mState; 1965 AndroidObjectState objState = ap->mAndroidObjState; 1966 1967 switch(ap->mAndroidObjType) { 1968 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 1969 switch (playState) { 1970 case SL_PLAYSTATE_STOPPED: 1971 SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_STOPPED"); 1972 if (ap->mAudioTrack != 0) { 1973 ap->mAudioTrack->stop(); 1974 } 1975 break; 1976 case SL_PLAYSTATE_PAUSED: 1977 SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PAUSED"); 1978 if (ap->mAudioTrack != 0) { 1979 ap->mAudioTrack->pause(); 1980 } 1981 break; 1982 case SL_PLAYSTATE_PLAYING: 1983 SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PLAYING"); 1984 if (ap->mAudioTrack != 0) { 1985 // instead of ap->mAudioTrack->start(); 1986 ap->mDeferredStart = true; 1987 } 1988 break; 1989 default: 1990 // checked by caller, should not happen 1991 break; 1992 } 1993 break; 1994 1995 case AUDIOPLAYER_FROM_URIFD: // intended fall-through 1996 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through 1997 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: // intended fall-through 1998 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 1999 // FIXME report and use the return code to the lock mechanism, which is where play state 2000 // changes are updated (see object_unlock_exclusive_attributes()) 2001 aplayer_setPlayState(ap->mAPlayer, playState, &(ap->mAndroidObjState)); 2002 break; 2003 default: 2004 SL_LOGE(ERROR_PLAYERSETPLAYSTATE_UNEXPECTED_OBJECT_TYPE_D, ap->mAndroidObjType); 2005 break; 2006 } 2007} 2008 2009 2010//----------------------------------------------------------------------------- 2011// call when either player event flags, marker position, or position update period changes 2012void android_audioPlayer_usePlayEventMask(CAudioPlayer *ap) { 2013 IPlay *pPlayItf = &ap->mPlay; 2014 SLuint32 eventFlags = pPlayItf->mEventFlags; 2015 /*switch(ap->mAndroidObjType) { 2016 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:*/ 2017 2018 if (ap->mAPlayer != 0) { 2019 assert(ap->mAudioTrack == 0); 2020 ap->mAPlayer->setPlayEvents((int32_t) eventFlags, (int32_t) pPlayItf->mMarkerPosition, 2021 (int32_t) pPlayItf->mPositionUpdatePeriod); 2022 return; 2023 } 2024 2025 if (ap->mAudioTrack == 0) { 2026 return; 2027 } 2028 2029 if (eventFlags & SL_PLAYEVENT_HEADATMARKER) { 2030 ap->mAudioTrack->setMarkerPosition((uint32_t)((((int64_t)pPlayItf->mMarkerPosition 2031 * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000)); 2032 } else { 2033 // clear marker 2034 ap->mAudioTrack->setMarkerPosition(0); 2035 } 2036 2037 if (eventFlags & SL_PLAYEVENT_HEADATNEWPOS) { 2038 ap->mAudioTrack->setPositionUpdatePeriod( 2039 (uint32_t)((((int64_t)pPlayItf->mPositionUpdatePeriod 2040 * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000)); 2041 } else { 2042 // clear periodic update 2043 ap->mAudioTrack->setPositionUpdatePeriod(0); 2044 } 2045 2046 if (eventFlags & SL_PLAYEVENT_HEADATEND) { 2047 // nothing to do for SL_PLAYEVENT_HEADATEND, callback event will be checked against mask 2048 } 2049 2050 if (eventFlags & SL_PLAYEVENT_HEADMOVING) { 2051 // FIXME support SL_PLAYEVENT_HEADMOVING 2052 SL_LOGD("[ FIXME: IPlay_SetCallbackEventsMask(SL_PLAYEVENT_HEADMOVING) on an " 2053 "SL_OBJECTID_AUDIOPLAYER to be implemented ]"); 2054 } 2055 if (eventFlags & SL_PLAYEVENT_HEADSTALLED) { 2056 // nothing to do for SL_PLAYEVENT_HEADSTALLED, callback event will be checked against mask 2057 } 2058 2059} 2060 2061 2062//----------------------------------------------------------------------------- 2063SLresult android_audioPlayer_getDuration(IPlay *pPlayItf, SLmillisecond *pDurMsec) { 2064 CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis; 2065 switch(ap->mAndroidObjType) { 2066 2067 case AUDIOPLAYER_FROM_URIFD: // intended fall-through 2068 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: { 2069 int32_t durationMsec = ANDROID_UNKNOWN_TIME; 2070 if (ap->mAPlayer != 0) { 2071 ap->mAPlayer->getDurationMsec(&durationMsec); 2072 } 2073 *pDurMsec = durationMsec == ANDROID_UNKNOWN_TIME ? SL_TIME_UNKNOWN : durationMsec; 2074 break; 2075 } 2076 2077 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through 2078 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 2079 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 2080 default: { 2081 *pDurMsec = SL_TIME_UNKNOWN; 2082 } 2083 } 2084 return SL_RESULT_SUCCESS; 2085} 2086 2087 2088//----------------------------------------------------------------------------- 2089void android_audioPlayer_getPosition(IPlay *pPlayItf, SLmillisecond *pPosMsec) { 2090 CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis; 2091 switch(ap->mAndroidObjType) { 2092 2093 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 2094 if ((ap->mSampleRateMilliHz == UNKNOWN_SAMPLERATE) || (ap->mAudioTrack == 0)) { 2095 *pPosMsec = 0; 2096 } else { 2097 uint32_t positionInFrames; 2098 ap->mAudioTrack->getPosition(&positionInFrames); 2099 *pPosMsec = ((int64_t)positionInFrames * 1000) / 2100 sles_to_android_sampleRate(ap->mSampleRateMilliHz); 2101 } 2102 break; 2103 2104 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through 2105 case AUDIOPLAYER_FROM_URIFD: 2106 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 2107 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: { 2108 int32_t posMsec = ANDROID_UNKNOWN_TIME; 2109 if (ap->mAPlayer != 0) { 2110 ap->mAPlayer->getPositionMsec(&posMsec); 2111 } 2112 *pPosMsec = posMsec == ANDROID_UNKNOWN_TIME ? 0 : posMsec; 2113 break; 2114 } 2115 2116 default: 2117 *pPosMsec = 0; 2118 } 2119} 2120 2121 2122//----------------------------------------------------------------------------- 2123SLresult android_audioPlayer_seek(CAudioPlayer *ap, SLmillisecond posMsec) { 2124 SLresult result = SL_RESULT_SUCCESS; 2125 2126 switch(ap->mAndroidObjType) { 2127 2128 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: // intended fall-through 2129 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: 2130 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 2131 result = SL_RESULT_FEATURE_UNSUPPORTED; 2132 break; 2133 2134 case AUDIOPLAYER_FROM_URIFD: // intended fall-through 2135 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 2136 if (ap->mAPlayer != 0) { 2137 ap->mAPlayer->seek(posMsec); 2138 } 2139 break; 2140 2141 default: 2142 break; 2143 } 2144 return result; 2145} 2146 2147 2148//----------------------------------------------------------------------------- 2149SLresult android_audioPlayer_loop(CAudioPlayer *ap, SLboolean loopEnable) { 2150 SLresult result = SL_RESULT_SUCCESS; 2151 2152 switch (ap->mAndroidObjType) { 2153 case AUDIOPLAYER_FROM_URIFD: 2154 // case AUDIOPLAY_FROM_URIFD_TO_PCM_BUFFERQUEUE: 2155 // would actually work, but what's the point? 2156 if (ap->mAPlayer != 0) { 2157 ap->mAPlayer->loop((bool)loopEnable); 2158 } 2159 break; 2160 default: 2161 result = SL_RESULT_FEATURE_UNSUPPORTED; 2162 break; 2163 } 2164 return result; 2165} 2166 2167 2168//----------------------------------------------------------------------------- 2169SLresult android_audioPlayer_setBufferingUpdateThresholdPerMille(CAudioPlayer *ap, 2170 SLpermille threshold) { 2171 SLresult result = SL_RESULT_SUCCESS; 2172 2173 switch (ap->mAndroidObjType) { 2174 case AUDIOPLAYER_FROM_URIFD: 2175 if (ap->mAPlayer != 0) { 2176 ap->mAPlayer->setBufferingUpdateThreshold(threshold / 10); 2177 } 2178 break; 2179 2180 default: {} 2181 } 2182 2183 return result; 2184} 2185 2186 2187//----------------------------------------------------------------------------- 2188void android_audioPlayer_bufferQueue_onRefilled_l(CAudioPlayer *ap) { 2189 // the AudioTrack associated with the AudioPlayer receiving audio from a PCM buffer 2190 // queue was stopped when the queue become empty, we restart as soon as a new buffer 2191 // has been enqueued since we're in playing state 2192 if (ap->mAudioTrack != 0) { 2193 // instead of ap->mAudioTrack->start(); 2194 ap->mDeferredStart = true; 2195 } 2196 2197 // when the queue became empty, an underflow on the prefetch status itf was sent. Now the queue 2198 // has received new data, signal it has sufficient data 2199 if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) { 2200 // we wouldn't have been called unless we were previously in the underflow state 2201 assert(SL_PREFETCHSTATUS_UNDERFLOW == ap->mPrefetchStatus.mStatus); 2202 assert(0 == ap->mPrefetchStatus.mLevel); 2203 ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA; 2204 ap->mPrefetchStatus.mLevel = 1000; 2205 // callback or no callback? 2206 SLuint32 prefetchEvents = ap->mPrefetchStatus.mCallbackEventsMask & 2207 (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE); 2208 if (SL_PREFETCHEVENT_NONE != prefetchEvents) { 2209 ap->mPrefetchStatus.mDeferredPrefetchCallback = ap->mPrefetchStatus.mCallback; 2210 ap->mPrefetchStatus.mDeferredPrefetchContext = ap->mPrefetchStatus.mContext; 2211 ap->mPrefetchStatus.mDeferredPrefetchEvents = prefetchEvents; 2212 } 2213 } 2214} 2215 2216 2217//----------------------------------------------------------------------------- 2218/* 2219 * BufferQueue::Clear 2220 */ 2221SLresult android_audioPlayer_bufferQueue_onClear(CAudioPlayer *ap) { 2222 SLresult result = SL_RESULT_SUCCESS; 2223 2224 switch (ap->mAndroidObjType) { 2225 //----------------------------------- 2226 // AudioTrack 2227 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 2228 if (ap->mAudioTrack != 0) { 2229 ap->mAudioTrack->flush(); 2230 } 2231 break; 2232 default: 2233 result = SL_RESULT_INTERNAL_ERROR; 2234 break; 2235 } 2236 2237 return result; 2238} 2239 2240 2241//----------------------------------------------------------------------------- 2242SLresult android_audioPlayer_androidBufferQueue_registerCallback_l(CAudioPlayer *ap) { 2243 SLresult result = SL_RESULT_SUCCESS; 2244 assert(ap->mAPlayer != 0); 2245 switch (ap->mAndroidObjType) { 2246 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: { 2247 android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get()); 2248 splr->registerQueueCallback(&ap->mAndroidBufferQueue); 2249 } break; 2250 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: { 2251 android::AacBqToPcmCbRenderer* dec = 2252 static_cast<android::AacBqToPcmCbRenderer*>(ap->mAPlayer.get()); 2253 dec->registerSourceQueueCallback((const void*)ap /*user*/, 2254 ap->mAndroidBufferQueue.mContext /*context*/, 2255 (const void*)&(ap->mAndroidBufferQueue.mItf) /*caller*/); 2256 } break; 2257 default: 2258 SL_LOGE("Error registering AndroidBufferQueue callback: unexpected object type %d", 2259 ap->mAndroidObjType); 2260 result = SL_RESULT_INTERNAL_ERROR; 2261 break; 2262 } 2263 return result; 2264} 2265 2266//----------------------------------------------------------------------------- 2267void android_audioPlayer_androidBufferQueue_clear_l(CAudioPlayer *ap) { 2268 switch (ap->mAndroidObjType) { 2269 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: 2270 if (ap->mAPlayer != 0) { 2271 android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get()); 2272 splr->appClear_l(); 2273 } break; 2274 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 2275 // nothing to do here, fall through 2276 default: 2277 break; 2278 } 2279} 2280 2281void android_audioPlayer_androidBufferQueue_onRefilled_l(CAudioPlayer *ap) { 2282 switch (ap->mAndroidObjType) { 2283 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: 2284 if (ap->mAPlayer != 0) { 2285 android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get()); 2286 splr->queueRefilled(); 2287 } break; 2288 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: 2289 // FIXME this may require waking up the decoder if it is currently starved and isn't polling 2290 default: 2291 break; 2292 } 2293} 2294