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