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