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