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