AudioPlayer_to_android.cpp revision f093dcf23cb5f54ced676c03a64cc68a165266f4
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, prefetch, and play 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 case android::GenericPlayer::kEventPlay: { 869 slPlayCallback callback = NULL; 870 void* callbackPContext = NULL; 871 872 interface_lock_shared(&ap->mPlay); 873 callback = ap->mPlay.mCallback; 874 callbackPContext = ap->mPlay.mContext; 875 interface_unlock_shared(&ap->mPlay); 876 877 if (NULL != callback) { 878 SLuint32 event = (SLuint32) data1; // SL_PLAYEVENT_HEAD* 879#ifndef USE_ASYNCHRONOUS_PLAY_CALLBACK 880 // synchronous callback requires a synchronous GetPosition implementation 881 (*callback)(&ap->mPlay.mItf, callbackPContext, event); 882#else 883 // asynchronous callback works with any GetPosition implementation 884 SLresult result = EnqueueAsyncCallback_ppi(ap, callback, &ap->mPlay.mItf, 885 callbackPContext, event); 886 if (SL_RESULT_SUCCESS != result) { 887 LOGW("Callback %p(%p, %p, 0x%x) dropped", callback, 888 &ap->mPlay.mItf, callbackPContext, event); 889 } 890#endif 891 } 892 } 893 break; 894 895 default: 896 break; 897 } 898 899 ap->mCallbackProtector->exitCb(); 900} 901 902 903//----------------------------------------------------------------------------- 904SLresult android_audioPlayer_checkSourceSink(CAudioPlayer *pAudioPlayer) 905{ 906 // verify that the locator types for the source / sink combination is supported 907 pAudioPlayer->mAndroidObjType = audioPlayer_getAndroidObjectTypeForSourceSink(pAudioPlayer); 908 if (INVALID_TYPE == pAudioPlayer->mAndroidObjType) { 909 return SL_RESULT_PARAMETER_INVALID; 910 } 911 912 const SLDataSource *pAudioSrc = &pAudioPlayer->mDataSource.u.mSource; 913 const SLDataSink *pAudioSnk = &pAudioPlayer->mDataSink.u.mSink; 914 915 // format check: 916 const SLuint32 sourceLocatorType = *(SLuint32 *)pAudioSrc->pLocator; 917 const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator; 918 const SLuint32 sourceFormatType = *(SLuint32 *)pAudioSrc->pFormat; 919 const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSnk->pFormat; 920 921 switch (sourceLocatorType) { 922 //------------------ 923 // Buffer Queues 924 case SL_DATALOCATOR_BUFFERQUEUE: 925 case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE: 926 { 927 SLDataLocator_BufferQueue *dl_bq = (SLDataLocator_BufferQueue *) pAudioSrc->pLocator; 928 929 // Buffer format 930 switch (sourceFormatType) { 931 // currently only PCM buffer queues are supported, 932 case SL_DATAFORMAT_PCM: { 933 SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *) pAudioSrc->pFormat; 934 switch (df_pcm->numChannels) { 935 case 1: 936 case 2: 937 break; 938 default: 939 // this should have already been rejected by checkDataFormat 940 SL_LOGE("Cannot create audio player: unsupported " \ 941 "PCM data source with %u channels", (unsigned) df_pcm->numChannels); 942 return SL_RESULT_CONTENT_UNSUPPORTED; 943 } 944 switch (df_pcm->samplesPerSec) { 945 case SL_SAMPLINGRATE_8: 946 case SL_SAMPLINGRATE_11_025: 947 case SL_SAMPLINGRATE_12: 948 case SL_SAMPLINGRATE_16: 949 case SL_SAMPLINGRATE_22_05: 950 case SL_SAMPLINGRATE_24: 951 case SL_SAMPLINGRATE_32: 952 case SL_SAMPLINGRATE_44_1: 953 case SL_SAMPLINGRATE_48: 954 break; 955 case SL_SAMPLINGRATE_64: 956 case SL_SAMPLINGRATE_88_2: 957 case SL_SAMPLINGRATE_96: 958 case SL_SAMPLINGRATE_192: 959 default: 960 SL_LOGE("Cannot create audio player: unsupported sample rate %u milliHz", 961 (unsigned) df_pcm->samplesPerSec); 962 return SL_RESULT_CONTENT_UNSUPPORTED; 963 } 964 switch (df_pcm->bitsPerSample) { 965 case SL_PCMSAMPLEFORMAT_FIXED_8: 966 // FIXME We should support this 967 //SL_LOGE("Cannot create audio player: unsupported 8-bit data"); 968 //return SL_RESULT_CONTENT_UNSUPPORTED; 969 case SL_PCMSAMPLEFORMAT_FIXED_16: 970 break; 971 // others 972 default: 973 // this should have already been rejected by checkDataFormat 974 SL_LOGE("Cannot create audio player: unsupported sample bit depth %u", 975 (SLuint32)df_pcm->bitsPerSample); 976 return SL_RESULT_CONTENT_UNSUPPORTED; 977 } 978 switch (df_pcm->containerSize) { 979 case 8: 980 case 16: 981 break; 982 // others 983 default: 984 SL_LOGE("Cannot create audio player: unsupported container size %u", 985 (unsigned) df_pcm->containerSize); 986 return SL_RESULT_CONTENT_UNSUPPORTED; 987 } 988 switch (df_pcm->channelMask) { 989 // FIXME needs work 990 default: 991 break; 992 } 993 switch (df_pcm->endianness) { 994 case SL_BYTEORDER_LITTLEENDIAN: 995 break; 996 case SL_BYTEORDER_BIGENDIAN: 997 SL_LOGE("Cannot create audio player: unsupported big-endian byte order"); 998 return SL_RESULT_CONTENT_UNSUPPORTED; 999 // native is proposed but not yet in spec 1000 default: 1001 SL_LOGE("Cannot create audio player: unsupported byte order %u", 1002 (unsigned) df_pcm->endianness); 1003 return SL_RESULT_CONTENT_UNSUPPORTED; 1004 } 1005 } //case SL_DATAFORMAT_PCM 1006 break; 1007 case SL_DATAFORMAT_MIME: 1008 case XA_DATAFORMAT_RAWIMAGE: 1009 SL_LOGE("Cannot create audio player with buffer queue data source " 1010 "without SL_DATAFORMAT_PCM format"); 1011 return SL_RESULT_CONTENT_UNSUPPORTED; 1012 default: 1013 // invalid data format is detected earlier 1014 assert(false); 1015 return SL_RESULT_INTERNAL_ERROR; 1016 } // switch (sourceFormatType) 1017 } // case SL_DATALOCATOR_BUFFERQUEUE or SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE 1018 break; 1019 //------------------ 1020 // URI 1021 case SL_DATALOCATOR_URI: 1022 { 1023 SLDataLocator_URI *dl_uri = (SLDataLocator_URI *) pAudioSrc->pLocator; 1024 if (NULL == dl_uri->URI) { 1025 return SL_RESULT_PARAMETER_INVALID; 1026 } 1027 // URI format 1028 switch (sourceFormatType) { 1029 case SL_DATAFORMAT_MIME: 1030 break; 1031 case SL_DATAFORMAT_PCM: 1032 case XA_DATAFORMAT_RAWIMAGE: 1033 SL_LOGE("Cannot create audio player with SL_DATALOCATOR_URI data source without " 1034 "SL_DATAFORMAT_MIME format"); 1035 return SL_RESULT_CONTENT_UNSUPPORTED; 1036 } // switch (sourceFormatType) 1037 // decoding format check 1038 if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) && 1039 !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) { 1040 return SL_RESULT_CONTENT_UNSUPPORTED; 1041 } 1042 } // case SL_DATALOCATOR_URI 1043 break; 1044 //------------------ 1045 // File Descriptor 1046 case SL_DATALOCATOR_ANDROIDFD: 1047 { 1048 // fd is already non null 1049 switch (sourceFormatType) { 1050 case SL_DATAFORMAT_MIME: 1051 break; 1052 case SL_DATAFORMAT_PCM: 1053 // FIXME implement 1054 SL_LOGD("[ FIXME implement PCM FD data sources ]"); 1055 break; 1056 case XA_DATAFORMAT_RAWIMAGE: 1057 SL_LOGE("Cannot create audio player with SL_DATALOCATOR_ANDROIDFD data source " 1058 "without SL_DATAFORMAT_MIME or SL_DATAFORMAT_PCM format"); 1059 return SL_RESULT_CONTENT_UNSUPPORTED; 1060 default: 1061 // invalid data format is detected earlier 1062 assert(false); 1063 return SL_RESULT_INTERNAL_ERROR; 1064 } // switch (sourceFormatType) 1065 if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) && 1066 !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) { 1067 return SL_RESULT_CONTENT_UNSUPPORTED; 1068 } 1069 } // case SL_DATALOCATOR_ANDROIDFD 1070 break; 1071 //------------------ 1072 // Stream 1073 case SL_DATALOCATOR_ANDROIDBUFFERQUEUE: 1074 { 1075 switch (sourceFormatType) { 1076 case SL_DATAFORMAT_MIME: 1077 { 1078 SLDataFormat_MIME *df_mime = (SLDataFormat_MIME *) pAudioSrc->pFormat; 1079 if (SL_CONTAINERTYPE_MPEG_TS != df_mime->containerType) { 1080 SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source " 1081 "that is not fed MPEG-2 TS data"); 1082 return SL_RESULT_CONTENT_UNSUPPORTED; 1083 } 1084 } 1085 break; 1086 default: 1087 SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source " 1088 "without SL_DATAFORMAT_MIME format"); 1089 return SL_RESULT_CONTENT_UNSUPPORTED; 1090 } 1091 } 1092 break; // case SL_DATALOCATOR_ANDROIDBUFFERQUEUE 1093 //------------------ 1094 // Address 1095 case SL_DATALOCATOR_ADDRESS: 1096 case SL_DATALOCATOR_IODEVICE: 1097 case SL_DATALOCATOR_OUTPUTMIX: 1098 case XA_DATALOCATOR_NATIVEDISPLAY: 1099 case SL_DATALOCATOR_MIDIBUFFERQUEUE: 1100 SL_LOGE("Cannot create audio player with data locator type 0x%x", 1101 (unsigned) sourceLocatorType); 1102 return SL_RESULT_CONTENT_UNSUPPORTED; 1103 default: 1104 SL_LOGE("Cannot create audio player with invalid data locator type 0x%x", 1105 (unsigned) sourceLocatorType); 1106 return SL_RESULT_PARAMETER_INVALID; 1107 }// switch (locatorType) 1108 1109 return SL_RESULT_SUCCESS; 1110} 1111 1112 1113 1114//----------------------------------------------------------------------------- 1115static void audioTrack_callBack_uri(int event, void* user, void *info) { 1116 // EVENT_MORE_DATA needs to be handled with priority over the other events 1117 // because it will be called the most often during playback 1118 1119 if (event == android::AudioTrack::EVENT_MORE_DATA) { 1120 //SL_LOGV("received event EVENT_MORE_DATA from AudioTrack"); 1121 // set size to 0 to signal we're not using the callback to write more data 1122 android::AudioTrack::Buffer* pBuff = (android::AudioTrack::Buffer*)info; 1123 pBuff->size = 0; 1124 } else if (NULL != user) { 1125 CAudioPlayer *ap = (CAudioPlayer *)user; 1126 if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) { 1127 // it is not safe to enter the callback (the track is about to go away) 1128 return; 1129 } 1130 switch (event) { 1131 case android::AudioTrack::EVENT_MARKER : 1132 audioTrack_handleMarker_lockPlay(ap); 1133 break; 1134 case android::AudioTrack::EVENT_NEW_POS : 1135 audioTrack_handleNewPos_lockPlay(ap); 1136 break; 1137 case android::AudioTrack::EVENT_UNDERRUN : 1138 audioTrack_handleUnderrun_lockPlay(ap); 1139 break; 1140 case android::AudioTrack::EVENT_BUFFER_END : 1141 case android::AudioTrack::EVENT_LOOP_END : 1142 break; 1143 default: 1144 SL_LOGE("Encountered unknown AudioTrack event %d for CAudioPlayer %p", event, 1145 ap); 1146 break; 1147 } 1148 ap->mCallbackProtector->exitCb(); 1149 } 1150} 1151 1152//----------------------------------------------------------------------------- 1153// Callback associated with an AudioTrack of an SL ES AudioPlayer that gets its data 1154// from a buffer queue. This will not be called once the AudioTrack has been destroyed. 1155static void audioTrack_callBack_pullFromBuffQueue(int event, void* user, void *info) { 1156 CAudioPlayer *ap = (CAudioPlayer *)user; 1157 1158 if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) { 1159 // it is not safe to enter the callback (the track is about to go away) 1160 return; 1161 } 1162 1163 void * callbackPContext = NULL; 1164 switch(event) { 1165 1166 case android::AudioTrack::EVENT_MORE_DATA: { 1167 //SL_LOGV("received event EVENT_MORE_DATA from AudioTrack TID=%d", gettid()); 1168 slBufferQueueCallback callback = NULL; 1169 android::AudioTrack::Buffer* pBuff = (android::AudioTrack::Buffer*)info; 1170 1171 // retrieve data from the buffer queue 1172 interface_lock_exclusive(&ap->mBufferQueue); 1173 1174 if (ap->mBufferQueue.mState.count != 0) { 1175 //SL_LOGV("nbBuffers in queue = %u",ap->mBufferQueue.mState.count); 1176 assert(ap->mBufferQueue.mFront != ap->mBufferQueue.mRear); 1177 1178 BufferHeader *oldFront = ap->mBufferQueue.mFront; 1179 BufferHeader *newFront = &oldFront[1]; 1180 1181 // FIXME handle 8bit based on buffer format 1182 short *pSrc = (short*)((char *)oldFront->mBuffer 1183 + ap->mBufferQueue.mSizeConsumed); 1184 if (ap->mBufferQueue.mSizeConsumed + pBuff->size < oldFront->mSize) { 1185 // can't consume the whole or rest of the buffer in one shot 1186 ap->mBufferQueue.mSizeConsumed += pBuff->size; 1187 // leave pBuff->size untouched 1188 // consume data 1189 // FIXME can we avoid holding the lock during the copy? 1190 memcpy (pBuff->i16, pSrc, pBuff->size); 1191 } else { 1192 // finish consuming the buffer or consume the buffer in one shot 1193 pBuff->size = oldFront->mSize - ap->mBufferQueue.mSizeConsumed; 1194 ap->mBufferQueue.mSizeConsumed = 0; 1195 1196 if (newFront == 1197 &ap->mBufferQueue.mArray 1198 [ap->mBufferQueue.mNumBuffers + 1]) 1199 { 1200 newFront = ap->mBufferQueue.mArray; 1201 } 1202 ap->mBufferQueue.mFront = newFront; 1203 1204 ap->mBufferQueue.mState.count--; 1205 ap->mBufferQueue.mState.playIndex++; 1206 1207 // consume data 1208 // FIXME can we avoid holding the lock during the copy? 1209 memcpy (pBuff->i16, pSrc, pBuff->size); 1210 1211 // data has been consumed, and the buffer queue state has been updated 1212 // we will notify the client if applicable 1213 callback = ap->mBufferQueue.mCallback; 1214 // save callback data 1215 callbackPContext = ap->mBufferQueue.mContext; 1216 } 1217 } else { // empty queue 1218 // signal no data available 1219 pBuff->size = 0; 1220 1221 // signal we're at the end of the content, but don't pause (see note in function) 1222 audioPlayer_dispatch_headAtEnd_lockPlay(ap, false /*set state to paused?*/, false); 1223 1224 // signal underflow to prefetch status itf 1225 if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) { 1226 audioPlayer_dispatch_prefetchStatus_lockPrefetch(ap, SL_PREFETCHSTATUS_UNDERFLOW, 1227 false); 1228 } 1229 1230 // stop the track so it restarts playing faster when new data is enqueued 1231 ap->mAudioTrack->stop(); 1232 } 1233 interface_unlock_exclusive(&ap->mBufferQueue); 1234 1235 // notify client 1236 if (NULL != callback) { 1237 (*callback)(&ap->mBufferQueue.mItf, callbackPContext); 1238 } 1239 } 1240 break; 1241 1242 case android::AudioTrack::EVENT_MARKER: 1243 //SL_LOGI("received event EVENT_MARKER from AudioTrack"); 1244 audioTrack_handleMarker_lockPlay(ap); 1245 break; 1246 1247 case android::AudioTrack::EVENT_NEW_POS: 1248 //SL_LOGI("received event EVENT_NEW_POS from AudioTrack"); 1249 audioTrack_handleNewPos_lockPlay(ap); 1250 break; 1251 1252 case android::AudioTrack::EVENT_UNDERRUN: 1253 //SL_LOGI("received event EVENT_UNDERRUN from AudioTrack"); 1254 audioTrack_handleUnderrun_lockPlay(ap); 1255 break; 1256 1257 default: 1258 // FIXME where does the notification of SL_PLAYEVENT_HEADMOVING fit? 1259 SL_LOGE("Encountered unknown AudioTrack event %d for CAudioPlayer %p", event, 1260 (CAudioPlayer *)user); 1261 break; 1262 } 1263 1264 ap->mCallbackProtector->exitCb(); 1265} 1266 1267 1268//----------------------------------------------------------------------------- 1269SLresult android_audioPlayer_create(CAudioPlayer *pAudioPlayer) { 1270 1271 SLresult result = SL_RESULT_SUCCESS; 1272 // pAudioPlayer->mAndroidObjType has been set in audioPlayer_getAndroidObjectTypeForSourceSink() 1273 if (INVALID_TYPE == pAudioPlayer->mAndroidObjType) { 1274 audioPlayer_setInvalid(pAudioPlayer); 1275 result = SL_RESULT_PARAMETER_INVALID; 1276 } else { 1277 1278 // These initializations are in the same order as the field declarations in classes.h 1279 1280 // FIXME Consolidate initializations (many of these already in IEngine_CreateAudioPlayer) 1281 pAudioPlayer->mpLock = new android::Mutex(); 1282 // mAndroidObjType: see above comment 1283 pAudioPlayer->mAndroidObjState = ANDROID_UNINITIALIZED; 1284 pAudioPlayer->mSessionId = android::AudioSystem::newAudioSessionId(); 1285 pAudioPlayer->mStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE; 1286 1287 // mAudioTrack 1288 pAudioPlayer->mCallbackProtector = new android::CallbackProtector(); 1289 // mAPLayer 1290 // mAuxEffect 1291 1292 pAudioPlayer->mAuxSendLevel = 0; 1293 pAudioPlayer->mAmplFromDirectLevel = 1.0f; // matches initial mDirectLevel value 1294 pAudioPlayer->mDeferredStart = false; 1295 // Already initialized in IEngine_CreateAudioPlayer, to be consolidated 1296 pAudioPlayer->mDirectLevel = 0; // no attenuation 1297 1298 // This section re-initializes interface-specific fields that 1299 // can be set or used regardless of whether the interface is 1300 // exposed on the AudioPlayer or not 1301 1302 // Only AudioTrack supports a non-trivial playback rate 1303 switch (pAudioPlayer->mAndroidObjType) { 1304 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 1305 pAudioPlayer->mPlaybackRate.mMinRate = AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE; 1306 pAudioPlayer->mPlaybackRate.mMaxRate = AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE; 1307 break; 1308 default: 1309 // use the default range 1310 break; 1311 } 1312 1313 } 1314 1315 return result; 1316} 1317 1318 1319//----------------------------------------------------------------------------- 1320SLresult android_audioPlayer_setConfig(CAudioPlayer *ap, const SLchar *configKey, 1321 const void *pConfigValue, SLuint32 valueSize) { 1322 1323 SLresult result; 1324 1325 assert(NULL != ap && NULL != configKey && NULL != pConfigValue); 1326 if(strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) { 1327 1328 // stream type 1329 if (KEY_STREAM_TYPE_PARAMSIZE > valueSize) { 1330 SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW); 1331 result = SL_RESULT_BUFFER_INSUFFICIENT; 1332 } else { 1333 result = audioPlayer_setStreamType(ap, *(SLuint32*)pConfigValue); 1334 } 1335 1336 } else { 1337 SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY); 1338 result = SL_RESULT_PARAMETER_INVALID; 1339 } 1340 1341 return result; 1342} 1343 1344 1345//----------------------------------------------------------------------------- 1346SLresult android_audioPlayer_getConfig(CAudioPlayer* ap, const SLchar *configKey, 1347 SLuint32* pValueSize, void *pConfigValue) { 1348 1349 SLresult result; 1350 1351 assert(NULL != ap && NULL != configKey && NULL != pValueSize); 1352 if(strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) { 1353 1354 // stream type 1355 if (NULL == pConfigValue) { 1356 result = SL_RESULT_SUCCESS; 1357 } else if (KEY_STREAM_TYPE_PARAMSIZE > *pValueSize) { 1358 SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW); 1359 result = SL_RESULT_BUFFER_INSUFFICIENT; 1360 } else { 1361 result = audioPlayer_getStreamType(ap, (SLint32*)pConfigValue); 1362 } 1363 *pValueSize = KEY_STREAM_TYPE_PARAMSIZE; 1364 1365 } else { 1366 SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY); 1367 result = SL_RESULT_PARAMETER_INVALID; 1368 } 1369 1370 return result; 1371} 1372 1373 1374//----------------------------------------------------------------------------- 1375SLresult android_audioPlayer_realize(CAudioPlayer *pAudioPlayer, SLboolean async) { 1376 1377 SLresult result = SL_RESULT_SUCCESS; 1378 SL_LOGV("Realize pAudioPlayer=%p", pAudioPlayer); 1379 1380 switch (pAudioPlayer->mAndroidObjType) { 1381 //----------------------------------- 1382 // AudioTrack 1383 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 1384 { 1385 // initialize platform-specific CAudioPlayer fields 1386 1387 SLDataLocator_BufferQueue *dl_bq = (SLDataLocator_BufferQueue *) 1388 pAudioPlayer->mDynamicSource.mDataSource; 1389 SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *) 1390 pAudioPlayer->mDynamicSource.mDataSource->pFormat; 1391 1392 uint32_t sampleRate = sles_to_android_sampleRate(df_pcm->samplesPerSec); 1393 1394 pAudioPlayer->mAudioTrack = new android::AudioTrackProxy(new android::AudioTrack( 1395 pAudioPlayer->mStreamType, // streamType 1396 sampleRate, // sampleRate 1397 sles_to_android_sampleFormat(df_pcm->bitsPerSample), // format 1398 sles_to_android_channelMaskOut(df_pcm->numChannels, df_pcm->channelMask), 1399 //channel mask 1400 0, // frameCount (here min) 1401 0, // flags 1402 audioTrack_callBack_pullFromBuffQueue, // callback 1403 (void *) pAudioPlayer, // user 1404 0 // FIXME find appropriate frame count // notificationFrame 1405 , pAudioPlayer->mSessionId 1406 )); 1407 android::status_t status = pAudioPlayer->mAudioTrack->initCheck(); 1408 if (status != android::NO_ERROR) { 1409 SL_LOGE("AudioTrack::initCheck status %u", status); 1410 result = SL_RESULT_CONTENT_UNSUPPORTED; 1411 pAudioPlayer->mAudioTrack.clear(); 1412 return result; 1413 } 1414 1415 // initialize platform-independent CAudioPlayer fields 1416 1417 pAudioPlayer->mNumChannels = df_pcm->numChannels; 1418 pAudioPlayer->mSampleRateMilliHz = df_pcm->samplesPerSec; // Note: bad field name in SL ES 1419 1420 pAudioPlayer->mAndroidObjState = ANDROID_READY; 1421 } 1422 break; 1423 //----------------------------------- 1424 // MediaPlayer 1425 case AUDIOPLAYER_FROM_URIFD: { 1426 object_lock_exclusive(&pAudioPlayer->mObject); 1427 1428 assert(pAudioPlayer->mAndroidObjState == ANDROID_UNINITIALIZED); 1429 assert(pAudioPlayer->mNumChannels == UNKNOWN_NUMCHANNELS); 1430 assert(pAudioPlayer->mSampleRateMilliHz == UNKNOWN_SAMPLERATE); 1431 assert(pAudioPlayer->mAudioTrack == 0); 1432 1433 AudioPlayback_Parameters app; 1434 app.sessionId = pAudioPlayer->mSessionId; 1435 app.streamType = pAudioPlayer->mStreamType; 1436 app.trackcb = audioTrack_callBack_uri; 1437 app.trackcbUser = (void *) pAudioPlayer; 1438 1439 pAudioPlayer->mAPlayer = new android::LocAVPlayer(&app, false /*hasVideo*/); 1440 pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent, 1441 (void*)pAudioPlayer /*notifUSer*/); 1442 1443 object_unlock_exclusive(&pAudioPlayer->mObject); 1444 1445 switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) { 1446 case SL_DATALOCATOR_URI: 1447 pAudioPlayer->mAPlayer->setDataSource( 1448 (const char*)pAudioPlayer->mDataSource.mLocator.mURI.URI); 1449 break; 1450 case SL_DATALOCATOR_ANDROIDFD: { 1451 int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset; 1452 pAudioPlayer->mAPlayer->setDataSource( 1453 (int)pAudioPlayer->mDataSource.mLocator.mFD.fd, 1454 offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ? 1455 (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset, 1456 (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length); 1457 } 1458 break; 1459 default: 1460 SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR); 1461 break; 1462 } 1463 1464 } 1465 break; 1466 //----------------------------------- 1467 // StreamPlayer 1468 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: { 1469 object_lock_exclusive(&pAudioPlayer->mObject); 1470 1471 android_StreamPlayer_realize_l(pAudioPlayer, sfplayer_handlePrefetchEvent, 1472 (void*)pAudioPlayer); 1473 1474 object_unlock_exclusive(&pAudioPlayer->mObject); 1475 } 1476 break; 1477 //----------------------------------- 1478 // AudioToCbRenderer 1479 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: { 1480 object_lock_exclusive(&pAudioPlayer->mObject); 1481 1482 AudioPlayback_Parameters app; 1483 app.sessionId = pAudioPlayer->mSessionId; 1484 app.streamType = pAudioPlayer->mStreamType; 1485 1486 android::AudioToCbRenderer* decoder = new android::AudioToCbRenderer(&app); 1487 pAudioPlayer->mAPlayer = decoder; 1488 decoder->setDataPushListener(adecoder_writeToBufferQueue, (void*)pAudioPlayer); 1489 decoder->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer); 1490 1491 switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) { 1492 case SL_DATALOCATOR_URI: 1493 decoder->setDataSource( 1494 (const char*)pAudioPlayer->mDataSource.mLocator.mURI.URI); 1495 break; 1496 case SL_DATALOCATOR_ANDROIDFD: { 1497 int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset; 1498 decoder->setDataSource( 1499 (int)pAudioPlayer->mDataSource.mLocator.mFD.fd, 1500 offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ? 1501 (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset, 1502 (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length); 1503 } 1504 break; 1505 default: 1506 SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR); 1507 break; 1508 } 1509 1510 object_unlock_exclusive(&pAudioPlayer->mObject); 1511 } 1512 break; 1513 //----------------------------------- 1514 default: 1515 SL_LOGE(ERROR_PLAYERREALIZE_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType); 1516 result = SL_RESULT_INTERNAL_ERROR; 1517 break; 1518 } 1519 1520 1521 // proceed with effect initialization 1522 // initialize EQ 1523 // FIXME use a table of effect descriptors when adding support for more effects 1524 if (memcmp(SL_IID_EQUALIZER, &pAudioPlayer->mEqualizer.mEqDescriptor.type, 1525 sizeof(effect_uuid_t)) == 0) { 1526 SL_LOGV("Need to initialize EQ for AudioPlayer=%p", pAudioPlayer); 1527 android_eq_init(pAudioPlayer->mSessionId, &pAudioPlayer->mEqualizer); 1528 } 1529 // initialize BassBoost 1530 if (memcmp(SL_IID_BASSBOOST, &pAudioPlayer->mBassBoost.mBassBoostDescriptor.type, 1531 sizeof(effect_uuid_t)) == 0) { 1532 SL_LOGV("Need to initialize BassBoost for AudioPlayer=%p", pAudioPlayer); 1533 android_bb_init(pAudioPlayer->mSessionId, &pAudioPlayer->mBassBoost); 1534 } 1535 // initialize Virtualizer 1536 if (memcmp(SL_IID_VIRTUALIZER, &pAudioPlayer->mVirtualizer.mVirtualizerDescriptor.type, 1537 sizeof(effect_uuid_t)) == 0) { 1538 SL_LOGV("Need to initialize Virtualizer for AudioPlayer=%p", pAudioPlayer); 1539 android_virt_init(pAudioPlayer->mSessionId, &pAudioPlayer->mVirtualizer); 1540 } 1541 1542 // initialize EffectSend 1543 // FIXME initialize EffectSend 1544 1545 return result; 1546} 1547 1548 1549//----------------------------------------------------------------------------- 1550/** 1551 * Called with a lock on AudioPlayer 1552 */ 1553SLresult android_audioPlayer_preDestroy(CAudioPlayer *pAudioPlayer) { 1554 SL_LOGD("android_audioPlayer_preDestroy(%p)", pAudioPlayer); 1555 SLresult result = SL_RESULT_SUCCESS; 1556 1557 if (pAudioPlayer->mAPlayer != 0) { 1558 pAudioPlayer->mAPlayer->preDestroy(); 1559 } 1560 SL_LOGD("android_audioPlayer_preDestroy(%p) after mAPlayer->preDestroy()", pAudioPlayer); 1561 1562 object_unlock_exclusive(&pAudioPlayer->mObject); 1563 if (pAudioPlayer->mCallbackProtector != 0) { 1564 pAudioPlayer->mCallbackProtector->requestCbExitAndWait(); 1565 } 1566 object_lock_exclusive(&pAudioPlayer->mObject); 1567 1568 return result; 1569} 1570 1571 1572//----------------------------------------------------------------------------- 1573SLresult android_audioPlayer_destroy(CAudioPlayer *pAudioPlayer) { 1574 SLresult result = SL_RESULT_SUCCESS; 1575 SL_LOGV("android_audioPlayer_destroy(%p)", pAudioPlayer); 1576 switch (pAudioPlayer->mAndroidObjType) { 1577 1578 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 1579 // We own the audio track for PCM buffer queue players 1580 if (pAudioPlayer->mAudioTrack != 0) { 1581 pAudioPlayer->mAudioTrack->stop(); 1582 // Note that there may still be another reference in post-unlock phase of SetPlayState 1583 pAudioPlayer->mAudioTrack.clear(); 1584 } 1585 break; 1586 1587 case AUDIOPLAYER_FROM_URIFD: // intended fall-through 1588 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through 1589 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1590 pAudioPlayer->mAPlayer.clear(); 1591 break; 1592 //----------------------------------- 1593 default: 1594 SL_LOGE(ERROR_PLAYERDESTROY_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType); 1595 result = SL_RESULT_INTERNAL_ERROR; 1596 break; 1597 } 1598 1599 pAudioPlayer->mCallbackProtector.clear(); 1600 1601 // FIXME might not be needed 1602 pAudioPlayer->mAndroidObjType = INVALID_TYPE; 1603 1604 // explicit destructor 1605 pAudioPlayer->mAudioTrack.~sp(); 1606 // note that SetPlayState(PLAYING) may still hold a reference 1607 pAudioPlayer->mCallbackProtector.~sp(); 1608 pAudioPlayer->mAuxEffect.~sp(); 1609 pAudioPlayer->mAPlayer.~sp(); 1610 1611 if (pAudioPlayer->mpLock != NULL) { 1612 delete pAudioPlayer->mpLock; 1613 pAudioPlayer->mpLock = NULL; 1614 } 1615 1616 return result; 1617} 1618 1619 1620//----------------------------------------------------------------------------- 1621SLresult android_audioPlayer_setPlaybackRateAndConstraints(CAudioPlayer *ap, SLpermille rate, 1622 SLuint32 constraints) { 1623 SLresult result = SL_RESULT_SUCCESS; 1624 switch(ap->mAndroidObjType) { 1625 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: { 1626 // these asserts were already checked by the platform-independent layer 1627 assert((AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE <= rate) && 1628 (rate <= AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE)); 1629 assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO); 1630 // get the content sample rate 1631 uint32_t contentRate = sles_to_android_sampleRate(ap->mSampleRateMilliHz); 1632 // apply the SL ES playback rate on the AudioTrack as a factor of its content sample rate 1633 if (ap->mAudioTrack != 0) { 1634 ap->mAudioTrack->setSampleRate(contentRate * (rate/1000.0f)); 1635 } 1636 } 1637 break; 1638 case AUDIOPLAYER_FROM_URIFD: 1639 assert(rate == 1000); 1640 assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO); 1641 // that was easy 1642 break; 1643 1644 default: 1645 SL_LOGE("Unexpected object type %d", ap->mAndroidObjType); 1646 result = SL_RESULT_FEATURE_UNSUPPORTED; 1647 break; 1648 } 1649 return result; 1650} 1651 1652 1653//----------------------------------------------------------------------------- 1654// precondition 1655// called with no lock held 1656// ap != NULL 1657// pItemCount != NULL 1658SLresult android_audioPlayer_metadata_getItemCount(CAudioPlayer *ap, SLuint32 *pItemCount) { 1659 if (ap->mAPlayer == 0) { 1660 return SL_RESULT_PARAMETER_INVALID; 1661 } 1662 switch(ap->mAndroidObjType) { 1663 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1664 { 1665 android::AudioSfDecoder* decoder = 1666 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get()); 1667 *pItemCount = decoder->getPcmFormatKeyCount(); 1668 } 1669 break; 1670 default: 1671 *pItemCount = 0; 1672 break; 1673 } 1674 return SL_RESULT_SUCCESS; 1675} 1676 1677 1678//----------------------------------------------------------------------------- 1679// precondition 1680// called with no lock held 1681// ap != NULL 1682// pKeySize != NULL 1683SLresult android_audioPlayer_metadata_getKeySize(CAudioPlayer *ap, 1684 SLuint32 index, SLuint32 *pKeySize) { 1685 if (ap->mAPlayer == 0) { 1686 return SL_RESULT_PARAMETER_INVALID; 1687 } 1688 SLresult res = SL_RESULT_SUCCESS; 1689 switch(ap->mAndroidObjType) { 1690 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1691 { 1692 android::AudioSfDecoder* decoder = 1693 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get()); 1694 SLuint32 keyNameSize = 0; 1695 if (!decoder->getPcmFormatKeySize(index, &keyNameSize)) { 1696 res = SL_RESULT_PARAMETER_INVALID; 1697 } else { 1698 // *pKeySize is the size of the region used to store the key name AND 1699 // the information about the key (size, lang, encoding) 1700 *pKeySize = keyNameSize + sizeof(SLMetadataInfo); 1701 } 1702 } 1703 break; 1704 default: 1705 *pKeySize = 0; 1706 res = SL_RESULT_PARAMETER_INVALID; 1707 break; 1708 } 1709 return res; 1710} 1711 1712 1713//----------------------------------------------------------------------------- 1714// precondition 1715// called with no lock held 1716// ap != NULL 1717// pKey != NULL 1718SLresult android_audioPlayer_metadata_getKey(CAudioPlayer *ap, 1719 SLuint32 index, SLuint32 size, SLMetadataInfo *pKey) { 1720 if (ap->mAPlayer == 0) { 1721 return SL_RESULT_PARAMETER_INVALID; 1722 } 1723 SLresult res = SL_RESULT_SUCCESS; 1724 switch(ap->mAndroidObjType) { 1725 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1726 { 1727 android::AudioSfDecoder* decoder = 1728 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get()); 1729 if ((size < sizeof(SLMetadataInfo) || 1730 (!decoder->getPcmFormatKeyName(index, size - sizeof(SLMetadataInfo), 1731 (char*)pKey->data)))) { 1732 res = SL_RESULT_PARAMETER_INVALID; 1733 } else { 1734 // successfully retrieved the key value, update the other fields 1735 pKey->encoding = SL_CHARACTERENCODING_UTF8; 1736 memcpy((char *) pKey->langCountry, "en", 3); 1737 pKey->size = strlen((char*)pKey->data) + 1; 1738 } 1739 } 1740 break; 1741 default: 1742 res = SL_RESULT_PARAMETER_INVALID; 1743 break; 1744 } 1745 return res; 1746} 1747 1748 1749//----------------------------------------------------------------------------- 1750// precondition 1751// called with no lock held 1752// ap != NULL 1753// pValueSize != NULL 1754SLresult android_audioPlayer_metadata_getValueSize(CAudioPlayer *ap, 1755 SLuint32 index, SLuint32 *pValueSize) { 1756 if (ap->mAPlayer == 0) { 1757 return SL_RESULT_PARAMETER_INVALID; 1758 } 1759 SLresult res = SL_RESULT_SUCCESS; 1760 switch(ap->mAndroidObjType) { 1761 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1762 { 1763 android::AudioSfDecoder* decoder = 1764 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get()); 1765 SLuint32 valueSize = 0; 1766 if (!decoder->getPcmFormatValueSize(index, &valueSize)) { 1767 res = SL_RESULT_PARAMETER_INVALID; 1768 } else { 1769 // *pValueSize is the size of the region used to store the key value AND 1770 // the information about the value (size, lang, encoding) 1771 *pValueSize = valueSize + sizeof(SLMetadataInfo); 1772 } 1773 } 1774 break; 1775 default: 1776 *pValueSize = 0; 1777 res = SL_RESULT_PARAMETER_INVALID; 1778 break; 1779 } 1780 return res; 1781} 1782 1783 1784//----------------------------------------------------------------------------- 1785// precondition 1786// called with no lock held 1787// ap != NULL 1788// pValue != NULL 1789SLresult android_audioPlayer_metadata_getValue(CAudioPlayer *ap, 1790 SLuint32 index, SLuint32 size, SLMetadataInfo *pValue) { 1791 if (ap->mAPlayer == 0) { 1792 return SL_RESULT_PARAMETER_INVALID; 1793 } 1794 SLresult res = SL_RESULT_SUCCESS; 1795 switch(ap->mAndroidObjType) { 1796 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1797 { 1798 android::AudioSfDecoder* decoder = 1799 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get()); 1800 pValue->encoding = SL_CHARACTERENCODING_BINARY; 1801 memcpy((char *) pValue->langCountry, "en", 3); // applicable here? 1802 SLuint32 valueSize = 0; 1803 if ((size < sizeof(SLMetadataInfo) 1804 || (!decoder->getPcmFormatValueSize(index, &valueSize)) 1805 || (!decoder->getPcmFormatKeyValue(index, size - sizeof(SLMetadataInfo), 1806 (SLuint32*)pValue->data)))) { 1807 res = SL_RESULT_PARAMETER_INVALID; 1808 } else { 1809 pValue->size = valueSize; 1810 } 1811 } 1812 break; 1813 default: 1814 res = SL_RESULT_PARAMETER_INVALID; 1815 break; 1816 } 1817 return res; 1818} 1819 1820//----------------------------------------------------------------------------- 1821// preconditions 1822// ap != NULL 1823// mutex is locked 1824// play state has changed 1825void android_audioPlayer_setPlayState(CAudioPlayer *ap) { 1826 1827 SLuint32 playState = ap->mPlay.mState; 1828 AndroidObjectState objState = ap->mAndroidObjState; 1829 1830 switch(ap->mAndroidObjType) { 1831 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 1832 switch (playState) { 1833 case SL_PLAYSTATE_STOPPED: 1834 SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_STOPPED"); 1835 if (ap->mAudioTrack != 0) { 1836 ap->mAudioTrack->stop(); 1837 } 1838 break; 1839 case SL_PLAYSTATE_PAUSED: 1840 SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PAUSED"); 1841 if (ap->mAudioTrack != 0) { 1842 ap->mAudioTrack->pause(); 1843 } 1844 break; 1845 case SL_PLAYSTATE_PLAYING: 1846 SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PLAYING"); 1847 if (ap->mAudioTrack != 0) { 1848 // instead of ap->mAudioTrack->start(); 1849 ap->mDeferredStart = true; 1850 } 1851 break; 1852 default: 1853 // checked by caller, should not happen 1854 break; 1855 } 1856 break; 1857 1858 case AUDIOPLAYER_FROM_URIFD: // intended fall-through 1859 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through 1860 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1861 // FIXME report and use the return code to the lock mechanism, which is where play state 1862 // changes are updated (see object_unlock_exclusive_attributes()) 1863 aplayer_setPlayState(ap->mAPlayer, playState, &(ap->mAndroidObjState)); 1864 break; 1865 default: 1866 SL_LOGE(ERROR_PLAYERSETPLAYSTATE_UNEXPECTED_OBJECT_TYPE_D, ap->mAndroidObjType); 1867 break; 1868 } 1869} 1870 1871 1872//----------------------------------------------------------------------------- 1873// call when either player event flags, marker position, or position update period changes 1874void android_audioPlayer_useEventMask(CAudioPlayer *ap) { 1875 IPlay *pPlayItf = &ap->mPlay; 1876 SLuint32 eventFlags = pPlayItf->mEventFlags; 1877 /*switch(ap->mAndroidObjType) { 1878 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:*/ 1879 1880 if (ap->mAPlayer != 0) { 1881 assert(ap->mAudioTrack == 0); 1882 ap->mAPlayer->setPlayEvents((int32_t) eventFlags, (int32_t) pPlayItf->mMarkerPosition, 1883 (int32_t) pPlayItf->mPositionUpdatePeriod); 1884 return; 1885 } 1886 1887 if (ap->mAudioTrack == 0) { 1888 return; 1889 } 1890 1891 if (eventFlags & SL_PLAYEVENT_HEADATMARKER) { 1892 ap->mAudioTrack->setMarkerPosition((uint32_t)((((int64_t)pPlayItf->mMarkerPosition 1893 * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000)); 1894 } else { 1895 // clear marker 1896 ap->mAudioTrack->setMarkerPosition(0); 1897 } 1898 1899 if (eventFlags & SL_PLAYEVENT_HEADATNEWPOS) { 1900 ap->mAudioTrack->setPositionUpdatePeriod( 1901 (uint32_t)((((int64_t)pPlayItf->mPositionUpdatePeriod 1902 * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000)); 1903 } else { 1904 // clear periodic update 1905 ap->mAudioTrack->setPositionUpdatePeriod(0); 1906 } 1907 1908 if (eventFlags & SL_PLAYEVENT_HEADATEND) { 1909 // nothing to do for SL_PLAYEVENT_HEADATEND, callback event will be checked against mask 1910 } 1911 1912 if (eventFlags & SL_PLAYEVENT_HEADMOVING) { 1913 // FIXME support SL_PLAYEVENT_HEADMOVING 1914 SL_LOGD("[ FIXME: IPlay_SetCallbackEventsMask(SL_PLAYEVENT_HEADMOVING) on an " 1915 "SL_OBJECTID_AUDIOPLAYER to be implemented ]"); 1916 } 1917 if (eventFlags & SL_PLAYEVENT_HEADSTALLED) { 1918 // nothing to do for SL_PLAYEVENT_HEADSTALLED, callback event will be checked against mask 1919 } 1920 1921} 1922 1923 1924//----------------------------------------------------------------------------- 1925SLresult android_audioPlayer_getDuration(IPlay *pPlayItf, SLmillisecond *pDurMsec) { 1926 CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis; 1927 switch(ap->mAndroidObjType) { 1928 1929 case AUDIOPLAYER_FROM_URIFD: // intended fall-through 1930 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: { 1931 int32_t durationMsec = ANDROID_UNKNOWN_TIME; 1932 if (ap->mAPlayer != 0) { 1933 ap->mAPlayer->getDurationMsec(&durationMsec); 1934 } 1935 *pDurMsec = durationMsec == ANDROID_UNKNOWN_TIME ? SL_TIME_UNKNOWN : durationMsec; 1936 break; 1937 } 1938 1939 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through 1940 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: // intended fall-through 1941 default: { 1942 *pDurMsec = SL_TIME_UNKNOWN; 1943 } 1944 } 1945 return SL_RESULT_SUCCESS; 1946} 1947 1948 1949//----------------------------------------------------------------------------- 1950void android_audioPlayer_getPosition(IPlay *pPlayItf, SLmillisecond *pPosMsec) { 1951 CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis; 1952 switch(ap->mAndroidObjType) { 1953 1954 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 1955 if ((ap->mSampleRateMilliHz == UNKNOWN_SAMPLERATE) || (ap->mAudioTrack == 0)) { 1956 *pPosMsec = 0; 1957 } else { 1958 uint32_t positionInFrames; 1959 ap->mAudioTrack->getPosition(&positionInFrames); 1960 *pPosMsec = ((int64_t)positionInFrames * 1000) / 1961 sles_to_android_sampleRate(ap->mSampleRateMilliHz); 1962 } 1963 break; 1964 1965 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through 1966 case AUDIOPLAYER_FROM_URIFD: // intended fall-through 1967 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: { 1968 int32_t posMsec = ANDROID_UNKNOWN_TIME; 1969 if (ap->mAPlayer != 0) { 1970 ap->mAPlayer->getPositionMsec(&posMsec); 1971 } 1972 *pPosMsec = posMsec == ANDROID_UNKNOWN_TIME ? 0 : posMsec; 1973 break; 1974 } 1975 1976 default: 1977 *pPosMsec = 0; 1978 } 1979} 1980 1981 1982//----------------------------------------------------------------------------- 1983void android_audioPlayer_seek(CAudioPlayer *ap, SLmillisecond posMsec) { 1984 1985 switch(ap->mAndroidObjType) { 1986 1987 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: // intended fall-through 1988 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: 1989 break; 1990 1991 case AUDIOPLAYER_FROM_URIFD: // intended fall-through 1992 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: 1993 if (ap->mAPlayer != 0) { 1994 ap->mAPlayer->seek(posMsec); 1995 } 1996 break; 1997 1998 default: 1999 break; 2000 } 2001} 2002 2003 2004//----------------------------------------------------------------------------- 2005void android_audioPlayer_loop(CAudioPlayer *ap, SLboolean loopEnable) { 2006 2007 if ((AUDIOPLAYER_FROM_URIFD == ap->mAndroidObjType) && (ap->mAPlayer != 0)) { 2008 ap->mAPlayer->loop((bool)loopEnable); 2009 } 2010} 2011 2012 2013//----------------------------------------------------------------------------- 2014SLresult android_audioPlayer_setBufferingUpdateThresholdPerMille(CAudioPlayer *ap, 2015 SLpermille threshold) { 2016 SLresult result = SL_RESULT_SUCCESS; 2017 2018 switch (ap->mAndroidObjType) { 2019 case AUDIOPLAYER_FROM_URIFD: 2020 if (ap->mAPlayer != 0) { 2021 ap->mAPlayer->setBufferingUpdateThreshold(threshold / 10); 2022 } 2023 break; 2024 2025 default: {} 2026 } 2027 2028 return result; 2029} 2030 2031 2032//----------------------------------------------------------------------------- 2033void android_audioPlayer_bufferQueue_onRefilled_l(CAudioPlayer *ap) { 2034 // the AudioTrack associated with the AudioPlayer receiving audio from a PCM buffer 2035 // queue was stopped when the queue become empty, we restart as soon as a new buffer 2036 // has been enqueued since we're in playing state 2037 if (ap->mAudioTrack != 0) { 2038 // instead of ap->mAudioTrack->start(); 2039 ap->mDeferredStart = true; 2040 } 2041 2042 // when the queue became empty, an underflow on the prefetch status itf was sent. Now the queue 2043 // has received new data, signal it has sufficient data 2044 if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) { 2045 audioPlayer_dispatch_prefetchStatus_lockPrefetch(ap, SL_PREFETCHSTATUS_SUFFICIENTDATA, 2046 true); 2047 } 2048} 2049 2050 2051//----------------------------------------------------------------------------- 2052/* 2053 * BufferQueue::Clear 2054 */ 2055SLresult android_audioPlayer_bufferQueue_onClear(CAudioPlayer *ap) { 2056 SLresult result = SL_RESULT_SUCCESS; 2057 2058 switch (ap->mAndroidObjType) { 2059 //----------------------------------- 2060 // AudioTrack 2061 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: 2062 if (ap->mAudioTrack != 0) { 2063 ap->mAudioTrack->flush(); 2064 } 2065 break; 2066 default: 2067 result = SL_RESULT_INTERNAL_ERROR; 2068 break; 2069 } 2070 2071 return result; 2072} 2073 2074 2075//----------------------------------------------------------------------------- 2076void android_audioPlayer_androidBufferQueue_registerCallback_l(CAudioPlayer *ap) { 2077 if ((ap->mAndroidObjType == AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE) && (ap->mAPlayer != 0)) { 2078 android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get()); 2079 splr->registerQueueCallback( 2080 (const void*)ap, true /*userIsAudioPlayer*/, 2081 ap->mAndroidBufferQueue.mContext, 2082 (const void*)&(ap->mAndroidBufferQueue.mItf)); 2083 } 2084} 2085 2086//----------------------------------------------------------------------------- 2087void android_audioPlayer_androidBufferQueue_clear_l(CAudioPlayer *ap) { 2088 if ((ap->mAndroidObjType == AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE) && (ap->mAPlayer != 0)) { 2089 android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get()); 2090 splr->appClear_l(); 2091 } 2092} 2093 2094void android_audioPlayer_androidBufferQueue_onRefilled_l(CAudioPlayer *ap) { 2095 if ((ap->mAndroidObjType == AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE) && (ap->mAPlayer != 0)) { 2096 android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get()); 2097 splr->queueRefilled_l(); 2098 } 2099} 2100