blob: 344eca5bf77f3ddbb4df8ee41aa481206cce050e [file] [log] [blame]
Hugo Hudsonb83ad732011-07-14 23:31:17 +01001/*
2 * Copyright (C) 2011 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 <variablespeed.h>
18
19#include <unistd.h>
20#include <stdlib.h>
21
22#include <sola_time_scaler.h>
23#include <ring_buffer.h>
24
25#include <hlogging.h>
26
27#include <vector>
28
29// ****************************************************************************
30// Constants, utility methods, structures and other miscellany used throughout
31// this file.
32
33namespace {
34
35// These variables are used to determine the size of the buffer queue used by
36// the decoder.
37// This is not the same as the large buffer used to hold the uncompressed data
38// - for that see the member variable decodeBuffer_.
39// The choice of 1152 corresponds to the number of samples per mp3 frame, so is
40// a good choice of size for a decoding buffer in the absence of other
41// information (we don't know exactly what formats we will be working with).
42const size_t kNumberOfBuffersInQueue = 4;
43const size_t kNumberOfSamplesPerBuffer = 1152;
44const size_t kBufferSizeInBytes = 2 * kNumberOfSamplesPerBuffer;
45const size_t kSampleSizeInBytes = 4;
46
Hugo Hudson0bd6ec52011-07-26 20:05:25 +010047// Keys used when extracting metadata from the decoder.
48// TODO: Remove these constants once they are part of OpenSLES_Android.h.
49const char* kKeyPcmFormatNumChannels = "AndroidPcmFormatNumChannels";
50const char* kKeyPcmFormatSamplesPerSec = "AndroidPcmFormatSamplesPerSec";
51
Hugo Hudsonb83ad732011-07-14 23:31:17 +010052// When calculating play buffer size before pushing to audio player.
53const size_t kNumberOfBytesPerInt16 = 2;
54
55// How long to sleep during the main play loop and the decoding callback loop.
56// In due course this should be replaced with the better signal and wait on
57// condition rather than busy-looping.
58const int kSleepTimeMicros = 1000;
59
60// Used in detecting errors with the OpenSL ES framework.
61const SLuint32 kPrefetchErrorCandidate =
62 SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE;
63
64// Structure used when we perform a decoding callback.
65typedef struct CallbackContext_ {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +010066 // Pointer to local storage buffers for decoded audio data.
67 int8_t* pDataBase;
68 // Pointer to the current buffer within local storage.
69 int8_t* pData;
70 // Used to read the sample rate and channels from the decoding stream during
71 // the first decoding callback.
72 SLMetadataExtractionItf decoderMetadata;
73 // The play interface used for reading duration.
74 SLPlayItf playItf;
Hugo Hudsonb83ad732011-07-14 23:31:17 +010075} CallbackContext;
76
77// Local storage for decoded audio data.
78int8_t pcmData[kNumberOfBuffersInQueue * kBufferSizeInBytes];
79
80#define CheckSLResult(message, result) \
81 CheckSLResult_Real(message, result, __LINE__)
82
83// Helper function for debugging - checks the OpenSL result for success.
84void CheckSLResult_Real(const char* message, SLresult result, int line) {
85 // This can be helpful when debugging.
86 // LOGD("sl result %d for %s", result, message);
87 if (SL_RESULT_SUCCESS != result) {
88 LOGE("slresult was %d at %s file variablespeed line %d",
89 static_cast<int>(result), message, line);
90 }
91 CHECK(SL_RESULT_SUCCESS == result);
92}
93
94} // namespace
95
96// ****************************************************************************
97// Static instance of audio engine, and methods for getting, setting and
98// deleting it.
99
100// The single global audio engine instance.
101AudioEngine* AudioEngine::audioEngine_ = NULL;
102android::Mutex publishEngineLock_;
103
104AudioEngine* AudioEngine::GetEngine() {
105 android::Mutex::Autolock autoLock(publishEngineLock_);
106 if (audioEngine_ == NULL) {
107 LOGE("you haven't initialized the audio engine");
108 CHECK(false);
109 return NULL;
110 }
111 return audioEngine_;
112}
113
114void AudioEngine::SetEngine(AudioEngine* engine) {
115 if (audioEngine_ != NULL) {
116 LOGE("you have already set the audio engine");
117 CHECK(false);
118 return;
119 }
120 audioEngine_ = engine;
121}
122
123void AudioEngine::DeleteEngine() {
124 if (audioEngine_ == NULL) {
125 LOGE("you haven't initialized the audio engine");
126 CHECK(false);
127 return;
128 }
129 delete audioEngine_;
130 audioEngine_ = NULL;
131}
132
133// ****************************************************************************
134// The callbacks from the engine require static callback functions.
135// Here are the static functions - they just delegate to instance methods on
136// the engine.
137
138static void PlayingBufferQueueCb(SLAndroidSimpleBufferQueueItf, void*) {
139 AudioEngine::GetEngine()->PlayingBufferQueueCallback();
140}
141
142static void PrefetchEventCb(SLPrefetchStatusItf caller, void*, SLuint32 event) {
143 AudioEngine::GetEngine()->PrefetchEventCallback(caller, event);
144}
145
146static void DecodingBufferQueueCb(SLAndroidSimpleBufferQueueItf queueItf,
147 void *context) {
148 AudioEngine::GetEngine()->DecodingBufferQueueCallback(queueItf, context);
149}
150
151static void DecodingEventCb(SLPlayItf caller, void*, SLuint32 event) {
152 AudioEngine::GetEngine()->DecodingEventCallback(caller, event);
153}
154
155// ****************************************************************************
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100156// Macros for making working with OpenSL easier.
157
158// #define LOG_OPENSL_API_CALL(string) LOGV(string)
159#define LOG_OPENSL_API_CALL(string) false
160
161// The regular macro: log an api call, make the api call, check the result.
162#define OpenSL(obj, method, ...) \
163{ \
164 LOG_OPENSL_API_CALL("OpenSL " #method "(" #obj ", " #__VA_ARGS__ ")"); \
165 SLresult result = (*obj)->method(obj, __VA_ARGS__); \
166 CheckSLResult("OpenSL " #method "(" #obj ", " #__VA_ARGS__ ")", result); \
167}
168
169// Special case call for api call that has void return value, can't be checked.
170#define VoidOpenSL(obj, method) \
171{ \
172 LOG_OPENSL_API_CALL("OpenSL (void) " #method "(" #obj ")"); \
173 (*obj)->method(obj); \
174}
175
176// Special case for api call with checked result but takes no arguments.
177#define OpenSL0(obj, method) \
178{ \
179 LOG_OPENSL_API_CALL("OpenSL " #method "(" #obj ")"); \
180 SLresult result = (*obj)->method(obj); \
181 CheckSLResult("OpenSL " #method "(" #obj ")", result); \
182}
183
184// Special case for api call whose result we want to store, not check.
185// We have to encapsulate the two calls in braces, so that this expression
186// evaluates to the last expression not the first.
187#define ReturnOpenSL(obj, method, ...) \
188( \
189 LOG_OPENSL_API_CALL("OpenSL (int) " \
190 #method "(" #obj ", " #__VA_ARGS__ ")"), \
191 (*obj)->method(obj, __VA_ARGS__) \
192) \
193
194// ****************************************************************************
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100195// Static utility methods.
196
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100197// Must be called with callbackLock_ held.
198static void ReadSampleRateAndChannelCount(CallbackContext *pContext,
199 SLuint32 *sampleRateOut, SLuint32 *channelsOut) {
200 SLMetadataExtractionItf decoderMetadata = pContext->decoderMetadata;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100201 SLuint32 itemCount;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100202 OpenSL(decoderMetadata, GetItemCount, &itemCount);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100203 SLuint32 i, keySize, valueSize;
204 SLMetadataInfo *keyInfo, *value;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100205 for (i = 0; i < itemCount; ++i) {
206 keyInfo = value = NULL;
207 keySize = valueSize = 0;
208 OpenSL(decoderMetadata, GetKeySize, i, &keySize);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100209 keyInfo = static_cast<SLMetadataInfo*>(malloc(keySize));
210 if (keyInfo) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100211 OpenSL(decoderMetadata, GetKey, i, keySize, keyInfo);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100212 if (keyInfo->encoding == SL_CHARACTERENCODING_ASCII
213 || keyInfo->encoding == SL_CHARACTERENCODING_UTF8) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100214 OpenSL(decoderMetadata, GetValueSize, i, &valueSize);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100215 value = static_cast<SLMetadataInfo*>(malloc(valueSize));
216 if (value) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100217 OpenSL(decoderMetadata, GetValue, i, valueSize, value);
218 if (strcmp((char*) keyInfo->data, kKeyPcmFormatSamplesPerSec) == 0) {
219 SLuint32 sampleRate = *(reinterpret_cast<SLuint32*>(value->data));
220 LOGD("sample Rate: %d", sampleRate);
221 *sampleRateOut = sampleRate;
222 } else if (strcmp((char*) keyInfo->data, kKeyPcmFormatNumChannels) == 0) {
223 SLuint32 channels = *(reinterpret_cast<SLuint32*>(value->data));
224 LOGD("channels: %d", channels);
225 *channelsOut = channels;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100226 }
227 free(value);
228 }
229 }
230 free(keyInfo);
231 }
232 }
233}
234
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100235// Must be called with callbackLock_ held.
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100236static void RegisterCallbackContextAndAddEnqueueBuffersToDecoder(
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100237 SLAndroidSimpleBufferQueueItf decoderQueue, CallbackContext* context) {
238 // Register a callback on the decoder queue, so that we will be called
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100239 // throughout the decoding process (and can then extract the decoded audio
240 // for the next bit of the pipeline).
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100241 OpenSL(decoderQueue, RegisterCallback, DecodingBufferQueueCb, context);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100242
243 // Enqueue buffers to map the region of memory allocated to store the
244 // decoded data.
245 for (size_t i = 0; i < kNumberOfBuffersInQueue; i++) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100246 OpenSL(decoderQueue, Enqueue, context->pData, kBufferSizeInBytes);
Hugo Hudson9730f152011-07-25 17:04:42 +0100247 context->pData += kBufferSizeInBytes;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100248 }
Hugo Hudson9730f152011-07-25 17:04:42 +0100249 context->pData = context->pDataBase;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100250}
251
252// ****************************************************************************
253// Constructor and Destructor.
254
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100255AudioEngine::AudioEngine(size_t targetFrames, float windowDuration,
256 float windowOverlapDuration, size_t maxPlayBufferCount, float initialRate,
257 size_t decodeInitialSize, size_t decodeMaxSize, size_t startPositionMillis)
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100258 : decodeBuffer_(decodeInitialSize, decodeMaxSize),
259 playingBuffers_(), freeBuffers_(), timeScaler_(NULL),
260 floatBuffer_(NULL), injectBuffer_(NULL),
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100261 mSampleRate(0), mChannels(0),
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100262 targetFrames_(targetFrames),
263 windowDuration_(windowDuration),
264 windowOverlapDuration_(windowOverlapDuration),
265 maxPlayBufferCount_(maxPlayBufferCount), initialRate_(initialRate),
266 startPositionMillis_(startPositionMillis),
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100267 totalDurationMs_(0), decoderCurrentPosition_(0), startRequested_(false),
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100268 stopRequested_(false), finishedDecoding_(false) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100269}
270
271AudioEngine::~AudioEngine() {
272 // destroy the time scaler
273 if (timeScaler_ != NULL) {
274 delete timeScaler_;
275 timeScaler_ = NULL;
276 }
277
278 // delete all outstanding playing and free buffers
279 android::Mutex::Autolock autoLock(playBufferLock_);
280 while (playingBuffers_.size() > 0) {
281 delete[] playingBuffers_.front();
282 playingBuffers_.pop();
283 }
284 while (freeBuffers_.size() > 0) {
285 delete[] freeBuffers_.top();
286 freeBuffers_.pop();
287 }
288
289 delete[] floatBuffer_;
290 floatBuffer_ = NULL;
291 delete[] injectBuffer_;
292 injectBuffer_ = NULL;
293}
294
295// ****************************************************************************
296// Regular AudioEngine class methods.
297
298void AudioEngine::SetVariableSpeed(float speed) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100299 // TODO: Mutex for shared time scaler accesses.
Hugo Hudson64f5ba62011-08-10 15:57:28 +0100300 if (HasSampleRateAndChannels()) {
301 GetTimeScaler()->set_speed(speed);
302 } else {
303 // This is being called at a point where we have not yet processed enough
304 // data to determine the sample rate and number of channels.
305 // Ignore the call. See http://b/5140693.
306 LOGD("set varaible speed called, sample rate and channels not ready yet");
307 }
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100308}
309
310void AudioEngine::RequestStart() {
311 android::Mutex::Autolock autoLock(lock_);
312 startRequested_ = true;
313}
314
315void AudioEngine::ClearRequestStart() {
316 android::Mutex::Autolock autoLock(lock_);
317 startRequested_ = false;
318}
319
320bool AudioEngine::GetWasStartRequested() {
321 android::Mutex::Autolock autoLock(lock_);
322 return startRequested_;
323}
324
325void AudioEngine::RequestStop() {
326 android::Mutex::Autolock autoLock(lock_);
327 stopRequested_ = true;
328}
329
330int AudioEngine::GetCurrentPosition() {
331 android::Mutex::Autolock autoLock(decodeBufferLock_);
332 double result = decodeBuffer_.GetTotalAdvancedCount();
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100333 // TODO: This is horrible, but should be removed soon once the outstanding
334 // issue with get current position on decoder is fixed.
335 android::Mutex::Autolock autoLock2(callbackLock_);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100336 return static_cast<int>(
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100337 (result * 1000) / mSampleRate / mChannels + startPositionMillis_);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100338}
339
340int AudioEngine::GetTotalDuration() {
341 android::Mutex::Autolock autoLock(lock_);
342 return static_cast<int>(totalDurationMs_);
343}
344
345video_editing::SolaTimeScaler* AudioEngine::GetTimeScaler() {
346 if (timeScaler_ == NULL) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100347 CHECK(HasSampleRateAndChannels());
348 android::Mutex::Autolock autoLock(callbackLock_);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100349 timeScaler_ = new video_editing::SolaTimeScaler();
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100350 timeScaler_->Init(mSampleRate, mChannels, initialRate_, windowDuration_,
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100351 windowOverlapDuration_);
352 }
353 return timeScaler_;
354}
355
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100356bool AudioEngine::EnqueueNextBufferOfAudio(
357 SLAndroidSimpleBufferQueueItf audioPlayerQueue) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100358 size_t channels;
359 {
360 android::Mutex::Autolock autoLock(callbackLock_);
361 channels = mChannels;
362 }
363 size_t frameSizeInBytes = kSampleSizeInBytes * channels;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100364 size_t frameCount = 0;
365 while (frameCount < targetFrames_) {
366 size_t framesLeft = targetFrames_ - frameCount;
367 // If there is data already in the time scaler, retrieve it.
368 if (GetTimeScaler()->available() > 0) {
369 size_t retrieveCount = min(GetTimeScaler()->available(), framesLeft);
370 int count = GetTimeScaler()->RetrieveSamples(
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100371 floatBuffer_ + frameCount * channels, retrieveCount);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100372 if (count <= 0) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100373 LOGD("error: count was %d", count);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100374 break;
375 }
376 frameCount += count;
377 continue;
378 }
379 // If there is no data in the time scaler, then feed some into it.
380 android::Mutex::Autolock autoLock(decodeBufferLock_);
381 size_t framesInDecodeBuffer =
382 decodeBuffer_.GetSizeInBytes() / frameSizeInBytes;
383 size_t framesScalerCanHandle = GetTimeScaler()->input_limit();
384 size_t framesToInject = min(framesInDecodeBuffer,
385 min(targetFrames_, framesScalerCanHandle));
386 if (framesToInject <= 0) {
387 // No more frames left to inject.
388 break;
389 }
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100390 for (size_t i = 0; i < framesToInject * channels; ++i) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100391 injectBuffer_[i] = decodeBuffer_.GetAtIndex(i);
392 }
393 int count = GetTimeScaler()->InjectSamples(injectBuffer_, framesToInject);
394 if (count <= 0) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100395 LOGD("error: count was %d", count);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100396 break;
397 }
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100398 decodeBuffer_.AdvanceHeadPointerShorts(count * channels);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100399 }
400 if (frameCount <= 0) {
401 // We must have finished playback.
402 if (GetEndOfDecoderReached()) {
403 // If we've finished decoding, clear the buffer - so we will terminate.
404 ClearDecodeBuffer();
405 }
406 return false;
407 }
408
409 // Get a free playing buffer.
410 int16* playBuffer;
411 {
412 android::Mutex::Autolock autoLock(playBufferLock_);
413 if (freeBuffers_.size() > 0) {
414 // If we have a free buffer, recycle it.
415 playBuffer = freeBuffers_.top();
416 freeBuffers_.pop();
417 } else {
418 // Otherwise allocate a new one.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100419 playBuffer = new int16[targetFrames_ * channels];
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100420 }
421 }
422
423 // Try to play the buffer.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100424 for (size_t i = 0; i < frameCount * channels; ++i) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100425 playBuffer[i] = floatBuffer_[i];
426 }
427 size_t sizeOfPlayBufferInBytes =
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100428 frameCount * channels * kNumberOfBytesPerInt16;
429 SLresult result = ReturnOpenSL(audioPlayerQueue, Enqueue, playBuffer,
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100430 sizeOfPlayBufferInBytes);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100431 if (result == SL_RESULT_SUCCESS) {
432 android::Mutex::Autolock autoLock(playBufferLock_);
433 playingBuffers_.push(playBuffer);
434 } else {
435 LOGE("could not enqueue audio buffer");
436 delete[] playBuffer;
437 }
438
439 return (result == SL_RESULT_SUCCESS);
440}
441
442bool AudioEngine::GetEndOfDecoderReached() {
443 android::Mutex::Autolock autoLock(lock_);
444 return finishedDecoding_;
445}
446
447void AudioEngine::SetEndOfDecoderReached() {
448 android::Mutex::Autolock autoLock(lock_);
449 finishedDecoding_ = true;
450}
451
452bool AudioEngine::PlayFileDescriptor(int fd, int64 offset, int64 length) {
453 SLDataLocator_AndroidFD loc_fd = {
454 SL_DATALOCATOR_ANDROIDFD, fd, offset, length };
455 SLDataFormat_MIME format_mime = {
456 SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED };
457 SLDataSource audioSrc = { &loc_fd, &format_mime };
458 return PlayFromThisSource(audioSrc);
459}
460
461bool AudioEngine::PlayUri(const char* uri) {
462 // Source of audio data for the decoding
463 SLDataLocator_URI decUri = { SL_DATALOCATOR_URI,
464 const_cast<SLchar*>(reinterpret_cast<const SLchar*>(uri)) };
465 SLDataFormat_MIME decMime = {
466 SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED };
467 SLDataSource decSource = { &decUri, &decMime };
468 return PlayFromThisSource(decSource);
469}
470
471bool AudioEngine::IsDecodeBufferEmpty() {
472 android::Mutex::Autolock autoLock(decodeBufferLock_);
473 return decodeBuffer_.GetSizeInBytes() <= 0;
474}
475
476void AudioEngine::ClearDecodeBuffer() {
477 android::Mutex::Autolock autoLock(decodeBufferLock_);
478 decodeBuffer_.Clear();
479}
480
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100481static size_t ReadDuration(SLPlayItf playItf) {
482 SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
483 OpenSL(playItf, GetDuration, &durationInMsec);
484 if (durationInMsec == SL_TIME_UNKNOWN) {
485 LOGE("can't get duration");
486 return 0;
487 }
488 LOGD("duration: %d", static_cast<int>(durationInMsec));
489 return durationInMsec;
490}
491
492static size_t ReadPosition(SLPlayItf playItf) {
493 SLmillisecond positionInMsec = SL_TIME_UNKNOWN;
494 OpenSL(playItf, GetPosition, &positionInMsec);
495 if (positionInMsec == SL_TIME_UNKNOWN) {
496 LOGE("can't get position");
497 return 0;
498 }
499 LOGW("decoder position: %d", static_cast<int>(positionInMsec));
500 return positionInMsec;
501}
502
Hugo Hudson9730f152011-07-25 17:04:42 +0100503static void CreateAndRealizeEngine(SLObjectItf &engine,
504 SLEngineItf &engineInterface) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100505 SLEngineOption EngineOption[] = { {
506 SL_ENGINEOPTION_THREADSAFE, SL_BOOLEAN_TRUE } };
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100507 SLresult result = slCreateEngine(&engine, 1, EngineOption, 0, NULL, NULL);
508 CheckSLResult("create engine", result);
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100509 OpenSL(engine, Realize, SL_BOOLEAN_FALSE);
510 OpenSL(engine, GetInterface, SL_IID_ENGINE, &engineInterface);
Hugo Hudson9730f152011-07-25 17:04:42 +0100511}
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100512
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100513SLuint32 AudioEngine::GetSLSampleRate() {
514 android::Mutex::Autolock autoLock(callbackLock_);
515 return mSampleRate * 1000;
Hugo Hudson9730f152011-07-25 17:04:42 +0100516}
517
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100518SLuint32 AudioEngine::GetSLChannels() {
519 android::Mutex::Autolock autoLock(callbackLock_);
520 switch (mChannels) {
Hugo Hudson9730f152011-07-25 17:04:42 +0100521 case 2:
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100522 return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
Hugo Hudson9730f152011-07-25 17:04:42 +0100523 case 1:
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100524 return SL_SPEAKER_FRONT_CENTER;
Hugo Hudson9730f152011-07-25 17:04:42 +0100525 default:
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100526 LOGE("unknown channels %d, using 2", mChannels);
527 return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
Hugo Hudson9730f152011-07-25 17:04:42 +0100528 }
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100529}
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100530
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100531SLuint32 AudioEngine::GetChannelCount() {
532 android::Mutex::Autolock autoLock(callbackLock_);
533 return mChannels;
534}
535
536static void CreateAndRealizeAudioPlayer(SLuint32 slSampleRate,
537 size_t channelCount, SLuint32 slChannels, SLObjectItf &outputMix,
538 SLObjectItf &audioPlayer, SLEngineItf &engineInterface) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100539 // Define the source and sink for the audio player: comes from a buffer queue
540 // and goes to the output mix.
541 SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {
542 SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2 };
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100543 SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, channelCount, slSampleRate,
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100544 SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16,
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100545 slChannels, SL_BYTEORDER_LITTLEENDIAN};
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100546 SLDataSource playingSrc = {&loc_bufq, &format_pcm};
547 SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMix};
548 SLDataSink audioSnk = {&loc_outmix, NULL};
549
550 // Create the audio player, which will play from the buffer queue and send to
551 // the output mix.
552 const size_t playerInterfaceCount = 1;
553 const SLInterfaceID iids[playerInterfaceCount] = {
554 SL_IID_ANDROIDSIMPLEBUFFERQUEUE };
555 const SLboolean reqs[playerInterfaceCount] = { SL_BOOLEAN_TRUE };
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100556 OpenSL(engineInterface, CreateAudioPlayer, &audioPlayer, &playingSrc,
557 &audioSnk, playerInterfaceCount, iids, reqs);
558 OpenSL(audioPlayer, Realize, SL_BOOLEAN_FALSE);
Hugo Hudson9730f152011-07-25 17:04:42 +0100559}
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100560
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100561bool AudioEngine::HasSampleRateAndChannels() {
562 android::Mutex::Autolock autoLock(callbackLock_);
563 return mChannels != 0 && mSampleRate != 0;
Hugo Hudson9730f152011-07-25 17:04:42 +0100564}
565
566bool AudioEngine::PlayFromThisSource(const SLDataSource& audioSrc) {
567 ClearDecodeBuffer();
568
Hugo Hudson9730f152011-07-25 17:04:42 +0100569 SLObjectItf engine;
570 SLEngineItf engineInterface;
571 CreateAndRealizeEngine(engine, engineInterface);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100572
573 // Define the source and sink for the decoding player: comes from the source
574 // this method was called with, is sent to another buffer queue.
575 SLDataLocator_AndroidSimpleBufferQueue decBuffQueue;
576 decBuffQueue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
577 decBuffQueue.numBuffers = kNumberOfBuffersInQueue;
578 // A valid value seems required here but is currently ignored.
Hugo Hudson9730f152011-07-25 17:04:42 +0100579 SLDataFormat_PCM pcm = {SL_DATAFORMAT_PCM, 1, SL_SAMPLINGRATE_44_1,
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100580 SL_PCMSAMPLEFORMAT_FIXED_16, 16,
581 SL_SPEAKER_FRONT_LEFT, SL_BYTEORDER_LITTLEENDIAN};
582 SLDataSink decDest = { &decBuffQueue, &pcm };
583
584 // Create the decoder with the given source and sink.
585 const size_t decoderInterfaceCount = 4;
586 SLObjectItf decoder;
587 const SLInterfaceID decodePlayerInterfaces[decoderInterfaceCount] = {
588 SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_PREFETCHSTATUS, SL_IID_SEEK,
589 SL_IID_METADATAEXTRACTION };
590 const SLboolean decodePlayerRequired[decoderInterfaceCount] = {
591 SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };
592 SLDataSource sourceCopy(audioSrc);
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100593 OpenSL(engineInterface, CreateAudioPlayer, &decoder, &sourceCopy, &decDest,
594 decoderInterfaceCount, decodePlayerInterfaces, decodePlayerRequired);
595 OpenSL(decoder, Realize, SL_BOOLEAN_FALSE);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100596
597 // Get the play interface from the decoder, and register event callbacks.
598 // Get the buffer queue, prefetch and seek interfaces.
Hugo Hudson9730f152011-07-25 17:04:42 +0100599 SLPlayItf decoderPlay = NULL;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100600 SLAndroidSimpleBufferQueueItf decoderQueue = NULL;
601 SLPrefetchStatusItf decoderPrefetch = NULL;
602 SLSeekItf decoderSeek = NULL;
603 SLMetadataExtractionItf decoderMetadata = NULL;
604 OpenSL(decoder, GetInterface, SL_IID_PLAY, &decoderPlay);
605 OpenSL(decoderPlay, SetCallbackEventsMask, SL_PLAYEVENT_HEADATEND);
606 OpenSL(decoderPlay, RegisterCallback, DecodingEventCb, NULL);
607 OpenSL(decoder, GetInterface, SL_IID_PREFETCHSTATUS, &decoderPrefetch);
608 OpenSL(decoder, GetInterface, SL_IID_SEEK, &decoderSeek);
609 OpenSL(decoder, GetInterface, SL_IID_METADATAEXTRACTION, &decoderMetadata);
610 OpenSL(decoder, GetInterface, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
611 &decoderQueue);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100612
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100613 // Initialize the callback structure, used during the decoding.
Hugo Hudson9730f152011-07-25 17:04:42 +0100614 CallbackContext callbackContext;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100615 {
616 android::Mutex::Autolock autoLock(callbackLock_);
617 callbackContext.pDataBase = pcmData;
618 callbackContext.pData = pcmData;
619 callbackContext.decoderMetadata = decoderMetadata;
620 callbackContext.playItf = decoderPlay;
621 RegisterCallbackContextAndAddEnqueueBuffersToDecoder(
622 decoderQueue, &callbackContext);
623 }
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100624
625 // Initialize the callback for prefetch errors, if we can't open the
626 // resource to decode.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100627 OpenSL(decoderPrefetch, SetCallbackEventsMask, kPrefetchErrorCandidate);
628 OpenSL(decoderPrefetch, RegisterCallback, PrefetchEventCb, &decoderPrefetch);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100629
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100630 // Seek to the start position.
631 OpenSL(decoderSeek, SetPosition, startPositionMillis_, SL_SEEKMODE_ACCURATE);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100632
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100633 // Start decoding immediately.
634 OpenSL(decoderPlay, SetPlayState, SL_PLAYSTATE_PLAYING);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100635
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100636 // These variables hold the audio player and its output.
637 // They will only be constructed once the decoder has invoked the callback,
638 // and given us the correct sample rate, number of channels and duration.
Hugo Hudson9730f152011-07-25 17:04:42 +0100639 SLObjectItf outputMix = NULL;
640 SLObjectItf audioPlayer = NULL;
641 SLPlayItf audioPlayerPlay = NULL;
642 SLAndroidSimpleBufferQueueItf audioPlayerQueue = NULL;
643
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100644 // The main loop - until we're told to stop: if there is audio data coming
645 // out of the decoder, feed it through the time scaler.
646 // As it comes out of the time scaler, feed it into the audio player.
647 while (!Finished()) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100648 if (GetWasStartRequested() && HasSampleRateAndChannels()) {
649 // Build the audio player.
650 // TODO: What happens if I maliciously call start lots of times?
651 floatBuffer_ = new float[targetFrames_ * mChannels];
652 injectBuffer_ = new float[targetFrames_ * mChannels];
653 OpenSL(engineInterface, CreateOutputMix, &outputMix, 0, NULL, NULL);
654 OpenSL(outputMix, Realize, SL_BOOLEAN_FALSE);
655 CreateAndRealizeAudioPlayer(GetSLSampleRate(), GetChannelCount(),
656 GetSLChannels(), outputMix, audioPlayer, engineInterface);
657 OpenSL(audioPlayer, GetInterface, SL_IID_PLAY, &audioPlayerPlay);
658 OpenSL(audioPlayer, GetInterface, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
659 &audioPlayerQueue);
660 OpenSL(audioPlayerQueue, RegisterCallback, PlayingBufferQueueCb, NULL);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100661 ClearRequestStart();
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100662 OpenSL(audioPlayerPlay, SetPlayState, SL_PLAYSTATE_PLAYING);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100663 }
664 EnqueueMoreAudioIfNecessary(audioPlayerQueue);
665 usleep(kSleepTimeMicros);
666 }
667
Hugo Hudson9730f152011-07-25 17:04:42 +0100668 // Delete the audio player and output mix, iff they have been created.
669 if (audioPlayer != NULL) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100670 OpenSL(audioPlayerPlay, SetPlayState, SL_PLAYSTATE_STOPPED);
671 OpenSL0(audioPlayerQueue, Clear);
672 OpenSL(audioPlayerQueue, RegisterCallback, NULL, NULL);
673 VoidOpenSL(audioPlayer, AbortAsyncOperation);
674 VoidOpenSL(audioPlayer, Destroy);
675 VoidOpenSL(outputMix, Destroy);
Hugo Hudson9730f152011-07-25 17:04:42 +0100676 audioPlayer = NULL;
677 audioPlayerPlay = NULL;
678 audioPlayerQueue = NULL;
679 outputMix = NULL;
680 }
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100681
682 // Delete the decoder.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100683 OpenSL(decoderPlay, SetPlayState, SL_PLAYSTATE_STOPPED);
684 OpenSL(decoderPrefetch, RegisterCallback, NULL, NULL);
Hugo Hudson9730f152011-07-25 17:04:42 +0100685 // This is returning slresult 13 if I do no playback.
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100686 // Repro is to comment out all before this line, and all after enqueueing
687 // my buffers.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100688 // OpenSL0(decoderQueue, Clear);
689 OpenSL(decoderQueue, RegisterCallback, NULL, NULL);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100690 decoderSeek = NULL;
691 decoderPrefetch = NULL;
692 decoderQueue = NULL;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100693 OpenSL(decoderPlay, RegisterCallback, NULL, NULL);
694 VoidOpenSL(decoder, AbortAsyncOperation);
695 VoidOpenSL(decoder, Destroy);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100696 decoderPlay = NULL;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100697
Hugo Hudson9730f152011-07-25 17:04:42 +0100698 // Delete the engine.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100699 VoidOpenSL(engine, Destroy);
Hugo Hudson9730f152011-07-25 17:04:42 +0100700 engineInterface = NULL;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100701
702 return true;
703}
704
705bool AudioEngine::Finished() {
706 if (GetWasStopRequested()) {
707 return true;
708 }
709 android::Mutex::Autolock autoLock(playBufferLock_);
710 return playingBuffers_.size() <= 0 &&
711 IsDecodeBufferEmpty() &&
712 GetEndOfDecoderReached();
713}
714
715bool AudioEngine::GetWasStopRequested() {
716 android::Mutex::Autolock autoLock(lock_);
717 return stopRequested_;
718}
719
720bool AudioEngine::GetHasReachedPlayingBuffersLimit() {
721 android::Mutex::Autolock autoLock(playBufferLock_);
722 return playingBuffers_.size() >= maxPlayBufferCount_;
723}
724
725void AudioEngine::EnqueueMoreAudioIfNecessary(
726 SLAndroidSimpleBufferQueueItf audioPlayerQueue) {
727 bool keepEnqueueing = true;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100728 while (audioPlayerQueue != NULL &&
729 !GetWasStopRequested() &&
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100730 !IsDecodeBufferEmpty() &&
731 !GetHasReachedPlayingBuffersLimit() &&
732 keepEnqueueing) {
733 keepEnqueueing = EnqueueNextBufferOfAudio(audioPlayerQueue);
734 }
735}
736
737bool AudioEngine::DecodeBufferTooFull() {
738 android::Mutex::Autolock autoLock(decodeBufferLock_);
739 return decodeBuffer_.IsTooLarge();
740}
741
742// ****************************************************************************
743// Code for handling the static callbacks.
744
745void AudioEngine::PlayingBufferQueueCallback() {
746 // The head playing buffer is done, move it to the free list.
747 android::Mutex::Autolock autoLock(playBufferLock_);
748 if (playingBuffers_.size() > 0) {
749 freeBuffers_.push(playingBuffers_.front());
750 playingBuffers_.pop();
751 }
752}
753
754void AudioEngine::PrefetchEventCallback(
755 SLPrefetchStatusItf caller, SLuint32 event) {
756 // If there was a problem during decoding, then signal the end.
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100757 SLpermille level = 0;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100758 SLuint32 status;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100759 OpenSL(caller, GetFillLevel, &level);
760 OpenSL(caller, GetPrefetchStatus, &status);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100761 if ((kPrefetchErrorCandidate == (event & kPrefetchErrorCandidate)) &&
762 (level == 0) &&
763 (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100764 LOGI("prefetcheventcallback error while prefetching data");
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100765 SetEndOfDecoderReached();
766 }
767 if (SL_PREFETCHSTATUS_SUFFICIENTDATA == event) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100768 // android::Mutex::Autolock autoLock(prefetchLock_);
769 // prefetchCondition_.broadcast();
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100770 }
771}
772
773void AudioEngine::DecodingBufferQueueCallback(
774 SLAndroidSimpleBufferQueueItf queueItf, void *context) {
775 if (GetWasStopRequested()) {
776 return;
777 }
778
779 CallbackContext *pCntxt;
780 {
781 android::Mutex::Autolock autoLock(callbackLock_);
782 pCntxt = reinterpret_cast<CallbackContext*>(context);
783 }
784 {
785 android::Mutex::Autolock autoLock(decodeBufferLock_);
786 decodeBuffer_.AddData(pCntxt->pDataBase, kBufferSizeInBytes);
787 }
788
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100789 if (!HasSampleRateAndChannels()) {
790 android::Mutex::Autolock autoLock(callbackLock_);
791 ReadSampleRateAndChannelCount(pCntxt, &mSampleRate, &mChannels);
792 }
793
794 {
795 android::Mutex::Autolock autoLock(lock_);
796 if (totalDurationMs_ == 0) {
797 totalDurationMs_ = ReadDuration(pCntxt->playItf);
798 }
799 // TODO: This isn't working, it always reports zero.
800 // ReadPosition(pCntxt->playItf);
801 }
Hugo Hudson9730f152011-07-25 17:04:42 +0100802
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100803 // Increase data pointer by buffer size
804 pCntxt->pData += kBufferSizeInBytes;
805 if (pCntxt->pData >= pCntxt->pDataBase +
806 (kNumberOfBuffersInQueue * kBufferSizeInBytes)) {
807 pCntxt->pData = pCntxt->pDataBase;
808 }
809
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100810 OpenSL(queueItf, Enqueue, pCntxt->pDataBase, kBufferSizeInBytes);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100811
812 // If we get too much data into the decoder,
813 // sleep until the playback catches up.
814 while (!GetWasStopRequested() && DecodeBufferTooFull()) {
815 usleep(kSleepTimeMicros);
816 }
817}
818
819void AudioEngine::DecodingEventCallback(SLPlayItf, SLuint32 event) {
820 if (SL_PLAYEVENT_HEADATEND & event) {
821 SetEndOfDecoderReached();
822 }
823}