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