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