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