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