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