2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "sles_allinclusive.h"
18 #include "android_prompts.h"
19 #include "android/android_AudioToCbRenderer.h"
20 #include "android/android_StreamPlayer.h"
21 #include "android/android_LocAVPlayer.h"
22 #include "android/include/AacBqToPcmCbRenderer.h"
24 #include <system/audio.h>
26 template class android::KeyedVector<SLuint32, android::AudioEffect* > ;
28 #define KEY_STREAM_TYPE_PARAMSIZE sizeof(SLint32)
30 #define AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE 500
31 #define AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE 2000
33 //-----------------------------------------------------------------------------
34 // FIXME this method will be absorbed into android_audioPlayer_setPlayState() once
35 // bufferqueue and uri/fd playback are moved under the GenericPlayer C++ object
36 SLresult aplayer_setPlayState(const android::sp<android::GenericPlayer> &ap, SLuint32 playState,
37 AndroidObjectState* pObjState) {
38 SLresult result = SL_RESULT_SUCCESS;
39 AndroidObjectState objState = *pObjState;
42 case SL_PLAYSTATE_STOPPED:
43 SL_LOGV("setting GenericPlayer to SL_PLAYSTATE_STOPPED");
46 case SL_PLAYSTATE_PAUSED:
47 SL_LOGV("setting GenericPlayer to SL_PLAYSTATE_PAUSED");
49 case ANDROID_UNINITIALIZED:
50 *pObjState = ANDROID_PREPARING;
53 case ANDROID_PREPARING:
59 SL_LOGE(ERROR_PLAYERSETPLAYSTATE_INVALID_OBJECT_STATE_D, playState);
60 result = SL_RESULT_INTERNAL_ERROR;
64 case SL_PLAYSTATE_PLAYING: {
65 SL_LOGV("setting GenericPlayer to SL_PLAYSTATE_PLAYING");
67 case ANDROID_UNINITIALIZED:
68 *pObjState = ANDROID_PREPARING;
70 // intended fall through
71 case ANDROID_PREPARING:
72 // intended fall through
77 SL_LOGE(ERROR_PLAYERSETPLAYSTATE_INVALID_OBJECT_STATE_D, playState);
78 result = SL_RESULT_INTERNAL_ERROR;
84 // checked by caller, should not happen
85 SL_LOGE(ERROR_SHOULDNT_BE_HERE_S, "aplayer_setPlayState");
86 result = SL_RESULT_INTERNAL_ERROR;
94 //-----------------------------------------------------------------------------
95 // Callback associated with a AudioToCbRenderer of an SL ES AudioPlayer that gets its data
96 // from a URI or FD, to write the decoded audio data to a buffer queue
97 static size_t adecoder_writeToBufferQueue(const uint8_t *data, size_t size, void* user) {
98 size_t sizeConsumed = 0;
102 SL_LOGD("received %d bytes from decoder", size);
103 CAudioPlayer *ap = (CAudioPlayer *)user;
104 slBufferQueueCallback callback = NULL;
105 void * callbackPContext = NULL;
107 // push decoded data to the buffer queue
108 object_lock_exclusive(&ap->mObject);
110 if (ap->mBufferQueue.mState.count != 0) {
111 assert(ap->mBufferQueue.mFront != ap->mBufferQueue.mRear);
113 BufferHeader *oldFront = ap->mBufferQueue.mFront;
114 BufferHeader *newFront = &oldFront[1];
116 uint8_t *pDest = (uint8_t *)oldFront->mBuffer + ap->mBufferQueue.mSizeConsumed;
117 if (ap->mBufferQueue.mSizeConsumed + size < oldFront->mSize) {
118 // room to consume the whole or rest of the decoded data in one shot
119 ap->mBufferQueue.mSizeConsumed += size;
120 // consume data but no callback to the BufferQueue interface here
121 memcpy (pDest, data, size);
124 // push as much as possible of the decoded data into the buffer queue
125 sizeConsumed = oldFront->mSize - ap->mBufferQueue.mSizeConsumed;
127 // the buffer at the head of the buffer queue is full, update the state
128 ap->mBufferQueue.mSizeConsumed = 0;
129 if (newFront == &ap->mBufferQueue.mArray[ap->mBufferQueue.mNumBuffers + 1]) {
130 newFront = ap->mBufferQueue.mArray;
132 ap->mBufferQueue.mFront = newFront;
134 ap->mBufferQueue.mState.count--;
135 ap->mBufferQueue.mState.playIndex++;
137 memcpy (pDest, data, sizeConsumed);
138 // data has been copied to the buffer, and the buffer queue state has been updated
139 // we will notify the client if applicable
140 callback = ap->mBufferQueue.mCallback;
141 // save callback data
142 callbackPContext = ap->mBufferQueue.mContext;
146 // no available buffers in the queue to write the decoded data
150 object_unlock_exclusive(&ap->mObject);
152 if (NULL != callback) {
153 (*callback)(&ap->mBufferQueue.mItf, callbackPContext);
159 //-----------------------------------------------------------------------------
160 int android_getMinFrameCount(uint32_t sampleRate) {
162 if (android::AudioSystem::getOutputSamplingRate(&afSampleRate,
163 ANDROID_DEFAULT_OUTPUT_STREAM_TYPE) != android::NO_ERROR) {
164 return ANDROID_DEFAULT_AUDIOTRACK_BUFFER_SIZE;
167 if (android::AudioSystem::getOutputFrameCount(&afFrameCount,
168 ANDROID_DEFAULT_OUTPUT_STREAM_TYPE) != android::NO_ERROR) {
169 return ANDROID_DEFAULT_AUDIOTRACK_BUFFER_SIZE;
172 if (android::AudioSystem::getOutputLatency(&afLatency,
173 ANDROID_DEFAULT_OUTPUT_STREAM_TYPE) != android::NO_ERROR) {
174 return ANDROID_DEFAULT_AUDIOTRACK_BUFFER_SIZE;
176 // minimum nb of buffers to cover output latency, given the size of each hardware audio buffer
177 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
178 if (minBufCount < 2) minBufCount = 2;
179 // minimum number of frames to cover output latency at the sample rate of the content
180 return (afFrameCount*sampleRate*minBufCount)/afSampleRate;
184 //-----------------------------------------------------------------------------
185 #define LEFT_CHANNEL_MASK 0x1 << 0
186 #define RIGHT_CHANNEL_MASK 0x1 << 1
188 void android_audioPlayer_volumeUpdate(CAudioPlayer* ap)
192 // the source's channel count, where zero means unknown
193 SLuint8 channelCount = ap->mNumChannels;
195 // whether each channel is audible
196 bool leftAudibilityFactor, rightAudibilityFactor;
198 // mute has priority over solo
199 if (channelCount >= STEREO_CHANNELS) {
200 if (ap->mMuteMask & LEFT_CHANNEL_MASK) {
202 leftAudibilityFactor = false;
205 if (ap->mSoloMask & LEFT_CHANNEL_MASK) {
207 leftAudibilityFactor = true;
210 if (ap->mSoloMask & RIGHT_CHANNEL_MASK) {
211 // right solo silences left
212 leftAudibilityFactor = false;
214 // left and right are not soloed, and left is not muted
215 leftAudibilityFactor = true;
220 if (ap->mMuteMask & RIGHT_CHANNEL_MASK) {
222 rightAudibilityFactor = false;
225 if (ap->mSoloMask & RIGHT_CHANNEL_MASK) {
227 rightAudibilityFactor = true;
230 if (ap->mSoloMask & LEFT_CHANNEL_MASK) {
231 // left solo silences right
232 rightAudibilityFactor = false;
234 // left and right are not soloed, and right is not muted
235 rightAudibilityFactor = true;
240 // channel mute and solo are ignored for mono and unknown channel count sources
242 leftAudibilityFactor = true;
243 rightAudibilityFactor = true;
246 // compute volumes without setting
247 const bool audibilityFactors[2] = {leftAudibilityFactor, rightAudibilityFactor};
249 android_player_volumeUpdate(volumes, &ap->mVolume, channelCount, ap->mAmplFromDirectLevel,
251 float leftVol = volumes[0], rightVol = volumes[1];
253 // set volume on the underlying media player or audio track
254 if (ap->mAPlayer != 0) {
255 ap->mAPlayer->setVolume(leftVol, rightVol);
256 } else if (ap->mAudioTrack != 0) {
257 ap->mAudioTrack->setVolume(leftVol, rightVol);
260 // changes in the AudioPlayer volume must be reflected in the send level:
261 // in SLEffectSendItf or in SLAndroidEffectSendItf?
262 // FIXME replace interface test by an internal API once we have one.
263 if (NULL != ap->mEffectSend.mItf) {
264 for (unsigned int i=0 ; i<AUX_MAX ; i++) {
265 if (ap->mEffectSend.mEnableLevels[i].mEnable) {
266 android_fxSend_setSendLevel(ap,
267 ap->mEffectSend.mEnableLevels[i].mSendLevel + ap->mVolume.mLevel);
268 // there's a single aux bus on Android, so we can stop looking once the first
269 // aux effect is found.
273 } else if (NULL != ap->mAndroidEffectSend.mItf) {
274 android_fxSend_setSendLevel(ap, ap->mAndroidEffectSend.mSendLevel + ap->mVolume.mLevel);
278 // Called by android_audioPlayer_volumeUpdate and android_mediaPlayer_volumeUpdate to compute
279 // volumes, but setting volumes is handled by the caller.
281 void android_player_volumeUpdate(float *pVolumes /*[2]*/, const IVolume *volumeItf, unsigned
282 channelCount, float amplFromDirectLevel, const bool *audibilityFactors /*[2]*/)
284 assert(pVolumes != NULL);
285 assert(volumeItf != NULL);
286 // OK for audibilityFactors to be NULL
288 bool leftAudibilityFactor, rightAudibilityFactor;
290 // apply player mute factor
291 // note that AudioTrack has mute() but not MediaPlayer, so it's easier to use volume
292 // to mute for both rather than calling mute() for AudioTrack
295 if (volumeItf->mMute) {
296 leftAudibilityFactor = false;
297 rightAudibilityFactor = false;
298 // player isn't muted, and channel mute/solo audibility factors are available (AudioPlayer)
299 } else if (audibilityFactors != NULL) {
300 leftAudibilityFactor = audibilityFactors[0];
301 rightAudibilityFactor = audibilityFactors[1];
302 // player isn't muted, and channel mute/solo audibility factors aren't available (MediaPlayer)
304 leftAudibilityFactor = true;
305 rightAudibilityFactor = true;
308 // compute amplification as the combination of volume level and stereo position
309 // amplification (or attenuation) from volume level
310 float amplFromVolLevel = sles_to_android_amplification(volumeItf->mLevel);
311 // amplification from direct level (changed in SLEffectSendtItf and SLAndroidEffectSendItf)
312 float leftVol = amplFromVolLevel * amplFromDirectLevel;
313 float rightVol = leftVol;
315 // amplification from stereo position
316 if (volumeItf->mEnableStereoPosition) {
317 // Left/right amplification (can be attenuations) factors derived for the StereoPosition
318 float amplFromStereoPos[STEREO_CHANNELS];
319 // panning law depends on content channel count: mono to stereo panning vs stereo balance
320 if (1 == channelCount) {
321 // mono to stereo panning
322 double theta = (1000+volumeItf->mStereoPosition)*M_PI_4/1000.0f; // 0 <= theta <= Pi/2
323 amplFromStereoPos[0] = cos(theta);
324 amplFromStereoPos[1] = sin(theta);
325 // channel count is 0 (unknown), 2 (stereo), or > 2 (multi-channel)
328 if (volumeItf->mStereoPosition > 0) {
329 amplFromStereoPos[0] = (1000-volumeItf->mStereoPosition)/1000.0f;
330 amplFromStereoPos[1] = 1.0f;
332 amplFromStereoPos[0] = 1.0f;
333 amplFromStereoPos[1] = (1000+volumeItf->mStereoPosition)/1000.0f;
336 leftVol *= amplFromStereoPos[0];
337 rightVol *= amplFromStereoPos[1];
340 // apply audibility factors
341 if (!leftAudibilityFactor) {
344 if (!rightAudibilityFactor) {
348 // return the computed volumes
349 pVolumes[0] = leftVol;
350 pVolumes[1] = rightVol;
353 //-----------------------------------------------------------------------------
354 void audioTrack_handleMarker_lockPlay(CAudioPlayer* ap) {
355 //SL_LOGV("received event EVENT_MARKER from AudioTrack");
356 slPlayCallback callback = NULL;
357 void* callbackPContext = NULL;
359 interface_lock_shared(&ap->mPlay);
360 callback = ap->mPlay.mCallback;
361 callbackPContext = ap->mPlay.mContext;
362 interface_unlock_shared(&ap->mPlay);
364 if (NULL != callback) {
365 // getting this event implies SL_PLAYEVENT_HEADATMARKER was set in the event mask
366 (*callback)(&ap->mPlay.mItf, callbackPContext, SL_PLAYEVENT_HEADATMARKER);
370 //-----------------------------------------------------------------------------
371 void audioTrack_handleNewPos_lockPlay(CAudioPlayer* ap) {
372 //SL_LOGV("received event EVENT_NEW_POS from AudioTrack");
373 slPlayCallback callback = NULL;
374 void* callbackPContext = NULL;
376 interface_lock_shared(&ap->mPlay);
377 callback = ap->mPlay.mCallback;
378 callbackPContext = ap->mPlay.mContext;
379 interface_unlock_shared(&ap->mPlay);
381 if (NULL != callback) {
382 // getting this event implies SL_PLAYEVENT_HEADATNEWPOS was set in the event mask
383 (*callback)(&ap->mPlay.mItf, callbackPContext, SL_PLAYEVENT_HEADATNEWPOS);
388 //-----------------------------------------------------------------------------
389 void audioTrack_handleUnderrun_lockPlay(CAudioPlayer* ap) {
390 slPlayCallback callback = NULL;
391 void* callbackPContext = NULL;
393 interface_lock_shared(&ap->mPlay);
394 callback = ap->mPlay.mCallback;
395 callbackPContext = ap->mPlay.mContext;
396 bool headStalled = (ap->mPlay.mEventFlags & SL_PLAYEVENT_HEADSTALLED) != 0;
397 interface_unlock_shared(&ap->mPlay);
399 if ((NULL != callback) && headStalled) {
400 (*callback)(&ap->mPlay.mItf, callbackPContext, SL_PLAYEVENT_HEADSTALLED);
405 //-----------------------------------------------------------------------------
407 * post-condition: play state of AudioPlayer is SL_PLAYSTATE_PAUSED if setPlayStateToPaused is true
409 * note: a conditional flag, setPlayStateToPaused, is used here to specify whether the play state
410 * needs to be changed when the player reaches the end of the content to play. This is
411 * relative to what the specification describes for buffer queues vs the
412 * SL_PLAYEVENT_HEADATEND event. In the OpenSL ES specification 1.0.1:
413 * - section 8.12 SLBufferQueueItf states "In the case of starvation due to insufficient
414 * buffers in the queue, the playing of audio data stops. The player remains in the
415 * SL_PLAYSTATE_PLAYING state."
416 * - section 9.2.31 SL_PLAYEVENT states "SL_PLAYEVENT_HEADATEND Playback head is at the end
417 * of the current content and the player has paused."
419 void audioPlayer_dispatch_headAtEnd_lockPlay(CAudioPlayer *ap, bool setPlayStateToPaused,
421 //SL_LOGV("ap=%p, setPlayStateToPaused=%d, needToLock=%d", ap, setPlayStateToPaused,
423 slPlayCallback playCallback = NULL;
424 void * playContext = NULL;
425 // SLPlayItf callback or no callback?
427 interface_lock_exclusive(&ap->mPlay);
429 if (ap->mPlay.mEventFlags & SL_PLAYEVENT_HEADATEND) {
430 playCallback = ap->mPlay.mCallback;
431 playContext = ap->mPlay.mContext;
433 if (setPlayStateToPaused) {
434 ap->mPlay.mState = SL_PLAYSTATE_PAUSED;
437 interface_unlock_exclusive(&ap->mPlay);
439 // enqueue callback with no lock held
440 if (NULL != playCallback) {
441 SLresult result = EnqueueAsyncCallback_ppi(ap, playCallback, &ap->mPlay.mItf, playContext,
442 SL_PLAYEVENT_HEADATEND);
443 if (SL_RESULT_SUCCESS != result) {
444 LOGW("Callback %p(%p, %p, SL_PLAYEVENT_HEADATEND) dropped", playCallback,
445 &ap->mPlay.mItf, playContext);
452 //-----------------------------------------------------------------------------
454 * pre-condition: AudioPlayer has SLPrefetchStatusItf initialized
456 * - ap->mPrefetchStatus.mStatus == status
457 * - the prefetch status callback, if any, has been notified if a change occurred
460 void audioPlayer_dispatch_prefetchStatus_lockPrefetch(CAudioPlayer *ap, SLuint32 status,
462 slPrefetchCallback prefetchCallback = NULL;
463 void * prefetchContext = NULL;
466 interface_lock_exclusive(&ap->mPrefetchStatus);
469 if (ap->mPrefetchStatus.mStatus != status) {
470 ap->mPrefetchStatus.mStatus = status;
471 // callback or no callback?
472 if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE) {
473 prefetchCallback = ap->mPrefetchStatus.mCallback;
474 prefetchContext = ap->mPrefetchStatus.mContext;
478 interface_unlock_exclusive(&ap->mPrefetchStatus);
481 // callback with no lock held
482 if (NULL != prefetchCallback) {
483 (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext, status);
488 //-----------------------------------------------------------------------------
489 SLresult audioPlayer_setStreamType(CAudioPlayer* ap, SLint32 type) {
490 SLresult result = SL_RESULT_SUCCESS;
491 SL_LOGV("type %d", type);
493 int newStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
495 case SL_ANDROID_STREAM_VOICE:
496 newStreamType = AUDIO_STREAM_VOICE_CALL;
498 case SL_ANDROID_STREAM_SYSTEM:
499 newStreamType = AUDIO_STREAM_SYSTEM;
501 case SL_ANDROID_STREAM_RING:
502 newStreamType = AUDIO_STREAM_RING;
504 case SL_ANDROID_STREAM_MEDIA:
505 newStreamType = AUDIO_STREAM_MUSIC;
507 case SL_ANDROID_STREAM_ALARM:
508 newStreamType = AUDIO_STREAM_ALARM;
510 case SL_ANDROID_STREAM_NOTIFICATION:
511 newStreamType = AUDIO_STREAM_NOTIFICATION;
514 SL_LOGE(ERROR_PLAYERSTREAMTYPE_SET_UNKNOWN_TYPE);
515 result = SL_RESULT_PARAMETER_INVALID;
519 // stream type needs to be set before the object is realized
520 // (ap->mAudioTrack is supposed to be NULL until then)
521 if (SL_OBJECT_STATE_UNREALIZED != ap->mObject.mState) {
522 SL_LOGE(ERROR_PLAYERSTREAMTYPE_REALIZED);
523 result = SL_RESULT_PRECONDITIONS_VIOLATED;
525 ap->mStreamType = newStreamType;
532 //-----------------------------------------------------------------------------
533 SLresult audioPlayer_getStreamType(CAudioPlayer* ap, SLint32 *pType) {
534 SLresult result = SL_RESULT_SUCCESS;
536 switch(ap->mStreamType) {
537 case AUDIO_STREAM_VOICE_CALL:
538 *pType = SL_ANDROID_STREAM_VOICE;
540 case AUDIO_STREAM_SYSTEM:
541 *pType = SL_ANDROID_STREAM_SYSTEM;
543 case AUDIO_STREAM_RING:
544 *pType = SL_ANDROID_STREAM_RING;
546 case AUDIO_STREAM_DEFAULT:
547 case AUDIO_STREAM_MUSIC:
548 *pType = SL_ANDROID_STREAM_MEDIA;
550 case AUDIO_STREAM_ALARM:
551 *pType = SL_ANDROID_STREAM_ALARM;
553 case AUDIO_STREAM_NOTIFICATION:
554 *pType = SL_ANDROID_STREAM_NOTIFICATION;
557 result = SL_RESULT_INTERNAL_ERROR;
558 *pType = SL_ANDROID_STREAM_MEDIA;
566 //-----------------------------------------------------------------------------
567 void audioPlayer_auxEffectUpdate(CAudioPlayer* ap) {
568 if ((ap->mAudioTrack != 0) && (ap->mAuxEffect != 0)) {
569 android_fxSend_attach(ap, true, ap->mAuxEffect, ap->mVolume.mLevel + ap->mAuxSendLevel);
574 //-----------------------------------------------------------------------------
575 void audioPlayer_setInvalid(CAudioPlayer* ap) {
576 ap->mAndroidObjType = INVALID_TYPE;
581 //-----------------------------------------------------------------------------
583 * returns true if the given data sink is supported by AudioPlayer that doesn't
584 * play to an OutputMix object, false otherwise
586 * pre-condition: the locator of the audio sink is not SL_DATALOCATOR_OUTPUTMIX
588 bool audioPlayer_isSupportedNonOutputMixSink(const SLDataSink* pAudioSink) {
590 const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSink->pLocator;
591 const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSink->pFormat;
593 switch (sinkLocatorType) {
595 case SL_DATALOCATOR_BUFFERQUEUE:
596 case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
597 if (SL_DATAFORMAT_PCM != sinkFormatType) {
598 SL_LOGE("Unsupported sink format 0x%x, expected SL_DATAFORMAT_PCM",
599 (unsigned)sinkFormatType);
602 // it's no use checking the PCM format fields because additional characteristics
603 // such as the number of channels, or sample size are unknown to the player at this stage
607 SL_LOGE("Unsupported sink locator type 0x%x", (unsigned)sinkLocatorType);
616 //-----------------------------------------------------------------------------
618 * returns the Android object type if the locator type combinations for the source and sinks
619 * are supported by this implementation, INVALID_TYPE otherwise
621 AndroidObjectType audioPlayer_getAndroidObjectTypeForSourceSink(CAudioPlayer *ap) {
623 const SLDataSource *pAudioSrc = &ap->mDataSource.u.mSource;
624 const SLDataSink *pAudioSnk = &ap->mDataSink.u.mSink;
625 const SLuint32 sourceLocatorType = *(SLuint32 *)pAudioSrc->pLocator;
626 const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator;
627 AndroidObjectType type = INVALID_TYPE;
629 //--------------------------------------
630 // Sink / source matching check:
631 // the following source / sink combinations are supported
632 // SL_DATALOCATOR_BUFFERQUEUE / SL_DATALOCATOR_OUTPUTMIX
633 // SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE / SL_DATALOCATOR_OUTPUTMIX
634 // SL_DATALOCATOR_URI / SL_DATALOCATOR_OUTPUTMIX
635 // SL_DATALOCATOR_ANDROIDFD / SL_DATALOCATOR_OUTPUTMIX
636 // SL_DATALOCATOR_ANDROIDBUFFERQUEUE / SL_DATALOCATOR_OUTPUTMIX
637 // SL_DATALOCATOR_ANDROIDBUFFERQUEUE / SL_DATALOCATOR_BUFFERQUEUE
638 // SL_DATALOCATOR_URI / SL_DATALOCATOR_BUFFERQUEUE
639 // SL_DATALOCATOR_ANDROIDFD / SL_DATALOCATOR_BUFFERQUEUE
640 // SL_DATALOCATOR_URI / SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
641 // SL_DATALOCATOR_ANDROIDFD / SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
642 switch (sinkLocatorType) {
644 case SL_DATALOCATOR_OUTPUTMIX: {
645 switch (sourceLocatorType) {
647 // Buffer Queue to AudioTrack
648 case SL_DATALOCATOR_BUFFERQUEUE:
649 case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
650 type = AUDIOPLAYER_FROM_PCM_BUFFERQUEUE;
653 // URI or FD to MediaPlayer
654 case SL_DATALOCATOR_URI:
655 case SL_DATALOCATOR_ANDROIDFD:
656 type = AUDIOPLAYER_FROM_URIFD;
659 // Android BufferQueue to MediaPlayer (shared memory streaming)
660 case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
661 type = AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE;
665 SL_LOGE("Source data locator 0x%x not supported with SL_DATALOCATOR_OUTPUTMIX sink",
666 (unsigned)sourceLocatorType);
672 case SL_DATALOCATOR_BUFFERQUEUE:
673 case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
674 switch (sourceLocatorType) {
676 // URI or FD decoded to PCM in a buffer queue
677 case SL_DATALOCATOR_URI:
678 case SL_DATALOCATOR_ANDROIDFD:
679 type = AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE;
682 // AAC ADTS Android buffer queue decoded to PCM in a buffer queue
683 case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
684 type = AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE;
688 SL_LOGE("Source data locator 0x%x not supported with SL_DATALOCATOR_BUFFERQUEUE sink",
689 (unsigned)sourceLocatorType);
695 SL_LOGE("Sink data locator 0x%x not supported", (unsigned)sinkLocatorType);
703 //-----------------------------------------------------------------------------
705 * Callback associated with an SfPlayer of an SL ES AudioPlayer that gets its data
706 * from a URI or FD, for prepare, prefetch, and play events
708 static void sfplayer_handlePrefetchEvent(int event, int data1, int data2, void* user) {
713 CAudioPlayer *ap = (CAudioPlayer *)user;
714 if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) {
715 // it is not safe to enter the callback (the track is about to go away)
723 SL_LOGV("sfplayer_handlePrefetchEvent(event='%c%c%c%c' (%d), data1=%d, data2=%d, user=%p) from "
724 "SfAudioPlayer", u.c[3], u.c[2], u.c[1], u.c[0], event, data1, data2, user);
727 case android::GenericPlayer::kEventPrepared: {
729 if (PLAYER_SUCCESS != data1) {
730 object_lock_exclusive(&ap->mObject);
732 // already initialized at object creation, and can only prepare once so never reset
733 assert(ap->mAudioTrack == 0);
734 assert(ap->mNumChannels == UNKNOWN_NUMCHANNELS);
735 assert(ap->mSampleRateMilliHz == UNKNOWN_SAMPLERATE);
736 assert(ap->mAndroidObjState == ANDROID_PREPARING);
737 ap->mAndroidObjState = ANDROID_READY;
739 object_unlock_exclusive(&ap->mObject);
741 // SfPlayer prepare() failed prefetching, there is no event in SLPrefetchStatus to
742 // indicate a prefetch error, so we signal it by sending simulataneously two events:
743 // - SL_PREFETCHEVENT_FILLLEVELCHANGE with a level of 0
744 // - SL_PREFETCHEVENT_STATUSCHANGE with a status of SL_PREFETCHSTATUS_UNDERFLOW
745 SL_LOGE(ERROR_PLAYER_PREFETCH_d, data1);
746 if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
750 slPrefetchCallback callback = NULL;
751 void* callbackPContext = NULL;
753 interface_lock_exclusive(&ap->mPrefetchStatus);
754 ap->mPrefetchStatus.mLevel = 0;
755 ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
756 if ((ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_FILLLEVELCHANGE)
757 && (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE)) {
758 callback = ap->mPrefetchStatus.mCallback;
759 callbackPContext = ap->mPrefetchStatus.mContext;
761 interface_unlock_exclusive(&ap->mPrefetchStatus);
763 // callback with no lock held
764 if (NULL != callback) {
765 (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext,
766 SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
772 object_lock_exclusive(&ap->mObject);
774 if (AUDIOPLAYER_FROM_URIFD == ap->mAndroidObjType) {
775 //**************************************
776 // FIXME move under GenericMediaPlayer
778 ap->mAudioTrack = ap->mSfPlayer->getAudioTrack();
779 ap->mNumChannels = ap->mSfPlayer->getNumChannels();
780 ap->mSampleRateMilliHz =
781 android_to_sles_sampleRate(ap->mSfPlayer->getSampleRateHz());
782 ap->mSfPlayer->startPrefetch_async();
783 // update the new track with the current settings
784 audioPlayer_auxEffectUpdate(ap);
785 android_audioPlayer_useEventMask(ap);
786 android_audioPlayer_volumeUpdate(ap);
787 android_audioPlayer_setPlayRate(ap, ap->mPlaybackRate.mRate, false /*lockAP*/);
789 } else if (AUDIOPLAYER_FROM_PCM_BUFFERQUEUE == ap->mAndroidObjType) {
790 if (ap->mAPlayer != 0) {
791 ((android::AudioToCbRenderer*)ap->mAPlayer.get())->startPrefetch_async();
793 } else if (AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE == ap->mAndroidObjType) {
794 SL_LOGD("Received SfPlayer::kEventPrepared from AVPlayer for CAudioPlayer %p", ap);
797 ap->mAndroidObjState = ANDROID_READY;
799 object_unlock_exclusive(&ap->mObject);
805 case android::GenericPlayer::kEventPrefetchFillLevelUpdate : {
806 if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
809 slPrefetchCallback callback = NULL;
810 void* callbackPContext = NULL;
812 // SLPrefetchStatusItf callback or no callback?
813 interface_lock_exclusive(&ap->mPrefetchStatus);
814 if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
815 callback = ap->mPrefetchStatus.mCallback;
816 callbackPContext = ap->mPrefetchStatus.mContext;
818 ap->mPrefetchStatus.mLevel = (SLpermille)data1;
819 interface_unlock_exclusive(&ap->mPrefetchStatus);
821 // callback with no lock held
822 if (NULL != callback) {
823 (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext,
824 SL_PREFETCHEVENT_FILLLEVELCHANGE);
829 case android::GenericPlayer::kEventPrefetchStatusChange: {
830 if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
833 slPrefetchCallback callback = NULL;
834 void* callbackPContext = NULL;
836 // SLPrefetchStatusItf callback or no callback?
837 object_lock_exclusive(&ap->mObject);
838 if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE) {
839 callback = ap->mPrefetchStatus.mCallback;
840 callbackPContext = ap->mPrefetchStatus.mContext;
842 if (data1 >= android::kStatusIntermediate) {
843 ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA;
844 ap->mAndroidObjState = ANDROID_READY;
845 } else if (data1 < android::kStatusIntermediate) {
846 ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
848 object_unlock_exclusive(&ap->mObject);
850 // callback with no lock held
851 if (NULL != callback) {
852 (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext, SL_PREFETCHEVENT_STATUSCHANGE);
857 case android::GenericPlayer::kEventEndOfStream: {
858 audioPlayer_dispatch_headAtEnd_lockPlay(ap, true /*set state to paused?*/, true);
859 if ((ap->mAudioTrack != 0) && (!ap->mSeek.mLoopEnabled)) {
860 ap->mAudioTrack->stop();
865 case android::GenericPlayer::kEventChannelCount: {
866 object_lock_exclusive(&ap->mObject);
867 if (UNKNOWN_NUMCHANNELS == ap->mNumChannels && UNKNOWN_NUMCHANNELS != data1) {
868 ap->mNumChannels = data1;
869 android_audioPlayer_volumeUpdate(ap);
871 object_unlock_exclusive(&ap->mObject);
875 case android::GenericPlayer::kEventPlay: {
876 slPlayCallback callback = NULL;
877 void* callbackPContext = NULL;
879 interface_lock_shared(&ap->mPlay);
880 callback = ap->mPlay.mCallback;
881 callbackPContext = ap->mPlay.mContext;
882 interface_unlock_shared(&ap->mPlay);
884 if (NULL != callback) {
885 SLuint32 event = (SLuint32) data1; // SL_PLAYEVENT_HEAD*
886 #ifndef USE_ASYNCHRONOUS_PLAY_CALLBACK
887 // synchronous callback requires a synchronous GetPosition implementation
888 (*callback)(&ap->mPlay.mItf, callbackPContext, event);
890 // asynchronous callback works with any GetPosition implementation
891 SLresult result = EnqueueAsyncCallback_ppi(ap, callback, &ap->mPlay.mItf,
892 callbackPContext, event);
893 if (SL_RESULT_SUCCESS != result) {
894 LOGW("Callback %p(%p, %p, 0x%x) dropped", callback,
895 &ap->mPlay.mItf, callbackPContext, event);
906 ap->mCallbackProtector->exitCb();
910 //-----------------------------------------------------------------------------
911 SLresult android_audioPlayer_checkSourceSink(CAudioPlayer *pAudioPlayer)
913 // verify that the locator types for the source / sink combination is supported
914 pAudioPlayer->mAndroidObjType = audioPlayer_getAndroidObjectTypeForSourceSink(pAudioPlayer);
915 if (INVALID_TYPE == pAudioPlayer->mAndroidObjType) {
916 return SL_RESULT_PARAMETER_INVALID;
919 const SLDataSource *pAudioSrc = &pAudioPlayer->mDataSource.u.mSource;
920 const SLDataSink *pAudioSnk = &pAudioPlayer->mDataSink.u.mSink;
923 const SLuint32 sourceLocatorType = *(SLuint32 *)pAudioSrc->pLocator;
924 const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator;
925 const SLuint32 sourceFormatType = *(SLuint32 *)pAudioSrc->pFormat;
926 const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSnk->pFormat;
928 switch (sourceLocatorType) {
931 case SL_DATALOCATOR_BUFFERQUEUE:
932 case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
934 SLDataLocator_BufferQueue *dl_bq = (SLDataLocator_BufferQueue *) pAudioSrc->pLocator;
937 switch (sourceFormatType) {
938 // currently only PCM buffer queues are supported,
939 case SL_DATAFORMAT_PCM: {
940 SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *) pAudioSrc->pFormat;
941 switch (df_pcm->numChannels) {
946 // this should have already been rejected by checkDataFormat
947 SL_LOGE("Cannot create audio player: unsupported " \
948 "PCM data source with %u channels", (unsigned) df_pcm->numChannels);
949 return SL_RESULT_CONTENT_UNSUPPORTED;
951 switch (df_pcm->samplesPerSec) {
952 case SL_SAMPLINGRATE_8:
953 case SL_SAMPLINGRATE_11_025:
954 case SL_SAMPLINGRATE_12:
955 case SL_SAMPLINGRATE_16:
956 case SL_SAMPLINGRATE_22_05:
957 case SL_SAMPLINGRATE_24:
958 case SL_SAMPLINGRATE_32:
959 case SL_SAMPLINGRATE_44_1:
960 case SL_SAMPLINGRATE_48:
962 case SL_SAMPLINGRATE_64:
963 case SL_SAMPLINGRATE_88_2:
964 case SL_SAMPLINGRATE_96:
965 case SL_SAMPLINGRATE_192:
967 SL_LOGE("Cannot create audio player: unsupported sample rate %u milliHz",
968 (unsigned) df_pcm->samplesPerSec);
969 return SL_RESULT_CONTENT_UNSUPPORTED;
971 switch (df_pcm->bitsPerSample) {
972 case SL_PCMSAMPLEFORMAT_FIXED_8:
973 // FIXME We should support this
974 //SL_LOGE("Cannot create audio player: unsupported 8-bit data");
975 //return SL_RESULT_CONTENT_UNSUPPORTED;
976 case SL_PCMSAMPLEFORMAT_FIXED_16:
980 // this should have already been rejected by checkDataFormat
981 SL_LOGE("Cannot create audio player: unsupported sample bit depth %u",
982 (SLuint32)df_pcm->bitsPerSample);
983 return SL_RESULT_CONTENT_UNSUPPORTED;
985 switch (df_pcm->containerSize) {
991 SL_LOGE("Cannot create audio player: unsupported container size %u",
992 (unsigned) df_pcm->containerSize);
993 return SL_RESULT_CONTENT_UNSUPPORTED;
995 switch (df_pcm->channelMask) {
1000 switch (df_pcm->endianness) {
1001 case SL_BYTEORDER_LITTLEENDIAN:
1003 case SL_BYTEORDER_BIGENDIAN:
1004 SL_LOGE("Cannot create audio player: unsupported big-endian byte order");
1005 return SL_RESULT_CONTENT_UNSUPPORTED;
1006 // native is proposed but not yet in spec
1008 SL_LOGE("Cannot create audio player: unsupported byte order %u",
1009 (unsigned) df_pcm->endianness);
1010 return SL_RESULT_CONTENT_UNSUPPORTED;
1012 } //case SL_DATAFORMAT_PCM
1014 case SL_DATAFORMAT_MIME:
1015 case XA_DATAFORMAT_RAWIMAGE:
1016 SL_LOGE("Cannot create audio player with buffer queue data source "
1017 "without SL_DATAFORMAT_PCM format");
1018 return SL_RESULT_CONTENT_UNSUPPORTED;
1020 // invalid data format is detected earlier
1022 return SL_RESULT_INTERNAL_ERROR;
1023 } // switch (sourceFormatType)
1024 } // case SL_DATALOCATOR_BUFFERQUEUE or SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
1026 //------------------
1028 case SL_DATALOCATOR_URI:
1030 SLDataLocator_URI *dl_uri = (SLDataLocator_URI *) pAudioSrc->pLocator;
1031 if (NULL == dl_uri->URI) {
1032 return SL_RESULT_PARAMETER_INVALID;
1035 switch (sourceFormatType) {
1036 case SL_DATAFORMAT_MIME:
1038 case SL_DATAFORMAT_PCM:
1039 case XA_DATAFORMAT_RAWIMAGE:
1040 SL_LOGE("Cannot create audio player with SL_DATALOCATOR_URI data source without "
1041 "SL_DATAFORMAT_MIME format");
1042 return SL_RESULT_CONTENT_UNSUPPORTED;
1043 } // switch (sourceFormatType)
1044 // decoding format check
1045 if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) &&
1046 !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) {
1047 return SL_RESULT_CONTENT_UNSUPPORTED;
1049 } // case SL_DATALOCATOR_URI
1051 //------------------
1053 case SL_DATALOCATOR_ANDROIDFD:
1055 // fd is already non null
1056 switch (sourceFormatType) {
1057 case SL_DATAFORMAT_MIME:
1059 case SL_DATAFORMAT_PCM:
1061 SL_LOGD("[ FIXME implement PCM FD data sources ]");
1063 case XA_DATAFORMAT_RAWIMAGE:
1064 SL_LOGE("Cannot create audio player with SL_DATALOCATOR_ANDROIDFD data source "
1065 "without SL_DATAFORMAT_MIME or SL_DATAFORMAT_PCM format");
1066 return SL_RESULT_CONTENT_UNSUPPORTED;
1068 // invalid data format is detected earlier
1070 return SL_RESULT_INTERNAL_ERROR;
1071 } // switch (sourceFormatType)
1072 if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) &&
1073 !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) {
1074 return SL_RESULT_CONTENT_UNSUPPORTED;
1076 } // case SL_DATALOCATOR_ANDROIDFD
1078 //------------------
1080 case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
1082 switch (sourceFormatType) {
1083 case SL_DATAFORMAT_MIME:
1085 SLDataFormat_MIME *df_mime = (SLDataFormat_MIME *) pAudioSrc->pFormat;
1086 if (NULL == df_mime) {
1087 SL_LOGE("MIME type null invalid");
1088 return SL_RESULT_CONTENT_UNSUPPORTED;
1090 SL_LOGD("source MIME is %s", (char*)df_mime->mimeType);
1091 switch(df_mime->containerType) {
1092 case SL_CONTAINERTYPE_MPEG_TS:
1093 if (strcasecmp((char*)df_mime->mimeType, ANDROID_MIME_MP2TS)) {
1094 SL_LOGE("Invalid MIME (%s) for container SL_CONTAINERTYPE_MPEG_TS, expects %s",
1095 (char*)df_mime->mimeType, ANDROID_MIME_MP2TS);
1096 return SL_RESULT_CONTENT_UNSUPPORTED;
1099 case SL_CONTAINERTYPE_RAW:
1100 case SL_CONTAINERTYPE_AAC:
1101 if (strcasecmp((char*)df_mime->mimeType, ANDROID_MIME_AACADTS) &&
1102 strcasecmp((char*)df_mime->mimeType,
1103 ANDROID_MIME_AACADTS_ANDROID_FRAMEWORK)) {
1104 SL_LOGE("Invalid MIME (%s) for container type %d, expects %s",
1105 (char*)df_mime->mimeType, df_mime->containerType,
1106 ANDROID_MIME_AACADTS);
1107 return SL_RESULT_CONTENT_UNSUPPORTED;
1111 SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
1112 "that is not fed MPEG-2 TS data or AAC ADTS data");
1113 return SL_RESULT_CONTENT_UNSUPPORTED;
1118 SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
1119 "without SL_DATAFORMAT_MIME format");
1120 return SL_RESULT_CONTENT_UNSUPPORTED;
1123 break; // case SL_DATALOCATOR_ANDROIDBUFFERQUEUE
1124 //------------------
1126 case SL_DATALOCATOR_ADDRESS:
1127 case SL_DATALOCATOR_IODEVICE:
1128 case SL_DATALOCATOR_OUTPUTMIX:
1129 case XA_DATALOCATOR_NATIVEDISPLAY:
1130 case SL_DATALOCATOR_MIDIBUFFERQUEUE:
1131 SL_LOGE("Cannot create audio player with data locator type 0x%x",
1132 (unsigned) sourceLocatorType);
1133 return SL_RESULT_CONTENT_UNSUPPORTED;
1135 SL_LOGE("Cannot create audio player with invalid data locator type 0x%x",
1136 (unsigned) sourceLocatorType);
1137 return SL_RESULT_PARAMETER_INVALID;
1138 }// switch (locatorType)
1140 return SL_RESULT_SUCCESS;
1145 //-----------------------------------------------------------------------------
1146 static void audioTrack_callBack_uri(int event, void* user, void *info) {
1147 // EVENT_MORE_DATA needs to be handled with priority over the other events
1148 // because it will be called the most often during playback
1150 if (event == android::AudioTrack::EVENT_MORE_DATA) {
1151 //SL_LOGV("received event EVENT_MORE_DATA from AudioTrack");
1152 // set size to 0 to signal we're not using the callback to write more data
1153 android::AudioTrack::Buffer* pBuff = (android::AudioTrack::Buffer*)info;
1155 } else if (NULL != user) {
1156 CAudioPlayer *ap = (CAudioPlayer *)user;
1157 if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) {
1158 // it is not safe to enter the callback (the track is about to go away)
1162 case android::AudioTrack::EVENT_MARKER :
1163 audioTrack_handleMarker_lockPlay(ap);
1165 case android::AudioTrack::EVENT_NEW_POS :
1166 audioTrack_handleNewPos_lockPlay(ap);
1168 case android::AudioTrack::EVENT_UNDERRUN :
1169 audioTrack_handleUnderrun_lockPlay(ap);
1171 case android::AudioTrack::EVENT_BUFFER_END :
1172 case android::AudioTrack::EVENT_LOOP_END :
1175 SL_LOGE("Encountered unknown AudioTrack event %d for CAudioPlayer %p", event,
1179 ap->mCallbackProtector->exitCb();
1183 //-----------------------------------------------------------------------------
1184 // Callback associated with an AudioTrack of an SL ES AudioPlayer that gets its data
1185 // from a buffer queue. This will not be called once the AudioTrack has been destroyed.
1186 static void audioTrack_callBack_pullFromBuffQueue(int event, void* user, void *info) {
1187 CAudioPlayer *ap = (CAudioPlayer *)user;
1189 if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) {
1190 // it is not safe to enter the callback (the track is about to go away)
1194 void * callbackPContext = NULL;
1197 case android::AudioTrack::EVENT_MORE_DATA: {
1198 //SL_LOGV("received event EVENT_MORE_DATA from AudioTrack TID=%d", gettid());
1199 slBufferQueueCallback callback = NULL;
1200 android::AudioTrack::Buffer* pBuff = (android::AudioTrack::Buffer*)info;
1202 // retrieve data from the buffer queue
1203 interface_lock_exclusive(&ap->mBufferQueue);
1205 if (ap->mBufferQueue.mState.count != 0) {
1206 //SL_LOGV("nbBuffers in queue = %u",ap->mBufferQueue.mState.count);
1207 assert(ap->mBufferQueue.mFront != ap->mBufferQueue.mRear);
1209 BufferHeader *oldFront = ap->mBufferQueue.mFront;
1210 BufferHeader *newFront = &oldFront[1];
1212 // FIXME handle 8bit based on buffer format
1213 short *pSrc = (short*)((char *)oldFront->mBuffer
1214 + ap->mBufferQueue.mSizeConsumed);
1215 if (ap->mBufferQueue.mSizeConsumed + pBuff->size < oldFront->mSize) {
1216 // can't consume the whole or rest of the buffer in one shot
1217 ap->mBufferQueue.mSizeConsumed += pBuff->size;
1218 // leave pBuff->size untouched
1220 // FIXME can we avoid holding the lock during the copy?
1221 memcpy (pBuff->i16, pSrc, pBuff->size);
1223 // finish consuming the buffer or consume the buffer in one shot
1224 pBuff->size = oldFront->mSize - ap->mBufferQueue.mSizeConsumed;
1225 ap->mBufferQueue.mSizeConsumed = 0;
1228 &ap->mBufferQueue.mArray
1229 [ap->mBufferQueue.mNumBuffers + 1])
1231 newFront = ap->mBufferQueue.mArray;
1233 ap->mBufferQueue.mFront = newFront;
1235 ap->mBufferQueue.mState.count--;
1236 ap->mBufferQueue.mState.playIndex++;
1239 // FIXME can we avoid holding the lock during the copy?
1240 memcpy (pBuff->i16, pSrc, pBuff->size);
1242 // data has been consumed, and the buffer queue state has been updated
1243 // we will notify the client if applicable
1244 callback = ap->mBufferQueue.mCallback;
1245 // save callback data
1246 callbackPContext = ap->mBufferQueue.mContext;
1248 } else { // empty queue
1249 // signal no data available
1252 // signal we're at the end of the content, but don't pause (see note in function)
1253 audioPlayer_dispatch_headAtEnd_lockPlay(ap, false /*set state to paused?*/, false);
1255 // signal underflow to prefetch status itf
1256 if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
1257 audioPlayer_dispatch_prefetchStatus_lockPrefetch(ap, SL_PREFETCHSTATUS_UNDERFLOW,
1261 // stop the track so it restarts playing faster when new data is enqueued
1262 ap->mAudioTrack->stop();
1264 interface_unlock_exclusive(&ap->mBufferQueue);
1267 if (NULL != callback) {
1268 (*callback)(&ap->mBufferQueue.mItf, callbackPContext);
1273 case android::AudioTrack::EVENT_MARKER:
1274 //SL_LOGI("received event EVENT_MARKER from AudioTrack");
1275 audioTrack_handleMarker_lockPlay(ap);
1278 case android::AudioTrack::EVENT_NEW_POS:
1279 //SL_LOGI("received event EVENT_NEW_POS from AudioTrack");
1280 audioTrack_handleNewPos_lockPlay(ap);
1283 case android::AudioTrack::EVENT_UNDERRUN:
1284 //SL_LOGI("received event EVENT_UNDERRUN from AudioTrack");
1285 audioTrack_handleUnderrun_lockPlay(ap);
1289 // FIXME where does the notification of SL_PLAYEVENT_HEADMOVING fit?
1290 SL_LOGE("Encountered unknown AudioTrack event %d for CAudioPlayer %p", event,
1291 (CAudioPlayer *)user);
1295 ap->mCallbackProtector->exitCb();
1299 //-----------------------------------------------------------------------------
1300 SLresult android_audioPlayer_create(CAudioPlayer *pAudioPlayer) {
1302 SLresult result = SL_RESULT_SUCCESS;
1303 // pAudioPlayer->mAndroidObjType has been set in audioPlayer_getAndroidObjectTypeForSourceSink()
1304 if (INVALID_TYPE == pAudioPlayer->mAndroidObjType) {
1305 audioPlayer_setInvalid(pAudioPlayer);
1306 result = SL_RESULT_PARAMETER_INVALID;
1309 // These initializations are in the same order as the field declarations in classes.h
1311 // FIXME Consolidate initializations (many of these already in IEngine_CreateAudioPlayer)
1312 pAudioPlayer->mpLock = new android::Mutex();
1313 // mAndroidObjType: see above comment
1314 pAudioPlayer->mAndroidObjState = ANDROID_UNINITIALIZED;
1315 pAudioPlayer->mSessionId = android::AudioSystem::newAudioSessionId();
1316 pAudioPlayer->mStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
1319 pAudioPlayer->mCallbackProtector = new android::CallbackProtector();
1323 pAudioPlayer->mAuxSendLevel = 0;
1324 pAudioPlayer->mAmplFromDirectLevel = 1.0f; // matches initial mDirectLevel value
1325 pAudioPlayer->mDeferredStart = false;
1326 // Already initialized in IEngine_CreateAudioPlayer, to be consolidated
1327 pAudioPlayer->mDirectLevel = 0; // no attenuation
1329 // This section re-initializes interface-specific fields that
1330 // can be set or used regardless of whether the interface is
1331 // exposed on the AudioPlayer or not
1333 // Only AudioTrack supports a non-trivial playback rate
1334 switch (pAudioPlayer->mAndroidObjType) {
1335 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1336 pAudioPlayer->mPlaybackRate.mMinRate = AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE;
1337 pAudioPlayer->mPlaybackRate.mMaxRate = AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE;
1340 // use the default range
1350 //-----------------------------------------------------------------------------
1351 SLresult android_audioPlayer_setConfig(CAudioPlayer *ap, const SLchar *configKey,
1352 const void *pConfigValue, SLuint32 valueSize) {
1356 assert(NULL != ap && NULL != configKey && NULL != pConfigValue);
1357 if(strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) {
1360 if (KEY_STREAM_TYPE_PARAMSIZE > valueSize) {
1361 SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1362 result = SL_RESULT_BUFFER_INSUFFICIENT;
1364 result = audioPlayer_setStreamType(ap, *(SLuint32*)pConfigValue);
1368 SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY);
1369 result = SL_RESULT_PARAMETER_INVALID;
1376 //-----------------------------------------------------------------------------
1377 SLresult android_audioPlayer_getConfig(CAudioPlayer* ap, const SLchar *configKey,
1378 SLuint32* pValueSize, void *pConfigValue) {
1382 assert(NULL != ap && NULL != configKey && NULL != pValueSize);
1383 if(strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) {
1386 if (NULL == pConfigValue) {
1387 result = SL_RESULT_SUCCESS;
1388 } else if (KEY_STREAM_TYPE_PARAMSIZE > *pValueSize) {
1389 SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1390 result = SL_RESULT_BUFFER_INSUFFICIENT;
1392 result = audioPlayer_getStreamType(ap, (SLint32*)pConfigValue);
1394 *pValueSize = KEY_STREAM_TYPE_PARAMSIZE;
1397 SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY);
1398 result = SL_RESULT_PARAMETER_INVALID;
1405 //-----------------------------------------------------------------------------
1406 SLresult android_audioPlayer_realize(CAudioPlayer *pAudioPlayer, SLboolean async) {
1408 SLresult result = SL_RESULT_SUCCESS;
1409 SL_LOGV("Realize pAudioPlayer=%p", pAudioPlayer);
1411 switch (pAudioPlayer->mAndroidObjType) {
1412 //-----------------------------------
1414 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1416 // initialize platform-specific CAudioPlayer fields
1418 SLDataLocator_BufferQueue *dl_bq = (SLDataLocator_BufferQueue *)
1419 pAudioPlayer->mDynamicSource.mDataSource;
1420 SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *)
1421 pAudioPlayer->mDynamicSource.mDataSource->pFormat;
1423 uint32_t sampleRate = sles_to_android_sampleRate(df_pcm->samplesPerSec);
1425 pAudioPlayer->mAudioTrack = new android::AudioTrackProxy(new android::AudioTrack(
1426 pAudioPlayer->mStreamType, // streamType
1427 sampleRate, // sampleRate
1428 sles_to_android_sampleFormat(df_pcm->bitsPerSample), // format
1429 sles_to_android_channelMaskOut(df_pcm->numChannels, df_pcm->channelMask),
1431 0, // frameCount (here min)
1433 audioTrack_callBack_pullFromBuffQueue, // callback
1434 (void *) pAudioPlayer, // user
1435 0 // FIXME find appropriate frame count // notificationFrame
1436 , pAudioPlayer->mSessionId
1438 android::status_t status = pAudioPlayer->mAudioTrack->initCheck();
1439 if (status != android::NO_ERROR) {
1440 SL_LOGE("AudioTrack::initCheck status %u", status);
1441 result = SL_RESULT_CONTENT_UNSUPPORTED;
1442 pAudioPlayer->mAudioTrack.clear();
1446 // initialize platform-independent CAudioPlayer fields
1448 pAudioPlayer->mNumChannels = df_pcm->numChannels;
1449 pAudioPlayer->mSampleRateMilliHz = df_pcm->samplesPerSec; // Note: bad field name in SL ES
1451 pAudioPlayer->mAndroidObjState = ANDROID_READY;
1454 //-----------------------------------
1456 case AUDIOPLAYER_FROM_URIFD: {
1457 object_lock_exclusive(&pAudioPlayer->mObject);
1459 assert(pAudioPlayer->mAndroidObjState == ANDROID_UNINITIALIZED);
1460 assert(pAudioPlayer->mNumChannels == UNKNOWN_NUMCHANNELS);
1461 assert(pAudioPlayer->mSampleRateMilliHz == UNKNOWN_SAMPLERATE);
1462 assert(pAudioPlayer->mAudioTrack == 0);
1464 AudioPlayback_Parameters app;
1465 app.sessionId = pAudioPlayer->mSessionId;
1466 app.streamType = pAudioPlayer->mStreamType;
1467 app.trackcb = audioTrack_callBack_uri;
1468 app.trackcbUser = (void *) pAudioPlayer;
1470 pAudioPlayer->mAPlayer = new android::LocAVPlayer(&app, false /*hasVideo*/);
1471 pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent,
1472 (void*)pAudioPlayer /*notifUSer*/);
1474 object_unlock_exclusive(&pAudioPlayer->mObject);
1476 switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) {
1477 case SL_DATALOCATOR_URI:
1478 pAudioPlayer->mAPlayer->setDataSource(
1479 (const char*)pAudioPlayer->mDataSource.mLocator.mURI.URI);
1481 case SL_DATALOCATOR_ANDROIDFD: {
1482 int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset;
1483 pAudioPlayer->mAPlayer->setDataSource(
1484 (int)pAudioPlayer->mDataSource.mLocator.mFD.fd,
1485 offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
1486 (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
1487 (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length);
1491 SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR);
1497 //-----------------------------------
1499 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: {
1500 object_lock_exclusive(&pAudioPlayer->mObject);
1502 android_StreamPlayer_realize_l(pAudioPlayer, sfplayer_handlePrefetchEvent,
1503 (void*)pAudioPlayer);
1505 object_unlock_exclusive(&pAudioPlayer->mObject);
1508 //-----------------------------------
1509 // AudioToCbRenderer
1510 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
1511 object_lock_exclusive(&pAudioPlayer->mObject);
1513 AudioPlayback_Parameters app;
1514 app.sessionId = pAudioPlayer->mSessionId;
1515 app.streamType = pAudioPlayer->mStreamType;
1517 android::AudioToCbRenderer* decoder = new android::AudioToCbRenderer(&app);
1518 pAudioPlayer->mAPlayer = decoder;
1519 // configures the callback for the sink buffer queue
1520 decoder->setDataPushListener(adecoder_writeToBufferQueue, (void*)pAudioPlayer);
1521 // configures the callback for the notifications coming from the SF code
1522 decoder->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1524 switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) {
1525 case SL_DATALOCATOR_URI:
1526 decoder->setDataSource(
1527 (const char*)pAudioPlayer->mDataSource.mLocator.mURI.URI);
1529 case SL_DATALOCATOR_ANDROIDFD: {
1530 int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset;
1531 decoder->setDataSource(
1532 (int)pAudioPlayer->mDataSource.mLocator.mFD.fd,
1533 offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
1534 (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
1535 (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length);
1539 SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR);
1543 object_unlock_exclusive(&pAudioPlayer->mObject);
1546 //-----------------------------------
1547 // AacBqToPcmCbRenderer
1548 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
1549 object_lock_exclusive(&pAudioPlayer->mObject);
1551 AudioPlayback_Parameters app;
1552 app.sessionId = pAudioPlayer->mSessionId;
1553 app.streamType = pAudioPlayer->mStreamType;
1555 app.trackcbUser = NULL;
1556 android::AacBqToPcmCbRenderer* bqtobq = new android::AacBqToPcmCbRenderer(&app);
1557 // configures the callback for the sink buffer queue
1558 bqtobq->setDataPushListener(adecoder_writeToBufferQueue, (void*)pAudioPlayer);
1559 pAudioPlayer->mAPlayer = bqtobq;
1560 // configures the callback for the notifications coming from the SF code,
1561 // but also implicitly configures the AndroidBufferQueue from which ADTS data is read
1562 pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1564 object_unlock_exclusive(&pAudioPlayer->mObject);
1567 //-----------------------------------
1569 SL_LOGE(ERROR_PLAYERREALIZE_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType);
1570 result = SL_RESULT_INTERNAL_ERROR;
1575 // proceed with effect initialization
1577 // FIXME use a table of effect descriptors when adding support for more effects
1578 if (memcmp(SL_IID_EQUALIZER, &pAudioPlayer->mEqualizer.mEqDescriptor.type,
1579 sizeof(effect_uuid_t)) == 0) {
1580 SL_LOGV("Need to initialize EQ for AudioPlayer=%p", pAudioPlayer);
1581 android_eq_init(pAudioPlayer->mSessionId, &pAudioPlayer->mEqualizer);
1583 // initialize BassBoost
1584 if (memcmp(SL_IID_BASSBOOST, &pAudioPlayer->mBassBoost.mBassBoostDescriptor.type,
1585 sizeof(effect_uuid_t)) == 0) {
1586 SL_LOGV("Need to initialize BassBoost for AudioPlayer=%p", pAudioPlayer);
1587 android_bb_init(pAudioPlayer->mSessionId, &pAudioPlayer->mBassBoost);
1589 // initialize Virtualizer
1590 if (memcmp(SL_IID_VIRTUALIZER, &pAudioPlayer->mVirtualizer.mVirtualizerDescriptor.type,
1591 sizeof(effect_uuid_t)) == 0) {
1592 SL_LOGV("Need to initialize Virtualizer for AudioPlayer=%p", pAudioPlayer);
1593 android_virt_init(pAudioPlayer->mSessionId, &pAudioPlayer->mVirtualizer);
1596 // initialize EffectSend
1597 // FIXME initialize EffectSend
1603 //-----------------------------------------------------------------------------
1605 * Called with a lock on AudioPlayer
1607 SLresult android_audioPlayer_preDestroy(CAudioPlayer *pAudioPlayer) {
1608 SL_LOGD("android_audioPlayer_preDestroy(%p)", pAudioPlayer);
1609 SLresult result = SL_RESULT_SUCCESS;
1611 if (pAudioPlayer->mAPlayer != 0) {
1612 pAudioPlayer->mAPlayer->preDestroy();
1614 SL_LOGD("android_audioPlayer_preDestroy(%p) after mAPlayer->preDestroy()", pAudioPlayer);
1616 object_unlock_exclusive(&pAudioPlayer->mObject);
1617 if (pAudioPlayer->mCallbackProtector != 0) {
1618 pAudioPlayer->mCallbackProtector->requestCbExitAndWait();
1620 object_lock_exclusive(&pAudioPlayer->mObject);
1626 //-----------------------------------------------------------------------------
1627 SLresult android_audioPlayer_destroy(CAudioPlayer *pAudioPlayer) {
1628 SLresult result = SL_RESULT_SUCCESS;
1629 SL_LOGV("android_audioPlayer_destroy(%p)", pAudioPlayer);
1630 switch (pAudioPlayer->mAndroidObjType) {
1632 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1633 // We own the audio track for PCM buffer queue players
1634 if (pAudioPlayer->mAudioTrack != 0) {
1635 pAudioPlayer->mAudioTrack->stop();
1636 // Note that there may still be another reference in post-unlock phase of SetPlayState
1637 pAudioPlayer->mAudioTrack.clear();
1641 case AUDIOPLAYER_FROM_URIFD: // intended fall-through
1642 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
1643 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: // intended fall-through
1644 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1645 pAudioPlayer->mAPlayer.clear();
1647 //-----------------------------------
1649 SL_LOGE(ERROR_PLAYERDESTROY_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType);
1650 result = SL_RESULT_INTERNAL_ERROR;
1654 pAudioPlayer->mCallbackProtector.clear();
1656 // FIXME might not be needed
1657 pAudioPlayer->mAndroidObjType = INVALID_TYPE;
1659 // explicit destructor
1660 pAudioPlayer->mAudioTrack.~sp();
1661 // note that SetPlayState(PLAYING) may still hold a reference
1662 pAudioPlayer->mCallbackProtector.~sp();
1663 pAudioPlayer->mAuxEffect.~sp();
1664 pAudioPlayer->mAPlayer.~sp();
1666 if (pAudioPlayer->mpLock != NULL) {
1667 delete pAudioPlayer->mpLock;
1668 pAudioPlayer->mpLock = NULL;
1675 //-----------------------------------------------------------------------------
1676 SLresult android_audioPlayer_setPlaybackRateAndConstraints(CAudioPlayer *ap, SLpermille rate,
1677 SLuint32 constraints) {
1678 SLresult result = SL_RESULT_SUCCESS;
1679 switch(ap->mAndroidObjType) {
1680 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: {
1681 // these asserts were already checked by the platform-independent layer
1682 assert((AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE <= rate) &&
1683 (rate <= AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE));
1684 assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO);
1685 // get the content sample rate
1686 uint32_t contentRate = sles_to_android_sampleRate(ap->mSampleRateMilliHz);
1687 // apply the SL ES playback rate on the AudioTrack as a factor of its content sample rate
1688 if (ap->mAudioTrack != 0) {
1689 ap->mAudioTrack->setSampleRate(contentRate * (rate/1000.0f));
1693 case AUDIOPLAYER_FROM_URIFD:
1694 assert(rate == 1000);
1695 assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO);
1700 SL_LOGE("Unexpected object type %d", ap->mAndroidObjType);
1701 result = SL_RESULT_FEATURE_UNSUPPORTED;
1708 //-----------------------------------------------------------------------------
1710 // called with no lock held
1712 // pItemCount != NULL
1713 SLresult android_audioPlayer_metadata_getItemCount(CAudioPlayer *ap, SLuint32 *pItemCount) {
1714 if (ap->mAPlayer == 0) {
1715 return SL_RESULT_PARAMETER_INVALID;
1717 switch(ap->mAndroidObjType) {
1718 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1720 android::AudioSfDecoder* decoder =
1721 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1722 *pItemCount = decoder->getPcmFormatKeyCount();
1729 return SL_RESULT_SUCCESS;
1733 //-----------------------------------------------------------------------------
1735 // called with no lock held
1738 SLresult android_audioPlayer_metadata_getKeySize(CAudioPlayer *ap,
1739 SLuint32 index, SLuint32 *pKeySize) {
1740 if (ap->mAPlayer == 0) {
1741 return SL_RESULT_PARAMETER_INVALID;
1743 SLresult res = SL_RESULT_SUCCESS;
1744 switch(ap->mAndroidObjType) {
1745 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1747 android::AudioSfDecoder* decoder =
1748 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1749 SLuint32 keyNameSize = 0;
1750 if (!decoder->getPcmFormatKeySize(index, &keyNameSize)) {
1751 res = SL_RESULT_PARAMETER_INVALID;
1753 // *pKeySize is the size of the region used to store the key name AND
1754 // the information about the key (size, lang, encoding)
1755 *pKeySize = keyNameSize + sizeof(SLMetadataInfo);
1761 res = SL_RESULT_PARAMETER_INVALID;
1768 //-----------------------------------------------------------------------------
1770 // called with no lock held
1773 SLresult android_audioPlayer_metadata_getKey(CAudioPlayer *ap,
1774 SLuint32 index, SLuint32 size, SLMetadataInfo *pKey) {
1775 if (ap->mAPlayer == 0) {
1776 return SL_RESULT_PARAMETER_INVALID;
1778 SLresult res = SL_RESULT_SUCCESS;
1779 switch(ap->mAndroidObjType) {
1780 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1782 android::AudioSfDecoder* decoder =
1783 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1784 if ((size < sizeof(SLMetadataInfo) ||
1785 (!decoder->getPcmFormatKeyName(index, size - sizeof(SLMetadataInfo),
1786 (char*)pKey->data)))) {
1787 res = SL_RESULT_PARAMETER_INVALID;
1789 // successfully retrieved the key value, update the other fields
1790 pKey->encoding = SL_CHARACTERENCODING_UTF8;
1791 memcpy((char *) pKey->langCountry, "en", 3);
1792 pKey->size = strlen((char*)pKey->data) + 1;
1797 res = SL_RESULT_PARAMETER_INVALID;
1804 //-----------------------------------------------------------------------------
1806 // called with no lock held
1808 // pValueSize != NULL
1809 SLresult android_audioPlayer_metadata_getValueSize(CAudioPlayer *ap,
1810 SLuint32 index, SLuint32 *pValueSize) {
1811 if (ap->mAPlayer == 0) {
1812 return SL_RESULT_PARAMETER_INVALID;
1814 SLresult res = SL_RESULT_SUCCESS;
1815 switch(ap->mAndroidObjType) {
1816 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1818 android::AudioSfDecoder* decoder =
1819 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1820 SLuint32 valueSize = 0;
1821 if (!decoder->getPcmFormatValueSize(index, &valueSize)) {
1822 res = SL_RESULT_PARAMETER_INVALID;
1824 // *pValueSize is the size of the region used to store the key value AND
1825 // the information about the value (size, lang, encoding)
1826 *pValueSize = valueSize + sizeof(SLMetadataInfo);
1832 res = SL_RESULT_PARAMETER_INVALID;
1839 //-----------------------------------------------------------------------------
1841 // called with no lock held
1844 SLresult android_audioPlayer_metadata_getValue(CAudioPlayer *ap,
1845 SLuint32 index, SLuint32 size, SLMetadataInfo *pValue) {
1846 if (ap->mAPlayer == 0) {
1847 return SL_RESULT_PARAMETER_INVALID;
1849 SLresult res = SL_RESULT_SUCCESS;
1850 switch(ap->mAndroidObjType) {
1851 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1853 android::AudioSfDecoder* decoder =
1854 static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1855 pValue->encoding = SL_CHARACTERENCODING_BINARY;
1856 memcpy((char *) pValue->langCountry, "en", 3); // applicable here?
1857 SLuint32 valueSize = 0;
1858 if ((size < sizeof(SLMetadataInfo)
1859 || (!decoder->getPcmFormatValueSize(index, &valueSize))
1860 || (!decoder->getPcmFormatKeyValue(index, size - sizeof(SLMetadataInfo),
1861 (SLuint32*)pValue->data)))) {
1862 res = SL_RESULT_PARAMETER_INVALID;
1864 pValue->size = valueSize;
1869 res = SL_RESULT_PARAMETER_INVALID;
1875 //-----------------------------------------------------------------------------
1879 // play state has changed
1880 void android_audioPlayer_setPlayState(CAudioPlayer *ap) {
1882 SLuint32 playState = ap->mPlay.mState;
1883 AndroidObjectState objState = ap->mAndroidObjState;
1885 switch(ap->mAndroidObjType) {
1886 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1887 switch (playState) {
1888 case SL_PLAYSTATE_STOPPED:
1889 SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_STOPPED");
1890 if (ap->mAudioTrack != 0) {
1891 ap->mAudioTrack->stop();
1894 case SL_PLAYSTATE_PAUSED:
1895 SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PAUSED");
1896 if (ap->mAudioTrack != 0) {
1897 ap->mAudioTrack->pause();
1900 case SL_PLAYSTATE_PLAYING:
1901 SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PLAYING");
1902 if (ap->mAudioTrack != 0) {
1903 // instead of ap->mAudioTrack->start();
1904 ap->mDeferredStart = true;
1908 // checked by caller, should not happen
1913 case AUDIOPLAYER_FROM_URIFD: // intended fall-through
1914 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
1915 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: // intended fall-through
1916 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1917 // FIXME report and use the return code to the lock mechanism, which is where play state
1918 // changes are updated (see object_unlock_exclusive_attributes())
1919 aplayer_setPlayState(ap->mAPlayer, playState, &(ap->mAndroidObjState));
1922 SL_LOGE(ERROR_PLAYERSETPLAYSTATE_UNEXPECTED_OBJECT_TYPE_D, ap->mAndroidObjType);
1928 //-----------------------------------------------------------------------------
1929 // call when either player event flags, marker position, or position update period changes
1930 void android_audioPlayer_useEventMask(CAudioPlayer *ap) {
1931 IPlay *pPlayItf = &ap->mPlay;
1932 SLuint32 eventFlags = pPlayItf->mEventFlags;
1933 /*switch(ap->mAndroidObjType) {
1934 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:*/
1936 if (ap->mAPlayer != 0) {
1937 assert(ap->mAudioTrack == 0);
1938 ap->mAPlayer->setPlayEvents((int32_t) eventFlags, (int32_t) pPlayItf->mMarkerPosition,
1939 (int32_t) pPlayItf->mPositionUpdatePeriod);
1943 if (ap->mAudioTrack == 0) {
1947 if (eventFlags & SL_PLAYEVENT_HEADATMARKER) {
1948 ap->mAudioTrack->setMarkerPosition((uint32_t)((((int64_t)pPlayItf->mMarkerPosition
1949 * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000));
1952 ap->mAudioTrack->setMarkerPosition(0);
1955 if (eventFlags & SL_PLAYEVENT_HEADATNEWPOS) {
1956 ap->mAudioTrack->setPositionUpdatePeriod(
1957 (uint32_t)((((int64_t)pPlayItf->mPositionUpdatePeriod
1958 * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000));
1960 // clear periodic update
1961 ap->mAudioTrack->setPositionUpdatePeriod(0);
1964 if (eventFlags & SL_PLAYEVENT_HEADATEND) {
1965 // nothing to do for SL_PLAYEVENT_HEADATEND, callback event will be checked against mask
1968 if (eventFlags & SL_PLAYEVENT_HEADMOVING) {
1969 // FIXME support SL_PLAYEVENT_HEADMOVING
1970 SL_LOGD("[ FIXME: IPlay_SetCallbackEventsMask(SL_PLAYEVENT_HEADMOVING) on an "
1971 "SL_OBJECTID_AUDIOPLAYER to be implemented ]");
1973 if (eventFlags & SL_PLAYEVENT_HEADSTALLED) {
1974 // nothing to do for SL_PLAYEVENT_HEADSTALLED, callback event will be checked against mask
1980 //-----------------------------------------------------------------------------
1981 SLresult android_audioPlayer_getDuration(IPlay *pPlayItf, SLmillisecond *pDurMsec) {
1982 CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis;
1983 switch(ap->mAndroidObjType) {
1985 case AUDIOPLAYER_FROM_URIFD: // intended fall-through
1986 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
1987 int32_t durationMsec = ANDROID_UNKNOWN_TIME;
1988 if (ap->mAPlayer != 0) {
1989 ap->mAPlayer->getDurationMsec(&durationMsec);
1991 *pDurMsec = durationMsec == ANDROID_UNKNOWN_TIME ? SL_TIME_UNKNOWN : durationMsec;
1995 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
1996 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: // intended fall-through
1998 *pDurMsec = SL_TIME_UNKNOWN;
2001 return SL_RESULT_SUCCESS;
2005 //-----------------------------------------------------------------------------
2006 void android_audioPlayer_getPosition(IPlay *pPlayItf, SLmillisecond *pPosMsec) {
2007 CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis;
2008 switch(ap->mAndroidObjType) {
2010 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2011 if ((ap->mSampleRateMilliHz == UNKNOWN_SAMPLERATE) || (ap->mAudioTrack == 0)) {
2014 uint32_t positionInFrames;
2015 ap->mAudioTrack->getPosition(&positionInFrames);
2016 *pPosMsec = ((int64_t)positionInFrames * 1000) /
2017 sles_to_android_sampleRate(ap->mSampleRateMilliHz);
2021 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
2022 case AUDIOPLAYER_FROM_URIFD: // intended fall-through
2023 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
2024 int32_t posMsec = ANDROID_UNKNOWN_TIME;
2025 if (ap->mAPlayer != 0) {
2026 ap->mAPlayer->getPositionMsec(&posMsec);
2028 *pPosMsec = posMsec == ANDROID_UNKNOWN_TIME ? 0 : posMsec;
2038 //-----------------------------------------------------------------------------
2039 void android_audioPlayer_seek(CAudioPlayer *ap, SLmillisecond posMsec) {
2041 switch(ap->mAndroidObjType) {
2043 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: // intended fall-through
2044 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2047 case AUDIOPLAYER_FROM_URIFD: // intended fall-through
2048 case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2049 if (ap->mAPlayer != 0) {
2050 ap->mAPlayer->seek(posMsec);
2060 //-----------------------------------------------------------------------------
2061 void android_audioPlayer_loop(CAudioPlayer *ap, SLboolean loopEnable) {
2063 if ((AUDIOPLAYER_FROM_URIFD == ap->mAndroidObjType) && (ap->mAPlayer != 0)) {
2064 ap->mAPlayer->loop((bool)loopEnable);
2069 //-----------------------------------------------------------------------------
2070 SLresult android_audioPlayer_setBufferingUpdateThresholdPerMille(CAudioPlayer *ap,
2071 SLpermille threshold) {
2072 SLresult result = SL_RESULT_SUCCESS;
2074 switch (ap->mAndroidObjType) {
2075 case AUDIOPLAYER_FROM_URIFD:
2076 if (ap->mAPlayer != 0) {
2077 ap->mAPlayer->setBufferingUpdateThreshold(threshold / 10);
2088 //-----------------------------------------------------------------------------
2089 void android_audioPlayer_bufferQueue_onRefilled_l(CAudioPlayer *ap) {
2090 // the AudioTrack associated with the AudioPlayer receiving audio from a PCM buffer
2091 // queue was stopped when the queue become empty, we restart as soon as a new buffer
2092 // has been enqueued since we're in playing state
2093 if (ap->mAudioTrack != 0) {
2094 // instead of ap->mAudioTrack->start();
2095 ap->mDeferredStart = true;
2098 // when the queue became empty, an underflow on the prefetch status itf was sent. Now the queue
2099 // has received new data, signal it has sufficient data
2100 if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
2101 audioPlayer_dispatch_prefetchStatus_lockPrefetch(ap, SL_PREFETCHSTATUS_SUFFICIENTDATA,
2107 //-----------------------------------------------------------------------------
2109 * BufferQueue::Clear
2111 SLresult android_audioPlayer_bufferQueue_onClear(CAudioPlayer *ap) {
2112 SLresult result = SL_RESULT_SUCCESS;
2114 switch (ap->mAndroidObjType) {
2115 //-----------------------------------
2117 case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2118 if (ap->mAudioTrack != 0) {
2119 ap->mAudioTrack->flush();
2123 result = SL_RESULT_INTERNAL_ERROR;
2131 //-----------------------------------------------------------------------------
2132 SLresult android_audioPlayer_androidBufferQueue_registerCallback_l(CAudioPlayer *ap) {
2133 SLresult result = SL_RESULT_SUCCESS;
2134 assert(ap->mAPlayer != 0);
2135 switch (ap->mAndroidObjType) {
2136 case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: {
2137 android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2138 splr->registerQueueCallback(
2139 (const void*)ap /*user*/, true /*userIsAudioPlayer*/,
2140 ap->mAndroidBufferQueue.mContext /*context*/,
2141 (const void*)&(ap->mAndroidBufferQueue.mItf) /*caller*/);
2143 case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
2144 android::AacBqToPcmCbRenderer* dec =
2145 static_cast<android::AacBqToPcmCbRenderer*>(ap->mAPlayer.get());
2146 dec->registerSourceQueueCallback((const void*)ap /*user*/,
2147 ap->mAndroidBufferQueue.mContext /*context*/,
2148 (const void*)&(ap->mAndroidBufferQueue.mItf) /*caller*/);
2151 SL_LOGE("Error registering AndroidBufferQueue callback: unexpected object type %d",
2152 ap->mAndroidObjType);
2153 result = SL_RESULT_INTERNAL_ERROR;
2159 //-----------------------------------------------------------------------------
2160 void android_audioPlayer_androidBufferQueue_clear_l(CAudioPlayer *ap) {
2161 if ((ap->mAndroidObjType == AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE) && (ap->mAPlayer != 0)) {
2162 android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2167 void android_audioPlayer_androidBufferQueue_onRefilled_l(CAudioPlayer *ap) {
2168 if ((ap->mAndroidObjType == AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE) && (ap->mAPlayer != 0)) {
2169 android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2170 splr->queueRefilled_l();