• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 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 <cassert>
18 
19 #include <SLES/OpenSLES.h>
20 #include <SLES/OpenSLES_Android.h>
21 #include <common/AudioClock.h>
22 
23 #include "oboe/AudioStreamBuilder.h"
24 #include "AudioOutputStreamOpenSLES.h"
25 #include "AudioStreamOpenSLES.h"
26 #include "OpenSLESUtilities.h"
27 #include "OutputMixerOpenSLES.h"
28 
29 using namespace oboe;
30 
OpenSLES_convertOutputUsage(Usage oboeUsage)31 static SLuint32 OpenSLES_convertOutputUsage(Usage oboeUsage) {
32     SLuint32 openslStream = SL_ANDROID_STREAM_MEDIA;
33     switch(oboeUsage) {
34         case Usage::Media:
35             openslStream = SL_ANDROID_STREAM_MEDIA;
36             break;
37         case Usage::VoiceCommunication:
38         case Usage::VoiceCommunicationSignalling:
39             openslStream = SL_ANDROID_STREAM_VOICE;
40             break;
41         case Usage::Alarm:
42             openslStream = SL_ANDROID_STREAM_ALARM;
43             break;
44         case Usage::Notification:
45         case Usage::NotificationRingtone:
46         case Usage::NotificationEvent:
47             openslStream = SL_ANDROID_STREAM_NOTIFICATION;
48             break;
49         case Usage::AssistanceAccessibility:
50         case Usage::AssistanceNavigationGuidance:
51         case Usage::AssistanceSonification:
52             openslStream = SL_ANDROID_STREAM_SYSTEM;
53             break;
54         case Usage::Game:
55             openslStream = SL_ANDROID_STREAM_MEDIA;
56             break;
57         case Usage::Assistant:
58         default:
59             openslStream = SL_ANDROID_STREAM_SYSTEM;
60             break;
61     }
62     return openslStream;
63 }
64 
AudioOutputStreamOpenSLES(const AudioStreamBuilder & builder)65 AudioOutputStreamOpenSLES::AudioOutputStreamOpenSLES(const AudioStreamBuilder &builder)
66         : AudioStreamOpenSLES(builder) {
67 }
68 
69 // These will wind up in <SLES/OpenSLES_Android.h>
70 constexpr int SL_ANDROID_SPEAKER_STEREO = (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
71 
72 constexpr int SL_ANDROID_SPEAKER_QUAD = (SL_ANDROID_SPEAKER_STEREO
73         | SL_SPEAKER_BACK_LEFT | SL_SPEAKER_BACK_RIGHT);
74 
75 constexpr int SL_ANDROID_SPEAKER_5DOT1 = (SL_ANDROID_SPEAKER_QUAD
76         | SL_SPEAKER_FRONT_CENTER  | SL_SPEAKER_LOW_FREQUENCY);
77 
78 constexpr int SL_ANDROID_SPEAKER_7DOT1 = (SL_ANDROID_SPEAKER_5DOT1 | SL_SPEAKER_SIDE_LEFT
79         | SL_SPEAKER_SIDE_RIGHT);
80 
channelCountToChannelMask(int channelCount) const81 SLuint32 AudioOutputStreamOpenSLES::channelCountToChannelMask(int channelCount) const {
82     SLuint32 channelMask = 0;
83 
84     switch (channelCount) {
85         case  1:
86             channelMask = SL_SPEAKER_FRONT_CENTER;
87             break;
88 
89         case  2:
90             channelMask = SL_ANDROID_SPEAKER_STEREO;
91             break;
92 
93         case  4: // Quad
94             channelMask = SL_ANDROID_SPEAKER_QUAD;
95             break;
96 
97         case  6: // 5.1
98             channelMask = SL_ANDROID_SPEAKER_5DOT1;
99             break;
100 
101         case  8: // 7.1
102             channelMask = SL_ANDROID_SPEAKER_7DOT1;
103             break;
104 
105         default:
106             channelMask = channelCountToChannelMaskDefault(channelCount);
107             break;
108     }
109     return channelMask;
110 }
111 
open()112 Result AudioOutputStreamOpenSLES::open() {
113     logUnsupportedAttributes();
114 
115     SLAndroidConfigurationItf configItf = nullptr;
116 
117 
118     if (getSdkVersion() < __ANDROID_API_L__ && mFormat == AudioFormat::Float){
119         // TODO: Allow floating point format on API <21 using float->int16 converter
120         return Result::ErrorInvalidFormat;
121     }
122 
123     // If audio format is unspecified then choose a suitable default.
124     // API 21+: FLOAT
125     // API <21: INT16
126     if (mFormat == AudioFormat::Unspecified){
127         mFormat = (getSdkVersion() < __ANDROID_API_L__) ?
128                   AudioFormat::I16 : AudioFormat::Float;
129     }
130 
131     Result oboeResult = AudioStreamOpenSLES::open();
132     if (Result::OK != oboeResult)  return oboeResult;
133 
134     SLresult result = OutputMixerOpenSL::getInstance().open();
135     if (SL_RESULT_SUCCESS != result) {
136         AudioStreamOpenSLES::close();
137         return Result::ErrorInternal;
138     }
139 
140     SLuint32 bitsPerSample = static_cast<SLuint32>(getBytesPerSample() * kBitsPerByte);
141 
142     // configure audio source
143     SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {
144             SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,    // locatorType
145             static_cast<SLuint32>(kBufferQueueLength)};   // numBuffers
146 
147     // Define the audio data format.
148     SLDataFormat_PCM format_pcm = {
149             SL_DATAFORMAT_PCM,       // formatType
150             static_cast<SLuint32>(mChannelCount),           // numChannels
151             static_cast<SLuint32>(mSampleRate * kMillisPerSecond),    // milliSamplesPerSec
152             bitsPerSample,                      // bitsPerSample
153             bitsPerSample,                      // containerSize;
154             channelCountToChannelMask(mChannelCount), // channelMask
155             getDefaultByteOrder(),
156     };
157 
158     SLDataSource audioSrc = {&loc_bufq, &format_pcm};
159 
160     /**
161      * API 21 (Lollipop) introduced support for floating-point data representation and an extended
162      * data format type: SLAndroidDataFormat_PCM_EX. If running on API 21+ use this newer format
163      * type, creating it from our original format.
164      */
165     SLAndroidDataFormat_PCM_EX format_pcm_ex;
166     if (getSdkVersion() >= __ANDROID_API_L__) {
167         SLuint32 representation = OpenSLES_ConvertFormatToRepresentation(getFormat());
168         // Fill in the format structure.
169         format_pcm_ex = OpenSLES_createExtendedFormat(format_pcm, representation);
170         // Use in place of the previous format.
171         audioSrc.pFormat = &format_pcm_ex;
172     }
173 
174     result = OutputMixerOpenSL::getInstance().createAudioPlayer(&mObjectInterface,
175                                                                           &audioSrc);
176     if (SL_RESULT_SUCCESS != result) {
177         LOGE("createAudioPlayer() result:%s", getSLErrStr(result));
178         goto error;
179     }
180 
181     // Configure the stream.
182     result = (*mObjectInterface)->GetInterface(mObjectInterface,
183                                                SL_IID_ANDROIDCONFIGURATION,
184                                                (void *)&configItf);
185     if (SL_RESULT_SUCCESS != result) {
186         LOGW("%s() GetInterface(SL_IID_ANDROIDCONFIGURATION) failed with %s",
187              __func__, getSLErrStr(result));
188     } else {
189         result = configurePerformanceMode(configItf);
190         if (SL_RESULT_SUCCESS != result) {
191             goto error;
192         }
193 
194         SLuint32 presetValue = OpenSLES_convertOutputUsage(getUsage());
195         result = (*configItf)->SetConfiguration(configItf,
196                                                 SL_ANDROID_KEY_STREAM_TYPE,
197                                                 &presetValue,
198                                                 sizeof(presetValue));
199         if (SL_RESULT_SUCCESS != result) {
200             goto error;
201         }
202     }
203 
204     result = (*mObjectInterface)->Realize(mObjectInterface, SL_BOOLEAN_FALSE);
205     if (SL_RESULT_SUCCESS != result) {
206         LOGE("Realize player object result:%s", getSLErrStr(result));
207         goto error;
208     }
209 
210     result = (*mObjectInterface)->GetInterface(mObjectInterface, SL_IID_PLAY, &mPlayInterface);
211     if (SL_RESULT_SUCCESS != result) {
212         LOGE("GetInterface PLAY result:%s", getSLErrStr(result));
213         goto error;
214     }
215 
216     result = AudioStreamOpenSLES::registerBufferQueueCallback();
217     if (SL_RESULT_SUCCESS != result) {
218         goto error;
219     }
220 
221     result = updateStreamParameters(configItf);
222     if (SL_RESULT_SUCCESS != result) {
223         goto error;
224     }
225 
226     oboeResult = configureBufferSizes(mSampleRate);
227     if (Result::OK != oboeResult) {
228         goto error;
229     }
230 
231     allocateFifo();
232 
233     setState(StreamState::Open);
234     return Result::OK;
235 
236 error:
237     return Result::ErrorInternal; // TODO convert error from SLES to OBOE
238 }
239 
onAfterDestroy()240 Result AudioOutputStreamOpenSLES::onAfterDestroy() {
241     OutputMixerOpenSL::getInstance().close();
242     return Result::OK;
243 }
244 
close()245 Result AudioOutputStreamOpenSLES::close() {
246     mLock.lock();
247     Result result = Result::OK;
248     if (getState() == StreamState::Closed){
249         result = Result::ErrorClosed;
250     } else {
251         mLock.unlock(); // avoid recursive lock
252         requestPause();
253         mLock.lock();
254         // invalidate any interfaces
255         mPlayInterface = nullptr;
256         result = AudioStreamOpenSLES::close();
257     }
258     mLock.unlock(); // avoid recursive lock
259     return result;
260 }
261 
setPlayState_l(SLuint32 newState)262 Result AudioOutputStreamOpenSLES::setPlayState_l(SLuint32 newState) {
263 
264     LOGD("AudioOutputStreamOpenSLES(): %s() called", __func__);
265     Result result = Result::OK;
266 
267     if (mPlayInterface == nullptr){
268         LOGE("AudioOutputStreamOpenSLES::%s() mPlayInterface is null", __func__);
269         return Result::ErrorInvalidState;
270     }
271 
272     SLresult slResult = (*mPlayInterface)->SetPlayState(mPlayInterface, newState);
273     if (SL_RESULT_SUCCESS != slResult) {
274         LOGW("AudioOutputStreamOpenSLES(): %s() returned %s", __func__, getSLErrStr(slResult));
275         result = Result::ErrorInternal; // TODO convert slResult to Result::Error
276     }
277     return result;
278 }
279 
requestStart()280 Result AudioOutputStreamOpenSLES::requestStart() {
281     LOGD("AudioOutputStreamOpenSLES(): %s() called", __func__);
282 
283     mLock.lock();
284     StreamState initialState = getState();
285     switch (initialState) {
286         case StreamState::Starting:
287         case StreamState::Started:
288             mLock.unlock();
289             return Result::OK;
290         case StreamState::Closed:
291             mLock.unlock();
292             return Result::ErrorClosed;
293         default:
294             break;
295     }
296 
297     // We use a callback if the user requests one
298     // OR if we have an internal callback to read the blocking IO buffer.
299     setDataCallbackEnabled(true);
300 
301     setState(StreamState::Starting);
302     Result result = setPlayState_l(SL_PLAYSTATE_PLAYING);
303     if (result == Result::OK) {
304         setState(StreamState::Started);
305         mLock.unlock();
306         if (getBufferDepth(mSimpleBufferQueueInterface) == 0) {
307             // Enqueue the first buffer if needed to start the streaming.
308             // This might call requestStop() so try to avoid a recursive lock.
309             processBufferCallback(mSimpleBufferQueueInterface);
310         }
311     } else {
312         setState(initialState);
313         mLock.unlock();
314     }
315     return result;
316 }
317 
requestPause()318 Result AudioOutputStreamOpenSLES::requestPause() {
319     LOGD("AudioOutputStreamOpenSLES(): %s() called", __func__);
320 
321     std::lock_guard<std::mutex> lock(mLock);
322     StreamState initialState = getState();
323     switch (initialState) {
324         case StreamState::Pausing:
325         case StreamState::Paused:
326             return Result::OK;
327         case StreamState::Closed:
328             return Result::ErrorClosed;
329         default:
330             break;
331     }
332 
333     setState(StreamState::Pausing);
334     Result result = setPlayState_l(SL_PLAYSTATE_PAUSED);
335     if (result == Result::OK) {
336         // Note that OpenSL ES does NOT reset its millisecond position when OUTPUT is paused.
337         int64_t framesWritten = getFramesWritten();
338         if (framesWritten >= 0) {
339             setFramesRead(framesWritten);
340         }
341         setState(StreamState::Paused);
342     } else {
343         setState(initialState);
344     }
345     return result;
346 }
347 
348 /**
349  * Flush/clear the queue buffers
350  */
requestFlush()351 Result AudioOutputStreamOpenSLES::requestFlush() {
352     std::lock_guard<std::mutex> lock(mLock);
353     return requestFlush_l();
354 }
355 
requestFlush_l()356 Result AudioOutputStreamOpenSLES::requestFlush_l() {
357     LOGD("AudioOutputStreamOpenSLES(): %s() called", __func__);
358     if (getState() == StreamState::Closed) {
359         return Result::ErrorClosed;
360     }
361 
362     Result result = Result::OK;
363     if (mPlayInterface == nullptr || mSimpleBufferQueueInterface == nullptr) {
364         result = Result::ErrorInvalidState;
365     } else {
366         SLresult slResult = (*mSimpleBufferQueueInterface)->Clear(mSimpleBufferQueueInterface);
367         if (slResult != SL_RESULT_SUCCESS){
368             LOGW("Failed to clear buffer queue. OpenSLES error: %d", result);
369             result = Result::ErrorInternal;
370         }
371     }
372     return result;
373 }
374 
requestStop()375 Result AudioOutputStreamOpenSLES::requestStop() {
376     LOGD("AudioOutputStreamOpenSLES(): %s() called", __func__);
377 
378     std::lock_guard<std::mutex> lock(mLock);
379     StreamState initialState = getState();
380     switch (initialState) {
381         case StreamState::Stopping:
382         case StreamState::Stopped:
383             return Result::OK;
384         case StreamState::Closed:
385             return Result::ErrorClosed;
386         default:
387             break;
388     }
389 
390     setState(StreamState::Stopping);
391 
392     Result result = setPlayState_l(SL_PLAYSTATE_STOPPED);
393     if (result == Result::OK) {
394 
395         // Also clear the buffer queue so the old data won't be played if the stream is restarted.
396         // Call the _l function that expects to already be under a lock.
397         if (requestFlush_l() != Result::OK) {
398             LOGW("Failed to flush the stream. Error %s", convertToText(flush()));
399         }
400 
401         mPositionMillis.reset32(); // OpenSL ES resets its millisecond position when stopped.
402         int64_t framesWritten = getFramesWritten();
403         if (framesWritten >= 0) {
404             setFramesRead(framesWritten);
405         }
406         setState(StreamState::Stopped);
407     } else {
408         setState(initialState);
409     }
410     return result;
411 }
412 
setFramesRead(int64_t framesRead)413 void AudioOutputStreamOpenSLES::setFramesRead(int64_t framesRead) {
414     int64_t millisWritten = framesRead * kMillisPerSecond / getSampleRate();
415     mPositionMillis.set(millisWritten);
416 }
417 
updateFramesRead()418 void AudioOutputStreamOpenSLES::updateFramesRead() {
419     if (usingFIFO()) {
420         AudioStreamBuffered::updateFramesRead();
421     } else {
422         mFramesRead = getFramesProcessedByServer();
423     }
424 }
425 
updateServiceFrameCounter()426 Result AudioOutputStreamOpenSLES::updateServiceFrameCounter() {
427     Result result = Result::OK;
428     // Avoid deadlock if another thread is trying to stop or close this stream
429     // and this is being called from a callback.
430     if (mLock.try_lock()) {
431 
432         if (mPlayInterface == nullptr) {
433             mLock.unlock();
434             return Result::ErrorNull;
435         }
436         SLmillisecond msec = 0;
437         SLresult slResult = (*mPlayInterface)->GetPosition(mPlayInterface, &msec);
438         if (SL_RESULT_SUCCESS != slResult) {
439             LOGW("%s(): GetPosition() returned %s", __func__, getSLErrStr(slResult));
440             // set result based on SLresult
441             result = Result::ErrorInternal;
442         } else {
443             mPositionMillis.update32(msec);
444         }
445         mLock.unlock();
446     }
447     return result;
448 }
449