AudioPlayer_to_android.cpp revision a4a505dff853ecb90aefae75a525fde324f5990e
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// From EffectDownmix.h
858const uint32_t kSides = AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT;
859const uint32_t kBacks = AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT;
860const uint32_t kUnsupported =
861        AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER | AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER |
862        AUDIO_CHANNEL_OUT_TOP_CENTER |
863        AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT |
864        AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER |
865        AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT |
866        AUDIO_CHANNEL_OUT_TOP_BACK_LEFT |
867        AUDIO_CHANNEL_OUT_TOP_BACK_CENTER |
868        AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT;
869
870//TODO(pmclean) This will need to be revisited when arbitrary N-channel support is added.
871SLresult android_audioPlayer_validateChannelMask(uint32_t mask, int numChans) {
872    // Check that the number of channels falls within bounds.
873    if (numChans < 0 || numChans > 8) {
874        return SL_RESULT_CONTENT_UNSUPPORTED;
875    }
876    // Are there the right number of channels in the mask?
877    if (popcount(mask) != numChans) {
878        return SL_RESULT_CONTENT_UNSUPPORTED;
879    }
880    // check against unsupported channels
881    if (mask & kUnsupported) {
882        ALOGE("Unsupported channels (top or front left/right of center)");
883        return SL_RESULT_CONTENT_UNSUPPORTED;
884    }
885    // verify has FL/FR if more than one channel
886    if (numChans > 1 && (mask & AUDIO_CHANNEL_OUT_STEREO) != AUDIO_CHANNEL_OUT_STEREO) {
887        ALOGE("Front channels must be present");
888        return SL_RESULT_CONTENT_UNSUPPORTED;
889    }
890    // verify uses SIDE as a pair (ok if not using SIDE at all)
891    bool hasSides = false;
892    if ((mask & kSides) != 0) {
893        if ((mask & kSides) != kSides) {
894            ALOGE("Side channels must be used as a pair");
895            return SL_RESULT_CONTENT_UNSUPPORTED;
896        }
897        hasSides = true;
898    }
899    // verify uses BACK as a pair (ok if not using BACK at all)
900    bool hasBacks = false;
901    if ((mask & kBacks) != 0) {
902        if ((mask & kBacks) != kBacks) {
903            ALOGE("Back channels must be used as a pair");
904            return SL_RESULT_CONTENT_UNSUPPORTED;
905        }
906        hasBacks = true;
907    }
908
909    return SL_RESULT_SUCCESS;
910}
911
912//-----------------------------------------------------------------------------
913SLresult android_audioPlayer_checkSourceSink(CAudioPlayer *pAudioPlayer)
914{
915    // verify that the locator types for the source / sink combination is supported
916    pAudioPlayer->mAndroidObjType = audioPlayer_getAndroidObjectTypeForSourceSink(pAudioPlayer);
917    if (INVALID_TYPE == pAudioPlayer->mAndroidObjType) {
918        return SL_RESULT_PARAMETER_INVALID;
919    }
920
921    const SLDataSource *pAudioSrc = &pAudioPlayer->mDataSource.u.mSource;
922    const SLDataSink *pAudioSnk = &pAudioPlayer->mDataSink.u.mSink;
923
924    // format check:
925    const SLuint32 sourceLocatorType = *(SLuint32 *)pAudioSrc->pLocator;
926    const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator;
927    const SLuint32 sourceFormatType = *(SLuint32 *)pAudioSrc->pFormat;
928    const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSnk->pFormat;
929
930    switch (sourceLocatorType) {
931    //------------------
932    //   Buffer Queues
933    case SL_DATALOCATOR_BUFFERQUEUE:
934    case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
935        {
936        SLDataLocator_BufferQueue *dl_bq = (SLDataLocator_BufferQueue *) pAudioSrc->pLocator;
937
938        // Buffer format
939        switch (sourceFormatType) {
940        //     currently only PCM buffer queues are supported,
941        case SL_DATAFORMAT_PCM: {
942            SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *) pAudioSrc->pFormat;
943            SLresult result = android_audioPlayer_validateChannelMask(df_pcm->channelMask,
944                                                                      df_pcm->numChannels);
945            if (result != SL_RESULT_SUCCESS) {
946                SL_LOGE("Cannot create audio player: unsupported PCM data source with %u channels",
947                        (unsigned) df_pcm->numChannels);
948                return result;
949            }
950
951            switch (df_pcm->samplesPerSec) {
952            case SL_SAMPLINGRATE_8:
953            case SL_SAMPLINGRATE_11_025:
954            case SL_SAMPLINGRATE_12:
955            case SL_SAMPLINGRATE_16:
956            case SL_SAMPLINGRATE_22_05:
957            case SL_SAMPLINGRATE_24:
958            case SL_SAMPLINGRATE_32:
959            case SL_SAMPLINGRATE_44_1:
960            case SL_SAMPLINGRATE_48:
961                break;
962            case SL_SAMPLINGRATE_64:
963            case SL_SAMPLINGRATE_88_2:
964            case SL_SAMPLINGRATE_96:
965            case SL_SAMPLINGRATE_192:
966            default:
967                SL_LOGE("Cannot create audio player: unsupported sample rate %u milliHz",
968                    (unsigned) df_pcm->samplesPerSec);
969                return SL_RESULT_CONTENT_UNSUPPORTED;
970            }
971            switch (df_pcm->bitsPerSample) {
972            case SL_PCMSAMPLEFORMAT_FIXED_8:
973            case SL_PCMSAMPLEFORMAT_FIXED_16:
974            case SL_PCMSAMPLEFORMAT_FIXED_24:
975                break;
976                // others
977            default:
978                // this should have already been rejected by checkDataFormat
979                SL_LOGE("Cannot create audio player: unsupported sample bit depth %u",
980                        (SLuint32)df_pcm->bitsPerSample);
981                return SL_RESULT_CONTENT_UNSUPPORTED;
982            }
983            switch (df_pcm->containerSize) {
984            case 8:
985            case 16:
986            case 24:
987                break;
988                // others
989            default:
990                SL_LOGE("Cannot create audio player: unsupported container size %u",
991                    (unsigned) df_pcm->containerSize);
992                return SL_RESULT_CONTENT_UNSUPPORTED;
993            }
994            // df_pcm->channelMask: the earlier platform-independent check and the
995            //     upcoming check by sles_to_android_channelMaskOut are sufficient
996            switch (df_pcm->endianness) {
997            case SL_BYTEORDER_LITTLEENDIAN:
998                break;
999            case SL_BYTEORDER_BIGENDIAN:
1000                SL_LOGE("Cannot create audio player: unsupported big-endian byte order");
1001                return SL_RESULT_CONTENT_UNSUPPORTED;
1002                // native is proposed but not yet in spec
1003            default:
1004                SL_LOGE("Cannot create audio player: unsupported byte order %u",
1005                    (unsigned) df_pcm->endianness);
1006                return SL_RESULT_CONTENT_UNSUPPORTED;
1007            }
1008            } //case SL_DATAFORMAT_PCM
1009            break;
1010        case SL_DATAFORMAT_MIME:
1011        case XA_DATAFORMAT_RAWIMAGE:
1012            SL_LOGE("Cannot create audio player with buffer queue data source "
1013                "without SL_DATAFORMAT_PCM format");
1014            return SL_RESULT_CONTENT_UNSUPPORTED;
1015        default:
1016            // invalid data format is detected earlier
1017            assert(false);
1018            return SL_RESULT_INTERNAL_ERROR;
1019        } // switch (sourceFormatType)
1020        } // case SL_DATALOCATOR_BUFFERQUEUE or SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
1021        break;
1022    //------------------
1023    //   URI
1024    case SL_DATALOCATOR_URI:
1025        {
1026        SLDataLocator_URI *dl_uri = (SLDataLocator_URI *) pAudioSrc->pLocator;
1027        if (NULL == dl_uri->URI) {
1028            return SL_RESULT_PARAMETER_INVALID;
1029        }
1030        // URI format
1031        switch (sourceFormatType) {
1032        case SL_DATAFORMAT_MIME:
1033            break;
1034        case SL_DATAFORMAT_PCM:
1035        case XA_DATAFORMAT_RAWIMAGE:
1036            SL_LOGE("Cannot create audio player with SL_DATALOCATOR_URI data source without "
1037                "SL_DATAFORMAT_MIME format");
1038            return SL_RESULT_CONTENT_UNSUPPORTED;
1039        } // switch (sourceFormatType)
1040        // decoding format check
1041        if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) &&
1042                !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) {
1043            return SL_RESULT_CONTENT_UNSUPPORTED;
1044        }
1045        } // case SL_DATALOCATOR_URI
1046        break;
1047    //------------------
1048    //   File Descriptor
1049    case SL_DATALOCATOR_ANDROIDFD:
1050        {
1051        // fd is already non null
1052        switch (sourceFormatType) {
1053        case SL_DATAFORMAT_MIME:
1054            break;
1055        case SL_DATAFORMAT_PCM:
1056            // FIXME implement
1057            SL_LOGD("[ FIXME implement PCM FD data sources ]");
1058            break;
1059        case XA_DATAFORMAT_RAWIMAGE:
1060            SL_LOGE("Cannot create audio player with SL_DATALOCATOR_ANDROIDFD data source "
1061                "without SL_DATAFORMAT_MIME or SL_DATAFORMAT_PCM format");
1062            return SL_RESULT_CONTENT_UNSUPPORTED;
1063        default:
1064            // invalid data format is detected earlier
1065            assert(false);
1066            return SL_RESULT_INTERNAL_ERROR;
1067        } // switch (sourceFormatType)
1068        if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) &&
1069                !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) {
1070            return SL_RESULT_CONTENT_UNSUPPORTED;
1071        }
1072        } // case SL_DATALOCATOR_ANDROIDFD
1073        break;
1074    //------------------
1075    //   Stream
1076    case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
1077    {
1078        switch (sourceFormatType) {
1079        case SL_DATAFORMAT_MIME:
1080        {
1081            SLDataFormat_MIME *df_mime = (SLDataFormat_MIME *) pAudioSrc->pFormat;
1082            if (NULL == df_mime) {
1083                SL_LOGE("MIME type null invalid");
1084                return SL_RESULT_CONTENT_UNSUPPORTED;
1085            }
1086            SL_LOGD("source MIME is %s", (char*)df_mime->mimeType);
1087            switch(df_mime->containerType) {
1088            case SL_CONTAINERTYPE_MPEG_TS:
1089                if (strcasecmp((char*)df_mime->mimeType, (const char *)XA_ANDROID_MIME_MP2TS)) {
1090                    SL_LOGE("Invalid MIME (%s) for container SL_CONTAINERTYPE_MPEG_TS, expects %s",
1091                            (char*)df_mime->mimeType, XA_ANDROID_MIME_MP2TS);
1092                    return SL_RESULT_CONTENT_UNSUPPORTED;
1093                }
1094                break;
1095            case SL_CONTAINERTYPE_RAW:
1096            case SL_CONTAINERTYPE_AAC:
1097                if (strcasecmp((char*)df_mime->mimeType, (const char *)SL_ANDROID_MIME_AACADTS) &&
1098                        strcasecmp((char*)df_mime->mimeType,
1099                                ANDROID_MIME_AACADTS_ANDROID_FRAMEWORK)) {
1100                    SL_LOGE("Invalid MIME (%s) for container type %d, expects %s",
1101                            (char*)df_mime->mimeType, df_mime->containerType,
1102                            SL_ANDROID_MIME_AACADTS);
1103                    return SL_RESULT_CONTENT_UNSUPPORTED;
1104                }
1105                break;
1106            default:
1107                SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
1108                                        "that is not fed MPEG-2 TS data or AAC ADTS data");
1109                return SL_RESULT_CONTENT_UNSUPPORTED;
1110            }
1111        }
1112        break;
1113        default:
1114            SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
1115                    "without SL_DATAFORMAT_MIME format");
1116            return SL_RESULT_CONTENT_UNSUPPORTED;
1117        }
1118    }
1119    break; // case SL_DATALOCATOR_ANDROIDBUFFERQUEUE
1120    //------------------
1121    //   Address
1122    case SL_DATALOCATOR_ADDRESS:
1123    case SL_DATALOCATOR_IODEVICE:
1124    case SL_DATALOCATOR_OUTPUTMIX:
1125    case XA_DATALOCATOR_NATIVEDISPLAY:
1126    case SL_DATALOCATOR_MIDIBUFFERQUEUE:
1127        SL_LOGE("Cannot create audio player with data locator type 0x%x",
1128                (unsigned) sourceLocatorType);
1129        return SL_RESULT_CONTENT_UNSUPPORTED;
1130    default:
1131        SL_LOGE("Cannot create audio player with invalid data locator type 0x%x",
1132                (unsigned) sourceLocatorType);
1133        return SL_RESULT_PARAMETER_INVALID;
1134    }// switch (locatorType)
1135
1136    return SL_RESULT_SUCCESS;
1137}
1138
1139
1140//-----------------------------------------------------------------------------
1141// Callback associated with an AudioTrack of an SL ES AudioPlayer that gets its data
1142// from a buffer queue. This will not be called once the AudioTrack has been destroyed.
1143static void audioTrack_callBack_pullFromBuffQueue(int event, void* user, void *info) {
1144    CAudioPlayer *ap = (CAudioPlayer *)user;
1145
1146    if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) {
1147        // it is not safe to enter the callback (the track is about to go away)
1148        return;
1149    }
1150
1151    void * callbackPContext = NULL;
1152    switch(event) {
1153
1154    case android::AudioTrack::EVENT_MORE_DATA: {
1155        //SL_LOGV("received event EVENT_MORE_DATA from AudioTrack TID=%d", gettid());
1156        slBufferQueueCallback callback = NULL;
1157        slPrefetchCallback prefetchCallback = NULL;
1158        void *prefetchContext = NULL;
1159        SLuint32 prefetchEvents = SL_PREFETCHEVENT_NONE;
1160        android::AudioTrack::Buffer* pBuff = (android::AudioTrack::Buffer*)info;
1161
1162        // retrieve data from the buffer queue
1163        interface_lock_exclusive(&ap->mBufferQueue);
1164
1165        if (ap->mBufferQueue.mState.count != 0) {
1166            //SL_LOGV("nbBuffers in queue = %u",ap->mBufferQueue.mState.count);
1167            assert(ap->mBufferQueue.mFront != ap->mBufferQueue.mRear);
1168
1169            BufferHeader *oldFront = ap->mBufferQueue.mFront;
1170            BufferHeader *newFront = &oldFront[1];
1171
1172            // declared as void * because this code supports both 8-bit and 16-bit PCM data
1173            void *pSrc = (char *)oldFront->mBuffer + ap->mBufferQueue.mSizeConsumed;
1174            if (ap->mBufferQueue.mSizeConsumed + pBuff->size < oldFront->mSize) {
1175                // can't consume the whole or rest of the buffer in one shot
1176                ap->mBufferQueue.mSizeConsumed += pBuff->size;
1177                // leave pBuff->size untouched
1178                // consume data
1179                // FIXME can we avoid holding the lock during the copy?
1180                memcpy (pBuff->raw, pSrc, pBuff->size);
1181            } else {
1182                // finish consuming the buffer or consume the buffer in one shot
1183                pBuff->size = oldFront->mSize - ap->mBufferQueue.mSizeConsumed;
1184                ap->mBufferQueue.mSizeConsumed = 0;
1185
1186                if (newFront ==
1187                        &ap->mBufferQueue.mArray
1188                            [ap->mBufferQueue.mNumBuffers + 1])
1189                {
1190                    newFront = ap->mBufferQueue.mArray;
1191                }
1192                ap->mBufferQueue.mFront = newFront;
1193
1194                ap->mBufferQueue.mState.count--;
1195                ap->mBufferQueue.mState.playIndex++;
1196
1197                // consume data
1198                // FIXME can we avoid holding the lock during the copy?
1199                memcpy (pBuff->raw, pSrc, pBuff->size);
1200
1201                // data has been consumed, and the buffer queue state has been updated
1202                // we will notify the client if applicable
1203                callback = ap->mBufferQueue.mCallback;
1204                // save callback data
1205                callbackPContext = ap->mBufferQueue.mContext;
1206            }
1207        } else { // empty queue
1208            // signal no data available
1209            pBuff->size = 0;
1210
1211            // signal we're at the end of the content, but don't pause (see note in function)
1212            audioPlayer_dispatch_headAtEnd_lockPlay(ap, false /*set state to paused?*/, false);
1213
1214            // signal underflow to prefetch status itf
1215            if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
1216                ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
1217                ap->mPrefetchStatus.mLevel = 0;
1218                // callback or no callback?
1219                prefetchEvents = ap->mPrefetchStatus.mCallbackEventsMask &
1220                        (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE);
1221                if (SL_PREFETCHEVENT_NONE != prefetchEvents) {
1222                    prefetchCallback = ap->mPrefetchStatus.mCallback;
1223                    prefetchContext  = ap->mPrefetchStatus.mContext;
1224                }
1225            }
1226
1227            // stop the track so it restarts playing faster when new data is enqueued
1228            ap->mAudioTrack->stop();
1229        }
1230        interface_unlock_exclusive(&ap->mBufferQueue);
1231
1232        // notify client
1233        if (NULL != prefetchCallback) {
1234            assert(SL_PREFETCHEVENT_NONE != prefetchEvents);
1235            // spec requires separate callbacks for each event
1236            if (prefetchEvents & SL_PREFETCHEVENT_STATUSCHANGE) {
1237                (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext,
1238                        SL_PREFETCHEVENT_STATUSCHANGE);
1239            }
1240            if (prefetchEvents & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
1241                (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext,
1242                        SL_PREFETCHEVENT_FILLLEVELCHANGE);
1243            }
1244        }
1245        if (NULL != callback) {
1246            (*callback)(&ap->mBufferQueue.mItf, callbackPContext);
1247        }
1248    }
1249    break;
1250
1251    case android::AudioTrack::EVENT_MARKER:
1252        //SL_LOGI("received event EVENT_MARKER from AudioTrack");
1253        audioTrack_handleMarker_lockPlay(ap);
1254        break;
1255
1256    case android::AudioTrack::EVENT_NEW_POS:
1257        //SL_LOGI("received event EVENT_NEW_POS from AudioTrack");
1258        audioTrack_handleNewPos_lockPlay(ap);
1259        break;
1260
1261    case android::AudioTrack::EVENT_UNDERRUN:
1262        //SL_LOGI("received event EVENT_UNDERRUN from AudioTrack");
1263        audioTrack_handleUnderrun_lockPlay(ap);
1264        break;
1265
1266    case android::AudioTrack::EVENT_BUFFER_END:
1267    case android::AudioTrack::EVENT_LOOP_END:
1268        // These are unexpected so fall through
1269    default:
1270        // FIXME where does the notification of SL_PLAYEVENT_HEADMOVING fit?
1271        SL_LOGE("Encountered unknown AudioTrack event %d for CAudioPlayer %p", event,
1272                (CAudioPlayer *)user);
1273        break;
1274    }
1275
1276    ap->mCallbackProtector->exitCb();
1277}
1278
1279
1280//-----------------------------------------------------------------------------
1281void android_audioPlayer_create(CAudioPlayer *pAudioPlayer) {
1282
1283    // pAudioPlayer->mAndroidObjType has been set in android_audioPlayer_checkSourceSink()
1284    // and if it was == INVALID_TYPE, then IEngine_CreateAudioPlayer would never call us
1285    assert(INVALID_TYPE != pAudioPlayer->mAndroidObjType);
1286
1287    // These initializations are in the same order as the field declarations in classes.h
1288
1289    // FIXME Consolidate initializations (many of these already in IEngine_CreateAudioPlayer)
1290    // mAndroidObjType: see above comment
1291    pAudioPlayer->mAndroidObjState = ANDROID_UNINITIALIZED;
1292    pAudioPlayer->mSessionId = android::AudioSystem::newAudioSessionId();
1293
1294    // placeholder: not necessary yet as session ID lifetime doesn't extend beyond player
1295    // android::AudioSystem::acquireAudioSessionId(pAudioPlayer->mSessionId);
1296
1297    pAudioPlayer->mStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
1298
1299    // mAudioTrack
1300    pAudioPlayer->mCallbackProtector = new android::CallbackProtector();
1301    // mAPLayer
1302    // mAuxEffect
1303
1304    pAudioPlayer->mAuxSendLevel = 0;
1305    pAudioPlayer->mAmplFromDirectLevel = 1.0f; // matches initial mDirectLevel value
1306    pAudioPlayer->mDeferredStart = false;
1307
1308    // This section re-initializes interface-specific fields that
1309    // can be set or used regardless of whether the interface is
1310    // exposed on the AudioPlayer or not
1311
1312    switch (pAudioPlayer->mAndroidObjType) {
1313    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1314        pAudioPlayer->mPlaybackRate.mMinRate = AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE;
1315        pAudioPlayer->mPlaybackRate.mMaxRate = AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE;
1316        break;
1317    case AUDIOPLAYER_FROM_URIFD:
1318        pAudioPlayer->mPlaybackRate.mMinRate = MEDIAPLAYER_MIN_PLAYBACKRATE_PERMILLE;
1319        pAudioPlayer->mPlaybackRate.mMaxRate = MEDIAPLAYER_MAX_PLAYBACKRATE_PERMILLE;
1320        break;
1321    default:
1322        // use the default range
1323        break;
1324    }
1325
1326}
1327
1328
1329//-----------------------------------------------------------------------------
1330SLresult android_audioPlayer_setConfig(CAudioPlayer *ap, const SLchar *configKey,
1331        const void *pConfigValue, SLuint32 valueSize) {
1332
1333    SLresult result;
1334
1335    assert(NULL != ap && NULL != configKey && NULL != pConfigValue);
1336    if (strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) {
1337
1338        // stream type
1339        if (KEY_STREAM_TYPE_PARAMSIZE > valueSize) {
1340            SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1341            result = SL_RESULT_BUFFER_INSUFFICIENT;
1342        } else {
1343            result = audioPlayer_setStreamType(ap, *(SLuint32*)pConfigValue);
1344        }
1345
1346    } else {
1347        SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY);
1348        result = SL_RESULT_PARAMETER_INVALID;
1349    }
1350
1351    return result;
1352}
1353
1354
1355//-----------------------------------------------------------------------------
1356SLresult android_audioPlayer_getConfig(CAudioPlayer* ap, const SLchar *configKey,
1357        SLuint32* pValueSize, void *pConfigValue) {
1358
1359    SLresult result;
1360
1361    assert(NULL != ap && NULL != configKey && NULL != pValueSize);
1362    if (strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) {
1363
1364        // stream type
1365        if (NULL == pConfigValue) {
1366            result = SL_RESULT_SUCCESS;
1367        } else if (KEY_STREAM_TYPE_PARAMSIZE > *pValueSize) {
1368            SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1369            result = SL_RESULT_BUFFER_INSUFFICIENT;
1370        } else {
1371            result = audioPlayer_getStreamType(ap, (SLint32*)pConfigValue);
1372        }
1373        *pValueSize = KEY_STREAM_TYPE_PARAMSIZE;
1374
1375    } else {
1376        SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY);
1377        result = SL_RESULT_PARAMETER_INVALID;
1378    }
1379
1380    return result;
1381}
1382
1383
1384// Called from android_audioPlayer_realize for a PCM buffer queue player
1385// to determine if it can use a fast track.
1386static bool canUseFastTrack(CAudioPlayer *pAudioPlayer)
1387{
1388    assert(pAudioPlayer->mAndroidObjType == AUDIOPLAYER_FROM_PCM_BUFFERQUEUE);
1389
1390    // no need to check the buffer queue size, application side
1391    // double-buffering (and more) is not a requirement for using fast tracks
1392
1393    // Check a blacklist of interfaces that are incompatible with fast tracks.
1394    // The alternative, to check a whitelist of compatible interfaces, is
1395    // more maintainable but is too slow.  As a compromise, in a debug build
1396    // we use both methods and warn if they produce different results.
1397    // In release builds, we only use the blacklist method.
1398    // If a blacklisted interface is added after realization using
1399    // DynamicInterfaceManagement::AddInterface,
1400    // then this won't be detected but the interface will be ineffective.
1401    bool blacklistResult = true;
1402    static const unsigned blacklist[] = {
1403        MPH_BASSBOOST,
1404        MPH_EFFECTSEND,
1405        MPH_ENVIRONMENTALREVERB,
1406        MPH_EQUALIZER,
1407        MPH_PLAYBACKRATE,
1408        MPH_PRESETREVERB,
1409        MPH_VIRTUALIZER,
1410        MPH_ANDROIDEFFECT,
1411        MPH_ANDROIDEFFECTSEND,
1412        // FIXME The problem with a blacklist is remembering to add new interfaces here
1413    };
1414    for (unsigned i = 0; i < sizeof(blacklist)/sizeof(blacklist[0]); ++i) {
1415        if (IsInterfaceInitialized(&pAudioPlayer->mObject, blacklist[i])) {
1416            blacklistResult = false;
1417            break;
1418        }
1419    }
1420#if LOG_NDEBUG == 0
1421    bool whitelistResult = true;
1422    static const unsigned whitelist[] = {
1423        MPH_BUFFERQUEUE,
1424        MPH_DYNAMICINTERFACEMANAGEMENT,
1425        MPH_METADATAEXTRACTION,
1426        MPH_MUTESOLO,
1427        MPH_OBJECT,
1428        MPH_PLAY,
1429        MPH_PREFETCHSTATUS,
1430        MPH_VOLUME,
1431        MPH_ANDROIDCONFIGURATION,
1432        MPH_ANDROIDSIMPLEBUFFERQUEUE,
1433        MPH_ANDROIDBUFFERQUEUESOURCE,
1434    };
1435    for (unsigned mph = MPH_MIN; mph < MPH_MAX; ++mph) {
1436        for (unsigned i = 0; i < sizeof(whitelist)/sizeof(whitelist[0]); ++i) {
1437            if (mph == whitelist[i]) {
1438                goto compatible;
1439            }
1440        }
1441        if (IsInterfaceInitialized(&pAudioPlayer->mObject, mph)) {
1442            whitelistResult = false;
1443            break;
1444        }
1445compatible: ;
1446    }
1447    if (whitelistResult != blacklistResult) {
1448        ALOGW("whitelistResult != blacklistResult");
1449        // and use blacklistResult below
1450    }
1451#endif
1452    return blacklistResult;
1453}
1454
1455
1456//-----------------------------------------------------------------------------
1457// FIXME abstract out the diff between CMediaPlayer and CAudioPlayer
1458SLresult android_audioPlayer_realize(CAudioPlayer *pAudioPlayer, SLboolean async) {
1459
1460    SLresult result = SL_RESULT_SUCCESS;
1461    SL_LOGV("Realize pAudioPlayer=%p", pAudioPlayer);
1462
1463    AudioPlayback_Parameters app;
1464    app.sessionId = pAudioPlayer->mSessionId;
1465    app.streamType = pAudioPlayer->mStreamType;
1466
1467    switch (pAudioPlayer->mAndroidObjType) {
1468
1469    //-----------------------------------
1470    // AudioTrack
1471    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1472        {
1473        // initialize platform-specific CAudioPlayer fields
1474
1475        SLDataLocator_BufferQueue *dl_bq = (SLDataLocator_BufferQueue *)
1476                pAudioPlayer->mDynamicSource.mDataSource;
1477        SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *)
1478                pAudioPlayer->mDynamicSource.mDataSource->pFormat;
1479
1480        uint32_t sampleRate = sles_to_android_sampleRate(df_pcm->samplesPerSec);
1481
1482        audio_output_flags_t policy;
1483        if (canUseFastTrack(pAudioPlayer)) {
1484            policy = AUDIO_OUTPUT_FLAG_FAST;
1485        } else {
1486            policy = AUDIO_OUTPUT_FLAG_NONE;
1487        }
1488
1489        pAudioPlayer->mAudioTrack = new android::AudioTrack(
1490                pAudioPlayer->mStreamType,                           // streamType
1491                sampleRate,                                          // sampleRate
1492                sles_to_android_sampleFormat(df_pcm->bitsPerSample), // format
1493                sles_to_android_channelMaskOut(df_pcm->numChannels, df_pcm->channelMask),
1494                                                                     // channel mask
1495                0,                                                   // frameCount
1496                policy,                                              // flags
1497                audioTrack_callBack_pullFromBuffQueue,               // callback
1498                (void *) pAudioPlayer,                               // user
1499                0,     // FIXME find appropriate frame count         // notificationFrame
1500                pAudioPlayer->mSessionId);
1501        android::status_t status = pAudioPlayer->mAudioTrack->initCheck();
1502        if (status != android::NO_ERROR) {
1503            SL_LOGE("AudioTrack::initCheck status %u", status);
1504            result = SL_RESULT_CONTENT_UNSUPPORTED;
1505            pAudioPlayer->mAudioTrack.clear();
1506            return result;
1507        }
1508
1509        // initialize platform-independent CAudioPlayer fields
1510
1511        pAudioPlayer->mNumChannels = df_pcm->numChannels;
1512        pAudioPlayer->mSampleRateMilliHz = df_pcm->samplesPerSec; // Note: bad field name in SL ES
1513
1514        // This use case does not have a separate "prepare" step
1515        pAudioPlayer->mAndroidObjState = ANDROID_READY;
1516        }
1517        break;
1518
1519    //-----------------------------------
1520    // MediaPlayer
1521    case AUDIOPLAYER_FROM_URIFD: {
1522        pAudioPlayer->mAPlayer = new android::LocAVPlayer(&app, false /*hasVideo*/);
1523        pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent,
1524                        (void*)pAudioPlayer /*notifUSer*/);
1525
1526        switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) {
1527            case SL_DATALOCATOR_URI: {
1528                // The legacy implementation ran Stagefright within the application process, and
1529                // so allowed local pathnames specified by URI that were openable by
1530                // the application but were not openable by mediaserver.
1531                // The current implementation runs Stagefright (mostly) within mediaserver,
1532                // which runs as a different UID and likely a different current working directory.
1533                // For backwards compatibility with any applications which may have relied on the
1534                // previous behavior, we convert an openable file URI into an FD.
1535                // Note that unlike SL_DATALOCATOR_ANDROIDFD, this FD is owned by us
1536                // and so we close it as soon as we've passed it (via Binder dup) to mediaserver.
1537                const char *uri = (const char *)pAudioPlayer->mDataSource.mLocator.mURI.URI;
1538                if (!isDistantProtocol(uri)) {
1539                    // don't touch the original uri, we may need it later
1540                    const char *pathname = uri;
1541                    // skip over an optional leading file:// prefix
1542                    if (!strncasecmp(pathname, "file://", 7)) {
1543                        pathname += 7;
1544                    }
1545                    // attempt to open it as a file using the application's credentials
1546                    int fd = ::open(pathname, O_RDONLY);
1547                    if (fd >= 0) {
1548                        // if open is successful, then check to see if it's a regular file
1549                        struct stat statbuf;
1550                        if (!::fstat(fd, &statbuf) && S_ISREG(statbuf.st_mode)) {
1551                            // treat similarly to an FD data locator, but
1552                            // let setDataSource take responsibility for closing fd
1553                            pAudioPlayer->mAPlayer->setDataSource(fd, 0, statbuf.st_size, true);
1554                            break;
1555                        }
1556                        // we were able to open it, but it's not a file, so let mediaserver try
1557                        (void) ::close(fd);
1558                    }
1559                }
1560                // if either the URI didn't look like a file, or open failed, or not a file
1561                pAudioPlayer->mAPlayer->setDataSource(uri);
1562                } break;
1563            case SL_DATALOCATOR_ANDROIDFD: {
1564                int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset;
1565                pAudioPlayer->mAPlayer->setDataSource(
1566                        (int)pAudioPlayer->mDataSource.mLocator.mFD.fd,
1567                        offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
1568                                (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
1569                        (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length);
1570                }
1571                break;
1572            default:
1573                SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR);
1574                break;
1575        }
1576
1577        }
1578        break;
1579
1580    //-----------------------------------
1581    // StreamPlayer
1582    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: {
1583        android::StreamPlayer* splr = new android::StreamPlayer(&app, false /*hasVideo*/,
1584                &pAudioPlayer->mAndroidBufferQueue, pAudioPlayer->mCallbackProtector);
1585        pAudioPlayer->mAPlayer = splr;
1586        splr->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1587        }
1588        break;
1589
1590    //-----------------------------------
1591    // AudioToCbRenderer
1592    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
1593        android::AudioToCbRenderer* decoder = new android::AudioToCbRenderer(&app);
1594        pAudioPlayer->mAPlayer = decoder;
1595        // configures the callback for the sink buffer queue
1596        decoder->setDataPushListener(adecoder_writeToBufferQueue, pAudioPlayer);
1597        // configures the callback for the notifications coming from the SF code
1598        decoder->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1599
1600        switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) {
1601        case SL_DATALOCATOR_URI:
1602            decoder->setDataSource(
1603                    (const char*)pAudioPlayer->mDataSource.mLocator.mURI.URI);
1604            break;
1605        case SL_DATALOCATOR_ANDROIDFD: {
1606            int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset;
1607            decoder->setDataSource(
1608                    (int)pAudioPlayer->mDataSource.mLocator.mFD.fd,
1609                    offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
1610                            (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
1611                            (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length);
1612            }
1613            break;
1614        default:
1615            SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR);
1616            break;
1617        }
1618
1619        }
1620        break;
1621
1622    //-----------------------------------
1623    // AacBqToPcmCbRenderer
1624    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
1625        android::AacBqToPcmCbRenderer* bqtobq = new android::AacBqToPcmCbRenderer(&app,
1626                &pAudioPlayer->mAndroidBufferQueue);
1627        // configures the callback for the sink buffer queue
1628        bqtobq->setDataPushListener(adecoder_writeToBufferQueue, pAudioPlayer);
1629        pAudioPlayer->mAPlayer = bqtobq;
1630        // configures the callback for the notifications coming from the SF code,
1631        // but also implicitly configures the AndroidBufferQueue from which ADTS data is read
1632        pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1633        }
1634        break;
1635
1636    //-----------------------------------
1637    default:
1638        SL_LOGE(ERROR_PLAYERREALIZE_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType);
1639        result = SL_RESULT_INTERNAL_ERROR;
1640        break;
1641    }
1642
1643    // proceed with effect initialization
1644    // initialize EQ
1645    // FIXME use a table of effect descriptors when adding support for more effects
1646    if (memcmp(SL_IID_EQUALIZER, &pAudioPlayer->mEqualizer.mEqDescriptor.type,
1647            sizeof(effect_uuid_t)) == 0) {
1648        SL_LOGV("Need to initialize EQ for AudioPlayer=%p", pAudioPlayer);
1649        android_eq_init(pAudioPlayer->mSessionId, &pAudioPlayer->mEqualizer);
1650    }
1651    // initialize BassBoost
1652    if (memcmp(SL_IID_BASSBOOST, &pAudioPlayer->mBassBoost.mBassBoostDescriptor.type,
1653            sizeof(effect_uuid_t)) == 0) {
1654        SL_LOGV("Need to initialize BassBoost for AudioPlayer=%p", pAudioPlayer);
1655        android_bb_init(pAudioPlayer->mSessionId, &pAudioPlayer->mBassBoost);
1656    }
1657    // initialize Virtualizer
1658    if (memcmp(SL_IID_VIRTUALIZER, &pAudioPlayer->mVirtualizer.mVirtualizerDescriptor.type,
1659               sizeof(effect_uuid_t)) == 0) {
1660        SL_LOGV("Need to initialize Virtualizer for AudioPlayer=%p", pAudioPlayer);
1661        android_virt_init(pAudioPlayer->mSessionId, &pAudioPlayer->mVirtualizer);
1662    }
1663
1664    // initialize EffectSend
1665    // FIXME initialize EffectSend
1666
1667    return result;
1668}
1669
1670
1671//-----------------------------------------------------------------------------
1672/**
1673 * Called with a lock on AudioPlayer, and blocks until safe to destroy
1674 */
1675SLresult android_audioPlayer_preDestroy(CAudioPlayer *pAudioPlayer) {
1676    SL_LOGD("android_audioPlayer_preDestroy(%p)", pAudioPlayer);
1677    SLresult result = SL_RESULT_SUCCESS;
1678
1679    bool disableCallbacksBeforePreDestroy;
1680    switch (pAudioPlayer->mAndroidObjType) {
1681    // Not yet clear why this order is important, but it reduces detected deadlocks
1682    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1683        disableCallbacksBeforePreDestroy = true;
1684        break;
1685    // Use the old behavior for all other use cases until proven
1686    // case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1687    default:
1688        disableCallbacksBeforePreDestroy = false;
1689        break;
1690    }
1691
1692    if (disableCallbacksBeforePreDestroy) {
1693        object_unlock_exclusive(&pAudioPlayer->mObject);
1694        if (pAudioPlayer->mCallbackProtector != 0) {
1695            pAudioPlayer->mCallbackProtector->requestCbExitAndWait();
1696        }
1697        object_lock_exclusive(&pAudioPlayer->mObject);
1698    }
1699
1700    if (pAudioPlayer->mAPlayer != 0) {
1701        pAudioPlayer->mAPlayer->preDestroy();
1702    }
1703    SL_LOGD("android_audioPlayer_preDestroy(%p) after mAPlayer->preDestroy()", pAudioPlayer);
1704
1705    if (!disableCallbacksBeforePreDestroy) {
1706        object_unlock_exclusive(&pAudioPlayer->mObject);
1707        if (pAudioPlayer->mCallbackProtector != 0) {
1708            pAudioPlayer->mCallbackProtector->requestCbExitAndWait();
1709        }
1710        object_lock_exclusive(&pAudioPlayer->mObject);
1711    }
1712
1713    return result;
1714}
1715
1716
1717//-----------------------------------------------------------------------------
1718SLresult android_audioPlayer_destroy(CAudioPlayer *pAudioPlayer) {
1719    SLresult result = SL_RESULT_SUCCESS;
1720    SL_LOGV("android_audioPlayer_destroy(%p)", pAudioPlayer);
1721    switch (pAudioPlayer->mAndroidObjType) {
1722
1723    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1724        // We own the audio track for PCM buffer queue players
1725        if (pAudioPlayer->mAudioTrack != 0) {
1726            pAudioPlayer->mAudioTrack->stop();
1727            // Note that there may still be another reference in post-unlock phase of SetPlayState
1728            pAudioPlayer->mAudioTrack.clear();
1729        }
1730        break;
1731
1732    case AUDIOPLAYER_FROM_URIFD:     // intended fall-through
1733    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:    // intended fall-through
1734    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: // intended fall-through
1735    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1736        pAudioPlayer->mAPlayer.clear();
1737        break;
1738    //-----------------------------------
1739    default:
1740        SL_LOGE(ERROR_PLAYERDESTROY_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType);
1741        result = SL_RESULT_INTERNAL_ERROR;
1742        break;
1743    }
1744
1745    // placeholder: not necessary yet as session ID lifetime doesn't extend beyond player
1746    // android::AudioSystem::releaseAudioSessionId(pAudioPlayer->mSessionId);
1747
1748    pAudioPlayer->mCallbackProtector.clear();
1749
1750    // explicit destructor
1751    pAudioPlayer->mAudioTrack.~sp();
1752    // note that SetPlayState(PLAYING) may still hold a reference
1753    pAudioPlayer->mCallbackProtector.~sp();
1754    pAudioPlayer->mAuxEffect.~sp();
1755    pAudioPlayer->mAPlayer.~sp();
1756
1757    return result;
1758}
1759
1760
1761//-----------------------------------------------------------------------------
1762SLresult android_audioPlayer_setPlaybackRateAndConstraints(CAudioPlayer *ap, SLpermille rate,
1763        SLuint32 constraints) {
1764    SLresult result = SL_RESULT_SUCCESS;
1765    switch(ap->mAndroidObjType) {
1766    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: {
1767        // these asserts were already checked by the platform-independent layer
1768        assert((AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE <= rate) &&
1769                (rate <= AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE));
1770        assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO);
1771        // get the content sample rate
1772        uint32_t contentRate = sles_to_android_sampleRate(ap->mSampleRateMilliHz);
1773        // apply the SL ES playback rate on the AudioTrack as a factor of its content sample rate
1774        if (ap->mAudioTrack != 0) {
1775            ap->mAudioTrack->setSampleRate(contentRate * (rate/1000.0f));
1776        }
1777        }
1778        break;
1779    case AUDIOPLAYER_FROM_URIFD: {
1780        assert((MEDIAPLAYER_MIN_PLAYBACKRATE_PERMILLE <= rate) &&
1781                        (rate <= MEDIAPLAYER_MAX_PLAYBACKRATE_PERMILLE));
1782        assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO);
1783        // apply the SL ES playback rate on the GenericPlayer
1784        if (ap->mAPlayer != 0) {
1785            ap->mAPlayer->setPlaybackRate((int16_t)rate);
1786        }
1787        }
1788        break;
1789
1790    default:
1791        SL_LOGE("Unexpected object type %d", ap->mAndroidObjType);
1792        result = SL_RESULT_FEATURE_UNSUPPORTED;
1793        break;
1794    }
1795    return result;
1796}
1797
1798
1799//-----------------------------------------------------------------------------
1800// precondition
1801//  called with no lock held
1802//  ap != NULL
1803//  pItemCount != NULL
1804SLresult android_audioPlayer_metadata_getItemCount(CAudioPlayer *ap, SLuint32 *pItemCount) {
1805    if (ap->mAPlayer == 0) {
1806        return SL_RESULT_PARAMETER_INVALID;
1807    }
1808    switch(ap->mAndroidObjType) {
1809      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1810      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1811        {
1812            android::AudioSfDecoder* decoder =
1813                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1814            *pItemCount = decoder->getPcmFormatKeyCount();
1815        }
1816        break;
1817      default:
1818        *pItemCount = 0;
1819        break;
1820    }
1821    return SL_RESULT_SUCCESS;
1822}
1823
1824
1825//-----------------------------------------------------------------------------
1826// precondition
1827//  called with no lock held
1828//  ap != NULL
1829//  pKeySize != NULL
1830SLresult android_audioPlayer_metadata_getKeySize(CAudioPlayer *ap,
1831        SLuint32 index, SLuint32 *pKeySize) {
1832    if (ap->mAPlayer == 0) {
1833        return SL_RESULT_PARAMETER_INVALID;
1834    }
1835    SLresult res = SL_RESULT_SUCCESS;
1836    switch(ap->mAndroidObjType) {
1837      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1838      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1839        {
1840            android::AudioSfDecoder* decoder =
1841                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1842            SLuint32 keyNameSize = 0;
1843            if (!decoder->getPcmFormatKeySize(index, &keyNameSize)) {
1844                res = SL_RESULT_PARAMETER_INVALID;
1845            } else {
1846                // *pKeySize is the size of the region used to store the key name AND
1847                //   the information about the key (size, lang, encoding)
1848                *pKeySize = keyNameSize + sizeof(SLMetadataInfo);
1849            }
1850        }
1851        break;
1852      default:
1853        *pKeySize = 0;
1854        res = SL_RESULT_PARAMETER_INVALID;
1855        break;
1856    }
1857    return res;
1858}
1859
1860
1861//-----------------------------------------------------------------------------
1862// precondition
1863//  called with no lock held
1864//  ap != NULL
1865//  pKey != NULL
1866SLresult android_audioPlayer_metadata_getKey(CAudioPlayer *ap,
1867        SLuint32 index, SLuint32 size, SLMetadataInfo *pKey) {
1868    if (ap->mAPlayer == 0) {
1869        return SL_RESULT_PARAMETER_INVALID;
1870    }
1871    SLresult res = SL_RESULT_SUCCESS;
1872    switch(ap->mAndroidObjType) {
1873      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1874      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1875        {
1876            android::AudioSfDecoder* decoder =
1877                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1878            if ((size < sizeof(SLMetadataInfo) ||
1879                    (!decoder->getPcmFormatKeyName(index, size - sizeof(SLMetadataInfo),
1880                            (char*)pKey->data)))) {
1881                res = SL_RESULT_PARAMETER_INVALID;
1882            } else {
1883                // successfully retrieved the key value, update the other fields
1884                pKey->encoding = SL_CHARACTERENCODING_UTF8;
1885                memcpy((char *) pKey->langCountry, "en", 3);
1886                pKey->size = strlen((char*)pKey->data) + 1;
1887            }
1888        }
1889        break;
1890      default:
1891        res = SL_RESULT_PARAMETER_INVALID;
1892        break;
1893    }
1894    return res;
1895}
1896
1897
1898//-----------------------------------------------------------------------------
1899// precondition
1900//  called with no lock held
1901//  ap != NULL
1902//  pValueSize != NULL
1903SLresult android_audioPlayer_metadata_getValueSize(CAudioPlayer *ap,
1904        SLuint32 index, SLuint32 *pValueSize) {
1905    if (ap->mAPlayer == 0) {
1906        return SL_RESULT_PARAMETER_INVALID;
1907    }
1908    SLresult res = SL_RESULT_SUCCESS;
1909    switch(ap->mAndroidObjType) {
1910      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1911      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1912        {
1913            android::AudioSfDecoder* decoder =
1914                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1915            SLuint32 valueSize = 0;
1916            if (!decoder->getPcmFormatValueSize(index, &valueSize)) {
1917                res = SL_RESULT_PARAMETER_INVALID;
1918            } else {
1919                // *pValueSize is the size of the region used to store the key value AND
1920                //   the information about the value (size, lang, encoding)
1921                *pValueSize = valueSize + sizeof(SLMetadataInfo);
1922            }
1923        }
1924        break;
1925      default:
1926          *pValueSize = 0;
1927          res = SL_RESULT_PARAMETER_INVALID;
1928          break;
1929    }
1930    return res;
1931}
1932
1933
1934//-----------------------------------------------------------------------------
1935// precondition
1936//  called with no lock held
1937//  ap != NULL
1938//  pValue != NULL
1939SLresult android_audioPlayer_metadata_getValue(CAudioPlayer *ap,
1940        SLuint32 index, SLuint32 size, SLMetadataInfo *pValue) {
1941    if (ap->mAPlayer == 0) {
1942        return SL_RESULT_PARAMETER_INVALID;
1943    }
1944    SLresult res = SL_RESULT_SUCCESS;
1945    switch(ap->mAndroidObjType) {
1946      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1947      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1948        {
1949            android::AudioSfDecoder* decoder =
1950                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1951            pValue->encoding = SL_CHARACTERENCODING_BINARY;
1952            memcpy((char *) pValue->langCountry, "en", 3); // applicable here?
1953            SLuint32 valueSize = 0;
1954            if ((size < sizeof(SLMetadataInfo)
1955                    || (!decoder->getPcmFormatValueSize(index, &valueSize))
1956                    || (!decoder->getPcmFormatKeyValue(index, size - sizeof(SLMetadataInfo),
1957                            (SLuint32*)pValue->data)))) {
1958                res = SL_RESULT_PARAMETER_INVALID;
1959            } else {
1960                pValue->size = valueSize;
1961            }
1962        }
1963        break;
1964      default:
1965        res = SL_RESULT_PARAMETER_INVALID;
1966        break;
1967    }
1968    return res;
1969}
1970
1971//-----------------------------------------------------------------------------
1972// preconditions
1973//  ap != NULL
1974//  mutex is locked
1975//  play state has changed
1976void android_audioPlayer_setPlayState(CAudioPlayer *ap) {
1977
1978    SLuint32 playState = ap->mPlay.mState;
1979    AndroidObjectState objState = ap->mAndroidObjState;
1980
1981    switch(ap->mAndroidObjType) {
1982    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1983        switch (playState) {
1984        case SL_PLAYSTATE_STOPPED:
1985            SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_STOPPED");
1986            if (ap->mAudioTrack != 0) {
1987                ap->mAudioTrack->stop();
1988            }
1989            break;
1990        case SL_PLAYSTATE_PAUSED:
1991            SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PAUSED");
1992            if (ap->mAudioTrack != 0) {
1993                ap->mAudioTrack->pause();
1994            }
1995            break;
1996        case SL_PLAYSTATE_PLAYING:
1997            SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PLAYING");
1998            if (ap->mAudioTrack != 0) {
1999                // instead of ap->mAudioTrack->start();
2000                ap->mDeferredStart = true;
2001            }
2002            break;
2003        default:
2004            // checked by caller, should not happen
2005            break;
2006        }
2007        break;
2008
2009    case AUDIOPLAYER_FROM_URIFD:      // intended fall-through
2010    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:     // intended fall-through
2011    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:  // intended fall-through
2012    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2013        // FIXME report and use the return code to the lock mechanism, which is where play state
2014        //   changes are updated (see object_unlock_exclusive_attributes())
2015        aplayer_setPlayState(ap->mAPlayer, playState, &(ap->mAndroidObjState));
2016        break;
2017    default:
2018        SL_LOGE(ERROR_PLAYERSETPLAYSTATE_UNEXPECTED_OBJECT_TYPE_D, ap->mAndroidObjType);
2019        break;
2020    }
2021}
2022
2023
2024//-----------------------------------------------------------------------------
2025// call when either player event flags, marker position, or position update period changes
2026void android_audioPlayer_usePlayEventMask(CAudioPlayer *ap) {
2027    IPlay *pPlayItf = &ap->mPlay;
2028    SLuint32 eventFlags = pPlayItf->mEventFlags;
2029    /*switch(ap->mAndroidObjType) {
2030    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:*/
2031
2032    if (ap->mAPlayer != 0) {
2033        assert(ap->mAudioTrack == 0);
2034        ap->mAPlayer->setPlayEvents((int32_t) eventFlags, (int32_t) pPlayItf->mMarkerPosition,
2035                (int32_t) pPlayItf->mPositionUpdatePeriod);
2036        return;
2037    }
2038
2039    if (ap->mAudioTrack == 0) {
2040        return;
2041    }
2042
2043    if (eventFlags & SL_PLAYEVENT_HEADATMARKER) {
2044        ap->mAudioTrack->setMarkerPosition((uint32_t)((((int64_t)pPlayItf->mMarkerPosition
2045                * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000));
2046    } else {
2047        // clear marker
2048        ap->mAudioTrack->setMarkerPosition(0);
2049    }
2050
2051    if (eventFlags & SL_PLAYEVENT_HEADATNEWPOS) {
2052         ap->mAudioTrack->setPositionUpdatePeriod(
2053                (uint32_t)((((int64_t)pPlayItf->mPositionUpdatePeriod
2054                * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000));
2055    } else {
2056        // clear periodic update
2057        ap->mAudioTrack->setPositionUpdatePeriod(0);
2058    }
2059
2060    if (eventFlags & SL_PLAYEVENT_HEADATEND) {
2061        // nothing to do for SL_PLAYEVENT_HEADATEND, callback event will be checked against mask
2062    }
2063
2064    if (eventFlags & SL_PLAYEVENT_HEADMOVING) {
2065        // FIXME support SL_PLAYEVENT_HEADMOVING
2066        SL_LOGD("[ FIXME: IPlay_SetCallbackEventsMask(SL_PLAYEVENT_HEADMOVING) on an "
2067            "SL_OBJECTID_AUDIOPLAYER to be implemented ]");
2068    }
2069    if (eventFlags & SL_PLAYEVENT_HEADSTALLED) {
2070        // nothing to do for SL_PLAYEVENT_HEADSTALLED, callback event will be checked against mask
2071    }
2072
2073}
2074
2075
2076//-----------------------------------------------------------------------------
2077SLresult android_audioPlayer_getDuration(IPlay *pPlayItf, SLmillisecond *pDurMsec) {
2078    CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis;
2079    switch(ap->mAndroidObjType) {
2080
2081      case AUDIOPLAYER_FROM_URIFD:  // intended fall-through
2082      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
2083        int32_t durationMsec = ANDROID_UNKNOWN_TIME;
2084        if (ap->mAPlayer != 0) {
2085            ap->mAPlayer->getDurationMsec(&durationMsec);
2086        }
2087        *pDurMsec = durationMsec == ANDROID_UNKNOWN_TIME ? SL_TIME_UNKNOWN : durationMsec;
2088        break;
2089      }
2090
2091      case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
2092      case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2093      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2094      default: {
2095        *pDurMsec = SL_TIME_UNKNOWN;
2096      }
2097    }
2098    return SL_RESULT_SUCCESS;
2099}
2100
2101
2102//-----------------------------------------------------------------------------
2103void android_audioPlayer_getPosition(IPlay *pPlayItf, SLmillisecond *pPosMsec) {
2104    CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis;
2105    switch(ap->mAndroidObjType) {
2106
2107      case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2108        if ((ap->mSampleRateMilliHz == UNKNOWN_SAMPLERATE) || (ap->mAudioTrack == 0)) {
2109            *pPosMsec = 0;
2110        } else {
2111            uint32_t positionInFrames;
2112            ap->mAudioTrack->getPosition(&positionInFrames);
2113            *pPosMsec = ((int64_t)positionInFrames * 1000) /
2114                    sles_to_android_sampleRate(ap->mSampleRateMilliHz);
2115        }
2116        break;
2117
2118      case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:    // intended fall-through
2119      case AUDIOPLAYER_FROM_URIFD:
2120      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2121      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
2122        int32_t posMsec = ANDROID_UNKNOWN_TIME;
2123        if (ap->mAPlayer != 0) {
2124            ap->mAPlayer->getPositionMsec(&posMsec);
2125        }
2126        *pPosMsec = posMsec == ANDROID_UNKNOWN_TIME ? 0 : posMsec;
2127        break;
2128      }
2129
2130      default:
2131        *pPosMsec = 0;
2132    }
2133}
2134
2135
2136//-----------------------------------------------------------------------------
2137SLresult android_audioPlayer_seek(CAudioPlayer *ap, SLmillisecond posMsec) {
2138    SLresult result = SL_RESULT_SUCCESS;
2139
2140    switch(ap->mAndroidObjType) {
2141
2142      case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:      // intended fall-through
2143      case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2144      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2145        result = SL_RESULT_FEATURE_UNSUPPORTED;
2146        break;
2147
2148      case AUDIOPLAYER_FROM_URIFD:                   // intended fall-through
2149      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2150        if (ap->mAPlayer != 0) {
2151            ap->mAPlayer->seek(posMsec);
2152        }
2153        break;
2154
2155      default:
2156        break;
2157    }
2158    return result;
2159}
2160
2161
2162//-----------------------------------------------------------------------------
2163SLresult android_audioPlayer_loop(CAudioPlayer *ap, SLboolean loopEnable) {
2164    SLresult result = SL_RESULT_SUCCESS;
2165
2166    switch (ap->mAndroidObjType) {
2167    case AUDIOPLAYER_FROM_URIFD:
2168    // case AUDIOPLAY_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2169    //      would actually work, but what's the point?
2170      if (ap->mAPlayer != 0) {
2171        ap->mAPlayer->loop((bool)loopEnable);
2172      }
2173      break;
2174    default:
2175      result = SL_RESULT_FEATURE_UNSUPPORTED;
2176      break;
2177    }
2178    return result;
2179}
2180
2181
2182//-----------------------------------------------------------------------------
2183SLresult android_audioPlayer_setBufferingUpdateThresholdPerMille(CAudioPlayer *ap,
2184        SLpermille threshold) {
2185    SLresult result = SL_RESULT_SUCCESS;
2186
2187    switch (ap->mAndroidObjType) {
2188      case AUDIOPLAYER_FROM_URIFD:
2189        if (ap->mAPlayer != 0) {
2190            ap->mAPlayer->setBufferingUpdateThreshold(threshold / 10);
2191        }
2192        break;
2193
2194      default: {}
2195    }
2196
2197    return result;
2198}
2199
2200
2201//-----------------------------------------------------------------------------
2202void android_audioPlayer_bufferQueue_onRefilled_l(CAudioPlayer *ap) {
2203    // the AudioTrack associated with the AudioPlayer receiving audio from a PCM buffer
2204    // queue was stopped when the queue become empty, we restart as soon as a new buffer
2205    // has been enqueued since we're in playing state
2206    if (ap->mAudioTrack != 0) {
2207        // instead of ap->mAudioTrack->start();
2208        ap->mDeferredStart = true;
2209    }
2210
2211    // when the queue became empty, an underflow on the prefetch status itf was sent. Now the queue
2212    // has received new data, signal it has sufficient data
2213    if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
2214        // we wouldn't have been called unless we were previously in the underflow state
2215        assert(SL_PREFETCHSTATUS_UNDERFLOW == ap->mPrefetchStatus.mStatus);
2216        assert(0 == ap->mPrefetchStatus.mLevel);
2217        ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA;
2218        ap->mPrefetchStatus.mLevel = 1000;
2219        // callback or no callback?
2220        SLuint32 prefetchEvents = ap->mPrefetchStatus.mCallbackEventsMask &
2221                (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE);
2222        if (SL_PREFETCHEVENT_NONE != prefetchEvents) {
2223            ap->mPrefetchStatus.mDeferredPrefetchCallback = ap->mPrefetchStatus.mCallback;
2224            ap->mPrefetchStatus.mDeferredPrefetchContext  = ap->mPrefetchStatus.mContext;
2225            ap->mPrefetchStatus.mDeferredPrefetchEvents   = prefetchEvents;
2226        }
2227    }
2228}
2229
2230
2231//-----------------------------------------------------------------------------
2232/*
2233 * BufferQueue::Clear
2234 */
2235SLresult android_audioPlayer_bufferQueue_onClear(CAudioPlayer *ap) {
2236    SLresult result = SL_RESULT_SUCCESS;
2237
2238    switch (ap->mAndroidObjType) {
2239    //-----------------------------------
2240    // AudioTrack
2241    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2242        if (ap->mAudioTrack != 0) {
2243            ap->mAudioTrack->flush();
2244        }
2245        break;
2246    default:
2247        result = SL_RESULT_INTERNAL_ERROR;
2248        break;
2249    }
2250
2251    return result;
2252}
2253
2254
2255//-----------------------------------------------------------------------------
2256void android_audioPlayer_androidBufferQueue_clear_l(CAudioPlayer *ap) {
2257    switch (ap->mAndroidObjType) {
2258    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2259      if (ap->mAPlayer != 0) {
2260        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2261        splr->appClear_l();
2262      } break;
2263    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2264      // nothing to do here, fall through
2265    default:
2266      break;
2267    }
2268}
2269
2270void android_audioPlayer_androidBufferQueue_onRefilled_l(CAudioPlayer *ap) {
2271    switch (ap->mAndroidObjType) {
2272    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2273      if (ap->mAPlayer != 0) {
2274        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2275        splr->queueRefilled();
2276      } break;
2277    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2278      // FIXME this may require waking up the decoder if it is currently starved and isn't polling
2279    default:
2280      break;
2281    }
2282}
2283