AudioPlayer_to_android.cpp revision 36c0711b6919c2185a4d6e514d7f421b0d9c7bc6
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "sles_allinclusive.h"
18#include "android_prompts.h"
19#include "android/android_AudioToCbRenderer.h"
20#include "android/android_StreamPlayer.h"
21#include "android/android_LocAVPlayer.h"
22#include "android/include/AacBqToPcmCbRenderer.h"
23
24#include <fcntl.h>
25#include <sys/stat.h>
26
27#include <system/audio.h>
28
29template class android::KeyedVector<SLuint32, android::AudioEffect* > ;
30
31#define KEY_STREAM_TYPE_PARAMSIZE  sizeof(SLint32)
32
33#define AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE  500
34#define AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE 2000
35
36#define MEDIAPLAYER_MIN_PLAYBACKRATE_PERMILLE AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE
37#define MEDIAPLAYER_MAX_PLAYBACKRATE_PERMILLE AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE
38
39//-----------------------------------------------------------------------------
40// FIXME this method will be absorbed into android_audioPlayer_setPlayState() once
41//       bufferqueue and uri/fd playback are moved under the GenericPlayer C++ object
42SLresult aplayer_setPlayState(const android::sp<android::GenericPlayer> &ap, SLuint32 playState,
43        AndroidObjectState* pObjState) {
44    SLresult result = SL_RESULT_SUCCESS;
45    AndroidObjectState objState = *pObjState;
46
47    switch (playState) {
48     case SL_PLAYSTATE_STOPPED:
49         SL_LOGV("setting GenericPlayer to SL_PLAYSTATE_STOPPED");
50         ap->stop();
51         break;
52     case SL_PLAYSTATE_PAUSED:
53         SL_LOGV("setting GenericPlayer to SL_PLAYSTATE_PAUSED");
54         switch(objState) {
55         case ANDROID_UNINITIALIZED:
56             *pObjState = ANDROID_PREPARING;
57             ap->prepare();
58             break;
59         case ANDROID_PREPARING:
60             break;
61         case ANDROID_READY:
62             ap->pause();
63             break;
64         default:
65             SL_LOGE(ERROR_PLAYERSETPLAYSTATE_INVALID_OBJECT_STATE_D, playState);
66             result = SL_RESULT_INTERNAL_ERROR;
67             break;
68         }
69         break;
70     case SL_PLAYSTATE_PLAYING: {
71         SL_LOGV("setting GenericPlayer to SL_PLAYSTATE_PLAYING");
72         switch(objState) {
73         case ANDROID_UNINITIALIZED:
74             *pObjState = ANDROID_PREPARING;
75             ap->prepare();
76             // intended fall through
77         case ANDROID_PREPARING:
78             // intended fall through
79         case ANDROID_READY:
80             ap->play();
81             break;
82         default:
83             SL_LOGE(ERROR_PLAYERSETPLAYSTATE_INVALID_OBJECT_STATE_D, playState);
84             result = SL_RESULT_INTERNAL_ERROR;
85             break;
86         }
87         }
88         break;
89     default:
90         // checked by caller, should not happen
91         SL_LOGE(ERROR_SHOULDNT_BE_HERE_S, "aplayer_setPlayState");
92         result = SL_RESULT_INTERNAL_ERROR;
93         break;
94     }
95
96    return result;
97}
98
99
100//-----------------------------------------------------------------------------
101// Callback associated with a AudioToCbRenderer of an SL ES AudioPlayer that gets its data
102// from a URI or FD, to write the decoded audio data to a buffer queue
103static size_t adecoder_writeToBufferQueue(const uint8_t *data, size_t size, CAudioPlayer* ap) {
104    if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) {
105        // it is not safe to enter the callback (the player is about to go away)
106        return 0;
107    }
108    size_t sizeConsumed = 0;
109    SL_LOGD("received %d bytes from decoder", size);
110    slBufferQueueCallback callback = NULL;
111    void * callbackPContext = NULL;
112
113    // push decoded data to the buffer queue
114    object_lock_exclusive(&ap->mObject);
115
116    if (ap->mBufferQueue.mState.count != 0) {
117        assert(ap->mBufferQueue.mFront != ap->mBufferQueue.mRear);
118
119        BufferHeader *oldFront = ap->mBufferQueue.mFront;
120        BufferHeader *newFront = &oldFront[1];
121
122        uint8_t *pDest = (uint8_t *)oldFront->mBuffer + ap->mBufferQueue.mSizeConsumed;
123        if (ap->mBufferQueue.mSizeConsumed + size < oldFront->mSize) {
124            // room to consume the whole or rest of the decoded data in one shot
125            ap->mBufferQueue.mSizeConsumed += size;
126            // consume data but no callback to the BufferQueue interface here
127            memcpy (pDest, data, size);
128            sizeConsumed = size;
129        } else {
130            // push as much as possible of the decoded data into the buffer queue
131            sizeConsumed = oldFront->mSize - ap->mBufferQueue.mSizeConsumed;
132
133            // the buffer at the head of the buffer queue is full, update the state
134            ap->mBufferQueue.mSizeConsumed = 0;
135            if (newFront == &ap->mBufferQueue.mArray[ap->mBufferQueue.mNumBuffers + 1]) {
136                newFront = ap->mBufferQueue.mArray;
137            }
138            ap->mBufferQueue.mFront = newFront;
139
140            ap->mBufferQueue.mState.count--;
141            ap->mBufferQueue.mState.playIndex++;
142            // consume data
143            memcpy (pDest, data, sizeConsumed);
144            // data has been copied to the buffer, and the buffer queue state has been updated
145            // we will notify the client if applicable
146            callback = ap->mBufferQueue.mCallback;
147            // save callback data
148            callbackPContext = ap->mBufferQueue.mContext;
149        }
150
151    } else {
152        // no available buffers in the queue to write the decoded data
153        sizeConsumed = 0;
154    }
155
156    object_unlock_exclusive(&ap->mObject);
157    // notify client
158    if (NULL != callback) {
159        (*callback)(&ap->mBufferQueue.mItf, callbackPContext);
160    }
161
162    ap->mCallbackProtector->exitCb();
163    return sizeConsumed;
164}
165
166
167//-----------------------------------------------------------------------------
168#define LEFT_CHANNEL_MASK  0x1 << 0
169#define RIGHT_CHANNEL_MASK 0x1 << 1
170
171void android_audioPlayer_volumeUpdate(CAudioPlayer* ap)
172{
173    assert(ap != NULL);
174
175    // the source's channel count, where zero means unknown
176    SLuint8 channelCount = ap->mNumChannels;
177
178    // whether each channel is audible
179    bool leftAudibilityFactor, rightAudibilityFactor;
180
181    // mute has priority over solo
182    if (channelCount >= STEREO_CHANNELS) {
183        if (ap->mMuteMask & LEFT_CHANNEL_MASK) {
184            // left muted
185            leftAudibilityFactor = false;
186        } else {
187            // left not muted
188            if (ap->mSoloMask & LEFT_CHANNEL_MASK) {
189                // left soloed
190                leftAudibilityFactor = true;
191            } else {
192                // left not soloed
193                if (ap->mSoloMask & RIGHT_CHANNEL_MASK) {
194                    // right solo silences left
195                    leftAudibilityFactor = false;
196                } else {
197                    // left and right are not soloed, and left is not muted
198                    leftAudibilityFactor = true;
199                }
200            }
201        }
202
203        if (ap->mMuteMask & RIGHT_CHANNEL_MASK) {
204            // right muted
205            rightAudibilityFactor = false;
206        } else {
207            // right not muted
208            if (ap->mSoloMask & RIGHT_CHANNEL_MASK) {
209                // right soloed
210                rightAudibilityFactor = true;
211            } else {
212                // right not soloed
213                if (ap->mSoloMask & LEFT_CHANNEL_MASK) {
214                    // left solo silences right
215                    rightAudibilityFactor = false;
216                } else {
217                    // left and right are not soloed, and right is not muted
218                    rightAudibilityFactor = true;
219                }
220            }
221        }
222
223    // channel mute and solo are ignored for mono and unknown channel count sources
224    } else {
225        leftAudibilityFactor = true;
226        rightAudibilityFactor = true;
227    }
228
229    // compute volumes without setting
230    const bool audibilityFactors[2] = {leftAudibilityFactor, rightAudibilityFactor};
231    float volumes[2];
232    android_player_volumeUpdate(volumes, &ap->mVolume, channelCount, ap->mAmplFromDirectLevel,
233            audibilityFactors);
234    float leftVol = volumes[0], rightVol = volumes[1];
235
236    // set volume on the underlying media player or audio track
237    if (ap->mAPlayer != 0) {
238        ap->mAPlayer->setVolume(leftVol, rightVol);
239    } else if (ap->mAudioTrack != 0) {
240        ap->mAudioTrack->setVolume(leftVol, rightVol);
241    }
242
243    // changes in the AudioPlayer volume must be reflected in the send level:
244    //  in SLEffectSendItf or in SLAndroidEffectSendItf?
245    // FIXME replace interface test by an internal API once we have one.
246    if (NULL != ap->mEffectSend.mItf) {
247        for (unsigned int i=0 ; i<AUX_MAX ; i++) {
248            if (ap->mEffectSend.mEnableLevels[i].mEnable) {
249                android_fxSend_setSendLevel(ap,
250                        ap->mEffectSend.mEnableLevels[i].mSendLevel + ap->mVolume.mLevel);
251                // there's a single aux bus on Android, so we can stop looking once the first
252                // aux effect is found.
253                break;
254            }
255        }
256    } else if (NULL != ap->mAndroidEffectSend.mItf) {
257        android_fxSend_setSendLevel(ap, ap->mAndroidEffectSend.mSendLevel + ap->mVolume.mLevel);
258    }
259}
260
261// Called by android_audioPlayer_volumeUpdate and android_mediaPlayer_volumeUpdate to compute
262// volumes, but setting volumes is handled by the caller.
263
264void android_player_volumeUpdate(float *pVolumes /*[2]*/, const IVolume *volumeItf, unsigned
265channelCount, float amplFromDirectLevel, const bool *audibilityFactors /*[2]*/)
266{
267    assert(pVolumes != NULL);
268    assert(volumeItf != NULL);
269    // OK for audibilityFactors to be NULL
270
271    bool leftAudibilityFactor, rightAudibilityFactor;
272
273    // apply player mute factor
274    // note that AudioTrack has mute() but not MediaPlayer, so it's easier to use volume
275    // to mute for both rather than calling mute() for AudioTrack
276
277    // player is muted
278    if (volumeItf->mMute) {
279        leftAudibilityFactor = false;
280        rightAudibilityFactor = false;
281    // player isn't muted, and channel mute/solo audibility factors are available (AudioPlayer)
282    } else if (audibilityFactors != NULL) {
283        leftAudibilityFactor = audibilityFactors[0];
284        rightAudibilityFactor = audibilityFactors[1];
285    // player isn't muted, and channel mute/solo audibility factors aren't available (MediaPlayer)
286    } else {
287        leftAudibilityFactor = true;
288        rightAudibilityFactor = true;
289    }
290
291    // compute amplification as the combination of volume level and stereo position
292    //   amplification (or attenuation) from volume level
293    float amplFromVolLevel = sles_to_android_amplification(volumeItf->mLevel);
294    //   amplification from direct level (changed in SLEffectSendtItf and SLAndroidEffectSendItf)
295    float leftVol  = amplFromVolLevel * amplFromDirectLevel;
296    float rightVol = leftVol;
297
298    // amplification from stereo position
299    if (volumeItf->mEnableStereoPosition) {
300        // Left/right amplification (can be attenuations) factors derived for the StereoPosition
301        float amplFromStereoPos[STEREO_CHANNELS];
302        // panning law depends on content channel count: mono to stereo panning vs stereo balance
303        if (1 == channelCount) {
304            // mono to stereo panning
305            double theta = (1000+volumeItf->mStereoPosition)*M_PI_4/1000.0f; // 0 <= theta <= Pi/2
306            amplFromStereoPos[0] = cos(theta);
307            amplFromStereoPos[1] = sin(theta);
308        // channel count is 0 (unknown), 2 (stereo), or > 2 (multi-channel)
309        } else {
310            // stereo balance
311            if (volumeItf->mStereoPosition > 0) {
312                amplFromStereoPos[0] = (1000-volumeItf->mStereoPosition)/1000.0f;
313                amplFromStereoPos[1] = 1.0f;
314            } else {
315                amplFromStereoPos[0] = 1.0f;
316                amplFromStereoPos[1] = (1000+volumeItf->mStereoPosition)/1000.0f;
317            }
318        }
319        leftVol  *= amplFromStereoPos[0];
320        rightVol *= amplFromStereoPos[1];
321    }
322
323    // apply audibility factors
324    if (!leftAudibilityFactor) {
325        leftVol = 0.0;
326    }
327    if (!rightAudibilityFactor) {
328        rightVol = 0.0;
329    }
330
331    // return the computed volumes
332    pVolumes[0] = leftVol;
333    pVolumes[1] = rightVol;
334}
335
336//-----------------------------------------------------------------------------
337void audioTrack_handleMarker_lockPlay(CAudioPlayer* ap) {
338    //SL_LOGV("received event EVENT_MARKER from AudioTrack");
339    slPlayCallback callback = NULL;
340    void* callbackPContext = NULL;
341
342    interface_lock_shared(&ap->mPlay);
343    callback = ap->mPlay.mCallback;
344    callbackPContext = ap->mPlay.mContext;
345    interface_unlock_shared(&ap->mPlay);
346
347    if (NULL != callback) {
348        // getting this event implies SL_PLAYEVENT_HEADATMARKER was set in the event mask
349        (*callback)(&ap->mPlay.mItf, callbackPContext, SL_PLAYEVENT_HEADATMARKER);
350    }
351}
352
353//-----------------------------------------------------------------------------
354void audioTrack_handleNewPos_lockPlay(CAudioPlayer* ap) {
355    //SL_LOGV("received event EVENT_NEW_POS from AudioTrack");
356    slPlayCallback callback = NULL;
357    void* callbackPContext = NULL;
358
359    interface_lock_shared(&ap->mPlay);
360    callback = ap->mPlay.mCallback;
361    callbackPContext = ap->mPlay.mContext;
362    interface_unlock_shared(&ap->mPlay);
363
364    if (NULL != callback) {
365        // getting this event implies SL_PLAYEVENT_HEADATNEWPOS was set in the event mask
366        (*callback)(&ap->mPlay.mItf, callbackPContext, SL_PLAYEVENT_HEADATNEWPOS);
367    }
368}
369
370
371//-----------------------------------------------------------------------------
372void audioTrack_handleUnderrun_lockPlay(CAudioPlayer* ap) {
373    slPlayCallback callback = NULL;
374    void* callbackPContext = NULL;
375
376    interface_lock_shared(&ap->mPlay);
377    callback = ap->mPlay.mCallback;
378    callbackPContext = ap->mPlay.mContext;
379    bool headStalled = (ap->mPlay.mEventFlags & SL_PLAYEVENT_HEADSTALLED) != 0;
380    interface_unlock_shared(&ap->mPlay);
381
382    if ((NULL != callback) && headStalled) {
383        (*callback)(&ap->mPlay.mItf, callbackPContext, SL_PLAYEVENT_HEADSTALLED);
384    }
385}
386
387
388//-----------------------------------------------------------------------------
389/**
390 * post-condition: play state of AudioPlayer is SL_PLAYSTATE_PAUSED if setPlayStateToPaused is true
391 *
392 * note: a conditional flag, setPlayStateToPaused, is used here to specify whether the play state
393 *       needs to be changed when the player reaches the end of the content to play. This is
394 *       relative to what the specification describes for buffer queues vs the
395 *       SL_PLAYEVENT_HEADATEND event. In the OpenSL ES specification 1.0.1:
396 *        - section 8.12 SLBufferQueueItf states "In the case of starvation due to insufficient
397 *          buffers in the queue, the playing of audio data stops. The player remains in the
398 *          SL_PLAYSTATE_PLAYING state."
399 *        - section 9.2.31 SL_PLAYEVENT states "SL_PLAYEVENT_HEADATEND Playback head is at the end
400 *          of the current content and the player has paused."
401 */
402void audioPlayer_dispatch_headAtEnd_lockPlay(CAudioPlayer *ap, bool setPlayStateToPaused,
403        bool needToLock) {
404    //SL_LOGV("ap=%p, setPlayStateToPaused=%d, needToLock=%d", ap, setPlayStateToPaused,
405    //        needToLock);
406    slPlayCallback playCallback = NULL;
407    void * playContext = NULL;
408    // SLPlayItf callback or no callback?
409    if (needToLock) {
410        interface_lock_exclusive(&ap->mPlay);
411    }
412    if (ap->mPlay.mEventFlags & SL_PLAYEVENT_HEADATEND) {
413        playCallback = ap->mPlay.mCallback;
414        playContext = ap->mPlay.mContext;
415    }
416    if (setPlayStateToPaused) {
417        ap->mPlay.mState = SL_PLAYSTATE_PAUSED;
418    }
419    if (needToLock) {
420        interface_unlock_exclusive(&ap->mPlay);
421    }
422    // enqueue callback with no lock held
423    if (NULL != playCallback) {
424#ifndef USE_ASYNCHRONOUS_PLAY_CALLBACK
425        (*playCallback)(&ap->mPlay.mItf, playContext, SL_PLAYEVENT_HEADATEND);
426#else
427        SLresult result = EnqueueAsyncCallback_ppi(ap, playCallback, &ap->mPlay.mItf, playContext,
428                SL_PLAYEVENT_HEADATEND);
429        if (SL_RESULT_SUCCESS != result) {
430            ALOGW("Callback %p(%p, %p, SL_PLAYEVENT_HEADATEND) dropped", playCallback,
431                    &ap->mPlay.mItf, playContext);
432        }
433#endif
434    }
435
436}
437
438
439//-----------------------------------------------------------------------------
440SLresult audioPlayer_setStreamType(CAudioPlayer* ap, SLint32 type) {
441    SLresult result = SL_RESULT_SUCCESS;
442    SL_LOGV("type %d", type);
443
444    audio_stream_type_t newStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
445    switch(type) {
446    case SL_ANDROID_STREAM_VOICE:
447        newStreamType = AUDIO_STREAM_VOICE_CALL;
448        break;
449    case SL_ANDROID_STREAM_SYSTEM:
450        newStreamType = AUDIO_STREAM_SYSTEM;
451        break;
452    case SL_ANDROID_STREAM_RING:
453        newStreamType = AUDIO_STREAM_RING;
454        break;
455    case SL_ANDROID_STREAM_MEDIA:
456        newStreamType = AUDIO_STREAM_MUSIC;
457        break;
458    case SL_ANDROID_STREAM_ALARM:
459        newStreamType = AUDIO_STREAM_ALARM;
460        break;
461    case SL_ANDROID_STREAM_NOTIFICATION:
462        newStreamType = AUDIO_STREAM_NOTIFICATION;
463        break;
464    default:
465        SL_LOGE(ERROR_PLAYERSTREAMTYPE_SET_UNKNOWN_TYPE);
466        result = SL_RESULT_PARAMETER_INVALID;
467        break;
468    }
469
470    // stream type needs to be set before the object is realized
471    // (ap->mAudioTrack is supposed to be NULL until then)
472    if (SL_OBJECT_STATE_UNREALIZED != ap->mObject.mState) {
473        SL_LOGE(ERROR_PLAYERSTREAMTYPE_REALIZED);
474        result = SL_RESULT_PRECONDITIONS_VIOLATED;
475    } else {
476        ap->mStreamType = newStreamType;
477    }
478
479    return result;
480}
481
482
483//-----------------------------------------------------------------------------
484SLresult audioPlayer_getStreamType(CAudioPlayer* ap, SLint32 *pType) {
485    SLresult result = SL_RESULT_SUCCESS;
486
487    switch(ap->mStreamType) {
488    case AUDIO_STREAM_VOICE_CALL:
489        *pType = SL_ANDROID_STREAM_VOICE;
490        break;
491    case AUDIO_STREAM_SYSTEM:
492        *pType = SL_ANDROID_STREAM_SYSTEM;
493        break;
494    case AUDIO_STREAM_RING:
495        *pType = SL_ANDROID_STREAM_RING;
496        break;
497    case AUDIO_STREAM_DEFAULT:
498    case AUDIO_STREAM_MUSIC:
499        *pType = SL_ANDROID_STREAM_MEDIA;
500        break;
501    case AUDIO_STREAM_ALARM:
502        *pType = SL_ANDROID_STREAM_ALARM;
503        break;
504    case AUDIO_STREAM_NOTIFICATION:
505        *pType = SL_ANDROID_STREAM_NOTIFICATION;
506        break;
507    default:
508        result = SL_RESULT_INTERNAL_ERROR;
509        *pType = SL_ANDROID_STREAM_MEDIA;
510        break;
511    }
512
513    return result;
514}
515
516
517//-----------------------------------------------------------------------------
518void audioPlayer_auxEffectUpdate(CAudioPlayer* ap) {
519    if ((ap->mAudioTrack != 0) && (ap->mAuxEffect != 0)) {
520        android_fxSend_attach(ap, true, ap->mAuxEffect, ap->mVolume.mLevel + ap->mAuxSendLevel);
521    }
522}
523
524
525//-----------------------------------------------------------------------------
526/*
527 * returns true if the given data sink is supported by AudioPlayer that doesn't
528 *   play to an OutputMix object, false otherwise
529 *
530 * pre-condition: the locator of the audio sink is not SL_DATALOCATOR_OUTPUTMIX
531 */
532bool audioPlayer_isSupportedNonOutputMixSink(const SLDataSink* pAudioSink) {
533    bool result = true;
534    const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSink->pLocator;
535    const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSink->pFormat;
536
537    switch (sinkLocatorType) {
538
539    case SL_DATALOCATOR_BUFFERQUEUE:
540    case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
541        if (SL_DATAFORMAT_PCM != sinkFormatType) {
542            SL_LOGE("Unsupported sink format 0x%x, expected SL_DATAFORMAT_PCM",
543                    (unsigned)sinkFormatType);
544            result = false;
545        }
546        // it's no use checking the PCM format fields because additional characteristics
547        // such as the number of channels, or sample size are unknown to the player at this stage
548        break;
549
550    default:
551        SL_LOGE("Unsupported sink locator type 0x%x", (unsigned)sinkLocatorType);
552        result = false;
553        break;
554    }
555
556    return result;
557}
558
559
560//-----------------------------------------------------------------------------
561/*
562 * returns the Android object type if the locator type combinations for the source and sinks
563 *   are supported by this implementation, INVALID_TYPE otherwise
564 */
565AndroidObjectType audioPlayer_getAndroidObjectTypeForSourceSink(CAudioPlayer *ap) {
566
567    const SLDataSource *pAudioSrc = &ap->mDataSource.u.mSource;
568    const SLDataSink *pAudioSnk = &ap->mDataSink.u.mSink;
569    const SLuint32 sourceLocatorType = *(SLuint32 *)pAudioSrc->pLocator;
570    const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator;
571    AndroidObjectType type = INVALID_TYPE;
572
573    //--------------------------------------
574    // Sink / source matching check:
575    // the following source / sink combinations are supported
576    //     SL_DATALOCATOR_BUFFERQUEUE                / SL_DATALOCATOR_OUTPUTMIX
577    //     SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE   / SL_DATALOCATOR_OUTPUTMIX
578    //     SL_DATALOCATOR_URI                        / SL_DATALOCATOR_OUTPUTMIX
579    //     SL_DATALOCATOR_ANDROIDFD                  / SL_DATALOCATOR_OUTPUTMIX
580    //     SL_DATALOCATOR_ANDROIDBUFFERQUEUE         / SL_DATALOCATOR_OUTPUTMIX
581    //     SL_DATALOCATOR_ANDROIDBUFFERQUEUE         / SL_DATALOCATOR_BUFFERQUEUE
582    //     SL_DATALOCATOR_URI                        / SL_DATALOCATOR_BUFFERQUEUE
583    //     SL_DATALOCATOR_ANDROIDFD                  / SL_DATALOCATOR_BUFFERQUEUE
584    //     SL_DATALOCATOR_URI                        / SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
585    //     SL_DATALOCATOR_ANDROIDFD                  / SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
586    switch (sinkLocatorType) {
587
588    case SL_DATALOCATOR_OUTPUTMIX: {
589        switch (sourceLocatorType) {
590
591        //   Buffer Queue to AudioTrack
592        case SL_DATALOCATOR_BUFFERQUEUE:
593        case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
594            type = AUDIOPLAYER_FROM_PCM_BUFFERQUEUE;
595            break;
596
597        //   URI or FD to MediaPlayer
598        case SL_DATALOCATOR_URI:
599        case SL_DATALOCATOR_ANDROIDFD:
600            type = AUDIOPLAYER_FROM_URIFD;
601            break;
602
603        //   Android BufferQueue to MediaPlayer (shared memory streaming)
604        case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
605            type = AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE;
606            break;
607
608        default:
609            SL_LOGE("Source data locator 0x%x not supported with SL_DATALOCATOR_OUTPUTMIX sink",
610                    (unsigned)sourceLocatorType);
611            break;
612        }
613        }
614        break;
615
616    case SL_DATALOCATOR_BUFFERQUEUE:
617    case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
618        switch (sourceLocatorType) {
619
620        //   URI or FD decoded to PCM in a buffer queue
621        case SL_DATALOCATOR_URI:
622        case SL_DATALOCATOR_ANDROIDFD:
623            type = AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE;
624            break;
625
626        //   AAC ADTS Android buffer queue decoded to PCM in a buffer queue
627        case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
628            type = AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE;
629            break;
630
631        default:
632            SL_LOGE("Source data locator 0x%x not supported with SL_DATALOCATOR_BUFFERQUEUE sink",
633                    (unsigned)sourceLocatorType);
634            break;
635        }
636        break;
637
638    default:
639        SL_LOGE("Sink data locator 0x%x not supported", (unsigned)sinkLocatorType);
640        break;
641    }
642
643    return type;
644}
645
646
647//-----------------------------------------------------------------------------
648/*
649 * Callback associated with an SfPlayer of an SL ES AudioPlayer that gets its data
650 * from a URI or FD, for prepare, prefetch, and play events
651 */
652static void sfplayer_handlePrefetchEvent(int event, int data1, int data2, void* user) {
653
654    // FIXME see similar code and comment in player_handleMediaPlayerEventNotifications
655
656    if (NULL == user) {
657        return;
658    }
659
660    CAudioPlayer *ap = (CAudioPlayer *)user;
661    if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) {
662        // it is not safe to enter the callback (the track is about to go away)
663        return;
664    }
665    union {
666        char c[sizeof(int)];
667        int i;
668    } u;
669    u.i = event;
670    SL_LOGV("sfplayer_handlePrefetchEvent(event='%c%c%c%c' (%d), data1=%d, data2=%d, user=%p) from "
671            "SfAudioPlayer", u.c[3], u.c[2], u.c[1], u.c[0], event, data1, data2, user);
672    switch(event) {
673
674    case android::GenericPlayer::kEventPrepared: {
675        SL_LOGV("Received GenericPlayer::kEventPrepared for CAudioPlayer %p", ap);
676
677        // assume no callback
678        slPrefetchCallback callback = NULL;
679        void* callbackPContext;
680        SLuint32 events;
681
682        object_lock_exclusive(&ap->mObject);
683
684        // mark object as prepared; same state is used for successful or unsuccessful prepare
685        assert(ap->mAndroidObjState == ANDROID_PREPARING);
686        ap->mAndroidObjState = ANDROID_READY;
687
688        if (PLAYER_SUCCESS == data1) {
689            // Most of successful prepare completion for ap->mAPlayer
690            // is handled by GenericPlayer and its subclasses.
691        } else {
692            // SfPlayer prepare() failed prefetching, there is no event in SLPrefetchStatus to
693            //  indicate a prefetch error, so we signal it by sending simultaneously two events:
694            //  - SL_PREFETCHEVENT_FILLLEVELCHANGE with a level of 0
695            //  - SL_PREFETCHEVENT_STATUSCHANGE with a status of SL_PREFETCHSTATUS_UNDERFLOW
696            SL_LOGE(ERROR_PLAYER_PREFETCH_d, data1);
697            if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
698                ap->mPrefetchStatus.mLevel = 0;
699                ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
700                if (!(~ap->mPrefetchStatus.mCallbackEventsMask &
701                        (SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE))) {
702                    callback = ap->mPrefetchStatus.mCallback;
703                    callbackPContext = ap->mPrefetchStatus.mContext;
704                    events = SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE;
705                }
706            }
707        }
708
709        object_unlock_exclusive(&ap->mObject);
710
711        // callback with no lock held
712        if (NULL != callback) {
713            (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext, events);
714        }
715
716    }
717    break;
718
719    case android::GenericPlayer::kEventPrefetchFillLevelUpdate : {
720        if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
721            break;
722        }
723        slPrefetchCallback callback = NULL;
724        void* callbackPContext = NULL;
725
726        // SLPrefetchStatusItf callback or no callback?
727        interface_lock_exclusive(&ap->mPrefetchStatus);
728        if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
729            callback = ap->mPrefetchStatus.mCallback;
730            callbackPContext = ap->mPrefetchStatus.mContext;
731        }
732        ap->mPrefetchStatus.mLevel = (SLpermille)data1;
733        interface_unlock_exclusive(&ap->mPrefetchStatus);
734
735        // callback with no lock held
736        if (NULL != callback) {
737            (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext,
738                    SL_PREFETCHEVENT_FILLLEVELCHANGE);
739        }
740    }
741    break;
742
743    case android::GenericPlayer::kEventPrefetchStatusChange: {
744        if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
745            break;
746        }
747        slPrefetchCallback callback = NULL;
748        void* callbackPContext = NULL;
749
750        // SLPrefetchStatusItf callback or no callback?
751        object_lock_exclusive(&ap->mObject);
752        if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE) {
753            callback = ap->mPrefetchStatus.mCallback;
754            callbackPContext = ap->mPrefetchStatus.mContext;
755        }
756        if (data1 >= android::kStatusIntermediate) {
757            ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA;
758        } else if (data1 < android::kStatusIntermediate) {
759            ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
760        }
761        object_unlock_exclusive(&ap->mObject);
762
763        // callback with no lock held
764        if (NULL != callback) {
765            (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext, SL_PREFETCHEVENT_STATUSCHANGE);
766        }
767        }
768        break;
769
770    case android::GenericPlayer::kEventEndOfStream: {
771        audioPlayer_dispatch_headAtEnd_lockPlay(ap, true /*set state to paused?*/, true);
772        if ((ap->mAudioTrack != 0) && (!ap->mSeek.mLoopEnabled)) {
773            ap->mAudioTrack->stop();
774        }
775        }
776        break;
777
778    case android::GenericPlayer::kEventChannelCount: {
779        object_lock_exclusive(&ap->mObject);
780        if (UNKNOWN_NUMCHANNELS == ap->mNumChannels && UNKNOWN_NUMCHANNELS != data1) {
781            ap->mNumChannels = data1;
782            android_audioPlayer_volumeUpdate(ap);
783        }
784        object_unlock_exclusive(&ap->mObject);
785        }
786        break;
787
788    case android::GenericPlayer::kEventPlay: {
789        slPlayCallback callback = NULL;
790        void* callbackPContext = NULL;
791
792        interface_lock_shared(&ap->mPlay);
793        callback = ap->mPlay.mCallback;
794        callbackPContext = ap->mPlay.mContext;
795        interface_unlock_shared(&ap->mPlay);
796
797        if (NULL != callback) {
798            SLuint32 event = (SLuint32) data1;  // SL_PLAYEVENT_HEAD*
799#ifndef USE_ASYNCHRONOUS_PLAY_CALLBACK
800            // synchronous callback requires a synchronous GetPosition implementation
801            (*callback)(&ap->mPlay.mItf, callbackPContext, event);
802#else
803            // asynchronous callback works with any GetPosition implementation
804            SLresult result = EnqueueAsyncCallback_ppi(ap, callback, &ap->mPlay.mItf,
805                    callbackPContext, event);
806            if (SL_RESULT_SUCCESS != result) {
807                ALOGW("Callback %p(%p, %p, 0x%x) dropped", callback,
808                        &ap->mPlay.mItf, callbackPContext, event);
809            }
810#endif
811        }
812        }
813        break;
814
815      case android::GenericPlayer::kEventErrorAfterPrepare: {
816        SL_LOGV("kEventErrorAfterPrepare");
817
818        // assume no callback
819        slPrefetchCallback callback = NULL;
820        void* callbackPContext = NULL;
821
822        object_lock_exclusive(&ap->mObject);
823        if (IsInterfaceInitialized(&ap->mObject, MPH_PREFETCHSTATUS)) {
824            ap->mPrefetchStatus.mLevel = 0;
825            ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
826            if (!(~ap->mPrefetchStatus.mCallbackEventsMask &
827                    (SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE))) {
828                callback = ap->mPrefetchStatus.mCallback;
829                callbackPContext = ap->mPrefetchStatus.mContext;
830            }
831        }
832        object_unlock_exclusive(&ap->mObject);
833
834        // FIXME there's interesting information in data1, but no API to convey it to client
835        SL_LOGE("Error after prepare: %d", data1);
836
837        // callback with no lock held
838        if (NULL != callback) {
839            (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext,
840                    SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);
841        }
842
843      }
844      break;
845
846    case android::GenericPlayer::kEventHasVideoSize:
847        //SL_LOGW("Unexpected kEventHasVideoSize");
848        break;
849
850    default:
851        break;
852    }
853
854    ap->mCallbackProtector->exitCb();
855}
856
857
858//-----------------------------------------------------------------------------
859SLresult android_audioPlayer_checkSourceSink(CAudioPlayer *pAudioPlayer)
860{
861    // verify that the locator types for the source / sink combination is supported
862    pAudioPlayer->mAndroidObjType = audioPlayer_getAndroidObjectTypeForSourceSink(pAudioPlayer);
863    if (INVALID_TYPE == pAudioPlayer->mAndroidObjType) {
864        return SL_RESULT_PARAMETER_INVALID;
865    }
866
867    const SLDataSource *pAudioSrc = &pAudioPlayer->mDataSource.u.mSource;
868    const SLDataSink *pAudioSnk = &pAudioPlayer->mDataSink.u.mSink;
869
870    // format check:
871    const SLuint32 sourceLocatorType = *(SLuint32 *)pAudioSrc->pLocator;
872    const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator;
873    const SLuint32 sourceFormatType = *(SLuint32 *)pAudioSrc->pFormat;
874    const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSnk->pFormat;
875
876    switch (sourceLocatorType) {
877    //------------------
878    //   Buffer Queues
879    case SL_DATALOCATOR_BUFFERQUEUE:
880    case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
881        {
882        SLDataLocator_BufferQueue *dl_bq = (SLDataLocator_BufferQueue *) pAudioSrc->pLocator;
883
884        // Buffer format
885        switch (sourceFormatType) {
886        //     currently only PCM buffer queues are supported,
887        case SL_DATAFORMAT_PCM: {
888            SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *) pAudioSrc->pFormat;
889            switch (df_pcm->numChannels) {
890            case 1:
891            case 2:
892                break;
893            default:
894                // this should have already been rejected by checkDataFormat
895                SL_LOGE("Cannot create audio player: unsupported " \
896                    "PCM data source with %u channels", (unsigned) df_pcm->numChannels);
897                return SL_RESULT_CONTENT_UNSUPPORTED;
898            }
899            switch (df_pcm->samplesPerSec) {
900            case SL_SAMPLINGRATE_8:
901            case SL_SAMPLINGRATE_11_025:
902            case SL_SAMPLINGRATE_12:
903            case SL_SAMPLINGRATE_16:
904            case SL_SAMPLINGRATE_22_05:
905            case SL_SAMPLINGRATE_24:
906            case SL_SAMPLINGRATE_32:
907            case SL_SAMPLINGRATE_44_1:
908            case SL_SAMPLINGRATE_48:
909                break;
910            case SL_SAMPLINGRATE_64:
911            case SL_SAMPLINGRATE_88_2:
912            case SL_SAMPLINGRATE_96:
913            case SL_SAMPLINGRATE_192:
914            default:
915                SL_LOGE("Cannot create audio player: unsupported sample rate %u milliHz",
916                    (unsigned) df_pcm->samplesPerSec);
917                return SL_RESULT_CONTENT_UNSUPPORTED;
918            }
919            switch (df_pcm->bitsPerSample) {
920            case SL_PCMSAMPLEFORMAT_FIXED_8:
921            case SL_PCMSAMPLEFORMAT_FIXED_16:
922                break;
923                // others
924            default:
925                // this should have already been rejected by checkDataFormat
926                SL_LOGE("Cannot create audio player: unsupported sample bit depth %u",
927                        (SLuint32)df_pcm->bitsPerSample);
928                return SL_RESULT_CONTENT_UNSUPPORTED;
929            }
930            switch (df_pcm->containerSize) {
931            case 8:
932            case 16:
933                break;
934                // others
935            default:
936                SL_LOGE("Cannot create audio player: unsupported container size %u",
937                    (unsigned) df_pcm->containerSize);
938                return SL_RESULT_CONTENT_UNSUPPORTED;
939            }
940            // df_pcm->channelMask: the earlier platform-independent check and the
941            //     upcoming check by sles_to_android_channelMaskOut are sufficient
942            switch (df_pcm->endianness) {
943            case SL_BYTEORDER_LITTLEENDIAN:
944                break;
945            case SL_BYTEORDER_BIGENDIAN:
946                SL_LOGE("Cannot create audio player: unsupported big-endian byte order");
947                return SL_RESULT_CONTENT_UNSUPPORTED;
948                // native is proposed but not yet in spec
949            default:
950                SL_LOGE("Cannot create audio player: unsupported byte order %u",
951                    (unsigned) df_pcm->endianness);
952                return SL_RESULT_CONTENT_UNSUPPORTED;
953            }
954            } //case SL_DATAFORMAT_PCM
955            break;
956        case SL_DATAFORMAT_MIME:
957        case XA_DATAFORMAT_RAWIMAGE:
958            SL_LOGE("Cannot create audio player with buffer queue data source "
959                "without SL_DATAFORMAT_PCM format");
960            return SL_RESULT_CONTENT_UNSUPPORTED;
961        default:
962            // invalid data format is detected earlier
963            assert(false);
964            return SL_RESULT_INTERNAL_ERROR;
965        } // switch (sourceFormatType)
966        } // case SL_DATALOCATOR_BUFFERQUEUE or SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
967        break;
968    //------------------
969    //   URI
970    case SL_DATALOCATOR_URI:
971        {
972        SLDataLocator_URI *dl_uri = (SLDataLocator_URI *) pAudioSrc->pLocator;
973        if (NULL == dl_uri->URI) {
974            return SL_RESULT_PARAMETER_INVALID;
975        }
976        // URI format
977        switch (sourceFormatType) {
978        case SL_DATAFORMAT_MIME:
979            break;
980        case SL_DATAFORMAT_PCM:
981        case XA_DATAFORMAT_RAWIMAGE:
982            SL_LOGE("Cannot create audio player with SL_DATALOCATOR_URI data source without "
983                "SL_DATAFORMAT_MIME format");
984            return SL_RESULT_CONTENT_UNSUPPORTED;
985        } // switch (sourceFormatType)
986        // decoding format check
987        if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) &&
988                !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) {
989            return SL_RESULT_CONTENT_UNSUPPORTED;
990        }
991        } // case SL_DATALOCATOR_URI
992        break;
993    //------------------
994    //   File Descriptor
995    case SL_DATALOCATOR_ANDROIDFD:
996        {
997        // fd is already non null
998        switch (sourceFormatType) {
999        case SL_DATAFORMAT_MIME:
1000            break;
1001        case SL_DATAFORMAT_PCM:
1002            // FIXME implement
1003            SL_LOGD("[ FIXME implement PCM FD data sources ]");
1004            break;
1005        case XA_DATAFORMAT_RAWIMAGE:
1006            SL_LOGE("Cannot create audio player with SL_DATALOCATOR_ANDROIDFD data source "
1007                "without SL_DATAFORMAT_MIME or SL_DATAFORMAT_PCM format");
1008            return SL_RESULT_CONTENT_UNSUPPORTED;
1009        default:
1010            // invalid data format is detected earlier
1011            assert(false);
1012            return SL_RESULT_INTERNAL_ERROR;
1013        } // switch (sourceFormatType)
1014        if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) &&
1015                !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) {
1016            return SL_RESULT_CONTENT_UNSUPPORTED;
1017        }
1018        } // case SL_DATALOCATOR_ANDROIDFD
1019        break;
1020    //------------------
1021    //   Stream
1022    case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
1023    {
1024        switch (sourceFormatType) {
1025        case SL_DATAFORMAT_MIME:
1026        {
1027            SLDataFormat_MIME *df_mime = (SLDataFormat_MIME *) pAudioSrc->pFormat;
1028            if (NULL == df_mime) {
1029                SL_LOGE("MIME type null invalid");
1030                return SL_RESULT_CONTENT_UNSUPPORTED;
1031            }
1032            SL_LOGD("source MIME is %s", (char*)df_mime->mimeType);
1033            switch(df_mime->containerType) {
1034            case SL_CONTAINERTYPE_MPEG_TS:
1035                if (strcasecmp((char*)df_mime->mimeType, (const char *)XA_ANDROID_MIME_MP2TS)) {
1036                    SL_LOGE("Invalid MIME (%s) for container SL_CONTAINERTYPE_MPEG_TS, expects %s",
1037                            (char*)df_mime->mimeType, XA_ANDROID_MIME_MP2TS);
1038                    return SL_RESULT_CONTENT_UNSUPPORTED;
1039                }
1040                if (pAudioPlayer->mAndroidObjType != AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE) {
1041                    SL_LOGE("Invalid sink for container SL_CONTAINERTYPE_MPEG_TS");
1042                    return SL_RESULT_PARAMETER_INVALID;
1043                }
1044                break;
1045            case SL_CONTAINERTYPE_RAW:
1046            case SL_CONTAINERTYPE_AAC:
1047                if (strcasecmp((char*)df_mime->mimeType, (const char *)SL_ANDROID_MIME_AACADTS) &&
1048                        strcasecmp((char*)df_mime->mimeType,
1049                                ANDROID_MIME_AACADTS_ANDROID_FRAMEWORK)) {
1050                    SL_LOGE("Invalid MIME (%s) for container type %d, expects %s",
1051                            (char*)df_mime->mimeType, df_mime->containerType,
1052                            SL_ANDROID_MIME_AACADTS);
1053                    return SL_RESULT_CONTENT_UNSUPPORTED;
1054                }
1055                if (pAudioPlayer->mAndroidObjType != AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE) {
1056                    SL_LOGE("Invalid sink for container SL_CONTAINERTYPE_AAC");
1057                    return SL_RESULT_PARAMETER_INVALID;
1058                }
1059                break;
1060            default:
1061                SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
1062                                        "that is not fed MPEG-2 TS data or AAC ADTS data");
1063                return SL_RESULT_CONTENT_UNSUPPORTED;
1064            }
1065        }
1066        break;
1067        default:
1068            SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
1069                    "without SL_DATAFORMAT_MIME format");
1070            return SL_RESULT_CONTENT_UNSUPPORTED;
1071        }
1072    }
1073    break; // case SL_DATALOCATOR_ANDROIDBUFFERQUEUE
1074    //------------------
1075    //   Address
1076    case SL_DATALOCATOR_ADDRESS:
1077    case SL_DATALOCATOR_IODEVICE:
1078    case SL_DATALOCATOR_OUTPUTMIX:
1079    case XA_DATALOCATOR_NATIVEDISPLAY:
1080    case SL_DATALOCATOR_MIDIBUFFERQUEUE:
1081        SL_LOGE("Cannot create audio player with data locator type 0x%x",
1082                (unsigned) sourceLocatorType);
1083        return SL_RESULT_CONTENT_UNSUPPORTED;
1084    default:
1085        SL_LOGE("Cannot create audio player with invalid data locator type 0x%x",
1086                (unsigned) sourceLocatorType);
1087        return SL_RESULT_PARAMETER_INVALID;
1088    }// switch (locatorType)
1089
1090    return SL_RESULT_SUCCESS;
1091}
1092
1093
1094//-----------------------------------------------------------------------------
1095// Callback associated with an AudioTrack of an SL ES AudioPlayer that gets its data
1096// from a buffer queue. This will not be called once the AudioTrack has been destroyed.
1097static void audioTrack_callBack_pullFromBuffQueue(int event, void* user, void *info) {
1098    CAudioPlayer *ap = (CAudioPlayer *)user;
1099
1100    if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) {
1101        // it is not safe to enter the callback (the track is about to go away)
1102        return;
1103    }
1104
1105    void * callbackPContext = NULL;
1106    switch(event) {
1107
1108    case android::AudioTrack::EVENT_MORE_DATA: {
1109        //SL_LOGV("received event EVENT_MORE_DATA from AudioTrack TID=%d", gettid());
1110        slBufferQueueCallback callback = NULL;
1111        slPrefetchCallback prefetchCallback = NULL;
1112        void *prefetchContext = NULL;
1113        SLuint32 prefetchEvents = SL_PREFETCHEVENT_NONE;
1114        android::AudioTrack::Buffer* pBuff = (android::AudioTrack::Buffer*)info;
1115
1116        // retrieve data from the buffer queue
1117        interface_lock_exclusive(&ap->mBufferQueue);
1118
1119        if (ap->mBufferQueue.mState.count != 0) {
1120            //SL_LOGV("nbBuffers in queue = %u",ap->mBufferQueue.mState.count);
1121            assert(ap->mBufferQueue.mFront != ap->mBufferQueue.mRear);
1122
1123            BufferHeader *oldFront = ap->mBufferQueue.mFront;
1124            BufferHeader *newFront = &oldFront[1];
1125
1126            // declared as void * because this code supports both 8-bit and 16-bit PCM data
1127            void *pSrc = (char *)oldFront->mBuffer + ap->mBufferQueue.mSizeConsumed;
1128            if (ap->mBufferQueue.mSizeConsumed + pBuff->size < oldFront->mSize) {
1129                // can't consume the whole or rest of the buffer in one shot
1130                ap->mBufferQueue.mSizeConsumed += pBuff->size;
1131                // leave pBuff->size untouched
1132                // consume data
1133                // FIXME can we avoid holding the lock during the copy?
1134                memcpy (pBuff->raw, pSrc, pBuff->size);
1135            } else {
1136                // finish consuming the buffer or consume the buffer in one shot
1137                pBuff->size = oldFront->mSize - ap->mBufferQueue.mSizeConsumed;
1138                ap->mBufferQueue.mSizeConsumed = 0;
1139
1140                if (newFront ==
1141                        &ap->mBufferQueue.mArray
1142                            [ap->mBufferQueue.mNumBuffers + 1])
1143                {
1144                    newFront = ap->mBufferQueue.mArray;
1145                }
1146                ap->mBufferQueue.mFront = newFront;
1147
1148                ap->mBufferQueue.mState.count--;
1149                ap->mBufferQueue.mState.playIndex++;
1150
1151                // consume data
1152                // FIXME can we avoid holding the lock during the copy?
1153                memcpy (pBuff->raw, pSrc, pBuff->size);
1154
1155                // data has been consumed, and the buffer queue state has been updated
1156                // we will notify the client if applicable
1157                callback = ap->mBufferQueue.mCallback;
1158                // save callback data
1159                callbackPContext = ap->mBufferQueue.mContext;
1160            }
1161        } else { // empty queue
1162            // signal no data available
1163            pBuff->size = 0;
1164
1165            // signal we're at the end of the content, but don't pause (see note in function)
1166            audioPlayer_dispatch_headAtEnd_lockPlay(ap, false /*set state to paused?*/, false);
1167
1168            // signal underflow to prefetch status itf
1169            if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
1170                ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
1171                ap->mPrefetchStatus.mLevel = 0;
1172                // callback or no callback?
1173                prefetchEvents = ap->mPrefetchStatus.mCallbackEventsMask &
1174                        (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE);
1175                if (SL_PREFETCHEVENT_NONE != prefetchEvents) {
1176                    prefetchCallback = ap->mPrefetchStatus.mCallback;
1177                    prefetchContext  = ap->mPrefetchStatus.mContext;
1178                }
1179            }
1180
1181            // stop the track so it restarts playing faster when new data is enqueued
1182            ap->mAudioTrack->stop();
1183        }
1184        interface_unlock_exclusive(&ap->mBufferQueue);
1185
1186        // notify client
1187        if (NULL != prefetchCallback) {
1188            assert(SL_PREFETCHEVENT_NONE != prefetchEvents);
1189            // spec requires separate callbacks for each event
1190            if (prefetchEvents & SL_PREFETCHEVENT_STATUSCHANGE) {
1191                (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext,
1192                        SL_PREFETCHEVENT_STATUSCHANGE);
1193            }
1194            if (prefetchEvents & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
1195                (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext,
1196                        SL_PREFETCHEVENT_FILLLEVELCHANGE);
1197            }
1198        }
1199        if (NULL != callback) {
1200            (*callback)(&ap->mBufferQueue.mItf, callbackPContext);
1201        }
1202    }
1203    break;
1204
1205    case android::AudioTrack::EVENT_MARKER:
1206        //SL_LOGI("received event EVENT_MARKER from AudioTrack");
1207        audioTrack_handleMarker_lockPlay(ap);
1208        break;
1209
1210    case android::AudioTrack::EVENT_NEW_POS:
1211        //SL_LOGI("received event EVENT_NEW_POS from AudioTrack");
1212        audioTrack_handleNewPos_lockPlay(ap);
1213        break;
1214
1215    case android::AudioTrack::EVENT_UNDERRUN:
1216        //SL_LOGI("received event EVENT_UNDERRUN from AudioTrack");
1217        audioTrack_handleUnderrun_lockPlay(ap);
1218        break;
1219
1220    case android::AudioTrack::EVENT_BUFFER_END:
1221    case android::AudioTrack::EVENT_LOOP_END:
1222        // These are unexpected so fall through
1223    default:
1224        // FIXME where does the notification of SL_PLAYEVENT_HEADMOVING fit?
1225        SL_LOGE("Encountered unknown AudioTrack event %d for CAudioPlayer %p", event,
1226                (CAudioPlayer *)user);
1227        break;
1228    }
1229
1230    ap->mCallbackProtector->exitCb();
1231}
1232
1233
1234//-----------------------------------------------------------------------------
1235void android_audioPlayer_create(CAudioPlayer *pAudioPlayer) {
1236
1237    // pAudioPlayer->mAndroidObjType has been set in android_audioPlayer_checkSourceSink()
1238    // and if it was == INVALID_TYPE, then IEngine_CreateAudioPlayer would never call us
1239    assert(INVALID_TYPE != pAudioPlayer->mAndroidObjType);
1240
1241    // These initializations are in the same order as the field declarations in classes.h
1242
1243    // FIXME Consolidate initializations (many of these already in IEngine_CreateAudioPlayer)
1244    // mAndroidObjType: see above comment
1245    pAudioPlayer->mAndroidObjState = ANDROID_UNINITIALIZED;
1246    pAudioPlayer->mSessionId = android::AudioSystem::newAudioSessionId();
1247
1248    // placeholder: not necessary yet as session ID lifetime doesn't extend beyond player
1249    // android::AudioSystem::acquireAudioSessionId(pAudioPlayer->mSessionId);
1250
1251    pAudioPlayer->mStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
1252
1253    // mAudioTrack
1254    pAudioPlayer->mCallbackProtector = new android::CallbackProtector();
1255    // mAPLayer
1256    // mAuxEffect
1257
1258    pAudioPlayer->mAuxSendLevel = 0;
1259    pAudioPlayer->mAmplFromDirectLevel = 1.0f; // matches initial mDirectLevel value
1260    pAudioPlayer->mDeferredStart = false;
1261
1262    // This section re-initializes interface-specific fields that
1263    // can be set or used regardless of whether the interface is
1264    // exposed on the AudioPlayer or not
1265
1266    switch (pAudioPlayer->mAndroidObjType) {
1267    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1268        pAudioPlayer->mPlaybackRate.mMinRate = AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE;
1269        pAudioPlayer->mPlaybackRate.mMaxRate = AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE;
1270        break;
1271    case AUDIOPLAYER_FROM_URIFD:
1272        pAudioPlayer->mPlaybackRate.mMinRate = MEDIAPLAYER_MIN_PLAYBACKRATE_PERMILLE;
1273        pAudioPlayer->mPlaybackRate.mMaxRate = MEDIAPLAYER_MAX_PLAYBACKRATE_PERMILLE;
1274        break;
1275    default:
1276        // use the default range
1277        break;
1278    }
1279
1280}
1281
1282
1283//-----------------------------------------------------------------------------
1284SLresult android_audioPlayer_setConfig(CAudioPlayer *ap, const SLchar *configKey,
1285        const void *pConfigValue, SLuint32 valueSize) {
1286
1287    SLresult result;
1288
1289    assert(NULL != ap && NULL != configKey && NULL != pConfigValue);
1290    if (strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) {
1291
1292        // stream type
1293        if (KEY_STREAM_TYPE_PARAMSIZE > valueSize) {
1294            SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1295            result = SL_RESULT_BUFFER_INSUFFICIENT;
1296        } else {
1297            result = audioPlayer_setStreamType(ap, *(SLuint32*)pConfigValue);
1298        }
1299
1300    } else {
1301        SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY);
1302        result = SL_RESULT_PARAMETER_INVALID;
1303    }
1304
1305    return result;
1306}
1307
1308
1309//-----------------------------------------------------------------------------
1310SLresult android_audioPlayer_getConfig(CAudioPlayer* ap, const SLchar *configKey,
1311        SLuint32* pValueSize, void *pConfigValue) {
1312
1313    SLresult result;
1314
1315    assert(NULL != ap && NULL != configKey && NULL != pValueSize);
1316    if (strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) {
1317
1318        // stream type
1319        if (NULL == pConfigValue) {
1320            result = SL_RESULT_SUCCESS;
1321        } else if (KEY_STREAM_TYPE_PARAMSIZE > *pValueSize) {
1322            SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1323            result = SL_RESULT_BUFFER_INSUFFICIENT;
1324        } else {
1325            result = audioPlayer_getStreamType(ap, (SLint32*)pConfigValue);
1326        }
1327        *pValueSize = KEY_STREAM_TYPE_PARAMSIZE;
1328
1329    } else {
1330        SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY);
1331        result = SL_RESULT_PARAMETER_INVALID;
1332    }
1333
1334    return result;
1335}
1336
1337
1338// Called from android_audioPlayer_realize for a PCM buffer queue player
1339// to determine if it can use a fast track.
1340static bool canUseFastTrack(CAudioPlayer *pAudioPlayer)
1341{
1342    assert(pAudioPlayer->mAndroidObjType == AUDIOPLAYER_FROM_PCM_BUFFERQUEUE);
1343
1344    // no need to check the buffer queue size, application side
1345    // double-buffering (and more) is not a requirement for using fast tracks
1346
1347    // Check a blacklist of interfaces that are incompatible with fast tracks.
1348    // The alternative, to check a whitelist of compatible interfaces, is
1349    // more maintainable but is too slow.  As a compromise, in a debug build
1350    // we use both methods and warn if they produce different results.
1351    // In release builds, we only use the blacklist method.
1352    // If a blacklisted interface is added after realization using
1353    // DynamicInterfaceManagement::AddInterface,
1354    // then this won't be detected but the interface will be ineffective.
1355    bool blacklistResult = true;
1356    static const unsigned blacklist[] = {
1357        MPH_BASSBOOST,
1358        MPH_EFFECTSEND,
1359        MPH_ENVIRONMENTALREVERB,
1360        MPH_EQUALIZER,
1361        MPH_PLAYBACKRATE,
1362        MPH_PRESETREVERB,
1363        MPH_VIRTUALIZER,
1364        MPH_ANDROIDEFFECT,
1365        MPH_ANDROIDEFFECTSEND,
1366        // FIXME The problem with a blacklist is remembering to add new interfaces here
1367    };
1368    for (unsigned i = 0; i < sizeof(blacklist)/sizeof(blacklist[0]); ++i) {
1369        if (IsInterfaceInitialized(&pAudioPlayer->mObject, blacklist[i])) {
1370            blacklistResult = false;
1371            break;
1372        }
1373    }
1374#if LOG_NDEBUG == 0
1375    bool whitelistResult = true;
1376    static const unsigned whitelist[] = {
1377        MPH_BUFFERQUEUE,
1378        MPH_DYNAMICINTERFACEMANAGEMENT,
1379        MPH_METADATAEXTRACTION,
1380        MPH_MUTESOLO,
1381        MPH_OBJECT,
1382        MPH_PLAY,
1383        MPH_PREFETCHSTATUS,
1384        MPH_VOLUME,
1385        MPH_ANDROIDCONFIGURATION,
1386        MPH_ANDROIDSIMPLEBUFFERQUEUE,
1387        MPH_ANDROIDBUFFERQUEUESOURCE,
1388    };
1389    for (unsigned mph = MPH_MIN; mph < MPH_MAX; ++mph) {
1390        for (unsigned i = 0; i < sizeof(whitelist)/sizeof(whitelist[0]); ++i) {
1391            if (mph == whitelist[i]) {
1392                goto compatible;
1393            }
1394        }
1395        if (IsInterfaceInitialized(&pAudioPlayer->mObject, mph)) {
1396            whitelistResult = false;
1397            break;
1398        }
1399compatible: ;
1400    }
1401    if (whitelistResult != blacklistResult) {
1402        ALOGW("whitelistResult != blacklistResult");
1403        // and use blacklistResult below
1404    }
1405#endif
1406    return blacklistResult;
1407}
1408
1409
1410//-----------------------------------------------------------------------------
1411// FIXME abstract out the diff between CMediaPlayer and CAudioPlayer
1412SLresult android_audioPlayer_realize(CAudioPlayer *pAudioPlayer, SLboolean async) {
1413
1414    SLresult result = SL_RESULT_SUCCESS;
1415    SL_LOGV("Realize pAudioPlayer=%p", pAudioPlayer);
1416
1417    AudioPlayback_Parameters app;
1418    app.sessionId = pAudioPlayer->mSessionId;
1419    app.streamType = pAudioPlayer->mStreamType;
1420
1421    switch (pAudioPlayer->mAndroidObjType) {
1422
1423    //-----------------------------------
1424    // AudioTrack
1425    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1426        {
1427        // initialize platform-specific CAudioPlayer fields
1428
1429        SLDataLocator_BufferQueue *dl_bq = (SLDataLocator_BufferQueue *)
1430                pAudioPlayer->mDynamicSource.mDataSource;
1431        SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *)
1432                pAudioPlayer->mDynamicSource.mDataSource->pFormat;
1433
1434        uint32_t sampleRate = sles_to_android_sampleRate(df_pcm->samplesPerSec);
1435
1436        audio_output_flags_t policy;
1437        if (canUseFastTrack(pAudioPlayer)) {
1438            policy = AUDIO_OUTPUT_FLAG_FAST;
1439        } else {
1440            policy = AUDIO_OUTPUT_FLAG_NONE;
1441        }
1442
1443        pAudioPlayer->mAudioTrack = new android::AudioTrack(
1444                pAudioPlayer->mStreamType,                           // streamType
1445                sampleRate,                                          // sampleRate
1446                sles_to_android_sampleFormat(df_pcm->bitsPerSample), // format
1447                sles_to_android_channelMaskOut(df_pcm->numChannels, df_pcm->channelMask),
1448                                                                     // channel mask
1449                0,                                                   // frameCount
1450                policy,                                              // flags
1451                audioTrack_callBack_pullFromBuffQueue,               // callback
1452                (void *) pAudioPlayer,                               // user
1453                0,     // FIXME find appropriate frame count         // notificationFrame
1454                pAudioPlayer->mSessionId);
1455        android::status_t status = pAudioPlayer->mAudioTrack->initCheck();
1456        if (status != android::NO_ERROR) {
1457            SL_LOGE("AudioTrack::initCheck status %u", status);
1458            result = SL_RESULT_CONTENT_UNSUPPORTED;
1459            pAudioPlayer->mAudioTrack.clear();
1460            return result;
1461        }
1462
1463        // initialize platform-independent CAudioPlayer fields
1464
1465        pAudioPlayer->mNumChannels = df_pcm->numChannels;
1466        pAudioPlayer->mSampleRateMilliHz = df_pcm->samplesPerSec; // Note: bad field name in SL ES
1467
1468        // This use case does not have a separate "prepare" step
1469        pAudioPlayer->mAndroidObjState = ANDROID_READY;
1470        }
1471        break;
1472
1473    //-----------------------------------
1474    // MediaPlayer
1475    case AUDIOPLAYER_FROM_URIFD: {
1476        pAudioPlayer->mAPlayer = new android::LocAVPlayer(&app, false /*hasVideo*/);
1477        pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent,
1478                        (void*)pAudioPlayer /*notifUSer*/);
1479
1480        switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) {
1481            case SL_DATALOCATOR_URI: {
1482                // The legacy implementation ran Stagefright within the application process, and
1483                // so allowed local pathnames specified by URI that were openable by
1484                // the application but were not openable by mediaserver.
1485                // The current implementation runs Stagefright (mostly) within mediaserver,
1486                // which runs as a different UID and likely a different current working directory.
1487                // For backwards compatibility with any applications which may have relied on the
1488                // previous behavior, we convert an openable file URI into an FD.
1489                // Note that unlike SL_DATALOCATOR_ANDROIDFD, this FD is owned by us
1490                // and so we close it as soon as we've passed it (via Binder dup) to mediaserver.
1491                const char *uri = (const char *)pAudioPlayer->mDataSource.mLocator.mURI.URI;
1492                if (!isDistantProtocol(uri)) {
1493                    // don't touch the original uri, we may need it later
1494                    const char *pathname = uri;
1495                    // skip over an optional leading file:// prefix
1496                    if (!strncasecmp(pathname, "file://", 7)) {
1497                        pathname += 7;
1498                    }
1499                    // attempt to open it as a file using the application's credentials
1500                    int fd = ::open(pathname, O_RDONLY);
1501                    if (fd >= 0) {
1502                        // if open is successful, then check to see if it's a regular file
1503                        struct stat statbuf;
1504                        if (!::fstat(fd, &statbuf) && S_ISREG(statbuf.st_mode)) {
1505                            // treat similarly to an FD data locator, but
1506                            // let setDataSource take responsibility for closing fd
1507                            pAudioPlayer->mAPlayer->setDataSource(fd, 0, statbuf.st_size, true);
1508                            break;
1509                        }
1510                        // we were able to open it, but it's not a file, so let mediaserver try
1511                        (void) ::close(fd);
1512                    }
1513                }
1514                // if either the URI didn't look like a file, or open failed, or not a file
1515                pAudioPlayer->mAPlayer->setDataSource(uri);
1516                } break;
1517            case SL_DATALOCATOR_ANDROIDFD: {
1518                int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset;
1519                pAudioPlayer->mAPlayer->setDataSource(
1520                        (int)pAudioPlayer->mDataSource.mLocator.mFD.fd,
1521                        offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
1522                                (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
1523                        (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length);
1524                }
1525                break;
1526            default:
1527                SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR);
1528                break;
1529        }
1530
1531        }
1532        break;
1533
1534    //-----------------------------------
1535    // StreamPlayer
1536    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: {
1537        android::StreamPlayer* splr = new android::StreamPlayer(&app, false /*hasVideo*/,
1538                &pAudioPlayer->mAndroidBufferQueue, pAudioPlayer->mCallbackProtector);
1539        pAudioPlayer->mAPlayer = splr;
1540        splr->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1541        }
1542        break;
1543
1544    //-----------------------------------
1545    // AudioToCbRenderer
1546    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
1547        android::AudioToCbRenderer* decoder = new android::AudioToCbRenderer(&app);
1548        pAudioPlayer->mAPlayer = decoder;
1549        // configures the callback for the sink buffer queue
1550        decoder->setDataPushListener(adecoder_writeToBufferQueue, pAudioPlayer);
1551        // configures the callback for the notifications coming from the SF code
1552        decoder->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1553
1554        switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) {
1555        case SL_DATALOCATOR_URI:
1556            decoder->setDataSource(
1557                    (const char*)pAudioPlayer->mDataSource.mLocator.mURI.URI);
1558            break;
1559        case SL_DATALOCATOR_ANDROIDFD: {
1560            int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset;
1561            decoder->setDataSource(
1562                    (int)pAudioPlayer->mDataSource.mLocator.mFD.fd,
1563                    offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
1564                            (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
1565                            (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length);
1566            }
1567            break;
1568        default:
1569            SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR);
1570            break;
1571        }
1572
1573        }
1574        break;
1575
1576    //-----------------------------------
1577    // AacBqToPcmCbRenderer
1578    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
1579        android::AacBqToPcmCbRenderer* bqtobq = new android::AacBqToPcmCbRenderer(&app,
1580                &pAudioPlayer->mAndroidBufferQueue);
1581        // configures the callback for the sink buffer queue
1582        bqtobq->setDataPushListener(adecoder_writeToBufferQueue, pAudioPlayer);
1583        pAudioPlayer->mAPlayer = bqtobq;
1584        // configures the callback for the notifications coming from the SF code,
1585        // but also implicitly configures the AndroidBufferQueue from which ADTS data is read
1586        pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1587        }
1588        break;
1589
1590    //-----------------------------------
1591    default:
1592        SL_LOGE(ERROR_PLAYERREALIZE_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType);
1593        result = SL_RESULT_INTERNAL_ERROR;
1594        break;
1595    }
1596
1597    // proceed with effect initialization
1598    // initialize EQ
1599    // FIXME use a table of effect descriptors when adding support for more effects
1600    if (memcmp(SL_IID_EQUALIZER, &pAudioPlayer->mEqualizer.mEqDescriptor.type,
1601            sizeof(effect_uuid_t)) == 0) {
1602        SL_LOGV("Need to initialize EQ for AudioPlayer=%p", pAudioPlayer);
1603        android_eq_init(pAudioPlayer->mSessionId, &pAudioPlayer->mEqualizer);
1604    }
1605    // initialize BassBoost
1606    if (memcmp(SL_IID_BASSBOOST, &pAudioPlayer->mBassBoost.mBassBoostDescriptor.type,
1607            sizeof(effect_uuid_t)) == 0) {
1608        SL_LOGV("Need to initialize BassBoost for AudioPlayer=%p", pAudioPlayer);
1609        android_bb_init(pAudioPlayer->mSessionId, &pAudioPlayer->mBassBoost);
1610    }
1611    // initialize Virtualizer
1612    if (memcmp(SL_IID_VIRTUALIZER, &pAudioPlayer->mVirtualizer.mVirtualizerDescriptor.type,
1613               sizeof(effect_uuid_t)) == 0) {
1614        SL_LOGV("Need to initialize Virtualizer for AudioPlayer=%p", pAudioPlayer);
1615        android_virt_init(pAudioPlayer->mSessionId, &pAudioPlayer->mVirtualizer);
1616    }
1617
1618    // initialize EffectSend
1619    // FIXME initialize EffectSend
1620
1621    return result;
1622}
1623
1624
1625//-----------------------------------------------------------------------------
1626/**
1627 * Called with a lock on AudioPlayer, and blocks until safe to destroy
1628 */
1629SLresult android_audioPlayer_preDestroy(CAudioPlayer *pAudioPlayer) {
1630    SL_LOGD("android_audioPlayer_preDestroy(%p)", pAudioPlayer);
1631    SLresult result = SL_RESULT_SUCCESS;
1632
1633    bool disableCallbacksBeforePreDestroy;
1634    switch (pAudioPlayer->mAndroidObjType) {
1635    // Not yet clear why this order is important, but it reduces detected deadlocks
1636    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1637        disableCallbacksBeforePreDestroy = true;
1638        break;
1639    // Use the old behavior for all other use cases until proven
1640    // case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1641    default:
1642        disableCallbacksBeforePreDestroy = false;
1643        break;
1644    }
1645
1646    if (disableCallbacksBeforePreDestroy) {
1647        object_unlock_exclusive(&pAudioPlayer->mObject);
1648        if (pAudioPlayer->mCallbackProtector != 0) {
1649            pAudioPlayer->mCallbackProtector->requestCbExitAndWait();
1650        }
1651        object_lock_exclusive(&pAudioPlayer->mObject);
1652    }
1653
1654    if (pAudioPlayer->mAPlayer != 0) {
1655        pAudioPlayer->mAPlayer->preDestroy();
1656    }
1657    SL_LOGD("android_audioPlayer_preDestroy(%p) after mAPlayer->preDestroy()", pAudioPlayer);
1658
1659    if (!disableCallbacksBeforePreDestroy) {
1660        object_unlock_exclusive(&pAudioPlayer->mObject);
1661        if (pAudioPlayer->mCallbackProtector != 0) {
1662            pAudioPlayer->mCallbackProtector->requestCbExitAndWait();
1663        }
1664        object_lock_exclusive(&pAudioPlayer->mObject);
1665    }
1666
1667    return result;
1668}
1669
1670
1671//-----------------------------------------------------------------------------
1672SLresult android_audioPlayer_destroy(CAudioPlayer *pAudioPlayer) {
1673    SLresult result = SL_RESULT_SUCCESS;
1674    SL_LOGV("android_audioPlayer_destroy(%p)", pAudioPlayer);
1675    switch (pAudioPlayer->mAndroidObjType) {
1676
1677    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1678        // We own the audio track for PCM buffer queue players
1679        if (pAudioPlayer->mAudioTrack != 0) {
1680            pAudioPlayer->mAudioTrack->stop();
1681            // Note that there may still be another reference in post-unlock phase of SetPlayState
1682            pAudioPlayer->mAudioTrack.clear();
1683        }
1684        break;
1685
1686    case AUDIOPLAYER_FROM_URIFD:     // intended fall-through
1687    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:    // intended fall-through
1688    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: // intended fall-through
1689    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1690        pAudioPlayer->mAPlayer.clear();
1691        break;
1692    //-----------------------------------
1693    default:
1694        SL_LOGE(ERROR_PLAYERDESTROY_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType);
1695        result = SL_RESULT_INTERNAL_ERROR;
1696        break;
1697    }
1698
1699    // placeholder: not necessary yet as session ID lifetime doesn't extend beyond player
1700    // android::AudioSystem::releaseAudioSessionId(pAudioPlayer->mSessionId);
1701
1702    pAudioPlayer->mCallbackProtector.clear();
1703
1704    // explicit destructor
1705    pAudioPlayer->mAudioTrack.~sp();
1706    // note that SetPlayState(PLAYING) may still hold a reference
1707    pAudioPlayer->mCallbackProtector.~sp();
1708    pAudioPlayer->mAuxEffect.~sp();
1709    pAudioPlayer->mAPlayer.~sp();
1710
1711    return result;
1712}
1713
1714
1715//-----------------------------------------------------------------------------
1716SLresult android_audioPlayer_setPlaybackRateAndConstraints(CAudioPlayer *ap, SLpermille rate,
1717        SLuint32 constraints) {
1718    SLresult result = SL_RESULT_SUCCESS;
1719    switch(ap->mAndroidObjType) {
1720    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: {
1721        // these asserts were already checked by the platform-independent layer
1722        assert((AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE <= rate) &&
1723                (rate <= AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE));
1724        assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO);
1725        // get the content sample rate
1726        uint32_t contentRate = sles_to_android_sampleRate(ap->mSampleRateMilliHz);
1727        // apply the SL ES playback rate on the AudioTrack as a factor of its content sample rate
1728        if (ap->mAudioTrack != 0) {
1729            ap->mAudioTrack->setSampleRate(contentRate * (rate/1000.0f));
1730        }
1731        }
1732        break;
1733    case AUDIOPLAYER_FROM_URIFD: {
1734        assert((MEDIAPLAYER_MIN_PLAYBACKRATE_PERMILLE <= rate) &&
1735                        (rate <= MEDIAPLAYER_MAX_PLAYBACKRATE_PERMILLE));
1736        assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO);
1737        // apply the SL ES playback rate on the GenericPlayer
1738        if (ap->mAPlayer != 0) {
1739            ap->mAPlayer->setPlaybackRate((int16_t)rate);
1740        }
1741        }
1742        break;
1743
1744    default:
1745        SL_LOGE("Unexpected object type %d", ap->mAndroidObjType);
1746        result = SL_RESULT_FEATURE_UNSUPPORTED;
1747        break;
1748    }
1749    return result;
1750}
1751
1752
1753//-----------------------------------------------------------------------------
1754// precondition
1755//  called with no lock held
1756//  ap != NULL
1757//  pItemCount != NULL
1758SLresult android_audioPlayer_metadata_getItemCount(CAudioPlayer *ap, SLuint32 *pItemCount) {
1759    if (ap->mAPlayer == 0) {
1760        return SL_RESULT_PARAMETER_INVALID;
1761    }
1762    switch(ap->mAndroidObjType) {
1763      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1764      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1765        {
1766            android::AudioSfDecoder* decoder =
1767                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1768            *pItemCount = decoder->getPcmFormatKeyCount();
1769        }
1770        break;
1771      default:
1772        *pItemCount = 0;
1773        break;
1774    }
1775    return SL_RESULT_SUCCESS;
1776}
1777
1778
1779//-----------------------------------------------------------------------------
1780// precondition
1781//  called with no lock held
1782//  ap != NULL
1783//  pKeySize != NULL
1784SLresult android_audioPlayer_metadata_getKeySize(CAudioPlayer *ap,
1785        SLuint32 index, SLuint32 *pKeySize) {
1786    if (ap->mAPlayer == 0) {
1787        return SL_RESULT_PARAMETER_INVALID;
1788    }
1789    SLresult res = SL_RESULT_SUCCESS;
1790    switch(ap->mAndroidObjType) {
1791      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1792      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1793        {
1794            android::AudioSfDecoder* decoder =
1795                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1796            SLuint32 keyNameSize = 0;
1797            if (!decoder->getPcmFormatKeySize(index, &keyNameSize)) {
1798                res = SL_RESULT_PARAMETER_INVALID;
1799            } else {
1800                // *pKeySize is the size of the region used to store the key name AND
1801                //   the information about the key (size, lang, encoding)
1802                *pKeySize = keyNameSize + sizeof(SLMetadataInfo);
1803            }
1804        }
1805        break;
1806      default:
1807        *pKeySize = 0;
1808        res = SL_RESULT_PARAMETER_INVALID;
1809        break;
1810    }
1811    return res;
1812}
1813
1814
1815//-----------------------------------------------------------------------------
1816// precondition
1817//  called with no lock held
1818//  ap != NULL
1819//  pKey != NULL
1820SLresult android_audioPlayer_metadata_getKey(CAudioPlayer *ap,
1821        SLuint32 index, SLuint32 size, SLMetadataInfo *pKey) {
1822    if (ap->mAPlayer == 0) {
1823        return SL_RESULT_PARAMETER_INVALID;
1824    }
1825    SLresult res = SL_RESULT_SUCCESS;
1826    switch(ap->mAndroidObjType) {
1827      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1828      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1829        {
1830            android::AudioSfDecoder* decoder =
1831                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1832            if ((size < sizeof(SLMetadataInfo) ||
1833                    (!decoder->getPcmFormatKeyName(index, size - sizeof(SLMetadataInfo),
1834                            (char*)pKey->data)))) {
1835                res = SL_RESULT_PARAMETER_INVALID;
1836            } else {
1837                // successfully retrieved the key value, update the other fields
1838                pKey->encoding = SL_CHARACTERENCODING_UTF8;
1839                memcpy((char *) pKey->langCountry, "en", 3);
1840                pKey->size = strlen((char*)pKey->data) + 1;
1841            }
1842        }
1843        break;
1844      default:
1845        res = SL_RESULT_PARAMETER_INVALID;
1846        break;
1847    }
1848    return res;
1849}
1850
1851
1852//-----------------------------------------------------------------------------
1853// precondition
1854//  called with no lock held
1855//  ap != NULL
1856//  pValueSize != NULL
1857SLresult android_audioPlayer_metadata_getValueSize(CAudioPlayer *ap,
1858        SLuint32 index, SLuint32 *pValueSize) {
1859    if (ap->mAPlayer == 0) {
1860        return SL_RESULT_PARAMETER_INVALID;
1861    }
1862    SLresult res = SL_RESULT_SUCCESS;
1863    switch(ap->mAndroidObjType) {
1864      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1865      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1866        {
1867            android::AudioSfDecoder* decoder =
1868                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1869            SLuint32 valueSize = 0;
1870            if (!decoder->getPcmFormatValueSize(index, &valueSize)) {
1871                res = SL_RESULT_PARAMETER_INVALID;
1872            } else {
1873                // *pValueSize is the size of the region used to store the key value AND
1874                //   the information about the value (size, lang, encoding)
1875                *pValueSize = valueSize + sizeof(SLMetadataInfo);
1876            }
1877        }
1878        break;
1879      default:
1880          *pValueSize = 0;
1881          res = SL_RESULT_PARAMETER_INVALID;
1882          break;
1883    }
1884    return res;
1885}
1886
1887
1888//-----------------------------------------------------------------------------
1889// precondition
1890//  called with no lock held
1891//  ap != NULL
1892//  pValue != NULL
1893SLresult android_audioPlayer_metadata_getValue(CAudioPlayer *ap,
1894        SLuint32 index, SLuint32 size, SLMetadataInfo *pValue) {
1895    if (ap->mAPlayer == 0) {
1896        return SL_RESULT_PARAMETER_INVALID;
1897    }
1898    SLresult res = SL_RESULT_SUCCESS;
1899    switch(ap->mAndroidObjType) {
1900      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1901      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1902        {
1903            android::AudioSfDecoder* decoder =
1904                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1905            pValue->encoding = SL_CHARACTERENCODING_BINARY;
1906            memcpy((char *) pValue->langCountry, "en", 3); // applicable here?
1907            SLuint32 valueSize = 0;
1908            if ((size < sizeof(SLMetadataInfo)
1909                    || (!decoder->getPcmFormatValueSize(index, &valueSize))
1910                    || (!decoder->getPcmFormatKeyValue(index, size - sizeof(SLMetadataInfo),
1911                            (SLuint32*)pValue->data)))) {
1912                res = SL_RESULT_PARAMETER_INVALID;
1913            } else {
1914                pValue->size = valueSize;
1915            }
1916        }
1917        break;
1918      default:
1919        res = SL_RESULT_PARAMETER_INVALID;
1920        break;
1921    }
1922    return res;
1923}
1924
1925//-----------------------------------------------------------------------------
1926// preconditions
1927//  ap != NULL
1928//  mutex is locked
1929//  play state has changed
1930void android_audioPlayer_setPlayState(CAudioPlayer *ap) {
1931
1932    SLuint32 playState = ap->mPlay.mState;
1933    AndroidObjectState objState = ap->mAndroidObjState;
1934
1935    switch(ap->mAndroidObjType) {
1936    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1937        switch (playState) {
1938        case SL_PLAYSTATE_STOPPED:
1939            SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_STOPPED");
1940            if (ap->mAudioTrack != 0) {
1941                ap->mAudioTrack->stop();
1942            }
1943            break;
1944        case SL_PLAYSTATE_PAUSED:
1945            SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PAUSED");
1946            if (ap->mAudioTrack != 0) {
1947                ap->mAudioTrack->pause();
1948            }
1949            break;
1950        case SL_PLAYSTATE_PLAYING:
1951            SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PLAYING");
1952            if (ap->mAudioTrack != 0) {
1953                // instead of ap->mAudioTrack->start();
1954                ap->mDeferredStart = true;
1955            }
1956            break;
1957        default:
1958            // checked by caller, should not happen
1959            break;
1960        }
1961        break;
1962
1963    case AUDIOPLAYER_FROM_URIFD:      // intended fall-through
1964    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:     // intended fall-through
1965    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:  // intended fall-through
1966    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1967        // FIXME report and use the return code to the lock mechanism, which is where play state
1968        //   changes are updated (see object_unlock_exclusive_attributes())
1969        aplayer_setPlayState(ap->mAPlayer, playState, &(ap->mAndroidObjState));
1970        break;
1971    default:
1972        SL_LOGE(ERROR_PLAYERSETPLAYSTATE_UNEXPECTED_OBJECT_TYPE_D, ap->mAndroidObjType);
1973        break;
1974    }
1975}
1976
1977
1978//-----------------------------------------------------------------------------
1979// call when either player event flags, marker position, or position update period changes
1980void android_audioPlayer_usePlayEventMask(CAudioPlayer *ap) {
1981    IPlay *pPlayItf = &ap->mPlay;
1982    SLuint32 eventFlags = pPlayItf->mEventFlags;
1983    /*switch(ap->mAndroidObjType) {
1984    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:*/
1985
1986    if (ap->mAPlayer != 0) {
1987        assert(ap->mAudioTrack == 0);
1988        ap->mAPlayer->setPlayEvents((int32_t) eventFlags, (int32_t) pPlayItf->mMarkerPosition,
1989                (int32_t) pPlayItf->mPositionUpdatePeriod);
1990        return;
1991    }
1992
1993    if (ap->mAudioTrack == 0) {
1994        return;
1995    }
1996
1997    if (eventFlags & SL_PLAYEVENT_HEADATMARKER) {
1998        ap->mAudioTrack->setMarkerPosition((uint32_t)((((int64_t)pPlayItf->mMarkerPosition
1999                * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000));
2000    } else {
2001        // clear marker
2002        ap->mAudioTrack->setMarkerPosition(0);
2003    }
2004
2005    if (eventFlags & SL_PLAYEVENT_HEADATNEWPOS) {
2006         ap->mAudioTrack->setPositionUpdatePeriod(
2007                (uint32_t)((((int64_t)pPlayItf->mPositionUpdatePeriod
2008                * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000));
2009    } else {
2010        // clear periodic update
2011        ap->mAudioTrack->setPositionUpdatePeriod(0);
2012    }
2013
2014    if (eventFlags & SL_PLAYEVENT_HEADATEND) {
2015        // nothing to do for SL_PLAYEVENT_HEADATEND, callback event will be checked against mask
2016    }
2017
2018    if (eventFlags & SL_PLAYEVENT_HEADMOVING) {
2019        // FIXME support SL_PLAYEVENT_HEADMOVING
2020        SL_LOGD("[ FIXME: IPlay_SetCallbackEventsMask(SL_PLAYEVENT_HEADMOVING) on an "
2021            "SL_OBJECTID_AUDIOPLAYER to be implemented ]");
2022    }
2023    if (eventFlags & SL_PLAYEVENT_HEADSTALLED) {
2024        // nothing to do for SL_PLAYEVENT_HEADSTALLED, callback event will be checked against mask
2025    }
2026
2027}
2028
2029
2030//-----------------------------------------------------------------------------
2031SLresult android_audioPlayer_getDuration(IPlay *pPlayItf, SLmillisecond *pDurMsec) {
2032    CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis;
2033    switch(ap->mAndroidObjType) {
2034
2035      case AUDIOPLAYER_FROM_URIFD:  // intended fall-through
2036      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
2037        int32_t durationMsec = ANDROID_UNKNOWN_TIME;
2038        if (ap->mAPlayer != 0) {
2039            ap->mAPlayer->getDurationMsec(&durationMsec);
2040        }
2041        *pDurMsec = durationMsec == ANDROID_UNKNOWN_TIME ? SL_TIME_UNKNOWN : durationMsec;
2042        break;
2043      }
2044
2045      case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
2046      case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2047      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2048      default: {
2049        *pDurMsec = SL_TIME_UNKNOWN;
2050      }
2051    }
2052    return SL_RESULT_SUCCESS;
2053}
2054
2055
2056//-----------------------------------------------------------------------------
2057void android_audioPlayer_getPosition(IPlay *pPlayItf, SLmillisecond *pPosMsec) {
2058    CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis;
2059    switch(ap->mAndroidObjType) {
2060
2061      case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2062        if ((ap->mSampleRateMilliHz == UNKNOWN_SAMPLERATE) || (ap->mAudioTrack == 0)) {
2063            *pPosMsec = 0;
2064        } else {
2065            uint32_t positionInFrames;
2066            ap->mAudioTrack->getPosition(&positionInFrames);
2067            *pPosMsec = ((int64_t)positionInFrames * 1000) /
2068                    sles_to_android_sampleRate(ap->mSampleRateMilliHz);
2069        }
2070        break;
2071
2072      case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:    // intended fall-through
2073      case AUDIOPLAYER_FROM_URIFD:
2074      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2075      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
2076        int32_t posMsec = ANDROID_UNKNOWN_TIME;
2077        if (ap->mAPlayer != 0) {
2078            ap->mAPlayer->getPositionMsec(&posMsec);
2079        }
2080        *pPosMsec = posMsec == ANDROID_UNKNOWN_TIME ? 0 : posMsec;
2081        break;
2082      }
2083
2084      default:
2085        *pPosMsec = 0;
2086    }
2087}
2088
2089
2090//-----------------------------------------------------------------------------
2091SLresult android_audioPlayer_seek(CAudioPlayer *ap, SLmillisecond posMsec) {
2092    SLresult result = SL_RESULT_SUCCESS;
2093
2094    switch(ap->mAndroidObjType) {
2095
2096      case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:      // intended fall-through
2097      case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2098      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2099        result = SL_RESULT_FEATURE_UNSUPPORTED;
2100        break;
2101
2102      case AUDIOPLAYER_FROM_URIFD:                   // intended fall-through
2103      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2104        if (ap->mAPlayer != 0) {
2105            ap->mAPlayer->seek(posMsec);
2106        }
2107        break;
2108
2109      default:
2110        break;
2111    }
2112    return result;
2113}
2114
2115
2116//-----------------------------------------------------------------------------
2117SLresult android_audioPlayer_loop(CAudioPlayer *ap, SLboolean loopEnable) {
2118    SLresult result = SL_RESULT_SUCCESS;
2119
2120    switch (ap->mAndroidObjType) {
2121    case AUDIOPLAYER_FROM_URIFD:
2122    // case AUDIOPLAY_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2123    //      would actually work, but what's the point?
2124      if (ap->mAPlayer != 0) {
2125        ap->mAPlayer->loop((bool)loopEnable);
2126      }
2127      break;
2128    default:
2129      result = SL_RESULT_FEATURE_UNSUPPORTED;
2130      break;
2131    }
2132    return result;
2133}
2134
2135
2136//-----------------------------------------------------------------------------
2137SLresult android_audioPlayer_setBufferingUpdateThresholdPerMille(CAudioPlayer *ap,
2138        SLpermille threshold) {
2139    SLresult result = SL_RESULT_SUCCESS;
2140
2141    switch (ap->mAndroidObjType) {
2142      case AUDIOPLAYER_FROM_URIFD:
2143        if (ap->mAPlayer != 0) {
2144            ap->mAPlayer->setBufferingUpdateThreshold(threshold / 10);
2145        }
2146        break;
2147
2148      default: {}
2149    }
2150
2151    return result;
2152}
2153
2154
2155//-----------------------------------------------------------------------------
2156void android_audioPlayer_bufferQueue_onRefilled_l(CAudioPlayer *ap) {
2157    // the AudioTrack associated with the AudioPlayer receiving audio from a PCM buffer
2158    // queue was stopped when the queue become empty, we restart as soon as a new buffer
2159    // has been enqueued since we're in playing state
2160    if (ap->mAudioTrack != 0) {
2161        // instead of ap->mAudioTrack->start();
2162        ap->mDeferredStart = true;
2163    }
2164
2165    // when the queue became empty, an underflow on the prefetch status itf was sent. Now the queue
2166    // has received new data, signal it has sufficient data
2167    if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
2168        // we wouldn't have been called unless we were previously in the underflow state
2169        assert(SL_PREFETCHSTATUS_UNDERFLOW == ap->mPrefetchStatus.mStatus);
2170        assert(0 == ap->mPrefetchStatus.mLevel);
2171        ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA;
2172        ap->mPrefetchStatus.mLevel = 1000;
2173        // callback or no callback?
2174        SLuint32 prefetchEvents = ap->mPrefetchStatus.mCallbackEventsMask &
2175                (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE);
2176        if (SL_PREFETCHEVENT_NONE != prefetchEvents) {
2177            ap->mPrefetchStatus.mDeferredPrefetchCallback = ap->mPrefetchStatus.mCallback;
2178            ap->mPrefetchStatus.mDeferredPrefetchContext  = ap->mPrefetchStatus.mContext;
2179            ap->mPrefetchStatus.mDeferredPrefetchEvents   = prefetchEvents;
2180        }
2181    }
2182}
2183
2184
2185//-----------------------------------------------------------------------------
2186/*
2187 * BufferQueue::Clear
2188 */
2189SLresult android_audioPlayer_bufferQueue_onClear(CAudioPlayer *ap) {
2190    SLresult result = SL_RESULT_SUCCESS;
2191
2192    switch (ap->mAndroidObjType) {
2193    //-----------------------------------
2194    // AudioTrack
2195    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2196        if (ap->mAudioTrack != 0) {
2197            ap->mAudioTrack->flush();
2198        }
2199        break;
2200    default:
2201        result = SL_RESULT_INTERNAL_ERROR;
2202        break;
2203    }
2204
2205    return result;
2206}
2207
2208
2209//-----------------------------------------------------------------------------
2210void android_audioPlayer_androidBufferQueue_clear_l(CAudioPlayer *ap) {
2211    switch (ap->mAndroidObjType) {
2212    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2213      if (ap->mAPlayer != 0) {
2214        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2215        splr->appClear_l();
2216      } break;
2217    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2218      // nothing to do here, fall through
2219    default:
2220      break;
2221    }
2222}
2223
2224void android_audioPlayer_androidBufferQueue_onRefilled_l(CAudioPlayer *ap) {
2225    switch (ap->mAndroidObjType) {
2226    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2227      if (ap->mAPlayer != 0) {
2228        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2229        splr->queueRefilled();
2230      } break;
2231    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2232      // FIXME this may require waking up the decoder if it is currently starved and isn't polling
2233    default:
2234      break;
2235    }
2236}
2237