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