AudioPlayer_to_android.cpp revision 779a533785a4b8d2521123bc3c0a035b93ba078d
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//-----------------------------------------------------------------------------
461/**
462 * pre-condition: AudioPlayer has SLPrefetchStatusItf initialized
463 * post-condition:
464 *  - ap->mPrefetchStatus.mStatus == status
465 *  - the prefetch status callback, if any, has been notified if a change occurred
466 *
467 */
468void audioPlayer_dispatch_prefetchStatus_lockPrefetch(CAudioPlayer *ap, SLuint32 status,
469        bool needToLock) {
470    slPrefetchCallback prefetchCallback = NULL;
471    void * prefetchContext = NULL;
472
473    if (needToLock) {
474        interface_lock_exclusive(&ap->mPrefetchStatus);
475    }
476    // status change?
477    if (ap->mPrefetchStatus.mStatus != status) {
478        ap->mPrefetchStatus.mStatus = status;
479        // callback or no callback?
480        if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE) {
481            prefetchCallback = ap->mPrefetchStatus.mCallback;
482            prefetchContext  = ap->mPrefetchStatus.mContext;
483        }
484    }
485    if (needToLock) {
486        interface_unlock_exclusive(&ap->mPrefetchStatus);
487    }
488
489    // callback with no lock held
490    if (NULL != prefetchCallback) {
491        (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext, status);
492    }
493}
494
495
496//-----------------------------------------------------------------------------
497SLresult audioPlayer_setStreamType(CAudioPlayer* ap, SLint32 type) {
498    SLresult result = SL_RESULT_SUCCESS;
499    SL_LOGV("type %d", type);
500
501    int newStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
502    switch(type) {
503    case SL_ANDROID_STREAM_VOICE:
504        newStreamType = AUDIO_STREAM_VOICE_CALL;
505        break;
506    case SL_ANDROID_STREAM_SYSTEM:
507        newStreamType = AUDIO_STREAM_SYSTEM;
508        break;
509    case SL_ANDROID_STREAM_RING:
510        newStreamType = AUDIO_STREAM_RING;
511        break;
512    case SL_ANDROID_STREAM_MEDIA:
513        newStreamType = AUDIO_STREAM_MUSIC;
514        break;
515    case SL_ANDROID_STREAM_ALARM:
516        newStreamType = AUDIO_STREAM_ALARM;
517        break;
518    case SL_ANDROID_STREAM_NOTIFICATION:
519        newStreamType = AUDIO_STREAM_NOTIFICATION;
520        break;
521    default:
522        SL_LOGE(ERROR_PLAYERSTREAMTYPE_SET_UNKNOWN_TYPE);
523        result = SL_RESULT_PARAMETER_INVALID;
524        break;
525    }
526
527    // stream type needs to be set before the object is realized
528    // (ap->mAudioTrack is supposed to be NULL until then)
529    if (SL_OBJECT_STATE_UNREALIZED != ap->mObject.mState) {
530        SL_LOGE(ERROR_PLAYERSTREAMTYPE_REALIZED);
531        result = SL_RESULT_PRECONDITIONS_VIOLATED;
532    } else {
533        ap->mStreamType = newStreamType;
534    }
535
536    return result;
537}
538
539
540//-----------------------------------------------------------------------------
541SLresult audioPlayer_getStreamType(CAudioPlayer* ap, SLint32 *pType) {
542    SLresult result = SL_RESULT_SUCCESS;
543
544    switch(ap->mStreamType) {
545    case AUDIO_STREAM_VOICE_CALL:
546        *pType = SL_ANDROID_STREAM_VOICE;
547        break;
548    case AUDIO_STREAM_SYSTEM:
549        *pType = SL_ANDROID_STREAM_SYSTEM;
550        break;
551    case AUDIO_STREAM_RING:
552        *pType = SL_ANDROID_STREAM_RING;
553        break;
554    case AUDIO_STREAM_DEFAULT:
555    case AUDIO_STREAM_MUSIC:
556        *pType = SL_ANDROID_STREAM_MEDIA;
557        break;
558    case AUDIO_STREAM_ALARM:
559        *pType = SL_ANDROID_STREAM_ALARM;
560        break;
561    case AUDIO_STREAM_NOTIFICATION:
562        *pType = SL_ANDROID_STREAM_NOTIFICATION;
563        break;
564    default:
565        result = SL_RESULT_INTERNAL_ERROR;
566        *pType = SL_ANDROID_STREAM_MEDIA;
567        break;
568    }
569
570    return result;
571}
572
573
574//-----------------------------------------------------------------------------
575void audioPlayer_auxEffectUpdate(CAudioPlayer* ap) {
576    if ((ap->mAudioTrack != 0) && (ap->mAuxEffect != 0)) {
577        android_fxSend_attach(ap, true, ap->mAuxEffect, ap->mVolume.mLevel + ap->mAuxSendLevel);
578    }
579}
580
581
582//-----------------------------------------------------------------------------
583void audioPlayer_setInvalid(CAudioPlayer* ap) {
584    ap->mAndroidObjType = INVALID_TYPE;
585}
586
587
588//-----------------------------------------------------------------------------
589/*
590 * returns true if the given data sink is supported by AudioPlayer that doesn't
591 *   play to an OutputMix object, false otherwise
592 *
593 * pre-condition: the locator of the audio sink is not SL_DATALOCATOR_OUTPUTMIX
594 */
595bool audioPlayer_isSupportedNonOutputMixSink(const SLDataSink* pAudioSink) {
596    bool result = true;
597    const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSink->pLocator;
598    const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSink->pFormat;
599
600    switch (sinkLocatorType) {
601
602    case SL_DATALOCATOR_BUFFERQUEUE:
603    case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
604        if (SL_DATAFORMAT_PCM != sinkFormatType) {
605            SL_LOGE("Unsupported sink format 0x%x, expected SL_DATAFORMAT_PCM",
606                    (unsigned)sinkFormatType);
607            result = false;
608        }
609        // it's no use checking the PCM format fields because additional characteristics
610        // such as the number of channels, or sample size are unknown to the player at this stage
611        break;
612
613    default:
614        SL_LOGE("Unsupported sink locator type 0x%x", (unsigned)sinkLocatorType);
615        result = false;
616        break;
617    }
618
619    return result;
620}
621
622
623//-----------------------------------------------------------------------------
624/*
625 * returns the Android object type if the locator type combinations for the source and sinks
626 *   are supported by this implementation, INVALID_TYPE otherwise
627 */
628AndroidObjectType audioPlayer_getAndroidObjectTypeForSourceSink(CAudioPlayer *ap) {
629
630    const SLDataSource *pAudioSrc = &ap->mDataSource.u.mSource;
631    const SLDataSink *pAudioSnk = &ap->mDataSink.u.mSink;
632    const SLuint32 sourceLocatorType = *(SLuint32 *)pAudioSrc->pLocator;
633    const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator;
634    AndroidObjectType type = INVALID_TYPE;
635
636    //--------------------------------------
637    // Sink / source matching check:
638    // the following source / sink combinations are supported
639    //     SL_DATALOCATOR_BUFFERQUEUE                / SL_DATALOCATOR_OUTPUTMIX
640    //     SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE   / SL_DATALOCATOR_OUTPUTMIX
641    //     SL_DATALOCATOR_URI                        / SL_DATALOCATOR_OUTPUTMIX
642    //     SL_DATALOCATOR_ANDROIDFD                  / SL_DATALOCATOR_OUTPUTMIX
643    //     SL_DATALOCATOR_ANDROIDBUFFERQUEUE         / SL_DATALOCATOR_OUTPUTMIX
644    //     SL_DATALOCATOR_ANDROIDBUFFERQUEUE         / SL_DATALOCATOR_BUFFERQUEUE
645    //     SL_DATALOCATOR_URI                        / SL_DATALOCATOR_BUFFERQUEUE
646    //     SL_DATALOCATOR_ANDROIDFD                  / SL_DATALOCATOR_BUFFERQUEUE
647    //     SL_DATALOCATOR_URI                        / SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
648    //     SL_DATALOCATOR_ANDROIDFD                  / SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
649    switch (sinkLocatorType) {
650
651    case SL_DATALOCATOR_OUTPUTMIX: {
652        switch (sourceLocatorType) {
653
654        //   Buffer Queue to AudioTrack
655        case SL_DATALOCATOR_BUFFERQUEUE:
656        case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
657            type = AUDIOPLAYER_FROM_PCM_BUFFERQUEUE;
658            break;
659
660        //   URI or FD to MediaPlayer
661        case SL_DATALOCATOR_URI:
662        case SL_DATALOCATOR_ANDROIDFD:
663            type = AUDIOPLAYER_FROM_URIFD;
664            break;
665
666        //   Android BufferQueue to MediaPlayer (shared memory streaming)
667        case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
668            type = AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE;
669            break;
670
671        default:
672            SL_LOGE("Source data locator 0x%x not supported with SL_DATALOCATOR_OUTPUTMIX sink",
673                    (unsigned)sourceLocatorType);
674            break;
675        }
676        }
677        break;
678
679    case SL_DATALOCATOR_BUFFERQUEUE:
680    case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
681        switch (sourceLocatorType) {
682
683        //   URI or FD decoded to PCM in a buffer queue
684        case SL_DATALOCATOR_URI:
685        case SL_DATALOCATOR_ANDROIDFD:
686            type = AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE;
687            break;
688
689        //   AAC ADTS Android buffer queue decoded to PCM in a buffer queue
690        case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
691            type = AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE;
692            break;
693
694        default:
695            SL_LOGE("Source data locator 0x%x not supported with SL_DATALOCATOR_BUFFERQUEUE sink",
696                    (unsigned)sourceLocatorType);
697            break;
698        }
699        break;
700
701    default:
702        SL_LOGE("Sink data locator 0x%x not supported", (unsigned)sinkLocatorType);
703        break;
704    }
705
706    return type;
707}
708
709
710//-----------------------------------------------------------------------------
711/*
712 * Callback associated with an SfPlayer of an SL ES AudioPlayer that gets its data
713 * from a URI or FD, for prepare, prefetch, and play events
714 */
715static void sfplayer_handlePrefetchEvent(int event, int data1, int data2, void* user) {
716
717    // FIXME see similar code and comment in player_handleMediaPlayerEventNotifications
718
719    if (NULL == user) {
720        return;
721    }
722
723    CAudioPlayer *ap = (CAudioPlayer *)user;
724    if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) {
725        // it is not safe to enter the callback (the track is about to go away)
726        return;
727    }
728    union {
729        char c[sizeof(int)];
730        int i;
731    } u;
732    u.i = event;
733    SL_LOGV("sfplayer_handlePrefetchEvent(event='%c%c%c%c' (%d), data1=%d, data2=%d, user=%p) from "
734            "SfAudioPlayer", u.c[3], u.c[2], u.c[1], u.c[0], event, data1, data2, user);
735    switch(event) {
736
737    case android::GenericPlayer::kEventPrepared: {
738
739        if (PLAYER_SUCCESS != data1) {
740            object_lock_exclusive(&ap->mObject);
741
742            // already initialized at object creation, and can only prepare once so never reset
743            assert(ap->mAudioTrack == 0);
744            assert(ap->mNumChannels == UNKNOWN_NUMCHANNELS);
745            assert(ap->mSampleRateMilliHz == UNKNOWN_SAMPLERATE);
746            assert(ap->mAndroidObjState == ANDROID_PREPARING);
747            ap->mAndroidObjState = ANDROID_READY;
748
749            object_unlock_exclusive(&ap->mObject);
750
751            // SfPlayer prepare() failed prefetching, there is no event in SLPrefetchStatus to
752            //  indicate a prefetch error, so we signal it by sending simulataneously two events:
753            //  - SL_PREFETCHEVENT_FILLLEVELCHANGE with a level of 0
754            //  - SL_PREFETCHEVENT_STATUSCHANGE with a status of SL_PREFETCHSTATUS_UNDERFLOW
755            SL_LOGE(ERROR_PLAYER_PREFETCH_d, data1);
756            if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
757                break;
758            }
759
760            slPrefetchCallback callback = NULL;
761            void* callbackPContext = NULL;
762
763            interface_lock_exclusive(&ap->mPrefetchStatus);
764            ap->mPrefetchStatus.mLevel = 0;
765            ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
766            if ((ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_FILLLEVELCHANGE)
767                    && (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE)) {
768                callback = ap->mPrefetchStatus.mCallback;
769                callbackPContext = ap->mPrefetchStatus.mContext;
770            }
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 | SL_PREFETCHEVENT_STATUSCHANGE);
777            }
778
779
780        } else {
781
782            object_lock_exclusive(&ap->mObject);
783
784            // Most of successful prepare completion is handled by a subclass.
785            ap->mAndroidObjState = ANDROID_READY;
786
787            object_unlock_exclusive(&ap->mObject);
788        }
789
790    }
791    break;
792
793    case android::GenericPlayer::kEventPrefetchFillLevelUpdate : {
794        if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
795            break;
796        }
797        slPrefetchCallback callback = NULL;
798        void* callbackPContext = NULL;
799
800        // SLPrefetchStatusItf callback or no callback?
801        interface_lock_exclusive(&ap->mPrefetchStatus);
802        if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
803            callback = ap->mPrefetchStatus.mCallback;
804            callbackPContext = ap->mPrefetchStatus.mContext;
805        }
806        ap->mPrefetchStatus.mLevel = (SLpermille)data1;
807        interface_unlock_exclusive(&ap->mPrefetchStatus);
808
809        // callback with no lock held
810        if (NULL != callback) {
811            (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext,
812                    SL_PREFETCHEVENT_FILLLEVELCHANGE);
813        }
814    }
815    break;
816
817    case android::GenericPlayer::kEventPrefetchStatusChange: {
818        if (!IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
819            break;
820        }
821        slPrefetchCallback callback = NULL;
822        void* callbackPContext = NULL;
823
824        // SLPrefetchStatusItf callback or no callback?
825        object_lock_exclusive(&ap->mObject);
826        if (ap->mPrefetchStatus.mCallbackEventsMask & SL_PREFETCHEVENT_STATUSCHANGE) {
827            callback = ap->mPrefetchStatus.mCallback;
828            callbackPContext = ap->mPrefetchStatus.mContext;
829        }
830        if (data1 >= android::kStatusIntermediate) {
831            ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA;
832        } else if (data1 < android::kStatusIntermediate) {
833            ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
834        }
835        object_unlock_exclusive(&ap->mObject);
836
837        // callback with no lock held
838        if (NULL != callback) {
839            (*callback)(&ap->mPrefetchStatus.mItf, callbackPContext, SL_PREFETCHEVENT_STATUSCHANGE);
840        }
841        }
842        break;
843
844    case android::GenericPlayer::kEventEndOfStream: {
845        audioPlayer_dispatch_headAtEnd_lockPlay(ap, true /*set state to paused?*/, true);
846        if ((ap->mAudioTrack != 0) && (!ap->mSeek.mLoopEnabled)) {
847            ap->mAudioTrack->stop();
848        }
849        }
850        break;
851
852    case android::GenericPlayer::kEventChannelCount: {
853        object_lock_exclusive(&ap->mObject);
854        if (UNKNOWN_NUMCHANNELS == ap->mNumChannels && UNKNOWN_NUMCHANNELS != data1) {
855            ap->mNumChannels = data1;
856            android_audioPlayer_volumeUpdate(ap);
857        }
858        object_unlock_exclusive(&ap->mObject);
859        }
860        break;
861
862    case android::GenericPlayer::kEventPlay: {
863        slPlayCallback callback = NULL;
864        void* callbackPContext = NULL;
865
866        interface_lock_shared(&ap->mPlay);
867        callback = ap->mPlay.mCallback;
868        callbackPContext = ap->mPlay.mContext;
869        interface_unlock_shared(&ap->mPlay);
870
871        if (NULL != callback) {
872            SLuint32 event = (SLuint32) data1;  // SL_PLAYEVENT_HEAD*
873#ifndef USE_ASYNCHRONOUS_PLAY_CALLBACK
874            // synchronous callback requires a synchronous GetPosition implementation
875            (*callback)(&ap->mPlay.mItf, callbackPContext, event);
876#else
877            // asynchronous callback works with any GetPosition implementation
878            SLresult result = EnqueueAsyncCallback_ppi(ap, callback, &ap->mPlay.mItf,
879                    callbackPContext, event);
880            if (SL_RESULT_SUCCESS != result) {
881                LOGW("Callback %p(%p, %p, 0x%x) dropped", callback,
882                        &ap->mPlay.mItf, callbackPContext, event);
883            }
884#endif
885        }
886        }
887        break;
888
889    default:
890        break;
891    }
892
893    ap->mCallbackProtector->exitCb();
894}
895
896
897//-----------------------------------------------------------------------------
898SLresult android_audioPlayer_checkSourceSink(CAudioPlayer *pAudioPlayer)
899{
900    // verify that the locator types for the source / sink combination is supported
901    pAudioPlayer->mAndroidObjType = audioPlayer_getAndroidObjectTypeForSourceSink(pAudioPlayer);
902    if (INVALID_TYPE == pAudioPlayer->mAndroidObjType) {
903        return SL_RESULT_PARAMETER_INVALID;
904    }
905
906    const SLDataSource *pAudioSrc = &pAudioPlayer->mDataSource.u.mSource;
907    const SLDataSink *pAudioSnk = &pAudioPlayer->mDataSink.u.mSink;
908
909    // format check:
910    const SLuint32 sourceLocatorType = *(SLuint32 *)pAudioSrc->pLocator;
911    const SLuint32 sinkLocatorType = *(SLuint32 *)pAudioSnk->pLocator;
912    const SLuint32 sourceFormatType = *(SLuint32 *)pAudioSrc->pFormat;
913    const SLuint32 sinkFormatType = *(SLuint32 *)pAudioSnk->pFormat;
914
915    switch (sourceLocatorType) {
916    //------------------
917    //   Buffer Queues
918    case SL_DATALOCATOR_BUFFERQUEUE:
919    case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
920        {
921        SLDataLocator_BufferQueue *dl_bq =  (SLDataLocator_BufferQueue *) pAudioSrc->pLocator;
922
923        // Buffer format
924        switch (sourceFormatType) {
925        //     currently only PCM buffer queues are supported,
926        case SL_DATAFORMAT_PCM: {
927            SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *) pAudioSrc->pFormat;
928            switch (df_pcm->numChannels) {
929            case 1:
930            case 2:
931                break;
932            default:
933                // this should have already been rejected by checkDataFormat
934                SL_LOGE("Cannot create audio player: unsupported " \
935                    "PCM data source with %u channels", (unsigned) df_pcm->numChannels);
936                return SL_RESULT_CONTENT_UNSUPPORTED;
937            }
938            switch (df_pcm->samplesPerSec) {
939            case SL_SAMPLINGRATE_8:
940            case SL_SAMPLINGRATE_11_025:
941            case SL_SAMPLINGRATE_12:
942            case SL_SAMPLINGRATE_16:
943            case SL_SAMPLINGRATE_22_05:
944            case SL_SAMPLINGRATE_24:
945            case SL_SAMPLINGRATE_32:
946            case SL_SAMPLINGRATE_44_1:
947            case SL_SAMPLINGRATE_48:
948                break;
949            case SL_SAMPLINGRATE_64:
950            case SL_SAMPLINGRATE_88_2:
951            case SL_SAMPLINGRATE_96:
952            case SL_SAMPLINGRATE_192:
953            default:
954                SL_LOGE("Cannot create audio player: unsupported sample rate %u milliHz",
955                    (unsigned) df_pcm->samplesPerSec);
956                return SL_RESULT_CONTENT_UNSUPPORTED;
957            }
958            switch (df_pcm->bitsPerSample) {
959            case SL_PCMSAMPLEFORMAT_FIXED_8:
960            case SL_PCMSAMPLEFORMAT_FIXED_16:
961                break;
962                // others
963            default:
964                // this should have already been rejected by checkDataFormat
965                SL_LOGE("Cannot create audio player: unsupported sample bit depth %u",
966                        (SLuint32)df_pcm->bitsPerSample);
967                return SL_RESULT_CONTENT_UNSUPPORTED;
968            }
969            switch (df_pcm->containerSize) {
970            case 8:
971            case 16:
972                break;
973                // others
974            default:
975                SL_LOGE("Cannot create audio player: unsupported container size %u",
976                    (unsigned) df_pcm->containerSize);
977                return SL_RESULT_CONTENT_UNSUPPORTED;
978            }
979            // df_pcm->channelMask: the earlier platform-independent check and the
980            //     upcoming check by sles_to_android_channelMaskOut are sufficient
981            switch (df_pcm->endianness) {
982            case SL_BYTEORDER_LITTLEENDIAN:
983                break;
984            case SL_BYTEORDER_BIGENDIAN:
985                SL_LOGE("Cannot create audio player: unsupported big-endian byte order");
986                return SL_RESULT_CONTENT_UNSUPPORTED;
987                // native is proposed but not yet in spec
988            default:
989                SL_LOGE("Cannot create audio player: unsupported byte order %u",
990                    (unsigned) df_pcm->endianness);
991                return SL_RESULT_CONTENT_UNSUPPORTED;
992            }
993            } //case SL_DATAFORMAT_PCM
994            break;
995        case SL_DATAFORMAT_MIME:
996        case XA_DATAFORMAT_RAWIMAGE:
997            SL_LOGE("Cannot create audio player with buffer queue data source "
998                "without SL_DATAFORMAT_PCM format");
999            return SL_RESULT_CONTENT_UNSUPPORTED;
1000        default:
1001            // invalid data format is detected earlier
1002            assert(false);
1003            return SL_RESULT_INTERNAL_ERROR;
1004        } // switch (sourceFormatType)
1005        } // case SL_DATALOCATOR_BUFFERQUEUE or SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
1006        break;
1007    //------------------
1008    //   URI
1009    case SL_DATALOCATOR_URI:
1010        {
1011        SLDataLocator_URI *dl_uri =  (SLDataLocator_URI *) pAudioSrc->pLocator;
1012        if (NULL == dl_uri->URI) {
1013            return SL_RESULT_PARAMETER_INVALID;
1014        }
1015        // URI format
1016        switch (sourceFormatType) {
1017        case SL_DATAFORMAT_MIME:
1018            break;
1019        case SL_DATAFORMAT_PCM:
1020        case XA_DATAFORMAT_RAWIMAGE:
1021            SL_LOGE("Cannot create audio player with SL_DATALOCATOR_URI data source without "
1022                "SL_DATAFORMAT_MIME format");
1023            return SL_RESULT_CONTENT_UNSUPPORTED;
1024        } // switch (sourceFormatType)
1025        // decoding format check
1026        if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) &&
1027                !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) {
1028            return SL_RESULT_CONTENT_UNSUPPORTED;
1029        }
1030        } // case SL_DATALOCATOR_URI
1031        break;
1032    //------------------
1033    //   File Descriptor
1034    case SL_DATALOCATOR_ANDROIDFD:
1035        {
1036        // fd is already non null
1037        switch (sourceFormatType) {
1038        case SL_DATAFORMAT_MIME:
1039            break;
1040        case SL_DATAFORMAT_PCM:
1041            // FIXME implement
1042            SL_LOGD("[ FIXME implement PCM FD data sources ]");
1043            break;
1044        case XA_DATAFORMAT_RAWIMAGE:
1045            SL_LOGE("Cannot create audio player with SL_DATALOCATOR_ANDROIDFD data source "
1046                "without SL_DATAFORMAT_MIME or SL_DATAFORMAT_PCM format");
1047            return SL_RESULT_CONTENT_UNSUPPORTED;
1048        default:
1049            // invalid data format is detected earlier
1050            assert(false);
1051            return SL_RESULT_INTERNAL_ERROR;
1052        } // switch (sourceFormatType)
1053        if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) &&
1054                !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) {
1055            return SL_RESULT_CONTENT_UNSUPPORTED;
1056        }
1057        } // case SL_DATALOCATOR_ANDROIDFD
1058        break;
1059    //------------------
1060    //   Stream
1061    case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
1062    {
1063        switch (sourceFormatType) {
1064        case SL_DATAFORMAT_MIME:
1065        {
1066            SLDataFormat_MIME *df_mime = (SLDataFormat_MIME *) pAudioSrc->pFormat;
1067            if (NULL == df_mime) {
1068                SL_LOGE("MIME type null invalid");
1069                return SL_RESULT_CONTENT_UNSUPPORTED;
1070            }
1071            SL_LOGD("source MIME is %s", (char*)df_mime->mimeType);
1072            switch(df_mime->containerType) {
1073            case SL_CONTAINERTYPE_MPEG_TS:
1074                if (strcasecmp((char*)df_mime->mimeType, ANDROID_MIME_MP2TS)) {
1075                    SL_LOGE("Invalid MIME (%s) for container SL_CONTAINERTYPE_MPEG_TS, expects %s",
1076                            (char*)df_mime->mimeType, ANDROID_MIME_MP2TS);
1077                    return SL_RESULT_CONTENT_UNSUPPORTED;
1078                }
1079                break;
1080            case SL_CONTAINERTYPE_RAW:
1081            case SL_CONTAINERTYPE_AAC:
1082                if (strcasecmp((char*)df_mime->mimeType, ANDROID_MIME_AACADTS) &&
1083                        strcasecmp((char*)df_mime->mimeType,
1084                                ANDROID_MIME_AACADTS_ANDROID_FRAMEWORK)) {
1085                    SL_LOGE("Invalid MIME (%s) for container type %d, expects %s",
1086                            (char*)df_mime->mimeType, df_mime->containerType,
1087                            ANDROID_MIME_AACADTS);
1088                    return SL_RESULT_CONTENT_UNSUPPORTED;
1089                }
1090                break;
1091            default:
1092                SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
1093                                        "that is not fed MPEG-2 TS data or AAC ADTS data");
1094                return SL_RESULT_CONTENT_UNSUPPORTED;
1095            }
1096        }
1097        break;
1098        default:
1099            SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
1100                    "without SL_DATAFORMAT_MIME format");
1101            return SL_RESULT_CONTENT_UNSUPPORTED;
1102        }
1103    }
1104    break; // case SL_DATALOCATOR_ANDROIDBUFFERQUEUE
1105    //------------------
1106    //   Address
1107    case SL_DATALOCATOR_ADDRESS:
1108    case SL_DATALOCATOR_IODEVICE:
1109    case SL_DATALOCATOR_OUTPUTMIX:
1110    case XA_DATALOCATOR_NATIVEDISPLAY:
1111    case SL_DATALOCATOR_MIDIBUFFERQUEUE:
1112        SL_LOGE("Cannot create audio player with data locator type 0x%x",
1113                (unsigned) sourceLocatorType);
1114        return SL_RESULT_CONTENT_UNSUPPORTED;
1115    default:
1116        SL_LOGE("Cannot create audio player with invalid data locator type 0x%x",
1117                (unsigned) sourceLocatorType);
1118        return SL_RESULT_PARAMETER_INVALID;
1119    }// switch (locatorType)
1120
1121    return SL_RESULT_SUCCESS;
1122}
1123
1124
1125//-----------------------------------------------------------------------------
1126// Callback associated with an AudioTrack of an SL ES AudioPlayer that gets its data
1127// from a buffer queue. This will not be called once the AudioTrack has been destroyed.
1128static void audioTrack_callBack_pullFromBuffQueue(int event, void* user, void *info) {
1129    CAudioPlayer *ap = (CAudioPlayer *)user;
1130
1131    if (!android::CallbackProtector::enterCbIfOk(ap->mCallbackProtector)) {
1132        // it is not safe to enter the callback (the track is about to go away)
1133        return;
1134    }
1135
1136    void * callbackPContext = NULL;
1137    switch(event) {
1138
1139    case android::AudioTrack::EVENT_MORE_DATA: {
1140        //SL_LOGV("received event EVENT_MORE_DATA from AudioTrack TID=%d", gettid());
1141        slBufferQueueCallback callback = NULL;
1142        slPrefetchCallback prefetchCallback = NULL;
1143        void *prefetchContext = NULL;
1144        SLuint32 prefetchEvents = SL_PREFETCHEVENT_NONE;
1145        android::AudioTrack::Buffer* pBuff = (android::AudioTrack::Buffer*)info;
1146
1147        // retrieve data from the buffer queue
1148        interface_lock_exclusive(&ap->mBufferQueue);
1149
1150        if (ap->mBufferQueue.mState.count != 0) {
1151            //SL_LOGV("nbBuffers in queue = %u",ap->mBufferQueue.mState.count);
1152            assert(ap->mBufferQueue.mFront != ap->mBufferQueue.mRear);
1153
1154            BufferHeader *oldFront = ap->mBufferQueue.mFront;
1155            BufferHeader *newFront = &oldFront[1];
1156
1157            // declared as void * because this code supports both 8-bit and 16-bit PCM data
1158            void *pSrc = (char *)oldFront->mBuffer + ap->mBufferQueue.mSizeConsumed;
1159            if (ap->mBufferQueue.mSizeConsumed + pBuff->size < oldFront->mSize) {
1160                // can't consume the whole or rest of the buffer in one shot
1161                ap->mBufferQueue.mSizeConsumed += pBuff->size;
1162                // leave pBuff->size untouched
1163                // consume data
1164                // FIXME can we avoid holding the lock during the copy?
1165                memcpy (pBuff->raw, pSrc, pBuff->size);
1166            } else {
1167                // finish consuming the buffer or consume the buffer in one shot
1168                pBuff->size = oldFront->mSize - ap->mBufferQueue.mSizeConsumed;
1169                ap->mBufferQueue.mSizeConsumed = 0;
1170
1171                if (newFront ==
1172                        &ap->mBufferQueue.mArray
1173                            [ap->mBufferQueue.mNumBuffers + 1])
1174                {
1175                    newFront = ap->mBufferQueue.mArray;
1176                }
1177                ap->mBufferQueue.mFront = newFront;
1178
1179                ap->mBufferQueue.mState.count--;
1180                ap->mBufferQueue.mState.playIndex++;
1181
1182                // consume data
1183                // FIXME can we avoid holding the lock during the copy?
1184                memcpy (pBuff->raw, pSrc, pBuff->size);
1185
1186                // data has been consumed, and the buffer queue state has been updated
1187                // we will notify the client if applicable
1188                callback = ap->mBufferQueue.mCallback;
1189                // save callback data
1190                callbackPContext = ap->mBufferQueue.mContext;
1191            }
1192        } else { // empty queue
1193            // signal no data available
1194            pBuff->size = 0;
1195
1196            // signal we're at the end of the content, but don't pause (see note in function)
1197            audioPlayer_dispatch_headAtEnd_lockPlay(ap, false /*set state to paused?*/, false);
1198
1199            // signal underflow to prefetch status itf
1200            if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
1201                ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
1202                ap->mPrefetchStatus.mLevel = 0;
1203                // callback or no callback?
1204                prefetchEvents = ap->mPrefetchStatus.mCallbackEventsMask &
1205                        (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE);
1206                if (SL_PREFETCHEVENT_NONE != prefetchEvents) {
1207                    prefetchCallback = ap->mPrefetchStatus.mCallback;
1208                    prefetchContext  = ap->mPrefetchStatus.mContext;
1209                }
1210            }
1211
1212            // stop the track so it restarts playing faster when new data is enqueued
1213            ap->mAudioTrack->stop();
1214        }
1215        interface_unlock_exclusive(&ap->mBufferQueue);
1216
1217        // notify client
1218        if (NULL != prefetchCallback) {
1219            assert(SL_PREFETCHEVENT_NONE != prefetchEvents);
1220            // spec requires separate callbacks for each event
1221            if (prefetchEvents & SL_PREFETCHEVENT_STATUSCHANGE) {
1222                (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext,
1223                        SL_PREFETCHEVENT_STATUSCHANGE);
1224            }
1225            if (prefetchEvents & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
1226                (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext,
1227                        SL_PREFETCHEVENT_FILLLEVELCHANGE);
1228            }
1229        }
1230        if (NULL != callback) {
1231            (*callback)(&ap->mBufferQueue.mItf, callbackPContext);
1232        }
1233    }
1234    break;
1235
1236    case android::AudioTrack::EVENT_MARKER:
1237        //SL_LOGI("received event EVENT_MARKER from AudioTrack");
1238        audioTrack_handleMarker_lockPlay(ap);
1239        break;
1240
1241    case android::AudioTrack::EVENT_NEW_POS:
1242        //SL_LOGI("received event EVENT_NEW_POS from AudioTrack");
1243        audioTrack_handleNewPos_lockPlay(ap);
1244        break;
1245
1246    case android::AudioTrack::EVENT_UNDERRUN:
1247        //SL_LOGI("received event EVENT_UNDERRUN from AudioTrack");
1248        audioTrack_handleUnderrun_lockPlay(ap);
1249        break;
1250
1251    default:
1252        // FIXME where does the notification of SL_PLAYEVENT_HEADMOVING fit?
1253        SL_LOGE("Encountered unknown AudioTrack event %d for CAudioPlayer %p", event,
1254                (CAudioPlayer *)user);
1255        break;
1256    }
1257
1258    ap->mCallbackProtector->exitCb();
1259}
1260
1261
1262//-----------------------------------------------------------------------------
1263SLresult android_audioPlayer_create(CAudioPlayer *pAudioPlayer) {
1264
1265    SLresult result = SL_RESULT_SUCCESS;
1266    // pAudioPlayer->mAndroidObjType has been set in audioPlayer_getAndroidObjectTypeForSourceSink()
1267    if (INVALID_TYPE == pAudioPlayer->mAndroidObjType) {
1268        audioPlayer_setInvalid(pAudioPlayer);
1269        result = SL_RESULT_PARAMETER_INVALID;
1270    } else {
1271
1272        // These initializations are in the same order as the field declarations in classes.h
1273
1274        // FIXME Consolidate initializations (many of these already in IEngine_CreateAudioPlayer)
1275        // mAndroidObjType: see above comment
1276        pAudioPlayer->mAndroidObjState = ANDROID_UNINITIALIZED;
1277        pAudioPlayer->mSessionId = android::AudioSystem::newAudioSessionId();
1278        pAudioPlayer->mStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
1279
1280        // mAudioTrack
1281        pAudioPlayer->mCallbackProtector = new android::CallbackProtector();
1282        // mAPLayer
1283        // mAuxEffect
1284
1285        pAudioPlayer->mAuxSendLevel = 0;
1286        pAudioPlayer->mAmplFromDirectLevel = 1.0f; // matches initial mDirectLevel value
1287        pAudioPlayer->mDeferredStart = false;
1288
1289        // Already initialized in IEngine_CreateAudioPlayer, to be consolidated
1290        pAudioPlayer->mDirectLevel = 0; // no attenuation
1291
1292        // This section re-initializes interface-specific fields that
1293        // can be set or used regardless of whether the interface is
1294        // exposed on the AudioPlayer or not
1295
1296        // Only AudioTrack supports a non-trivial playback rate
1297        switch (pAudioPlayer->mAndroidObjType) {
1298        case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1299            pAudioPlayer->mPlaybackRate.mMinRate = AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE;
1300            pAudioPlayer->mPlaybackRate.mMaxRate = AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE;
1301            break;
1302        default:
1303            // use the default range
1304            break;
1305        }
1306
1307    }
1308
1309    return result;
1310}
1311
1312
1313//-----------------------------------------------------------------------------
1314SLresult android_audioPlayer_setConfig(CAudioPlayer *ap, const SLchar *configKey,
1315        const void *pConfigValue, SLuint32 valueSize) {
1316
1317    SLresult result;
1318
1319    assert(NULL != ap && NULL != configKey && NULL != pConfigValue);
1320    if(strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) {
1321
1322        // stream type
1323        if (KEY_STREAM_TYPE_PARAMSIZE > valueSize) {
1324            SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1325            result = SL_RESULT_BUFFER_INSUFFICIENT;
1326        } else {
1327            result = audioPlayer_setStreamType(ap, *(SLuint32*)pConfigValue);
1328        }
1329
1330    } else {
1331        SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY);
1332        result = SL_RESULT_PARAMETER_INVALID;
1333    }
1334
1335    return result;
1336}
1337
1338
1339//-----------------------------------------------------------------------------
1340SLresult android_audioPlayer_getConfig(CAudioPlayer* ap, const SLchar *configKey,
1341        SLuint32* pValueSize, void *pConfigValue) {
1342
1343    SLresult result;
1344
1345    assert(NULL != ap && NULL != configKey && NULL != pValueSize);
1346    if(strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) {
1347
1348        // stream type
1349        if (NULL == pConfigValue) {
1350            result = SL_RESULT_SUCCESS;
1351        } else if (KEY_STREAM_TYPE_PARAMSIZE > *pValueSize) {
1352            SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1353            result = SL_RESULT_BUFFER_INSUFFICIENT;
1354        } else {
1355            result = audioPlayer_getStreamType(ap, (SLint32*)pConfigValue);
1356        }
1357        *pValueSize = KEY_STREAM_TYPE_PARAMSIZE;
1358
1359    } else {
1360        SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY);
1361        result = SL_RESULT_PARAMETER_INVALID;
1362    }
1363
1364    return result;
1365}
1366
1367
1368//-----------------------------------------------------------------------------
1369// FIXME abstract out the diff between CMediaPlayer and CAudioPlayer
1370SLresult android_audioPlayer_realize(CAudioPlayer *pAudioPlayer, SLboolean async) {
1371
1372    SLresult result = SL_RESULT_SUCCESS;
1373    SL_LOGV("Realize pAudioPlayer=%p", pAudioPlayer);
1374
1375    switch (pAudioPlayer->mAndroidObjType) {
1376    //-----------------------------------
1377    // AudioTrack
1378    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1379        {
1380        // initialize platform-specific CAudioPlayer fields
1381
1382        SLDataLocator_BufferQueue *dl_bq =  (SLDataLocator_BufferQueue *)
1383                pAudioPlayer->mDynamicSource.mDataSource;
1384        SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *)
1385                pAudioPlayer->mDynamicSource.mDataSource->pFormat;
1386
1387        uint32_t sampleRate = sles_to_android_sampleRate(df_pcm->samplesPerSec);
1388
1389        pAudioPlayer->mAudioTrack = new android::AudioTrackProxy(new android::AudioTrack(
1390                pAudioPlayer->mStreamType,                           // streamType
1391                sampleRate,                                          // sampleRate
1392                sles_to_android_sampleFormat(df_pcm->bitsPerSample), // format
1393                sles_to_android_channelMaskOut(df_pcm->numChannels, df_pcm->channelMask),
1394                                                                     //channel mask
1395                0,                                                   // frameCount (here min)
1396                0,                                                   // flags
1397                audioTrack_callBack_pullFromBuffQueue,               // callback
1398                (void *) pAudioPlayer,                               // user
1399                0      // FIXME find appropriate frame count         // notificationFrame
1400                , pAudioPlayer->mSessionId
1401                ));
1402        android::status_t status = pAudioPlayer->mAudioTrack->initCheck();
1403        if (status != android::NO_ERROR) {
1404            SL_LOGE("AudioTrack::initCheck status %u", status);
1405            result = SL_RESULT_CONTENT_UNSUPPORTED;
1406            pAudioPlayer->mAudioTrack.clear();
1407            return result;
1408        }
1409
1410        // initialize platform-independent CAudioPlayer fields
1411
1412        pAudioPlayer->mNumChannels = df_pcm->numChannels;
1413        pAudioPlayer->mSampleRateMilliHz = df_pcm->samplesPerSec; // Note: bad field name in SL ES
1414
1415        // This use case does not have a separate "prepare" step
1416        pAudioPlayer->mAndroidObjState = ANDROID_READY;
1417        }
1418        break;
1419    //-----------------------------------
1420    // MediaPlayer
1421    case AUDIOPLAYER_FROM_URIFD: {
1422        assert(pAudioPlayer->mAndroidObjState == ANDROID_UNINITIALIZED);
1423        assert(pAudioPlayer->mNumChannels == UNKNOWN_NUMCHANNELS);
1424        assert(pAudioPlayer->mSampleRateMilliHz == UNKNOWN_SAMPLERATE);
1425        assert(pAudioPlayer->mAudioTrack == 0);
1426
1427        AudioPlayback_Parameters app;
1428        app.sessionId = pAudioPlayer->mSessionId;
1429        app.streamType = pAudioPlayer->mStreamType;
1430
1431        pAudioPlayer->mAPlayer = new android::LocAVPlayer(&app, false /*hasVideo*/);
1432        pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent,
1433                        (void*)pAudioPlayer /*notifUSer*/);
1434
1435        switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) {
1436            case SL_DATALOCATOR_URI: {
1437                // The legacy implementation ran Stagefright within the application process, and
1438                // so allowed local pathnames specified by URI that were openable by
1439                // the application but were not openable by mediaserver.
1440                // The current implementation runs Stagefright (mostly) within mediaserver,
1441                // which runs as a different UID and likely a different current working directory.
1442                // For backwards compatibility with any applications which may have relied on the
1443                // previous behavior, we convert an openable file URI into an FD.
1444                // Note that unlike SL_DATALOCATOR_ANDROIDFD, this FD is owned by us
1445                // and so we close it as soon as we've passed it (via Binder dup) to mediaserver.
1446                const char *uri = (const char *)pAudioPlayer->mDataSource.mLocator.mURI.URI;
1447                if (!isDistantProtocol(uri)) {
1448                    // don't touch the original uri, we may need it later
1449                    const char *pathname = uri;
1450                    // skip over an optional leading file:// prefix
1451                    if (!strncasecmp(pathname, "file://", 7)) {
1452                        pathname += 7;
1453                    }
1454                    // attempt to open it as a file using the application's credentials
1455                    int fd = ::open(pathname, O_RDONLY);
1456                    if (fd >= 0) {
1457                        // if open is successful, then check to see if it's a regular file
1458                        struct stat statbuf;
1459                        if (!::fstat(fd, &statbuf) && S_ISREG(statbuf.st_mode)) {
1460                            // treat similarly to an FD data locator, but
1461                            // let setDataSource take responsibility for closing fd
1462                            pAudioPlayer->mAPlayer->setDataSource(fd, 0, statbuf.st_size, true);
1463                            break;
1464                        }
1465                        // we were able to open it, but it's not a file, so let mediaserver try
1466                        (void) ::close(fd);
1467                    }
1468                }
1469                // if either the URI didn't look like a file, or open failed, or not a file
1470                pAudioPlayer->mAPlayer->setDataSource(uri);
1471                } break;
1472            case SL_DATALOCATOR_ANDROIDFD: {
1473                int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset;
1474                pAudioPlayer->mAPlayer->setDataSource(
1475                        (int)pAudioPlayer->mDataSource.mLocator.mFD.fd,
1476                        offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
1477                                (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
1478                        (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length);
1479                }
1480                break;
1481            default:
1482                SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR);
1483                break;
1484        }
1485
1486        }
1487        break;
1488    //-----------------------------------
1489    // StreamPlayer
1490    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: {
1491        AudioPlayback_Parameters ap_params;
1492        ap_params.sessionId = pAudioPlayer->mSessionId;
1493        ap_params.streamType = pAudioPlayer->mStreamType;
1494        android::StreamPlayer* splr = new android::StreamPlayer(&ap_params, false /*hasVideo*/,
1495                &pAudioPlayer->mAndroidBufferQueue, pAudioPlayer->mCallbackProtector);
1496        pAudioPlayer->mAPlayer = splr;
1497        splr->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1498        }
1499        break;
1500    //-----------------------------------
1501    // AudioToCbRenderer
1502    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
1503        AudioPlayback_Parameters app;
1504        app.sessionId = pAudioPlayer->mSessionId;
1505        app.streamType = pAudioPlayer->mStreamType;
1506
1507        android::AudioToCbRenderer* decoder = new android::AudioToCbRenderer(&app);
1508        pAudioPlayer->mAPlayer = decoder;
1509        // configures the callback for the sink buffer queue
1510        decoder->setDataPushListener(adecoder_writeToBufferQueue, pAudioPlayer);
1511        // configures the callback for the notifications coming from the SF code
1512        decoder->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1513
1514        switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) {
1515        case SL_DATALOCATOR_URI:
1516            decoder->setDataSource(
1517                    (const char*)pAudioPlayer->mDataSource.mLocator.mURI.URI);
1518            break;
1519        case SL_DATALOCATOR_ANDROIDFD: {
1520            int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset;
1521            decoder->setDataSource(
1522                    (int)pAudioPlayer->mDataSource.mLocator.mFD.fd,
1523                    offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
1524                            (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
1525                            (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length);
1526            }
1527            break;
1528        default:
1529            SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR);
1530            break;
1531        }
1532
1533        }
1534        break;
1535    //-----------------------------------
1536    // AacBqToPcmCbRenderer
1537    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
1538        AudioPlayback_Parameters app;
1539        app.sessionId = pAudioPlayer->mSessionId;
1540        app.streamType = pAudioPlayer->mStreamType;
1541        android::AacBqToPcmCbRenderer* bqtobq = new android::AacBqToPcmCbRenderer(&app);
1542        // configures the callback for the sink buffer queue
1543        bqtobq->setDataPushListener(adecoder_writeToBufferQueue, pAudioPlayer);
1544        pAudioPlayer->mAPlayer = bqtobq;
1545        // configures the callback for the notifications coming from the SF code,
1546        // but also implicitly configures the AndroidBufferQueue from which ADTS data is read
1547        pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1548        }
1549        break;
1550    //-----------------------------------
1551    default:
1552        SL_LOGE(ERROR_PLAYERREALIZE_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType);
1553        result = SL_RESULT_INTERNAL_ERROR;
1554        break;
1555    }
1556
1557
1558    // proceed with effect initialization
1559    // initialize EQ
1560    // FIXME use a table of effect descriptors when adding support for more effects
1561    if (memcmp(SL_IID_EQUALIZER, &pAudioPlayer->mEqualizer.mEqDescriptor.type,
1562            sizeof(effect_uuid_t)) == 0) {
1563        SL_LOGV("Need to initialize EQ for AudioPlayer=%p", pAudioPlayer);
1564        android_eq_init(pAudioPlayer->mSessionId, &pAudioPlayer->mEqualizer);
1565    }
1566    // initialize BassBoost
1567    if (memcmp(SL_IID_BASSBOOST, &pAudioPlayer->mBassBoost.mBassBoostDescriptor.type,
1568            sizeof(effect_uuid_t)) == 0) {
1569        SL_LOGV("Need to initialize BassBoost for AudioPlayer=%p", pAudioPlayer);
1570        android_bb_init(pAudioPlayer->mSessionId, &pAudioPlayer->mBassBoost);
1571    }
1572    // initialize Virtualizer
1573    if (memcmp(SL_IID_VIRTUALIZER, &pAudioPlayer->mVirtualizer.mVirtualizerDescriptor.type,
1574               sizeof(effect_uuid_t)) == 0) {
1575        SL_LOGV("Need to initialize Virtualizer for AudioPlayer=%p", pAudioPlayer);
1576        android_virt_init(pAudioPlayer->mSessionId, &pAudioPlayer->mVirtualizer);
1577    }
1578
1579    // initialize EffectSend
1580    // FIXME initialize EffectSend
1581
1582    return result;
1583}
1584
1585
1586//-----------------------------------------------------------------------------
1587/**
1588 * Called with a lock on AudioPlayer, and blocks until safe to destroy
1589 */
1590SLresult android_audioPlayer_preDestroy(CAudioPlayer *pAudioPlayer) {
1591    SL_LOGD("android_audioPlayer_preDestroy(%p)", pAudioPlayer);
1592    SLresult result = SL_RESULT_SUCCESS;
1593
1594  bool disableCallbacksBeforePreDestroy;
1595  switch (pAudioPlayer->mAndroidObjType) {
1596  // Not yet clear why this order is important, but it reduces detected deadlocks
1597  case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1598    disableCallbacksBeforePreDestroy = true;
1599    break;
1600  // Use the old behavior for all other use cases until proven
1601  // case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1602  default:
1603    disableCallbacksBeforePreDestroy = false;
1604    break;
1605  }
1606
1607  if (disableCallbacksBeforePreDestroy) {
1608    object_unlock_exclusive(&pAudioPlayer->mObject);
1609    if (pAudioPlayer->mCallbackProtector != 0) {
1610        pAudioPlayer->mCallbackProtector->requestCbExitAndWait();
1611    }
1612    object_lock_exclusive(&pAudioPlayer->mObject);
1613  }
1614
1615    if (pAudioPlayer->mAPlayer != 0) {
1616        pAudioPlayer->mAPlayer->preDestroy();
1617    }
1618    SL_LOGD("android_audioPlayer_preDestroy(%p) after mAPlayer->preDestroy()", pAudioPlayer);
1619
1620  if (!disableCallbacksBeforePreDestroy) {
1621    object_unlock_exclusive(&pAudioPlayer->mObject);
1622    if (pAudioPlayer->mCallbackProtector != 0) {
1623        pAudioPlayer->mCallbackProtector->requestCbExitAndWait();
1624    }
1625    object_lock_exclusive(&pAudioPlayer->mObject);
1626  }
1627
1628    return result;
1629}
1630
1631
1632//-----------------------------------------------------------------------------
1633SLresult android_audioPlayer_destroy(CAudioPlayer *pAudioPlayer) {
1634    SLresult result = SL_RESULT_SUCCESS;
1635    SL_LOGV("android_audioPlayer_destroy(%p)", pAudioPlayer);
1636    switch (pAudioPlayer->mAndroidObjType) {
1637
1638    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1639        // We own the audio track for PCM buffer queue players
1640        if (pAudioPlayer->mAudioTrack != 0) {
1641            pAudioPlayer->mAudioTrack->stop();
1642            // Note that there may still be another reference in post-unlock phase of SetPlayState
1643            pAudioPlayer->mAudioTrack.clear();
1644        }
1645        break;
1646
1647    case AUDIOPLAYER_FROM_URIFD:     // intended fall-through
1648    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:    // intended fall-through
1649    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: // intended fall-through
1650    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1651        pAudioPlayer->mAPlayer.clear();
1652        break;
1653    //-----------------------------------
1654    default:
1655        SL_LOGE(ERROR_PLAYERDESTROY_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType);
1656        result = SL_RESULT_INTERNAL_ERROR;
1657        break;
1658    }
1659
1660    pAudioPlayer->mCallbackProtector.clear();
1661
1662    // FIXME might not be needed
1663    pAudioPlayer->mAndroidObjType = INVALID_TYPE;
1664
1665    // explicit destructor
1666    pAudioPlayer->mAudioTrack.~sp();
1667    // note that SetPlayState(PLAYING) may still hold a reference
1668    pAudioPlayer->mCallbackProtector.~sp();
1669    pAudioPlayer->mAuxEffect.~sp();
1670    pAudioPlayer->mAPlayer.~sp();
1671
1672    return result;
1673}
1674
1675
1676//-----------------------------------------------------------------------------
1677SLresult android_audioPlayer_setPlaybackRateAndConstraints(CAudioPlayer *ap, SLpermille rate,
1678        SLuint32 constraints) {
1679    SLresult result = SL_RESULT_SUCCESS;
1680    switch(ap->mAndroidObjType) {
1681    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: {
1682        // these asserts were already checked by the platform-independent layer
1683        assert((AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE <= rate) &&
1684                (rate <= AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE));
1685        assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO);
1686        // get the content sample rate
1687        uint32_t contentRate = sles_to_android_sampleRate(ap->mSampleRateMilliHz);
1688        // apply the SL ES playback rate on the AudioTrack as a factor of its content sample rate
1689        if (ap->mAudioTrack != 0) {
1690            ap->mAudioTrack->setSampleRate(contentRate * (rate/1000.0f));
1691        }
1692        }
1693        break;
1694    case AUDIOPLAYER_FROM_URIFD:
1695        assert(rate == 1000);
1696        assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO);
1697        // that was easy
1698        break;
1699
1700    default:
1701        SL_LOGE("Unexpected object type %d", ap->mAndroidObjType);
1702        result = SL_RESULT_FEATURE_UNSUPPORTED;
1703        break;
1704    }
1705    return result;
1706}
1707
1708
1709//-----------------------------------------------------------------------------
1710// precondition
1711//  called with no lock held
1712//  ap != NULL
1713//  pItemCount != NULL
1714SLresult android_audioPlayer_metadata_getItemCount(CAudioPlayer *ap, SLuint32 *pItemCount) {
1715    if (ap->mAPlayer == 0) {
1716        return SL_RESULT_PARAMETER_INVALID;
1717    }
1718    switch(ap->mAndroidObjType) {
1719      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1720      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1721        {
1722            android::AudioSfDecoder* decoder =
1723                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1724            *pItemCount = decoder->getPcmFormatKeyCount();
1725        }
1726        break;
1727      default:
1728        *pItemCount = 0;
1729        break;
1730    }
1731    return SL_RESULT_SUCCESS;
1732}
1733
1734
1735//-----------------------------------------------------------------------------
1736// precondition
1737//  called with no lock held
1738//  ap != NULL
1739//  pKeySize != NULL
1740SLresult android_audioPlayer_metadata_getKeySize(CAudioPlayer *ap,
1741        SLuint32 index, SLuint32 *pKeySize) {
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            SLuint32 keyNameSize = 0;
1753            if (!decoder->getPcmFormatKeySize(index, &keyNameSize)) {
1754                res = SL_RESULT_PARAMETER_INVALID;
1755            } else {
1756                // *pKeySize is the size of the region used to store the key name AND
1757                //   the information about the key (size, lang, encoding)
1758                *pKeySize = keyNameSize + sizeof(SLMetadataInfo);
1759            }
1760        }
1761        break;
1762      default:
1763        *pKeySize = 0;
1764        res = SL_RESULT_PARAMETER_INVALID;
1765        break;
1766    }
1767    return res;
1768}
1769
1770
1771//-----------------------------------------------------------------------------
1772// precondition
1773//  called with no lock held
1774//  ap != NULL
1775//  pKey != NULL
1776SLresult android_audioPlayer_metadata_getKey(CAudioPlayer *ap,
1777        SLuint32 index, SLuint32 size, SLMetadataInfo *pKey) {
1778    if (ap->mAPlayer == 0) {
1779        return SL_RESULT_PARAMETER_INVALID;
1780    }
1781    SLresult res = SL_RESULT_SUCCESS;
1782    switch(ap->mAndroidObjType) {
1783      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1784      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1785        {
1786            android::AudioSfDecoder* decoder =
1787                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1788            if ((size < sizeof(SLMetadataInfo) ||
1789                    (!decoder->getPcmFormatKeyName(index, size - sizeof(SLMetadataInfo),
1790                            (char*)pKey->data)))) {
1791                res = SL_RESULT_PARAMETER_INVALID;
1792            } else {
1793                // successfully retrieved the key value, update the other fields
1794                pKey->encoding = SL_CHARACTERENCODING_UTF8;
1795                memcpy((char *) pKey->langCountry, "en", 3);
1796                pKey->size = strlen((char*)pKey->data) + 1;
1797            }
1798        }
1799        break;
1800      default:
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//  pValueSize != NULL
1813SLresult android_audioPlayer_metadata_getValueSize(CAudioPlayer *ap,
1814        SLuint32 index, SLuint32 *pValueSize) {
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            SLuint32 valueSize = 0;
1826            if (!decoder->getPcmFormatValueSize(index, &valueSize)) {
1827                res = SL_RESULT_PARAMETER_INVALID;
1828            } else {
1829                // *pValueSize is the size of the region used to store the key value AND
1830                //   the information about the value (size, lang, encoding)
1831                *pValueSize = valueSize + sizeof(SLMetadataInfo);
1832            }
1833        }
1834        break;
1835      default:
1836          *pValueSize = 0;
1837          res = SL_RESULT_PARAMETER_INVALID;
1838          break;
1839    }
1840    return res;
1841}
1842
1843
1844//-----------------------------------------------------------------------------
1845// precondition
1846//  called with no lock held
1847//  ap != NULL
1848//  pValue != NULL
1849SLresult android_audioPlayer_metadata_getValue(CAudioPlayer *ap,
1850        SLuint32 index, SLuint32 size, SLMetadataInfo *pValue) {
1851    if (ap->mAPlayer == 0) {
1852        return SL_RESULT_PARAMETER_INVALID;
1853    }
1854    SLresult res = SL_RESULT_SUCCESS;
1855    switch(ap->mAndroidObjType) {
1856      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1857      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1858        {
1859            android::AudioSfDecoder* decoder =
1860                    static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
1861            pValue->encoding = SL_CHARACTERENCODING_BINARY;
1862            memcpy((char *) pValue->langCountry, "en", 3); // applicable here?
1863            SLuint32 valueSize = 0;
1864            if ((size < sizeof(SLMetadataInfo)
1865                    || (!decoder->getPcmFormatValueSize(index, &valueSize))
1866                    || (!decoder->getPcmFormatKeyValue(index, size - sizeof(SLMetadataInfo),
1867                            (SLuint32*)pValue->data)))) {
1868                res = SL_RESULT_PARAMETER_INVALID;
1869            } else {
1870                pValue->size = valueSize;
1871            }
1872        }
1873        break;
1874      default:
1875        res = SL_RESULT_PARAMETER_INVALID;
1876        break;
1877    }
1878    return res;
1879}
1880
1881//-----------------------------------------------------------------------------
1882// preconditions
1883//  ap != NULL
1884//  mutex is locked
1885//  play state has changed
1886void android_audioPlayer_setPlayState(CAudioPlayer *ap) {
1887
1888    SLuint32 playState = ap->mPlay.mState;
1889    AndroidObjectState objState = ap->mAndroidObjState;
1890
1891    switch(ap->mAndroidObjType) {
1892    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1893        switch (playState) {
1894        case SL_PLAYSTATE_STOPPED:
1895            SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_STOPPED");
1896            if (ap->mAudioTrack != 0) {
1897                ap->mAudioTrack->stop();
1898            }
1899            break;
1900        case SL_PLAYSTATE_PAUSED:
1901            SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PAUSED");
1902            if (ap->mAudioTrack != 0) {
1903                ap->mAudioTrack->pause();
1904            }
1905            break;
1906        case SL_PLAYSTATE_PLAYING:
1907            SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PLAYING");
1908            if (ap->mAudioTrack != 0) {
1909                // instead of ap->mAudioTrack->start();
1910                ap->mDeferredStart = true;
1911            }
1912            break;
1913        default:
1914            // checked by caller, should not happen
1915            break;
1916        }
1917        break;
1918
1919    case AUDIOPLAYER_FROM_URIFD:      // intended fall-through
1920    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:     // intended fall-through
1921    case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:  // intended fall-through
1922    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1923        // FIXME report and use the return code to the lock mechanism, which is where play state
1924        //   changes are updated (see object_unlock_exclusive_attributes())
1925        aplayer_setPlayState(ap->mAPlayer, playState, &(ap->mAndroidObjState));
1926        break;
1927    default:
1928        SL_LOGE(ERROR_PLAYERSETPLAYSTATE_UNEXPECTED_OBJECT_TYPE_D, ap->mAndroidObjType);
1929        break;
1930    }
1931}
1932
1933
1934//-----------------------------------------------------------------------------
1935// call when either player event flags, marker position, or position update period changes
1936void android_audioPlayer_usePlayEventMask(CAudioPlayer *ap) {
1937    IPlay *pPlayItf = &ap->mPlay;
1938    SLuint32 eventFlags = pPlayItf->mEventFlags;
1939    /*switch(ap->mAndroidObjType) {
1940    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:*/
1941
1942    if (ap->mAPlayer != 0) {
1943        assert(ap->mAudioTrack == 0);
1944        ap->mAPlayer->setPlayEvents((int32_t) eventFlags, (int32_t) pPlayItf->mMarkerPosition,
1945                (int32_t) pPlayItf->mPositionUpdatePeriod);
1946        return;
1947    }
1948
1949    if (ap->mAudioTrack == 0) {
1950        return;
1951    }
1952
1953    if (eventFlags & SL_PLAYEVENT_HEADATMARKER) {
1954        ap->mAudioTrack->setMarkerPosition((uint32_t)((((int64_t)pPlayItf->mMarkerPosition
1955                * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000));
1956    } else {
1957        // clear marker
1958        ap->mAudioTrack->setMarkerPosition(0);
1959    }
1960
1961    if (eventFlags & SL_PLAYEVENT_HEADATNEWPOS) {
1962         ap->mAudioTrack->setPositionUpdatePeriod(
1963                (uint32_t)((((int64_t)pPlayItf->mPositionUpdatePeriod
1964                * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000));
1965    } else {
1966        // clear periodic update
1967        ap->mAudioTrack->setPositionUpdatePeriod(0);
1968    }
1969
1970    if (eventFlags & SL_PLAYEVENT_HEADATEND) {
1971        // nothing to do for SL_PLAYEVENT_HEADATEND, callback event will be checked against mask
1972    }
1973
1974    if (eventFlags & SL_PLAYEVENT_HEADMOVING) {
1975        // FIXME support SL_PLAYEVENT_HEADMOVING
1976        SL_LOGD("[ FIXME: IPlay_SetCallbackEventsMask(SL_PLAYEVENT_HEADMOVING) on an "
1977            "SL_OBJECTID_AUDIOPLAYER to be implemented ]");
1978    }
1979    if (eventFlags & SL_PLAYEVENT_HEADSTALLED) {
1980        // nothing to do for SL_PLAYEVENT_HEADSTALLED, callback event will be checked against mask
1981    }
1982
1983}
1984
1985
1986//-----------------------------------------------------------------------------
1987SLresult android_audioPlayer_getDuration(IPlay *pPlayItf, SLmillisecond *pDurMsec) {
1988    CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis;
1989    switch(ap->mAndroidObjType) {
1990
1991      case AUDIOPLAYER_FROM_URIFD:  // intended fall-through
1992      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
1993        int32_t durationMsec = ANDROID_UNKNOWN_TIME;
1994        if (ap->mAPlayer != 0) {
1995            ap->mAPlayer->getDurationMsec(&durationMsec);
1996        }
1997        *pDurMsec = durationMsec == ANDROID_UNKNOWN_TIME ? SL_TIME_UNKNOWN : durationMsec;
1998        break;
1999      }
2000
2001      case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
2002      case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2003      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2004      default: {
2005        *pDurMsec = SL_TIME_UNKNOWN;
2006      }
2007    }
2008    return SL_RESULT_SUCCESS;
2009}
2010
2011
2012//-----------------------------------------------------------------------------
2013void android_audioPlayer_getPosition(IPlay *pPlayItf, SLmillisecond *pPosMsec) {
2014    CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis;
2015    switch(ap->mAndroidObjType) {
2016
2017      case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2018        if ((ap->mSampleRateMilliHz == UNKNOWN_SAMPLERATE) || (ap->mAudioTrack == 0)) {
2019            *pPosMsec = 0;
2020        } else {
2021            uint32_t positionInFrames;
2022            ap->mAudioTrack->getPosition(&positionInFrames);
2023            *pPosMsec = ((int64_t)positionInFrames * 1000) /
2024                    sles_to_android_sampleRate(ap->mSampleRateMilliHz);
2025        }
2026        break;
2027
2028      case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:    // intended fall-through
2029      case AUDIOPLAYER_FROM_URIFD:
2030      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2031      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
2032        int32_t posMsec = ANDROID_UNKNOWN_TIME;
2033        if (ap->mAPlayer != 0) {
2034            ap->mAPlayer->getPositionMsec(&posMsec);
2035        }
2036        *pPosMsec = posMsec == ANDROID_UNKNOWN_TIME ? 0 : posMsec;
2037        break;
2038      }
2039
2040      default:
2041        *pPosMsec = 0;
2042    }
2043}
2044
2045
2046//-----------------------------------------------------------------------------
2047SLresult android_audioPlayer_seek(CAudioPlayer *ap, SLmillisecond posMsec) {
2048    SLresult result = SL_RESULT_SUCCESS;
2049
2050    switch(ap->mAndroidObjType) {
2051
2052      case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:      // intended fall-through
2053      case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2054      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2055        result = SL_RESULT_FEATURE_UNSUPPORTED;
2056        break;
2057
2058      case AUDIOPLAYER_FROM_URIFD:                   // intended fall-through
2059      case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2060        if (ap->mAPlayer != 0) {
2061            ap->mAPlayer->seek(posMsec);
2062        }
2063        break;
2064
2065      default:
2066        break;
2067    }
2068    return result;
2069}
2070
2071
2072//-----------------------------------------------------------------------------
2073SLresult android_audioPlayer_loop(CAudioPlayer *ap, SLboolean loopEnable) {
2074    SLresult result = SL_RESULT_SUCCESS;
2075
2076    switch (ap->mAndroidObjType) {
2077    case AUDIOPLAYER_FROM_URIFD:
2078    // case AUDIOPLAY_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2079    //      would actually work, but what's the point?
2080      if (ap->mAPlayer != 0) {
2081        ap->mAPlayer->loop((bool)loopEnable);
2082      }
2083      break;
2084    default:
2085      result = SL_RESULT_FEATURE_UNSUPPORTED;
2086      break;
2087    }
2088    return result;
2089}
2090
2091
2092//-----------------------------------------------------------------------------
2093SLresult android_audioPlayer_setBufferingUpdateThresholdPerMille(CAudioPlayer *ap,
2094        SLpermille threshold) {
2095    SLresult result = SL_RESULT_SUCCESS;
2096
2097    switch (ap->mAndroidObjType) {
2098      case AUDIOPLAYER_FROM_URIFD:
2099        if (ap->mAPlayer != 0) {
2100            ap->mAPlayer->setBufferingUpdateThreshold(threshold / 10);
2101        }
2102        break;
2103
2104      default: {}
2105    }
2106
2107    return result;
2108}
2109
2110
2111//-----------------------------------------------------------------------------
2112void android_audioPlayer_bufferQueue_onRefilled_l(CAudioPlayer *ap) {
2113    // the AudioTrack associated with the AudioPlayer receiving audio from a PCM buffer
2114    // queue was stopped when the queue become empty, we restart as soon as a new buffer
2115    // has been enqueued since we're in playing state
2116    if (ap->mAudioTrack != 0) {
2117        // instead of ap->mAudioTrack->start();
2118        ap->mDeferredStart = true;
2119    }
2120
2121    // when the queue became empty, an underflow on the prefetch status itf was sent. Now the queue
2122    // has received new data, signal it has sufficient data
2123    if (IsInterfaceInitialized(&(ap->mObject), MPH_PREFETCHSTATUS)) {
2124        // we wouldn't have been called unless we were previously in the underflow state
2125        assert(SL_PREFETCHSTATUS_UNDERFLOW == ap->mPrefetchStatus.mStatus);
2126        assert(0 == ap->mPrefetchStatus.mLevel);
2127        ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA;
2128        ap->mPrefetchStatus.mLevel = 1000;
2129        // callback or no callback?
2130        SLuint32 prefetchEvents = ap->mPrefetchStatus.mCallbackEventsMask &
2131                (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE);
2132        if (SL_PREFETCHEVENT_NONE != prefetchEvents) {
2133            ap->mPrefetchStatus.mDeferredPrefetchCallback = ap->mPrefetchStatus.mCallback;
2134            ap->mPrefetchStatus.mDeferredPrefetchContext  = ap->mPrefetchStatus.mContext;
2135            ap->mPrefetchStatus.mDeferredPrefetchEvents   = prefetchEvents;
2136        }
2137    }
2138}
2139
2140
2141//-----------------------------------------------------------------------------
2142/*
2143 * BufferQueue::Clear
2144 */
2145SLresult android_audioPlayer_bufferQueue_onClear(CAudioPlayer *ap) {
2146    SLresult result = SL_RESULT_SUCCESS;
2147
2148    switch (ap->mAndroidObjType) {
2149    //-----------------------------------
2150    // AudioTrack
2151    case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2152        if (ap->mAudioTrack != 0) {
2153            ap->mAudioTrack->flush();
2154        }
2155        break;
2156    default:
2157        result = SL_RESULT_INTERNAL_ERROR;
2158        break;
2159    }
2160
2161    return result;
2162}
2163
2164
2165//-----------------------------------------------------------------------------
2166SLresult android_audioPlayer_androidBufferQueue_registerCallback_l(CAudioPlayer *ap) {
2167    SLresult result = SL_RESULT_SUCCESS;
2168    assert(ap->mAPlayer != 0);
2169    // FIXME investigate why these two cases are not handled symmetrically any more
2170    switch (ap->mAndroidObjType) {
2171      case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: {
2172        } break;
2173      case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
2174          android::AacBqToPcmCbRenderer* dec =
2175                  static_cast<android::AacBqToPcmCbRenderer*>(ap->mAPlayer.get());
2176          dec->registerSourceQueueCallback((const void*)ap /*user*/,
2177                  ap->mAndroidBufferQueue.mContext /*context*/,
2178                  (const void*)&(ap->mAndroidBufferQueue.mItf) /*caller*/);
2179        } break;
2180      default:
2181        SL_LOGE("Error registering AndroidBufferQueue callback: unexpected object type %d",
2182                ap->mAndroidObjType);
2183        result = SL_RESULT_INTERNAL_ERROR;
2184        break;
2185    }
2186    return result;
2187}
2188
2189//-----------------------------------------------------------------------------
2190void android_audioPlayer_androidBufferQueue_clear_l(CAudioPlayer *ap) {
2191    switch (ap->mAndroidObjType) {
2192    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2193      if (ap->mAPlayer != 0) {
2194        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2195        splr->appClear_l();
2196      } break;
2197    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2198      // nothing to do here, fall through
2199    default:
2200      break;
2201    }
2202}
2203
2204void android_audioPlayer_androidBufferQueue_onRefilled_l(CAudioPlayer *ap) {
2205    switch (ap->mAndroidObjType) {
2206    case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2207      if (ap->mAPlayer != 0) {
2208        android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2209        splr->queueRefilled();
2210      } break;
2211    case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2212      // FIXME this may require waking up the decoder if it is currently starved and isn't polling
2213    default:
2214      break;
2215    }
2216}
2217