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