• 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     switch (sourceLocatorType) {
1053     //------------------
1054     //   Buffer Queues
1055     case SL_DATALOCATOR_BUFFERQUEUE:
1056     case SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE:
1057         {
1058         // Buffer format
1059         switch (sourceFormatType) {
1060         //     currently only PCM buffer queues are supported,
1061         case SL_ANDROID_DATAFORMAT_PCM_EX:
1062             FALLTHROUGH_INTENDED;
1063         case SL_DATAFORMAT_PCM: {
1064             // checkDataFormat() already did generic checks, now do the Android-specific checks
1065             const SLDataFormat_PCM *df_pcm = (const SLDataFormat_PCM *) pAudioSrc->pFormat;
1066             SLresult result = android_audioPlayer_validateChannelMask(df_pcm->channelMask,
1067                                                                       df_pcm->numChannels);
1068             if (result != SL_RESULT_SUCCESS) {
1069                 SL_LOGE("Cannot create audio player: unsupported PCM data source with %u channels",
1070                         (unsigned) df_pcm->numChannels);
1071                 return result;
1072             }
1073 
1074             // checkDataFormat() already checked sample rate
1075 
1076             // checkDataFormat() already checked bits per sample, container size, and representation
1077 
1078             // FIXME confirm the following
1079             // df_pcm->channelMask: the earlier platform-independent check and the
1080             //     upcoming check by sles_to_android_channelMaskOut are sufficient
1081 
1082             if (df_pcm->endianness != pAudioPlayer->mObject.mEngine->mEngine.mNativeEndianness) {
1083                 SL_LOGE("Cannot create audio player: unsupported byte order %u",
1084                         df_pcm->endianness);
1085                 return SL_RESULT_CONTENT_UNSUPPORTED;
1086             }
1087 
1088             // we don't support container size != sample depth
1089             if (df_pcm->containerSize != df_pcm->bitsPerSample) {
1090                 SL_LOGE("Cannot create audio player: unsupported container size %u bits for "
1091                         "sample depth %u bits",
1092                         df_pcm->containerSize, (SLuint32)df_pcm->bitsPerSample);
1093                 return SL_RESULT_CONTENT_UNSUPPORTED;
1094             }
1095 
1096             } //case SL_DATAFORMAT_PCM
1097             break;
1098         case SL_DATAFORMAT_MIME:
1099         case XA_DATAFORMAT_RAWIMAGE:
1100             SL_LOGE("Cannot create audio player with buffer queue data source "
1101                 "without SL_DATAFORMAT_PCM format");
1102             return SL_RESULT_CONTENT_UNSUPPORTED;
1103         default:
1104             // invalid data format is detected earlier
1105             assert(false);
1106             return SL_RESULT_INTERNAL_ERROR;
1107         } // switch (sourceFormatType)
1108         } // case SL_DATALOCATOR_BUFFERQUEUE or SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
1109         break;
1110     //------------------
1111     //   URI
1112     case SL_DATALOCATOR_URI:
1113         {
1114         SLDataLocator_URI *dl_uri = (SLDataLocator_URI *) pAudioSrc->pLocator;
1115         if (NULL == dl_uri->URI) {
1116             return SL_RESULT_PARAMETER_INVALID;
1117         }
1118         // URI format
1119         switch (sourceFormatType) {
1120         case SL_DATAFORMAT_MIME:
1121             break;
1122         default:
1123             SL_LOGE("Cannot create audio player with SL_DATALOCATOR_URI data source without "
1124                 "SL_DATAFORMAT_MIME format");
1125             return SL_RESULT_CONTENT_UNSUPPORTED;
1126         } // switch (sourceFormatType)
1127         // decoding format check
1128         if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) &&
1129                 !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) {
1130             return SL_RESULT_CONTENT_UNSUPPORTED;
1131         }
1132         } // case SL_DATALOCATOR_URI
1133         break;
1134     //------------------
1135     //   File Descriptor
1136     case SL_DATALOCATOR_ANDROIDFD:
1137         {
1138         // fd is already non null
1139         switch (sourceFormatType) {
1140         case SL_DATAFORMAT_MIME:
1141             break;
1142         default:
1143             SL_LOGE("Cannot create audio player with SL_DATALOCATOR_ANDROIDFD data source "
1144                 "without SL_DATAFORMAT_MIME format");
1145             return SL_RESULT_CONTENT_UNSUPPORTED;
1146         } // switch (sourceFormatType)
1147         if ((sinkLocatorType != SL_DATALOCATOR_OUTPUTMIX) &&
1148                 !audioPlayer_isSupportedNonOutputMixSink(pAudioSnk)) {
1149             return SL_RESULT_CONTENT_UNSUPPORTED;
1150         }
1151         } // case SL_DATALOCATOR_ANDROIDFD
1152         break;
1153     //------------------
1154     //   Stream
1155     case SL_DATALOCATOR_ANDROIDBUFFERQUEUE:
1156     {
1157         switch (sourceFormatType) {
1158         case SL_DATAFORMAT_MIME:
1159         {
1160             SLDataFormat_MIME *df_mime = (SLDataFormat_MIME *) pAudioSrc->pFormat;
1161             if (NULL == df_mime) {
1162                 SL_LOGE("MIME type null invalid");
1163                 return SL_RESULT_CONTENT_UNSUPPORTED;
1164             }
1165             SL_LOGD("source MIME is %s", (char*)df_mime->mimeType);
1166             switch (df_mime->containerType) {
1167             case SL_CONTAINERTYPE_MPEG_TS:
1168                 if (strcasecmp((char*)df_mime->mimeType, (const char *)XA_ANDROID_MIME_MP2TS)) {
1169                     SL_LOGE("Invalid MIME (%s) for container SL_CONTAINERTYPE_MPEG_TS, expects %s",
1170                             (char*)df_mime->mimeType, XA_ANDROID_MIME_MP2TS);
1171                     return SL_RESULT_CONTENT_UNSUPPORTED;
1172                 }
1173                 if (pAudioPlayer->mAndroidObjType != AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE) {
1174                     SL_LOGE("Invalid sink for container SL_CONTAINERTYPE_MPEG_TS");
1175                     return SL_RESULT_PARAMETER_INVALID;
1176                 }
1177                 break;
1178             case SL_CONTAINERTYPE_RAW:
1179             case SL_CONTAINERTYPE_AAC:
1180                 if (strcasecmp((char*)df_mime->mimeType, (const char *)SL_ANDROID_MIME_AACADTS) &&
1181                         strcasecmp((char*)df_mime->mimeType,
1182                                 ANDROID_MIME_AACADTS_ANDROID_FRAMEWORK)) {
1183                     SL_LOGE("Invalid MIME (%s) for container type %d, expects %s",
1184                             (char*)df_mime->mimeType, df_mime->containerType,
1185                             SL_ANDROID_MIME_AACADTS);
1186                     return SL_RESULT_CONTENT_UNSUPPORTED;
1187                 }
1188                 if (pAudioPlayer->mAndroidObjType != AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE) {
1189                     SL_LOGE("Invalid sink for container SL_CONTAINERTYPE_AAC");
1190                     return SL_RESULT_PARAMETER_INVALID;
1191                 }
1192                 break;
1193             default:
1194                 SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
1195                                         "that is not fed MPEG-2 TS data or AAC ADTS data");
1196                 return SL_RESULT_CONTENT_UNSUPPORTED;
1197             }
1198         }
1199         break;
1200         default:
1201             SL_LOGE("Cannot create player with SL_DATALOCATOR_ANDROIDBUFFERQUEUE data source "
1202                     "without SL_DATAFORMAT_MIME format");
1203             return SL_RESULT_CONTENT_UNSUPPORTED;
1204         }
1205     }
1206     break; // case SL_DATALOCATOR_ANDROIDBUFFERQUEUE
1207     //------------------
1208     //   Address
1209     case SL_DATALOCATOR_ADDRESS:
1210     case SL_DATALOCATOR_IODEVICE:
1211     case SL_DATALOCATOR_OUTPUTMIX:
1212     case XA_DATALOCATOR_NATIVEDISPLAY:
1213     case SL_DATALOCATOR_MIDIBUFFERQUEUE:
1214         SL_LOGE("Cannot create audio player with data locator type 0x%x",
1215                 (unsigned) sourceLocatorType);
1216         return SL_RESULT_CONTENT_UNSUPPORTED;
1217     default:
1218         SL_LOGE("Cannot create audio player with invalid data locator type 0x%x",
1219                 (unsigned) sourceLocatorType);
1220         return SL_RESULT_PARAMETER_INVALID;
1221     }// switch (locatorType)
1222 
1223     return SL_RESULT_SUCCESS;
1224 }
1225 
1226 
1227 //-----------------------------------------------------------------------------
1228 // Callback associated with an AudioTrack of an SL ES AudioPlayer that gets its data
1229 // 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)1230 size_t audioTrack_handleMoreData_lockPlay(CAudioPlayer* ap,
1231                                         const android::AudioTrack::Buffer& buffer) {
1232 
1233     void * callbackPContext = NULL;
1234     size_t bytesWritten = 0;
1235         //SL_LOGV("received event EVENT_MORE_DATA from AudioTrack TID=%d", gettid());
1236         slPrefetchCallback prefetchCallback = NULL;
1237         void *prefetchContext = NULL;
1238         SLuint32 prefetchEvents = SL_PREFETCHEVENT_NONE;
1239 
1240         // retrieve data from the buffer queue
1241         interface_lock_exclusive(&ap->mBufferQueue);
1242 
1243         if (ap->mBufferQueue.mCallbackPending) {
1244             // call callback with lock not held
1245             slBufferQueueCallback callback = ap->mBufferQueue.mCallback;
1246             if (NULL != callback) {
1247                 callbackPContext = ap->mBufferQueue.mContext;
1248                 interface_unlock_exclusive(&ap->mBufferQueue);
1249                 (*callback)(&ap->mBufferQueue.mItf, callbackPContext);
1250                 interface_lock_exclusive(&ap->mBufferQueue);
1251                 ap->mBufferQueue.mCallbackPending = false;
1252             }
1253         }
1254 
1255         if (ap->mBufferQueue.mState.count != 0) {
1256             //SL_LOGV("nbBuffers in queue = %u",ap->mBufferQueue.mState.count);
1257             assert(ap->mBufferQueue.mFront != ap->mBufferQueue.mRear);
1258 
1259             BufferHeader *oldFront = ap->mBufferQueue.mFront;
1260             BufferHeader *newFront = &oldFront[1];
1261 
1262             size_t availSource = oldFront->mSize - ap->mBufferQueue.mSizeConsumed;
1263             size_t availSink = buffer.size();
1264             size_t bytesToCopy = availSource < availSink ? availSource : availSink;
1265             void *pSrc = (char *)oldFront->mBuffer + ap->mBufferQueue.mSizeConsumed;
1266             memcpy(buffer.data(), pSrc, bytesToCopy);
1267             bytesWritten = bytesToCopy;
1268             if (bytesToCopy < availSource) {
1269                 ap->mBufferQueue.mSizeConsumed += bytesToCopy;
1270             } else {
1271                 // consumed an entire buffer, dequeue
1272                 ap->mBufferQueue.mSizeConsumed = 0;
1273                 if (newFront ==
1274                         &ap->mBufferQueue.mArray
1275                             [ap->mBufferQueue.mNumBuffers + 1])
1276                 {
1277                     newFront = ap->mBufferQueue.mArray;
1278                 }
1279                 ap->mBufferQueue.mFront = newFront;
1280 
1281                 ap->mBufferQueue.mState.count--;
1282                 ap->mBufferQueue.mState.playIndex++;
1283                 ap->mBufferQueue.mCallbackPending = true;
1284             }
1285         } else { // empty queue
1286 
1287             // signal we're at the end of the content, but don't pause (see note in function)
1288             audioPlayer_dispatch_headAtEnd_lockPlay(ap, false /*set state to paused?*/, false);
1289 
1290             // signal underflow to prefetch status itf
1291             if (IsInterfaceInitialized(&ap->mObject, MPH_PREFETCHSTATUS)) {
1292                 ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_UNDERFLOW;
1293                 ap->mPrefetchStatus.mLevel = 0;
1294                 // callback or no callback?
1295                 prefetchEvents = ap->mPrefetchStatus.mCallbackEventsMask &
1296                         (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE);
1297                 if (SL_PREFETCHEVENT_NONE != prefetchEvents) {
1298                     prefetchCallback = ap->mPrefetchStatus.mCallback;
1299                     prefetchContext  = ap->mPrefetchStatus.mContext;
1300                 }
1301             }
1302 
1303             // stop the track so it restarts playing faster when new data is enqueued
1304             ap->mTrackPlayer->stop();
1305         }
1306         interface_unlock_exclusive(&ap->mBufferQueue);
1307 
1308         // notify client
1309         if (NULL != prefetchCallback) {
1310             assert(SL_PREFETCHEVENT_NONE != prefetchEvents);
1311             // spec requires separate callbacks for each event
1312             if (prefetchEvents & SL_PREFETCHEVENT_STATUSCHANGE) {
1313                 (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext,
1314                         SL_PREFETCHEVENT_STATUSCHANGE);
1315             }
1316             if (prefetchEvents & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
1317                 (*prefetchCallback)(&ap->mPrefetchStatus.mItf, prefetchContext,
1318                         SL_PREFETCHEVENT_FILLLEVELCHANGE);
1319             }
1320         }
1321 
1322     return bytesWritten;
1323 }
1324 
1325 
1326 //-----------------------------------------------------------------------------
android_audioPlayer_create(CAudioPlayer * pAudioPlayer)1327 void android_audioPlayer_create(CAudioPlayer *pAudioPlayer) {
1328 
1329     // pAudioPlayer->mAndroidObjType has been set in android_audioPlayer_checkSourceSink()
1330     // and if it was == INVALID_TYPE, then IEngine_CreateAudioPlayer would never call us
1331     assert(INVALID_TYPE != pAudioPlayer->mAndroidObjType);
1332 
1333     // These initializations are in the same order as the field declarations in classes.h
1334 
1335     // FIXME Consolidate initializations (many of these already in IEngine_CreateAudioPlayer)
1336     // mAndroidObjType: see above comment
1337     pAudioPlayer->mAndroidObjState = ANDROID_UNINITIALIZED;
1338     pAudioPlayer->mSessionId = (audio_session_t) android::AudioSystem::newAudioUniqueId(
1339             AUDIO_UNIQUE_ID_USE_SESSION);
1340     pAudioPlayer->mPIId = PLAYER_PIID_INVALID;
1341 
1342     // placeholder: not necessary yet as session ID lifetime doesn't extend beyond player
1343     // android::AudioSystem::acquireAudioSessionId(pAudioPlayer->mSessionId);
1344 
1345     pAudioPlayer->mStreamType = ANDROID_DEFAULT_OUTPUT_STREAM_TYPE;
1346     pAudioPlayer->mPerformanceMode = ANDROID_PERFORMANCE_MODE_DEFAULT;
1347 
1348     // mAudioTrack lifecycle is handled through mTrackPlayer
1349     pAudioPlayer->mTrackPlayer = new android::TrackPlayerBase();
1350     assert(pAudioPlayer->mTrackPlayer != 0);
1351     pAudioPlayer->mCallbackProtector = new android::CallbackProtector();
1352     // mAPLayer
1353     // mAuxEffect
1354 
1355     pAudioPlayer->mAuxSendLevel = 0;
1356     pAudioPlayer->mAmplFromDirectLevel = 1.0f; // matches initial mDirectLevel value
1357     pAudioPlayer->mDeferredStart = false;
1358 
1359     // This section re-initializes interface-specific fields that
1360     // can be set or used regardless of whether the interface is
1361     // exposed on the AudioPlayer or not
1362 
1363     switch (pAudioPlayer->mAndroidObjType) {
1364     case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1365         pAudioPlayer->mPlaybackRate.mMinRate = AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE;
1366         pAudioPlayer->mPlaybackRate.mMaxRate = AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE;
1367         break;
1368     case AUDIOPLAYER_FROM_URIFD:
1369         pAudioPlayer->mPlaybackRate.mMinRate = MEDIAPLAYER_MIN_PLAYBACKRATE_PERMILLE;
1370         pAudioPlayer->mPlaybackRate.mMaxRate = MEDIAPLAYER_MAX_PLAYBACKRATE_PERMILLE;
1371         break;
1372     default:
1373         // use the default range
1374         break;
1375     }
1376 
1377 }
1378 
1379 
1380 //-----------------------------------------------------------------------------
android_audioPlayer_setConfig(CAudioPlayer * ap,const SLchar * configKey,const void * pConfigValue,SLuint32 valueSize)1381 SLresult android_audioPlayer_setConfig(CAudioPlayer *ap, const SLchar *configKey,
1382         const void *pConfigValue, SLuint32 valueSize) {
1383 
1384     SLresult result;
1385 
1386     assert(NULL != ap && NULL != configKey && NULL != pConfigValue);
1387     if (strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) {
1388 
1389         // stream type
1390         if (KEY_STREAM_TYPE_PARAMSIZE > valueSize) {
1391             SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1392             result = SL_RESULT_BUFFER_INSUFFICIENT;
1393         } else {
1394             result = audioPlayer_setStreamType(ap, *(SLuint32*)pConfigValue);
1395         }
1396     } else if (strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_PERFORMANCE_MODE) == 0) {
1397 
1398         // performance mode
1399         if (KEY_PERFORMANCE_MODE_PARAMSIZE > valueSize) {
1400             SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1401             result = SL_RESULT_BUFFER_INSUFFICIENT;
1402         } else {
1403             result = audioPlayer_setPerformanceMode(ap, *(SLuint32*)pConfigValue);
1404         }
1405 
1406     } else {
1407         SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY);
1408         result = SL_RESULT_PARAMETER_INVALID;
1409     }
1410 
1411     return result;
1412 }
1413 
1414 
1415 //-----------------------------------------------------------------------------
android_audioPlayer_getConfig(CAudioPlayer * ap,const SLchar * configKey,SLuint32 * pValueSize,void * pConfigValue)1416 SLresult android_audioPlayer_getConfig(CAudioPlayer* ap, const SLchar *configKey,
1417         SLuint32* pValueSize, void *pConfigValue) {
1418 
1419     SLresult result;
1420 
1421     assert(NULL != ap && NULL != configKey && NULL != pValueSize);
1422     if (strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_STREAM_TYPE) == 0) {
1423 
1424         // stream type
1425         if (NULL == pConfigValue) {
1426             result = SL_RESULT_SUCCESS;
1427         } else if (KEY_STREAM_TYPE_PARAMSIZE > *pValueSize) {
1428             SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1429             result = SL_RESULT_BUFFER_INSUFFICIENT;
1430         } else {
1431             result = audioPlayer_getStreamType(ap, (SLint32*)pConfigValue);
1432         }
1433         *pValueSize = KEY_STREAM_TYPE_PARAMSIZE;
1434 
1435     } else if (strcmp((const char*)configKey, (const char*)SL_ANDROID_KEY_PERFORMANCE_MODE) == 0) {
1436 
1437         // performance mode
1438         if (NULL == pConfigValue) {
1439             result = SL_RESULT_SUCCESS;
1440         } else if (KEY_PERFORMANCE_MODE_PARAMSIZE > *pValueSize) {
1441             SL_LOGE(ERROR_CONFIG_VALUESIZE_TOO_LOW);
1442             result = SL_RESULT_BUFFER_INSUFFICIENT;
1443         } else {
1444             result = audioPlayer_getPerformanceMode(ap, (SLuint32*)pConfigValue);
1445         }
1446         *pValueSize = KEY_PERFORMANCE_MODE_PARAMSIZE;
1447 
1448     } else {
1449         SL_LOGE(ERROR_CONFIG_UNKNOWN_KEY);
1450         result = SL_RESULT_PARAMETER_INVALID;
1451     }
1452 
1453     return result;
1454 }
1455 
1456 
1457 // Called from android_audioPlayer_realize for a PCM buffer queue player before creating the
1458 // AudioTrack to determine which performance modes are allowed based on effect interfaces present
checkAndSetPerformanceModePre(CAudioPlayer * pAudioPlayer)1459 static void checkAndSetPerformanceModePre(CAudioPlayer *pAudioPlayer)
1460 {
1461     SLuint32 allowedModes = ANDROID_PERFORMANCE_MODE_ALL;
1462     assert(pAudioPlayer->mAndroidObjType == AUDIOPLAYER_FROM_PCM_BUFFERQUEUE);
1463 
1464     // no need to check the buffer queue size, application side
1465     // double-buffering (and more) is not a requirement for using fast tracks
1466 
1467     // Check a denylist of interfaces that are incompatible with fast tracks.
1468     // The alternative, to check a allowlist of compatible interfaces, is
1469     // more maintainable but is too slow.  As a compromise, in a debug build
1470     // we use both methods and warn if they produce different results.
1471     // In release builds, we only use the denylist method.
1472     // If a denylisted interface is added after realization using
1473     // DynamicInterfaceManagement::AddInterface,
1474     // then this won't be detected but the interface will be ineffective.
1475     static const unsigned denylist[] = {
1476         MPH_BASSBOOST,
1477         MPH_EFFECTSEND,
1478         MPH_ENVIRONMENTALREVERB,
1479         MPH_EQUALIZER,
1480         MPH_PLAYBACKRATE,
1481         MPH_PRESETREVERB,
1482         MPH_VIRTUALIZER,
1483         MPH_ANDROIDEFFECT,
1484         MPH_ANDROIDEFFECTSEND,
1485         // FIXME The problem with a denylist is remembering to add new interfaces here
1486     };
1487     for (unsigned i = 0; i < sizeof(denylist)/sizeof(denylist[0]); ++i) {
1488         if (IsInterfaceInitialized(&pAudioPlayer->mObject, denylist[i])) {
1489             //TODO: query effect for EFFECT_FLAG_HW_ACC_xx flag to refine mode
1490             allowedModes &=
1491                     ~(ANDROID_PERFORMANCE_MODE_LATENCY|ANDROID_PERFORMANCE_MODE_LATENCY_EFFECTS);
1492             break;
1493         }
1494     }
1495 #if LOG_NDEBUG == 0
1496     bool denylistResult = (
1497             (allowedModes &
1498                 (ANDROID_PERFORMANCE_MODE_LATENCY|ANDROID_PERFORMANCE_MODE_LATENCY_EFFECTS)) != 0);
1499     bool allowlistResult = true;
1500     static const unsigned allowlist[] = {
1501         MPH_BUFFERQUEUE,
1502         MPH_DYNAMICINTERFACEMANAGEMENT,
1503         MPH_METADATAEXTRACTION,
1504         MPH_MUTESOLO,
1505         MPH_OBJECT,
1506         MPH_PLAY,
1507         MPH_PREFETCHSTATUS,
1508         MPH_VOLUME,
1509         MPH_ANDROIDCONFIGURATION,
1510         MPH_ANDROIDSIMPLEBUFFERQUEUE,
1511         MPH_ANDROIDBUFFERQUEUESOURCE,
1512     };
1513     for (unsigned mph = MPH_MIN; mph < MPH_MAX; ++mph) {
1514         for (unsigned i = 0; i < sizeof(allowlist)/sizeof(allowlist[0]); ++i) {
1515             if (mph == allowlist[i]) {
1516                 goto compatible;
1517             }
1518         }
1519         if (IsInterfaceInitialized(&pAudioPlayer->mObject, mph)) {
1520             allowlistResult = false;
1521             break;
1522         }
1523 compatible: ;
1524     }
1525     if (allowlistResult != denylistResult) {
1526         SL_LOGW("allowlistResult != denylistResult");
1527     }
1528 #endif
1529     if (pAudioPlayer->mPerformanceMode == ANDROID_PERFORMANCE_MODE_LATENCY) {
1530         if ((allowedModes & ANDROID_PERFORMANCE_MODE_LATENCY) == 0) {
1531             pAudioPlayer->mPerformanceMode = ANDROID_PERFORMANCE_MODE_LATENCY_EFFECTS;
1532         }
1533     }
1534     if (pAudioPlayer->mPerformanceMode == ANDROID_PERFORMANCE_MODE_LATENCY_EFFECTS) {
1535         if ((allowedModes & ANDROID_PERFORMANCE_MODE_LATENCY_EFFECTS) == 0) {
1536             pAudioPlayer->mPerformanceMode = ANDROID_PERFORMANCE_MODE_NONE;
1537         }
1538     }
1539 }
1540 
1541 // Called from android_audioPlayer_realize for a PCM buffer queue player after creating the
1542 // AudioTrack to adjust performance mode based on actual output flags
checkAndSetPerformanceModePost(CAudioPlayer * pAudioPlayer)1543 static void checkAndSetPerformanceModePost(CAudioPlayer *pAudioPlayer)
1544 {
1545     audio_output_flags_t flags = pAudioPlayer->mTrackPlayer->mAudioTrack->getFlags();
1546     switch (pAudioPlayer->mPerformanceMode) {
1547     case ANDROID_PERFORMANCE_MODE_LATENCY:
1548         if ((flags & (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_RAW)) ==
1549                 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_RAW)) {
1550             break;
1551         }
1552         pAudioPlayer->mPerformanceMode = ANDROID_PERFORMANCE_MODE_LATENCY_EFFECTS;
1553         FALLTHROUGH_INTENDED;
1554     case ANDROID_PERFORMANCE_MODE_LATENCY_EFFECTS:
1555         if ((flags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1556             pAudioPlayer->mPerformanceMode = ANDROID_PERFORMANCE_MODE_NONE;
1557         }
1558         break;
1559     case ANDROID_PERFORMANCE_MODE_POWER_SAVING:
1560         if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) == 0) {
1561             pAudioPlayer->mPerformanceMode = ANDROID_PERFORMANCE_MODE_NONE;
1562         }
1563         break;
1564     case ANDROID_PERFORMANCE_MODE_NONE:
1565     default:
1566         break;
1567     }
1568 }
1569 //-----------------------------------------------------------------------------
1570 // FIXME abstract out the diff between CMediaPlayer and CAudioPlayer
android_audioPlayer_realize(CAudioPlayer * pAudioPlayer,SLboolean async)1571 SLresult android_audioPlayer_realize(CAudioPlayer *pAudioPlayer, SLboolean async) {
1572 
1573     SLresult result = SL_RESULT_SUCCESS;
1574     SL_LOGV("Realize pAudioPlayer=%p", pAudioPlayer);
1575     AudioPlayback_Parameters app;
1576     app.sessionId = pAudioPlayer->mSessionId;
1577     app.streamType = pAudioPlayer->mStreamType;
1578 
1579     switch (pAudioPlayer->mAndroidObjType) {
1580 
1581     //-----------------------------------
1582     // AudioTrack
1583     case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: {
1584         // initialize platform-specific CAudioPlayer fields
1585 
1586         SLDataFormat_PCM *df_pcm = (SLDataFormat_PCM *)
1587                 pAudioPlayer->mDynamicSource.mDataSource->pFormat;
1588 
1589         uint32_t sampleRate = sles_to_android_sampleRate(df_pcm->samplesPerSec);
1590 
1591         audio_channel_mask_t channelMask;
1592         channelMask = sles_to_audio_output_channel_mask(df_pcm->channelMask);
1593 
1594         // To maintain backward compatibility with previous releases, ignore
1595         // channel masks that are not indexed.
1596         if (channelMask == AUDIO_CHANNEL_INVALID
1597                 || audio_channel_mask_get_representation(channelMask)
1598                         == AUDIO_CHANNEL_REPRESENTATION_POSITION) {
1599             channelMask = audio_channel_out_mask_from_count(df_pcm->numChannels);
1600             SL_LOGI("Emulating old channel mask behavior "
1601                     "(ignoring positional mask %#x, using default mask %#x based on "
1602                     "channel count of %d)", df_pcm->channelMask, channelMask,
1603                     df_pcm->numChannels);
1604         }
1605         SL_LOGV("AudioPlayer: mapped SLES channel mask %#x to android channel mask %#x",
1606             df_pcm->channelMask,
1607             channelMask);
1608 
1609         checkAndSetPerformanceModePre(pAudioPlayer);
1610 
1611         audio_output_flags_t policy;
1612         audio_flags_mask_t attrFlags = AUDIO_FLAG_NONE;
1613         switch (pAudioPlayer->mPerformanceMode) {
1614         case ANDROID_PERFORMANCE_MODE_POWER_SAVING:
1615             policy = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1616             attrFlags = static_cast<audio_flags_mask_t>(attrFlags | AUDIO_FLAG_DEEP_BUFFER);
1617             break;
1618         case ANDROID_PERFORMANCE_MODE_NONE:
1619             policy = AUDIO_OUTPUT_FLAG_NONE;
1620             break;
1621         case ANDROID_PERFORMANCE_MODE_LATENCY_EFFECTS:
1622             policy = AUDIO_OUTPUT_FLAG_FAST;
1623             attrFlags = static_cast<audio_flags_mask_t>(attrFlags | AUDIO_FLAG_LOW_LATENCY);
1624             break;
1625         case ANDROID_PERFORMANCE_MODE_LATENCY:
1626         default:
1627             policy = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_RAW);
1628             attrFlags = static_cast<audio_flags_mask_t>(attrFlags | AUDIO_FLAG_LOW_LATENCY);
1629             break;
1630         }
1631 
1632         int32_t notificationFrames;
1633         if ((policy & AUDIO_OUTPUT_FLAG_FAST) != 0) {
1634             // negative notificationFrames is the number of notifications (sub-buffers) per track
1635             // buffer for details see the explanation at frameworks/av/include/media/AudioTrack.h
1636             notificationFrames = -pAudioPlayer->mBufferQueue.mNumBuffers;
1637         } else {
1638             notificationFrames = 0;
1639         }
1640         audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
1641         attributes.usage = usageForStreamType(pAudioPlayer->mStreamType);
1642         attributes.flags = attrFlags;
1643 
1644         const auto callbackHandle = android::sp<android::AudioTrackCallback>::make(pAudioPlayer);
1645         const auto pat = android::sp<android::AudioTrack>::make(
1646                 AUDIO_STREAM_DEFAULT,                                // streamType
1647                 sampleRate,                                          // sampleRate
1648                 sles_to_android_sampleFormat(df_pcm),                // format
1649                 channelMask,                                         // channel mask
1650                 0,                                                   // frameCount
1651                 policy,                                              // flags
1652                 callbackHandle,                                      // callback
1653                 notificationFrames,                                  // see comment above
1654                 pAudioPlayer->mSessionId,
1655                 android::AudioTrack::TRANSFER_DEFAULT,               // transferType
1656                 nullptr,                                             // offloadInfo
1657                 AttributionSourceState(),                            // attributionSource
1658                 &attributes                                          // pAttributes
1659                 );
1660 
1661         // Set it here so it can be logged by the destructor if the open failed.
1662         pat->setCallerName(ANDROID_OPENSLES_CALLER_NAME);
1663 
1664         android::status_t status = pat->initCheck();
1665         if (status != android::NO_ERROR) {
1666             SL_LOGE("AudioTrack::initCheck status %u", status);
1667             // FIXME should return a more specific result depending on status
1668             result = SL_RESULT_CONTENT_UNSUPPORTED;
1669             return result;
1670         }
1671 
1672         pAudioPlayer->mTrackPlayer->init(
1673             pat, callbackHandle,
1674             android::PLAYER_TYPE_SLES_AUDIOPLAYER_BUFFERQUEUE,
1675             usageForStreamType(pAudioPlayer->mStreamType),
1676             pAudioPlayer->mSessionId);
1677 
1678         // update performance mode according to actual flags granted to AudioTrack
1679         checkAndSetPerformanceModePost(pAudioPlayer);
1680 
1681         // initialize platform-independent CAudioPlayer fields
1682 
1683         pAudioPlayer->mNumChannels = df_pcm->numChannels;
1684         pAudioPlayer->mSampleRateMilliHz = df_pcm->samplesPerSec; // Note: bad field name in SL ES
1685 
1686         // This use case does not have a separate "prepare" step
1687         pAudioPlayer->mAndroidObjState = ANDROID_READY;
1688 
1689         // If there is a JavaAudioRoutingProxy associated with this player, hook it up...
1690         JNIEnv* j_env = NULL;
1691         jclass clsAudioTrack = NULL;
1692         jmethodID midRoutingProxy_connect = NULL;
1693         if (pAudioPlayer->mAndroidConfiguration.mRoutingProxy != NULL &&
1694                 (j_env = android::AndroidRuntime::getJNIEnv()) != NULL &&
1695                 (clsAudioTrack = j_env->FindClass("android/media/AudioTrack")) != NULL &&
1696                 (midRoutingProxy_connect =
1697                     j_env->GetMethodID(clsAudioTrack, "deferred_connect", "(J)V")) != NULL) {
1698             j_env->ExceptionClear();
1699             j_env->CallVoidMethod(pAudioPlayer->mAndroidConfiguration.mRoutingProxy,
1700                                   midRoutingProxy_connect,
1701                                   (jlong)pAudioPlayer->mTrackPlayer->mAudioTrack.get());
1702             if (j_env->ExceptionCheck()) {
1703                 SL_LOGE("Java exception releasing player routing object.");
1704                 result = SL_RESULT_INTERNAL_ERROR;
1705                 pAudioPlayer->mTrackPlayer->mAudioTrack.clear();
1706                 return result;
1707             }
1708         }
1709     }
1710         break;
1711 
1712     //-----------------------------------
1713     // MediaPlayer
1714     case AUDIOPLAYER_FROM_URIFD: {
1715         pAudioPlayer->mAPlayer = new android::LocAVPlayer(&app, false /*hasVideo*/);
1716         pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent,
1717                         (void*)pAudioPlayer /*notifUSer*/);
1718 
1719         switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) {
1720             case SL_DATALOCATOR_URI: {
1721                 // The legacy implementation ran Stagefright within the application process, and
1722                 // so allowed local pathnames specified by URI that were openable by
1723                 // the application but were not openable by mediaserver.
1724                 // The current implementation runs Stagefright (mostly) within mediaserver,
1725                 // which runs as a different UID and likely a different current working directory.
1726                 // For backwards compatibility with any applications which may have relied on the
1727                 // previous behavior, we convert an openable file URI into an FD.
1728                 // Note that unlike SL_DATALOCATOR_ANDROIDFD, this FD is owned by us
1729                 // and so we close it as soon as we've passed it (via Binder dup) to mediaserver.
1730                 const char *uri = (const char *)pAudioPlayer->mDataSource.mLocator.mURI.URI;
1731                 if (!isDistantProtocol(uri)) {
1732                     // don't touch the original uri, we may need it later
1733                     const char *pathname = uri;
1734                     // skip over an optional leading file:// prefix
1735                     if (!strncasecmp(pathname, "file://", 7)) {
1736                         pathname += 7;
1737                     }
1738                     // attempt to open it as a file using the application's credentials
1739                     int fd = ::open(pathname, O_RDONLY);
1740                     if (fd >= 0) {
1741                         // if open is successful, then check to see if it's a regular file
1742                         struct stat statbuf;
1743                         if (!::fstat(fd, &statbuf) && S_ISREG(statbuf.st_mode)) {
1744                             // treat similarly to an FD data locator, but
1745                             // let setDataSource take responsibility for closing fd
1746                             pAudioPlayer->mAPlayer->setDataSource(fd, 0, statbuf.st_size, true);
1747                             break;
1748                         }
1749                         // we were able to open it, but it's not a file, so let mediaserver try
1750                         (void) ::close(fd);
1751                     }
1752                 }
1753                 // if either the URI didn't look like a file, or open failed, or not a file
1754                 pAudioPlayer->mAPlayer->setDataSource(uri);
1755                 } break;
1756             case SL_DATALOCATOR_ANDROIDFD: {
1757                 int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset;
1758                 pAudioPlayer->mAPlayer->setDataSource(
1759                         (int)pAudioPlayer->mDataSource.mLocator.mFD.fd,
1760                         offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
1761                                 (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
1762                         (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length);
1763                 }
1764                 break;
1765             default:
1766                 SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR);
1767                 break;
1768         }
1769 
1770         if (pAudioPlayer->mObject.mEngine->mAudioManager == 0) {
1771             SL_LOGE("AudioPlayer realize: no audio service, player will not be registered");
1772             pAudioPlayer->mPIId = 0;
1773         } else {
1774             pAudioPlayer->mPIId = pAudioPlayer->mObject.mEngine->mAudioManager->trackPlayer(
1775                     android::PLAYER_TYPE_SLES_AUDIOPLAYER_URI_FD,
1776                     usageForStreamType(pAudioPlayer->mStreamType), AUDIO_CONTENT_TYPE_UNKNOWN,
1777                     pAudioPlayer->mTrackPlayer, pAudioPlayer->mSessionId);
1778         }
1779         }
1780         break;
1781 
1782     //-----------------------------------
1783     // StreamPlayer
1784     case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: {
1785         android::StreamPlayer* splr = new android::StreamPlayer(&app, false /*hasVideo*/,
1786                 &pAudioPlayer->mAndroidBufferQueue, pAudioPlayer->mCallbackProtector);
1787         pAudioPlayer->mAPlayer = splr;
1788         splr->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1789         }
1790         break;
1791 
1792     //-----------------------------------
1793     // AudioToCbRenderer
1794     case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
1795         android::AudioToCbRenderer* decoder = new android::AudioToCbRenderer(&app);
1796         pAudioPlayer->mAPlayer = decoder;
1797         // configures the callback for the sink buffer queue
1798         decoder->setDataPushListener(adecoder_writeToBufferQueue, pAudioPlayer);
1799         // configures the callback for the notifications coming from the SF code
1800         decoder->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1801 
1802         switch (pAudioPlayer->mDataSource.mLocator.mLocatorType) {
1803         case SL_DATALOCATOR_URI:
1804             decoder->setDataSource(
1805                     (const char*)pAudioPlayer->mDataSource.mLocator.mURI.URI);
1806             break;
1807         case SL_DATALOCATOR_ANDROIDFD: {
1808             int64_t offset = (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.offset;
1809             decoder->setDataSource(
1810                     (int)pAudioPlayer->mDataSource.mLocator.mFD.fd,
1811                     offset == SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ?
1812                             (int64_t)PLAYER_FD_FIND_FILE_SIZE : offset,
1813                             (int64_t)pAudioPlayer->mDataSource.mLocator.mFD.length);
1814             }
1815             break;
1816         default:
1817             SL_LOGE(ERROR_PLAYERREALIZE_UNKNOWN_DATASOURCE_LOCATOR);
1818             break;
1819         }
1820 
1821         }
1822         break;
1823 
1824     //-----------------------------------
1825     // AacBqToPcmCbRenderer
1826     case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
1827         android::AacBqToPcmCbRenderer* bqtobq = new android::AacBqToPcmCbRenderer(&app,
1828                 &pAudioPlayer->mAndroidBufferQueue);
1829         // configures the callback for the sink buffer queue
1830         bqtobq->setDataPushListener(adecoder_writeToBufferQueue, pAudioPlayer);
1831         pAudioPlayer->mAPlayer = bqtobq;
1832         // configures the callback for the notifications coming from the SF code,
1833         // but also implicitly configures the AndroidBufferQueue from which ADTS data is read
1834         pAudioPlayer->mAPlayer->init(sfplayer_handlePrefetchEvent, (void*)pAudioPlayer);
1835         }
1836         break;
1837 
1838     //-----------------------------------
1839     default:
1840         SL_LOGE(ERROR_PLAYERREALIZE_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType);
1841         result = SL_RESULT_INTERNAL_ERROR;
1842         break;
1843     }
1844 
1845     if (result == SL_RESULT_SUCCESS) {
1846         // proceed with effect initialization
1847         // initialize EQ
1848         // FIXME use a table of effect descriptors when adding support for more effects
1849 
1850         // No session effects allowed even in latency with effects performance mode because HW
1851         // accelerated effects are only tolerated as post processing in this mode
1852         if ((pAudioPlayer->mAndroidObjType != AUDIOPLAYER_FROM_PCM_BUFFERQUEUE) ||
1853                 ((pAudioPlayer->mPerformanceMode != ANDROID_PERFORMANCE_MODE_LATENCY) &&
1854                  (pAudioPlayer->mPerformanceMode != ANDROID_PERFORMANCE_MODE_LATENCY_EFFECTS))) {
1855             if (memcmp(SL_IID_EQUALIZER, &pAudioPlayer->mEqualizer.mEqDescriptor.type,
1856                     sizeof(effect_uuid_t)) == 0) {
1857                 SL_LOGV("Need to initialize EQ for AudioPlayer=%p", pAudioPlayer);
1858                 android_eq_init(pAudioPlayer->mSessionId, &pAudioPlayer->mEqualizer);
1859             }
1860             // initialize BassBoost
1861             if (memcmp(SL_IID_BASSBOOST, &pAudioPlayer->mBassBoost.mBassBoostDescriptor.type,
1862                     sizeof(effect_uuid_t)) == 0) {
1863                 SL_LOGV("Need to initialize BassBoost for AudioPlayer=%p", pAudioPlayer);
1864                 android_bb_init(pAudioPlayer->mSessionId, &pAudioPlayer->mBassBoost);
1865             }
1866             // initialize Virtualizer
1867             if (memcmp(SL_IID_VIRTUALIZER, &pAudioPlayer->mVirtualizer.mVirtualizerDescriptor.type,
1868                        sizeof(effect_uuid_t)) == 0) {
1869                 SL_LOGV("Need to initialize Virtualizer for AudioPlayer=%p", pAudioPlayer);
1870                 android_virt_init(pAudioPlayer->mSessionId, &pAudioPlayer->mVirtualizer);
1871             }
1872         }
1873     }
1874 
1875     // initialize EffectSend
1876     // FIXME initialize EffectSend
1877 
1878     return result;
1879 }
1880 
1881 
1882 //-----------------------------------------------------------------------------
1883 /**
1884  * Called with a lock on AudioPlayer, and blocks until safe to destroy
1885  */
android_audioPlayer_preDestroy(CAudioPlayer * pAudioPlayer)1886 SLresult android_audioPlayer_preDestroy(CAudioPlayer *pAudioPlayer) {
1887     SL_LOGD("android_audioPlayer_preDestroy(%p)", pAudioPlayer);
1888     SLresult result = SL_RESULT_SUCCESS;
1889 
1890     bool disableCallbacksBeforePreDestroy;
1891     switch (pAudioPlayer->mAndroidObjType) {
1892     // Not yet clear why this order is important, but it reduces detected deadlocks
1893     case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1894         disableCallbacksBeforePreDestroy = true;
1895         break;
1896     // Use the old behavior for all other use cases until proven
1897     // case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1898     default:
1899         disableCallbacksBeforePreDestroy = false;
1900         break;
1901     }
1902 
1903     if (disableCallbacksBeforePreDestroy) {
1904         object_unlock_exclusive(&pAudioPlayer->mObject);
1905         if (pAudioPlayer->mCallbackProtector != 0) {
1906             pAudioPlayer->mCallbackProtector->requestCbExitAndWait();
1907         }
1908         object_lock_exclusive(&pAudioPlayer->mObject);
1909     }
1910 
1911     if (pAudioPlayer->mAPlayer != 0) {
1912         pAudioPlayer->mAPlayer->preDestroy();
1913     }
1914     SL_LOGD("android_audioPlayer_preDestroy(%p) after mAPlayer->preDestroy()", pAudioPlayer);
1915 
1916     if (!disableCallbacksBeforePreDestroy) {
1917         object_unlock_exclusive(&pAudioPlayer->mObject);
1918         if (pAudioPlayer->mCallbackProtector != 0) {
1919             pAudioPlayer->mCallbackProtector->requestCbExitAndWait();
1920         }
1921         object_lock_exclusive(&pAudioPlayer->mObject);
1922     }
1923 
1924     return result;
1925 }
1926 
1927 
1928 //-----------------------------------------------------------------------------
android_audioPlayer_destroy(CAudioPlayer * pAudioPlayer)1929 SLresult android_audioPlayer_destroy(CAudioPlayer *pAudioPlayer) {
1930     SLresult result = SL_RESULT_SUCCESS;
1931     SL_LOGV("android_audioPlayer_destroy(%p)", pAudioPlayer);
1932     switch (pAudioPlayer->mAndroidObjType) {
1933 
1934     case AUDIOPLAYER_FROM_URIFD:
1935         if (pAudioPlayer->mObject.mEngine->mAudioManager != 0) {
1936             pAudioPlayer->mObject.mEngine->mAudioManager->releasePlayer(pAudioPlayer->mPIId);
1937         }
1938         // intended fall-throughk, both types of players
1939         // use the TrackPlayerBase for playback
1940         FALLTHROUGH_INTENDED;
1941     case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
1942         if (pAudioPlayer->mTrackPlayer != 0) {
1943             pAudioPlayer->mTrackPlayer->destroy();
1944         }
1945         FALLTHROUGH_INTENDED;
1946     case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
1947         FALLTHROUGH_INTENDED;
1948     case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
1949         FALLTHROUGH_INTENDED;
1950     case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
1951         pAudioPlayer->mAPlayer.clear();
1952         break;
1953     //-----------------------------------
1954     default:
1955         SL_LOGE(ERROR_PLAYERDESTROY_UNEXPECTED_OBJECT_TYPE_D, pAudioPlayer->mAndroidObjType);
1956         result = SL_RESULT_INTERNAL_ERROR;
1957         break;
1958     }
1959 
1960     // placeholder: not necessary yet as session ID lifetime doesn't extend beyond player
1961     // android::AudioSystem::releaseAudioSessionId(pAudioPlayer->mSessionId);
1962 
1963     pAudioPlayer->mTrackPlayer.clear();
1964 
1965     pAudioPlayer->mCallbackProtector.clear();
1966 
1967     // explicit destructor
1968     pAudioPlayer->mTrackPlayer.~sp();
1969     // note that SetPlayState(PLAYING) may still hold a reference
1970     pAudioPlayer->mCallbackProtector.~sp();
1971     pAudioPlayer->mAuxEffect.~sp();
1972     pAudioPlayer->mAPlayer.~sp();
1973 
1974     return result;
1975 }
1976 
1977 
1978 //-----------------------------------------------------------------------------
android_audioPlayer_setPlaybackRateAndConstraints(CAudioPlayer * ap,SLpermille rate,SLuint32 constraints)1979 SLresult android_audioPlayer_setPlaybackRateAndConstraints(CAudioPlayer *ap, SLpermille rate,
1980         SLuint32 constraints) {
1981     SLresult result = SL_RESULT_SUCCESS;
1982     switch (ap->mAndroidObjType) {
1983     case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE: {
1984         // these asserts were already checked by the platform-independent layer
1985         assert((AUDIOTRACK_MIN_PLAYBACKRATE_PERMILLE <= rate) &&
1986                 (rate <= AUDIOTRACK_MAX_PLAYBACKRATE_PERMILLE));
1987         assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO);
1988         // get the content sample rate
1989         uint32_t contentRate = sles_to_android_sampleRate(ap->mSampleRateMilliHz);
1990         // apply the SL ES playback rate on the AudioTrack as a factor of its content sample rate
1991         if (ap->mTrackPlayer->mAudioTrack != 0) {
1992             ap->mTrackPlayer->mAudioTrack->setSampleRate(contentRate * (rate/1000.0f));
1993         }
1994         }
1995         break;
1996     case AUDIOPLAYER_FROM_URIFD: {
1997         assert((MEDIAPLAYER_MIN_PLAYBACKRATE_PERMILLE <= rate) &&
1998                         (rate <= MEDIAPLAYER_MAX_PLAYBACKRATE_PERMILLE));
1999         assert(constraints & SL_RATEPROP_NOPITCHCORAUDIO);
2000         // apply the SL ES playback rate on the GenericPlayer
2001         if (ap->mAPlayer != 0) {
2002             ap->mAPlayer->setPlaybackRate((int16_t)rate);
2003         }
2004         }
2005         break;
2006 
2007     default:
2008         SL_LOGE("Unexpected object type %d", ap->mAndroidObjType);
2009         result = SL_RESULT_FEATURE_UNSUPPORTED;
2010         break;
2011     }
2012     return result;
2013 }
2014 
2015 
2016 //-----------------------------------------------------------------------------
2017 // precondition
2018 //  called with no lock held
2019 //  ap != NULL
2020 //  pItemCount != NULL
android_audioPlayer_metadata_getItemCount(CAudioPlayer * ap,SLuint32 * pItemCount)2021 SLresult android_audioPlayer_metadata_getItemCount(CAudioPlayer *ap, SLuint32 *pItemCount) {
2022     if (ap->mAPlayer == 0) {
2023         return SL_RESULT_PARAMETER_INVALID;
2024     }
2025     switch (ap->mAndroidObjType) {
2026       case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2027       case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2028         {
2029             android::AudioSfDecoder* decoder =
2030                     static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
2031             *pItemCount = decoder->getPcmFormatKeyCount();
2032         }
2033         break;
2034       default:
2035         *pItemCount = 0;
2036         break;
2037     }
2038     return SL_RESULT_SUCCESS;
2039 }
2040 
2041 
2042 //-----------------------------------------------------------------------------
2043 // precondition
2044 //  called with no lock held
2045 //  ap != NULL
2046 //  pKeySize != NULL
android_audioPlayer_metadata_getKeySize(CAudioPlayer * ap,SLuint32 index,SLuint32 * pKeySize)2047 SLresult android_audioPlayer_metadata_getKeySize(CAudioPlayer *ap,
2048         SLuint32 index, SLuint32 *pKeySize) {
2049     if (ap->mAPlayer == 0) {
2050         return SL_RESULT_PARAMETER_INVALID;
2051     }
2052     SLresult res = SL_RESULT_SUCCESS;
2053     switch (ap->mAndroidObjType) {
2054       case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2055       case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2056         {
2057             android::AudioSfDecoder* decoder =
2058                     static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
2059             SLuint32 keyNameSize = 0;
2060             if (!decoder->getPcmFormatKeySize(index, &keyNameSize)) {
2061                 res = SL_RESULT_PARAMETER_INVALID;
2062             } else {
2063                 // *pKeySize is the size of the region used to store the key name AND
2064                 //   the information about the key (size, lang, encoding)
2065                 *pKeySize = keyNameSize + sizeof(SLMetadataInfo);
2066             }
2067         }
2068         break;
2069       default:
2070         *pKeySize = 0;
2071         res = SL_RESULT_PARAMETER_INVALID;
2072         break;
2073     }
2074     return res;
2075 }
2076 
2077 
2078 //-----------------------------------------------------------------------------
2079 // precondition
2080 //  called with no lock held
2081 //  ap != NULL
2082 //  pKey != NULL
android_audioPlayer_metadata_getKey(CAudioPlayer * ap,SLuint32 index,SLuint32 size,SLMetadataInfo * pKey)2083 SLresult android_audioPlayer_metadata_getKey(CAudioPlayer *ap,
2084         SLuint32 index, SLuint32 size, SLMetadataInfo *pKey) {
2085     if (ap->mAPlayer == 0) {
2086         return SL_RESULT_PARAMETER_INVALID;
2087     }
2088     SLresult res = SL_RESULT_SUCCESS;
2089     switch (ap->mAndroidObjType) {
2090       case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2091       case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2092         {
2093             android::AudioSfDecoder* decoder =
2094                     static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
2095             if ((size < sizeof(SLMetadataInfo) ||
2096                     (!decoder->getPcmFormatKeyName(index, size - sizeof(SLMetadataInfo),
2097                             (char*)pKey->data)))) {
2098                 res = SL_RESULT_PARAMETER_INVALID;
2099             } else {
2100                 // successfully retrieved the key value, update the other fields
2101                 pKey->encoding = SL_CHARACTERENCODING_UTF8;
2102                 memcpy((char *) pKey->langCountry, "en", 3);
2103                 pKey->size = strlen((char*)pKey->data) + 1;
2104             }
2105         }
2106         break;
2107       default:
2108         res = SL_RESULT_PARAMETER_INVALID;
2109         break;
2110     }
2111     return res;
2112 }
2113 
2114 
2115 //-----------------------------------------------------------------------------
2116 // precondition
2117 //  called with no lock held
2118 //  ap != NULL
2119 //  pValueSize != NULL
android_audioPlayer_metadata_getValueSize(CAudioPlayer * ap,SLuint32 index,SLuint32 * pValueSize)2120 SLresult android_audioPlayer_metadata_getValueSize(CAudioPlayer *ap,
2121         SLuint32 index, SLuint32 *pValueSize) {
2122     if (ap->mAPlayer == 0) {
2123         return SL_RESULT_PARAMETER_INVALID;
2124     }
2125     SLresult res = SL_RESULT_SUCCESS;
2126     switch (ap->mAndroidObjType) {
2127       case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2128       case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2129         {
2130             android::AudioSfDecoder* decoder =
2131                     static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
2132             SLuint32 valueSize = 0;
2133             if (!decoder->getPcmFormatValueSize(index, &valueSize)) {
2134                 res = SL_RESULT_PARAMETER_INVALID;
2135             } else {
2136                 // *pValueSize is the size of the region used to store the key value AND
2137                 //   the information about the value (size, lang, encoding)
2138                 *pValueSize = valueSize + sizeof(SLMetadataInfo);
2139             }
2140         }
2141         break;
2142       default:
2143           *pValueSize = 0;
2144           res = SL_RESULT_PARAMETER_INVALID;
2145           break;
2146     }
2147     return res;
2148 }
2149 
2150 
2151 //-----------------------------------------------------------------------------
2152 // precondition
2153 //  called with no lock held
2154 //  ap != NULL
2155 //  pValue != NULL
android_audioPlayer_metadata_getValue(CAudioPlayer * ap,SLuint32 index,SLuint32 size,SLMetadataInfo * pValue)2156 SLresult android_audioPlayer_metadata_getValue(CAudioPlayer *ap,
2157         SLuint32 index, SLuint32 size, SLMetadataInfo *pValue) {
2158     if (ap->mAPlayer == 0) {
2159         return SL_RESULT_PARAMETER_INVALID;
2160     }
2161     SLresult res = SL_RESULT_SUCCESS;
2162     switch (ap->mAndroidObjType) {
2163       case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2164       case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2165         {
2166             android::AudioSfDecoder* decoder =
2167                     static_cast<android::AudioSfDecoder*>(ap->mAPlayer.get());
2168             pValue->encoding = SL_CHARACTERENCODING_BINARY;
2169             memcpy((char *) pValue->langCountry, "en", 3); // applicable here?
2170             SLuint32 valueSize = 0;
2171             if ((size < sizeof(SLMetadataInfo)
2172                     || (!decoder->getPcmFormatValueSize(index, &valueSize))
2173                     || (!decoder->getPcmFormatKeyValue(index, size - sizeof(SLMetadataInfo),
2174                             (SLuint32*)pValue->data)))) {
2175                 res = SL_RESULT_PARAMETER_INVALID;
2176             } else {
2177                 pValue->size = valueSize;
2178             }
2179         }
2180         break;
2181       default:
2182         res = SL_RESULT_PARAMETER_INVALID;
2183         break;
2184     }
2185     return res;
2186 }
2187 
2188 //-----------------------------------------------------------------------------
2189 // preconditions
2190 //  ap != NULL
2191 //  mutex is locked
2192 //  play state has changed
android_audioPlayer_setPlayState(CAudioPlayer * ap)2193 void android_audioPlayer_setPlayState(CAudioPlayer *ap) {
2194 
2195     SLuint32 playState = ap->mPlay.mState;
2196 
2197     audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
2198     if (ap->mTrackPlayer != 0 && ap->mTrackPlayer->mAudioTrack != 0) {
2199         deviceId = ap->mTrackPlayer->mAudioTrack->getRoutedDeviceId();
2200     }
2201 
2202     switch (ap->mAndroidObjType) {
2203     case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2204         switch (playState) {
2205         case SL_PLAYSTATE_STOPPED:
2206             SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_STOPPED");
2207             ap->mTrackPlayer->stop();
2208             break;
2209         case SL_PLAYSTATE_PAUSED:
2210             SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PAUSED");
2211             ap->mTrackPlayer->pause();
2212             break;
2213         case SL_PLAYSTATE_PLAYING:
2214             SL_LOGV("setting AudioPlayer to SL_PLAYSTATE_PLAYING");
2215             if (ap->mTrackPlayer->mAudioTrack != 0) {
2216                 // instead of ap->mTrackPlayer->mAudioTrack->start();
2217                 if (!ap->mDeferredStart) {
2218                     // state change
2219                     ap->mTrackPlayer->reportEvent(android::PLAYER_STATE_STARTED, deviceId);
2220                 }
2221                 ap->mDeferredStart = true;
2222             }
2223             break;
2224         default:
2225             // checked by caller, should not happen
2226             break;
2227         }
2228         break;
2229 
2230     case AUDIOPLAYER_FROM_URIFD:
2231         switch (playState) {
2232         case SL_PLAYSTATE_STOPPED:
2233             aplayer_setPlayState(ap->mAPlayer, playState, &ap->mAndroidObjState);
2234             audioManagerPlayerEvent(ap, android::PLAYER_STATE_STOPPED, AUDIO_PORT_HANDLE_NONE);
2235             break;
2236         case SL_PLAYSTATE_PAUSED:
2237             aplayer_setPlayState(ap->mAPlayer, playState, &ap->mAndroidObjState);
2238             audioManagerPlayerEvent(ap, android::PLAYER_STATE_PAUSED, AUDIO_PORT_HANDLE_NONE);
2239             break;
2240         case SL_PLAYSTATE_PLAYING:
2241             audioManagerPlayerEvent(ap, android::PLAYER_STATE_STARTED, deviceId);
2242             aplayer_setPlayState(ap->mAPlayer, playState, &ap->mAndroidObjState);
2243             break;
2244         }
2245         break;
2246 
2247     case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2248         FALLTHROUGH_INTENDED;
2249     case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2250         FALLTHROUGH_INTENDED;
2251     case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2252         // FIXME report and use the return code to the lock mechanism, which is where play state
2253         //   changes are updated (see object_unlock_exclusive_attributes())
2254         aplayer_setPlayState(ap->mAPlayer, playState, &ap->mAndroidObjState);
2255         break;
2256     default:
2257         SL_LOGE(ERROR_PLAYERSETPLAYSTATE_UNEXPECTED_OBJECT_TYPE_D, ap->mAndroidObjType);
2258         break;
2259     }
2260 }
2261 
2262 
2263 //-----------------------------------------------------------------------------
2264 // call when either player event flags, marker position, or position update period changes
android_audioPlayer_usePlayEventMask(CAudioPlayer * ap)2265 void android_audioPlayer_usePlayEventMask(CAudioPlayer *ap) {
2266     IPlay *pPlayItf = &ap->mPlay;
2267     SLuint32 eventFlags = pPlayItf->mEventFlags;
2268     /*switch (ap->mAndroidObjType) {
2269     case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:*/
2270 
2271     if (ap->mAPlayer != 0) {
2272         assert(ap->mTrackPlayer->mAudioTrack == 0);
2273         ap->mAPlayer->setPlayEvents((int32_t) eventFlags, (int32_t) pPlayItf->mMarkerPosition,
2274                 (int32_t) pPlayItf->mPositionUpdatePeriod);
2275         return;
2276     }
2277 
2278     if (ap->mTrackPlayer->mAudioTrack == 0) {
2279         return;
2280     }
2281 
2282     if (eventFlags & SL_PLAYEVENT_HEADATMARKER) {
2283         ap->mTrackPlayer->mAudioTrack->setMarkerPosition(
2284             (uint32_t) (
2285                 (int64_t) pPlayItf->mMarkerPosition *
2286                 sles_to_android_sampleRate(ap->mSampleRateMilliHz) /
2287                 1000
2288             ));
2289     } else {
2290         // clear marker
2291         ap->mTrackPlayer->mAudioTrack->setMarkerPosition(0);
2292     }
2293 
2294     if (eventFlags & SL_PLAYEVENT_HEADATNEWPOS) {
2295          ap->mTrackPlayer->mAudioTrack->setPositionUpdatePeriod(
2296                 (uint32_t)((((int64_t)pPlayItf->mPositionUpdatePeriod
2297                 * sles_to_android_sampleRate(ap->mSampleRateMilliHz)))/1000));
2298     } else {
2299         // clear periodic update
2300         ap->mTrackPlayer->mAudioTrack->setPositionUpdatePeriod(0);
2301     }
2302 
2303     if (eventFlags & SL_PLAYEVENT_HEADATEND) {
2304         // nothing to do for SL_PLAYEVENT_HEADATEND, callback event will be checked against mask
2305     }
2306 
2307     if (eventFlags & SL_PLAYEVENT_HEADMOVING) {
2308         // FIXME support SL_PLAYEVENT_HEADMOVING
2309         SL_LOGD("[ FIXME: IPlay_SetCallbackEventsMask(SL_PLAYEVENT_HEADMOVING) on an "
2310             "SL_OBJECTID_AUDIOPLAYER to be implemented ]");
2311     }
2312     if (eventFlags & SL_PLAYEVENT_HEADSTALLED) {
2313         // nothing to do for SL_PLAYEVENT_HEADSTALLED, callback event will be checked against mask
2314     }
2315 
2316 }
2317 
2318 
2319 //-----------------------------------------------------------------------------
android_audioPlayer_getDuration(IPlay * pPlayItf,SLmillisecond * pDurMsec)2320 SLresult android_audioPlayer_getDuration(IPlay *pPlayItf, SLmillisecond *pDurMsec) {
2321     CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis;
2322     switch (ap->mAndroidObjType) {
2323 
2324       case AUDIOPLAYER_FROM_URIFD:
2325         FALLTHROUGH_INTENDED;
2326       case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE: {
2327         int32_t durationMsec = ANDROID_UNKNOWN_TIME;
2328         if (ap->mAPlayer != 0) {
2329             ap->mAPlayer->getDurationMsec(&durationMsec);
2330         }
2331         *pDurMsec = durationMsec == ANDROID_UNKNOWN_TIME ? SL_TIME_UNKNOWN : durationMsec;
2332         break;
2333       }
2334 
2335       case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE: // intended fall-through
2336       case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2337       case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2338       default: {
2339         *pDurMsec = SL_TIME_UNKNOWN;
2340       }
2341     }
2342     return SL_RESULT_SUCCESS;
2343 }
2344 
2345 
2346 //-----------------------------------------------------------------------------
android_audioPlayer_getPosition(IPlay * pPlayItf,SLmillisecond * pPosMsec)2347 void android_audioPlayer_getPosition(IPlay *pPlayItf, SLmillisecond *pPosMsec) {
2348     CAudioPlayer *ap = (CAudioPlayer *)pPlayItf->mThis;
2349     switch (ap->mAndroidObjType) {
2350 
2351       case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2352         if (ap->mSampleRateMilliHz == UNKNOWN_SAMPLERATE || ap->mTrackPlayer->mAudioTrack == 0) {
2353             *pPosMsec = 0;
2354         } else {
2355             uint32_t positionInFrames;
2356             ap->mTrackPlayer->mAudioTrack->getPosition(&positionInFrames);
2357             *pPosMsec = ((int64_t)positionInFrames * 1000) /
2358                     sles_to_android_sampleRate(ap->mSampleRateMilliHz);
2359         }
2360         break;
2361 
2362       case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:    // intended fall-through
2363       case AUDIOPLAYER_FROM_URIFD:
2364       case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2365       case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE: {
2366         int32_t posMsec = ANDROID_UNKNOWN_TIME;
2367         if (ap->mAPlayer != 0) {
2368             ap->mAPlayer->getPositionMsec(&posMsec);
2369         }
2370         *pPosMsec = posMsec == ANDROID_UNKNOWN_TIME ? 0 : posMsec;
2371         break;
2372       }
2373 
2374       default:
2375         *pPosMsec = 0;
2376     }
2377 }
2378 
2379 
2380 //-----------------------------------------------------------------------------
android_audioPlayer_seek(CAudioPlayer * ap,SLmillisecond posMsec)2381 SLresult android_audioPlayer_seek(CAudioPlayer *ap, SLmillisecond posMsec) {
2382     SLresult result = SL_RESULT_SUCCESS;
2383 
2384     switch (ap->mAndroidObjType) {
2385 
2386       case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:      // intended fall-through
2387       case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2388       case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2389         result = SL_RESULT_FEATURE_UNSUPPORTED;
2390         break;
2391 
2392       case AUDIOPLAYER_FROM_URIFD:                   // intended fall-through
2393       case AUDIOPLAYER_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2394         if (ap->mAPlayer != 0) {
2395             ap->mAPlayer->seek(posMsec);
2396         }
2397         break;
2398 
2399       default:
2400         break;
2401     }
2402     return result;
2403 }
2404 
2405 
2406 //-----------------------------------------------------------------------------
android_audioPlayer_loop(CAudioPlayer * ap,SLboolean loopEnable)2407 SLresult android_audioPlayer_loop(CAudioPlayer *ap, SLboolean loopEnable) {
2408     SLresult result = SL_RESULT_SUCCESS;
2409 
2410     switch (ap->mAndroidObjType) {
2411     case AUDIOPLAYER_FROM_URIFD:
2412     // case AUDIOPLAY_FROM_URIFD_TO_PCM_BUFFERQUEUE:
2413     //      would actually work, but what's the point?
2414       if (ap->mAPlayer != 0) {
2415         ap->mAPlayer->loop((bool)loopEnable);
2416       }
2417       break;
2418     default:
2419       result = SL_RESULT_FEATURE_UNSUPPORTED;
2420       break;
2421     }
2422     return result;
2423 }
2424 
2425 
2426 //-----------------------------------------------------------------------------
android_audioPlayer_setBufferingUpdateThresholdPerMille(CAudioPlayer * ap,SLpermille threshold)2427 SLresult android_audioPlayer_setBufferingUpdateThresholdPerMille(CAudioPlayer *ap,
2428         SLpermille threshold) {
2429     SLresult result = SL_RESULT_SUCCESS;
2430 
2431     switch (ap->mAndroidObjType) {
2432       case AUDIOPLAYER_FROM_URIFD:
2433         if (ap->mAPlayer != 0) {
2434             ap->mAPlayer->setBufferingUpdateThreshold(threshold / 10);
2435         }
2436         break;
2437 
2438       default: {}
2439     }
2440 
2441     return result;
2442 }
2443 
2444 
2445 //-----------------------------------------------------------------------------
android_audioPlayer_bufferQueue_onRefilled_l(CAudioPlayer * ap)2446 void android_audioPlayer_bufferQueue_onRefilled_l(CAudioPlayer *ap) {
2447     // the AudioTrack associated with the AudioPlayer receiving audio from a PCM buffer
2448     // queue was stopped when the queue become empty, we restart as soon as a new buffer
2449     // has been enqueued since we're in playing state
2450     if (ap->mTrackPlayer->mAudioTrack != 0) {
2451         ap->mTrackPlayer->reportEvent(android::PLAYER_STATE_STARTED,
2452                             ap->mTrackPlayer->mAudioTrack->getRoutedDeviceId());
2453         // instead of ap->mTrackPlayer->mAudioTrack->start();
2454         ap->mDeferredStart = true;
2455     }
2456 
2457     // when the queue became empty, an underflow on the prefetch status itf was sent. Now the queue
2458     // has received new data, signal it has sufficient data
2459     if (IsInterfaceInitialized(&ap->mObject, MPH_PREFETCHSTATUS)) {
2460         // we wouldn't have been called unless we were previously in the underflow state
2461         assert(SL_PREFETCHSTATUS_UNDERFLOW == ap->mPrefetchStatus.mStatus);
2462         assert(0 == ap->mPrefetchStatus.mLevel);
2463         ap->mPrefetchStatus.mStatus = SL_PREFETCHSTATUS_SUFFICIENTDATA;
2464         ap->mPrefetchStatus.mLevel = 1000;
2465         // callback or no callback?
2466         SLuint32 prefetchEvents = ap->mPrefetchStatus.mCallbackEventsMask &
2467                 (SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE);
2468         if (SL_PREFETCHEVENT_NONE != prefetchEvents) {
2469             ap->mPrefetchStatus.mDeferredPrefetchCallback = ap->mPrefetchStatus.mCallback;
2470             ap->mPrefetchStatus.mDeferredPrefetchContext  = ap->mPrefetchStatus.mContext;
2471             ap->mPrefetchStatus.mDeferredPrefetchEvents   = prefetchEvents;
2472         }
2473     }
2474 }
2475 
2476 
2477 //-----------------------------------------------------------------------------
2478 /*
2479  * BufferQueue::Clear
2480  */
android_audioPlayer_bufferQueue_onClear(CAudioPlayer * ap)2481 SLresult android_audioPlayer_bufferQueue_onClear(CAudioPlayer *ap) {
2482     SLresult result = SL_RESULT_SUCCESS;
2483 
2484     switch (ap->mAndroidObjType) {
2485     //-----------------------------------
2486     // AudioTrack
2487     case AUDIOPLAYER_FROM_PCM_BUFFERQUEUE:
2488         if (ap->mTrackPlayer->mAudioTrack != 0) {
2489             ap->mTrackPlayer->mAudioTrack->flush();
2490         }
2491         break;
2492     default:
2493         result = SL_RESULT_INTERNAL_ERROR;
2494         break;
2495     }
2496 
2497     return result;
2498 }
2499 
2500 
2501 //-----------------------------------------------------------------------------
android_audioPlayer_androidBufferQueue_clear_l(CAudioPlayer * ap)2502 void android_audioPlayer_androidBufferQueue_clear_l(CAudioPlayer *ap) {
2503     switch (ap->mAndroidObjType) {
2504     case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2505       if (ap->mAPlayer != 0) {
2506         android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2507         splr->appClear_l();
2508       } break;
2509     case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2510       // nothing to do here, fall through
2511       FALLTHROUGH_INTENDED;
2512     default:
2513       break;
2514     }
2515 }
2516 
android_audioPlayer_androidBufferQueue_onRefilled_l(CAudioPlayer * ap)2517 void android_audioPlayer_androidBufferQueue_onRefilled_l(CAudioPlayer *ap) {
2518     switch (ap->mAndroidObjType) {
2519     case AUDIOPLAYER_FROM_TS_ANDROIDBUFFERQUEUE:
2520       if (ap->mAPlayer != 0) {
2521         android::StreamPlayer* splr = static_cast<android::StreamPlayer*>(ap->mAPlayer.get());
2522         splr->queueRefilled();
2523       } break;
2524     case AUDIOPLAYER_FROM_ADTS_ABQ_TO_PCM_BUFFERQUEUE:
2525       // FIXME this may require waking up the decoder if it is currently starved and isn't polling
2526     default:
2527       break;
2528     }
2529 }
2530