blob: 12684f17ada22ad1dc3c4e295c3b1021a4963058 [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: Add test, prove that this doesn't crash if called before playing.
300 // TODO: Mutex for shared time scaler accesses.
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100301 GetTimeScaler()->set_speed(speed);
302}
303
304void AudioEngine::RequestStart() {
305 android::Mutex::Autolock autoLock(lock_);
306 startRequested_ = true;
307}
308
309void AudioEngine::ClearRequestStart() {
310 android::Mutex::Autolock autoLock(lock_);
311 startRequested_ = false;
312}
313
314bool AudioEngine::GetWasStartRequested() {
315 android::Mutex::Autolock autoLock(lock_);
316 return startRequested_;
317}
318
319void AudioEngine::RequestStop() {
320 android::Mutex::Autolock autoLock(lock_);
321 stopRequested_ = true;
322}
323
324int AudioEngine::GetCurrentPosition() {
325 android::Mutex::Autolock autoLock(decodeBufferLock_);
326 double result = decodeBuffer_.GetTotalAdvancedCount();
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100327 // TODO: This is horrible, but should be removed soon once the outstanding
328 // issue with get current position on decoder is fixed.
329 android::Mutex::Autolock autoLock2(callbackLock_);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100330 return static_cast<int>(
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100331 (result * 1000) / mSampleRate / mChannels + startPositionMillis_);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100332}
333
334int AudioEngine::GetTotalDuration() {
335 android::Mutex::Autolock autoLock(lock_);
336 return static_cast<int>(totalDurationMs_);
337}
338
339video_editing::SolaTimeScaler* AudioEngine::GetTimeScaler() {
340 if (timeScaler_ == NULL) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100341 CHECK(HasSampleRateAndChannels());
342 android::Mutex::Autolock autoLock(callbackLock_);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100343 timeScaler_ = new video_editing::SolaTimeScaler();
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100344 timeScaler_->Init(mSampleRate, mChannels, initialRate_, windowDuration_,
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100345 windowOverlapDuration_);
346 }
347 return timeScaler_;
348}
349
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100350bool AudioEngine::EnqueueNextBufferOfAudio(
351 SLAndroidSimpleBufferQueueItf audioPlayerQueue) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100352 size_t channels;
353 {
354 android::Mutex::Autolock autoLock(callbackLock_);
355 channels = mChannels;
356 }
357 size_t frameSizeInBytes = kSampleSizeInBytes * channels;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100358 size_t frameCount = 0;
359 while (frameCount < targetFrames_) {
360 size_t framesLeft = targetFrames_ - frameCount;
361 // If there is data already in the time scaler, retrieve it.
362 if (GetTimeScaler()->available() > 0) {
363 size_t retrieveCount = min(GetTimeScaler()->available(), framesLeft);
364 int count = GetTimeScaler()->RetrieveSamples(
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100365 floatBuffer_ + frameCount * channels, retrieveCount);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100366 if (count <= 0) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100367 LOGD("error: count was %d", count);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100368 break;
369 }
370 frameCount += count;
371 continue;
372 }
373 // If there is no data in the time scaler, then feed some into it.
374 android::Mutex::Autolock autoLock(decodeBufferLock_);
375 size_t framesInDecodeBuffer =
376 decodeBuffer_.GetSizeInBytes() / frameSizeInBytes;
377 size_t framesScalerCanHandle = GetTimeScaler()->input_limit();
378 size_t framesToInject = min(framesInDecodeBuffer,
379 min(targetFrames_, framesScalerCanHandle));
380 if (framesToInject <= 0) {
381 // No more frames left to inject.
382 break;
383 }
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100384 for (size_t i = 0; i < framesToInject * channels; ++i) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100385 injectBuffer_[i] = decodeBuffer_.GetAtIndex(i);
386 }
387 int count = GetTimeScaler()->InjectSamples(injectBuffer_, framesToInject);
388 if (count <= 0) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100389 LOGD("error: count was %d", count);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100390 break;
391 }
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100392 decodeBuffer_.AdvanceHeadPointerShorts(count * channels);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100393 }
394 if (frameCount <= 0) {
395 // We must have finished playback.
396 if (GetEndOfDecoderReached()) {
397 // If we've finished decoding, clear the buffer - so we will terminate.
398 ClearDecodeBuffer();
399 }
400 return false;
401 }
402
403 // Get a free playing buffer.
404 int16* playBuffer;
405 {
406 android::Mutex::Autolock autoLock(playBufferLock_);
407 if (freeBuffers_.size() > 0) {
408 // If we have a free buffer, recycle it.
409 playBuffer = freeBuffers_.top();
410 freeBuffers_.pop();
411 } else {
412 // Otherwise allocate a new one.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100413 playBuffer = new int16[targetFrames_ * channels];
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100414 }
415 }
416
417 // Try to play the buffer.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100418 for (size_t i = 0; i < frameCount * channels; ++i) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100419 playBuffer[i] = floatBuffer_[i];
420 }
421 size_t sizeOfPlayBufferInBytes =
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100422 frameCount * channels * kNumberOfBytesPerInt16;
423 SLresult result = ReturnOpenSL(audioPlayerQueue, Enqueue, playBuffer,
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100424 sizeOfPlayBufferInBytes);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100425 if (result == SL_RESULT_SUCCESS) {
426 android::Mutex::Autolock autoLock(playBufferLock_);
427 playingBuffers_.push(playBuffer);
428 } else {
429 LOGE("could not enqueue audio buffer");
430 delete[] playBuffer;
431 }
432
433 return (result == SL_RESULT_SUCCESS);
434}
435
436bool AudioEngine::GetEndOfDecoderReached() {
437 android::Mutex::Autolock autoLock(lock_);
438 return finishedDecoding_;
439}
440
441void AudioEngine::SetEndOfDecoderReached() {
442 android::Mutex::Autolock autoLock(lock_);
443 finishedDecoding_ = true;
444}
445
446bool AudioEngine::PlayFileDescriptor(int fd, int64 offset, int64 length) {
447 SLDataLocator_AndroidFD loc_fd = {
448 SL_DATALOCATOR_ANDROIDFD, fd, offset, length };
449 SLDataFormat_MIME format_mime = {
450 SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED };
451 SLDataSource audioSrc = { &loc_fd, &format_mime };
452 return PlayFromThisSource(audioSrc);
453}
454
455bool AudioEngine::PlayUri(const char* uri) {
456 // Source of audio data for the decoding
457 SLDataLocator_URI decUri = { SL_DATALOCATOR_URI,
458 const_cast<SLchar*>(reinterpret_cast<const SLchar*>(uri)) };
459 SLDataFormat_MIME decMime = {
460 SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED };
461 SLDataSource decSource = { &decUri, &decMime };
462 return PlayFromThisSource(decSource);
463}
464
465bool AudioEngine::IsDecodeBufferEmpty() {
466 android::Mutex::Autolock autoLock(decodeBufferLock_);
467 return decodeBuffer_.GetSizeInBytes() <= 0;
468}
469
470void AudioEngine::ClearDecodeBuffer() {
471 android::Mutex::Autolock autoLock(decodeBufferLock_);
472 decodeBuffer_.Clear();
473}
474
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100475static size_t ReadDuration(SLPlayItf playItf) {
476 SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
477 OpenSL(playItf, GetDuration, &durationInMsec);
478 if (durationInMsec == SL_TIME_UNKNOWN) {
479 LOGE("can't get duration");
480 return 0;
481 }
482 LOGD("duration: %d", static_cast<int>(durationInMsec));
483 return durationInMsec;
484}
485
486static size_t ReadPosition(SLPlayItf playItf) {
487 SLmillisecond positionInMsec = SL_TIME_UNKNOWN;
488 OpenSL(playItf, GetPosition, &positionInMsec);
489 if (positionInMsec == SL_TIME_UNKNOWN) {
490 LOGE("can't get position");
491 return 0;
492 }
493 LOGW("decoder position: %d", static_cast<int>(positionInMsec));
494 return positionInMsec;
495}
496
Hugo Hudson9730f152011-07-25 17:04:42 +0100497static void CreateAndRealizeEngine(SLObjectItf &engine,
498 SLEngineItf &engineInterface) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100499 SLEngineOption EngineOption[] = { {
500 SL_ENGINEOPTION_THREADSAFE, SL_BOOLEAN_TRUE } };
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100501 SLresult result = slCreateEngine(&engine, 1, EngineOption, 0, NULL, NULL);
502 CheckSLResult("create engine", result);
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100503 OpenSL(engine, Realize, SL_BOOLEAN_FALSE);
504 OpenSL(engine, GetInterface, SL_IID_ENGINE, &engineInterface);
Hugo Hudson9730f152011-07-25 17:04:42 +0100505}
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100506
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100507SLuint32 AudioEngine::GetSLSampleRate() {
508 android::Mutex::Autolock autoLock(callbackLock_);
509 return mSampleRate * 1000;
Hugo Hudson9730f152011-07-25 17:04:42 +0100510}
511
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100512SLuint32 AudioEngine::GetSLChannels() {
513 android::Mutex::Autolock autoLock(callbackLock_);
514 switch (mChannels) {
Hugo Hudson9730f152011-07-25 17:04:42 +0100515 case 2:
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100516 return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
Hugo Hudson9730f152011-07-25 17:04:42 +0100517 case 1:
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100518 return SL_SPEAKER_FRONT_CENTER;
Hugo Hudson9730f152011-07-25 17:04:42 +0100519 default:
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100520 LOGE("unknown channels %d, using 2", mChannels);
521 return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
Hugo Hudson9730f152011-07-25 17:04:42 +0100522 }
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100523}
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100524
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100525SLuint32 AudioEngine::GetChannelCount() {
526 android::Mutex::Autolock autoLock(callbackLock_);
527 return mChannels;
528}
529
530static void CreateAndRealizeAudioPlayer(SLuint32 slSampleRate,
531 size_t channelCount, SLuint32 slChannels, SLObjectItf &outputMix,
532 SLObjectItf &audioPlayer, SLEngineItf &engineInterface) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100533 // Define the source and sink for the audio player: comes from a buffer queue
534 // and goes to the output mix.
535 SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {
536 SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2 };
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100537 SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, channelCount, slSampleRate,
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100538 SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16,
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100539 slChannels, SL_BYTEORDER_LITTLEENDIAN};
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100540 SLDataSource playingSrc = {&loc_bufq, &format_pcm};
541 SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMix};
542 SLDataSink audioSnk = {&loc_outmix, NULL};
543
544 // Create the audio player, which will play from the buffer queue and send to
545 // the output mix.
546 const size_t playerInterfaceCount = 1;
547 const SLInterfaceID iids[playerInterfaceCount] = {
548 SL_IID_ANDROIDSIMPLEBUFFERQUEUE };
549 const SLboolean reqs[playerInterfaceCount] = { SL_BOOLEAN_TRUE };
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100550 OpenSL(engineInterface, CreateAudioPlayer, &audioPlayer, &playingSrc,
551 &audioSnk, playerInterfaceCount, iids, reqs);
552 OpenSL(audioPlayer, Realize, SL_BOOLEAN_FALSE);
Hugo Hudson9730f152011-07-25 17:04:42 +0100553}
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100554
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100555bool AudioEngine::HasSampleRateAndChannels() {
556 android::Mutex::Autolock autoLock(callbackLock_);
557 return mChannels != 0 && mSampleRate != 0;
Hugo Hudson9730f152011-07-25 17:04:42 +0100558}
559
560bool AudioEngine::PlayFromThisSource(const SLDataSource& audioSrc) {
561 ClearDecodeBuffer();
562
Hugo Hudson9730f152011-07-25 17:04:42 +0100563 SLObjectItf engine;
564 SLEngineItf engineInterface;
565 CreateAndRealizeEngine(engine, engineInterface);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100566
567 // Define the source and sink for the decoding player: comes from the source
568 // this method was called with, is sent to another buffer queue.
569 SLDataLocator_AndroidSimpleBufferQueue decBuffQueue;
570 decBuffQueue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
571 decBuffQueue.numBuffers = kNumberOfBuffersInQueue;
572 // A valid value seems required here but is currently ignored.
Hugo Hudson9730f152011-07-25 17:04:42 +0100573 SLDataFormat_PCM pcm = {SL_DATAFORMAT_PCM, 1, SL_SAMPLINGRATE_44_1,
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100574 SL_PCMSAMPLEFORMAT_FIXED_16, 16,
575 SL_SPEAKER_FRONT_LEFT, SL_BYTEORDER_LITTLEENDIAN};
576 SLDataSink decDest = { &decBuffQueue, &pcm };
577
578 // Create the decoder with the given source and sink.
579 const size_t decoderInterfaceCount = 4;
580 SLObjectItf decoder;
581 const SLInterfaceID decodePlayerInterfaces[decoderInterfaceCount] = {
582 SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_PREFETCHSTATUS, SL_IID_SEEK,
583 SL_IID_METADATAEXTRACTION };
584 const SLboolean decodePlayerRequired[decoderInterfaceCount] = {
585 SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };
586 SLDataSource sourceCopy(audioSrc);
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100587 OpenSL(engineInterface, CreateAudioPlayer, &decoder, &sourceCopy, &decDest,
588 decoderInterfaceCount, decodePlayerInterfaces, decodePlayerRequired);
589 OpenSL(decoder, Realize, SL_BOOLEAN_FALSE);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100590
591 // Get the play interface from the decoder, and register event callbacks.
592 // Get the buffer queue, prefetch and seek interfaces.
Hugo Hudson9730f152011-07-25 17:04:42 +0100593 SLPlayItf decoderPlay = NULL;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100594 SLAndroidSimpleBufferQueueItf decoderQueue = NULL;
595 SLPrefetchStatusItf decoderPrefetch = NULL;
596 SLSeekItf decoderSeek = NULL;
597 SLMetadataExtractionItf decoderMetadata = NULL;
598 OpenSL(decoder, GetInterface, SL_IID_PLAY, &decoderPlay);
599 OpenSL(decoderPlay, SetCallbackEventsMask, SL_PLAYEVENT_HEADATEND);
600 OpenSL(decoderPlay, RegisterCallback, DecodingEventCb, NULL);
601 OpenSL(decoder, GetInterface, SL_IID_PREFETCHSTATUS, &decoderPrefetch);
602 OpenSL(decoder, GetInterface, SL_IID_SEEK, &decoderSeek);
603 OpenSL(decoder, GetInterface, SL_IID_METADATAEXTRACTION, &decoderMetadata);
604 OpenSL(decoder, GetInterface, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
605 &decoderQueue);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100606
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100607 // Initialize the callback structure, used during the decoding.
Hugo Hudson9730f152011-07-25 17:04:42 +0100608 CallbackContext callbackContext;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100609 {
610 android::Mutex::Autolock autoLock(callbackLock_);
611 callbackContext.pDataBase = pcmData;
612 callbackContext.pData = pcmData;
613 callbackContext.decoderMetadata = decoderMetadata;
614 callbackContext.playItf = decoderPlay;
615 RegisterCallbackContextAndAddEnqueueBuffersToDecoder(
616 decoderQueue, &callbackContext);
617 }
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100618
619 // Initialize the callback for prefetch errors, if we can't open the
620 // resource to decode.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100621 OpenSL(decoderPrefetch, SetCallbackEventsMask, kPrefetchErrorCandidate);
622 OpenSL(decoderPrefetch, RegisterCallback, PrefetchEventCb, &decoderPrefetch);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100623
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100624 // Seek to the start position.
625 OpenSL(decoderSeek, SetPosition, startPositionMillis_, SL_SEEKMODE_ACCURATE);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100626
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100627 // Start decoding immediately.
628 OpenSL(decoderPlay, SetPlayState, SL_PLAYSTATE_PLAYING);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100629
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100630 // These variables hold the audio player and its output.
631 // They will only be constructed once the decoder has invoked the callback,
632 // and given us the correct sample rate, number of channels and duration.
Hugo Hudson9730f152011-07-25 17:04:42 +0100633 SLObjectItf outputMix = NULL;
634 SLObjectItf audioPlayer = NULL;
635 SLPlayItf audioPlayerPlay = NULL;
636 SLAndroidSimpleBufferQueueItf audioPlayerQueue = NULL;
637
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100638 // The main loop - until we're told to stop: if there is audio data coming
639 // out of the decoder, feed it through the time scaler.
640 // As it comes out of the time scaler, feed it into the audio player.
641 while (!Finished()) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100642 if (GetWasStartRequested() && HasSampleRateAndChannels()) {
643 // Build the audio player.
644 // TODO: What happens if I maliciously call start lots of times?
645 floatBuffer_ = new float[targetFrames_ * mChannels];
646 injectBuffer_ = new float[targetFrames_ * mChannels];
647 OpenSL(engineInterface, CreateOutputMix, &outputMix, 0, NULL, NULL);
648 OpenSL(outputMix, Realize, SL_BOOLEAN_FALSE);
649 CreateAndRealizeAudioPlayer(GetSLSampleRate(), GetChannelCount(),
650 GetSLChannels(), outputMix, audioPlayer, engineInterface);
651 OpenSL(audioPlayer, GetInterface, SL_IID_PLAY, &audioPlayerPlay);
652 OpenSL(audioPlayer, GetInterface, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
653 &audioPlayerQueue);
654 OpenSL(audioPlayerQueue, RegisterCallback, PlayingBufferQueueCb, NULL);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100655 ClearRequestStart();
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100656 OpenSL(audioPlayerPlay, SetPlayState, SL_PLAYSTATE_PLAYING);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100657 }
658 EnqueueMoreAudioIfNecessary(audioPlayerQueue);
659 usleep(kSleepTimeMicros);
660 }
661
Hugo Hudson9730f152011-07-25 17:04:42 +0100662 // Delete the audio player and output mix, iff they have been created.
663 if (audioPlayer != NULL) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100664 OpenSL(audioPlayerPlay, SetPlayState, SL_PLAYSTATE_STOPPED);
665 OpenSL0(audioPlayerQueue, Clear);
666 OpenSL(audioPlayerQueue, RegisterCallback, NULL, NULL);
667 VoidOpenSL(audioPlayer, AbortAsyncOperation);
668 VoidOpenSL(audioPlayer, Destroy);
669 VoidOpenSL(outputMix, Destroy);
Hugo Hudson9730f152011-07-25 17:04:42 +0100670 audioPlayer = NULL;
671 audioPlayerPlay = NULL;
672 audioPlayerQueue = NULL;
673 outputMix = NULL;
674 }
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100675
676 // Delete the decoder.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100677 OpenSL(decoderPlay, SetPlayState, SL_PLAYSTATE_STOPPED);
678 OpenSL(decoderPrefetch, RegisterCallback, NULL, NULL);
Hugo Hudson9730f152011-07-25 17:04:42 +0100679 // This is returning slresult 13 if I do no playback.
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100680 // Repro is to comment out all before this line, and all after enqueueing
681 // my buffers.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100682 // OpenSL0(decoderQueue, Clear);
683 OpenSL(decoderQueue, RegisterCallback, NULL, NULL);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100684 decoderSeek = NULL;
685 decoderPrefetch = NULL;
686 decoderQueue = NULL;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100687 OpenSL(decoderPlay, RegisterCallback, NULL, NULL);
688 VoidOpenSL(decoder, AbortAsyncOperation);
689 VoidOpenSL(decoder, Destroy);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100690 decoderPlay = NULL;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100691
Hugo Hudson9730f152011-07-25 17:04:42 +0100692 // Delete the engine.
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100693 VoidOpenSL(engine, Destroy);
Hugo Hudson9730f152011-07-25 17:04:42 +0100694 engineInterface = NULL;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100695
696 return true;
697}
698
699bool AudioEngine::Finished() {
700 if (GetWasStopRequested()) {
701 return true;
702 }
703 android::Mutex::Autolock autoLock(playBufferLock_);
704 return playingBuffers_.size() <= 0 &&
705 IsDecodeBufferEmpty() &&
706 GetEndOfDecoderReached();
707}
708
709bool AudioEngine::GetWasStopRequested() {
710 android::Mutex::Autolock autoLock(lock_);
711 return stopRequested_;
712}
713
714bool AudioEngine::GetHasReachedPlayingBuffersLimit() {
715 android::Mutex::Autolock autoLock(playBufferLock_);
716 return playingBuffers_.size() >= maxPlayBufferCount_;
717}
718
719void AudioEngine::EnqueueMoreAudioIfNecessary(
720 SLAndroidSimpleBufferQueueItf audioPlayerQueue) {
721 bool keepEnqueueing = true;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100722 while (audioPlayerQueue != NULL &&
723 !GetWasStopRequested() &&
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100724 !IsDecodeBufferEmpty() &&
725 !GetHasReachedPlayingBuffersLimit() &&
726 keepEnqueueing) {
727 keepEnqueueing = EnqueueNextBufferOfAudio(audioPlayerQueue);
728 }
729}
730
731bool AudioEngine::DecodeBufferTooFull() {
732 android::Mutex::Autolock autoLock(decodeBufferLock_);
733 return decodeBuffer_.IsTooLarge();
734}
735
736// ****************************************************************************
737// Code for handling the static callbacks.
738
739void AudioEngine::PlayingBufferQueueCallback() {
740 // The head playing buffer is done, move it to the free list.
741 android::Mutex::Autolock autoLock(playBufferLock_);
742 if (playingBuffers_.size() > 0) {
743 freeBuffers_.push(playingBuffers_.front());
744 playingBuffers_.pop();
745 }
746}
747
748void AudioEngine::PrefetchEventCallback(
749 SLPrefetchStatusItf caller, SLuint32 event) {
750 // If there was a problem during decoding, then signal the end.
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100751 SLpermille level = 0;
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100752 SLuint32 status;
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100753 OpenSL(caller, GetFillLevel, &level);
754 OpenSL(caller, GetPrefetchStatus, &status);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100755 if ((kPrefetchErrorCandidate == (event & kPrefetchErrorCandidate)) &&
756 (level == 0) &&
757 (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100758 LOGI("prefetcheventcallback error while prefetching data");
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100759 SetEndOfDecoderReached();
760 }
761 if (SL_PREFETCHSTATUS_SUFFICIENTDATA == event) {
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100762 // android::Mutex::Autolock autoLock(prefetchLock_);
763 // prefetchCondition_.broadcast();
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100764 }
765}
766
767void AudioEngine::DecodingBufferQueueCallback(
768 SLAndroidSimpleBufferQueueItf queueItf, void *context) {
769 if (GetWasStopRequested()) {
770 return;
771 }
772
773 CallbackContext *pCntxt;
774 {
775 android::Mutex::Autolock autoLock(callbackLock_);
776 pCntxt = reinterpret_cast<CallbackContext*>(context);
777 }
778 {
779 android::Mutex::Autolock autoLock(decodeBufferLock_);
780 decodeBuffer_.AddData(pCntxt->pDataBase, kBufferSizeInBytes);
781 }
782
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100783 if (!HasSampleRateAndChannels()) {
784 android::Mutex::Autolock autoLock(callbackLock_);
785 ReadSampleRateAndChannelCount(pCntxt, &mSampleRate, &mChannels);
786 }
787
788 {
789 android::Mutex::Autolock autoLock(lock_);
790 if (totalDurationMs_ == 0) {
791 totalDurationMs_ = ReadDuration(pCntxt->playItf);
792 }
793 // TODO: This isn't working, it always reports zero.
794 // ReadPosition(pCntxt->playItf);
795 }
Hugo Hudson9730f152011-07-25 17:04:42 +0100796
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100797 // Increase data pointer by buffer size
798 pCntxt->pData += kBufferSizeInBytes;
799 if (pCntxt->pData >= pCntxt->pDataBase +
800 (kNumberOfBuffersInQueue * kBufferSizeInBytes)) {
801 pCntxt->pData = pCntxt->pDataBase;
802 }
803
Hugo Hudson0bd6ec52011-07-26 20:05:25 +0100804 OpenSL(queueItf, Enqueue, pCntxt->pDataBase, kBufferSizeInBytes);
Hugo Hudsonb83ad732011-07-14 23:31:17 +0100805
806 // If we get too much data into the decoder,
807 // sleep until the playback catches up.
808 while (!GetWasStopRequested() && DecodeBufferTooFull()) {
809 usleep(kSleepTimeMicros);
810 }
811}
812
813void AudioEngine::DecodingEventCallback(SLPlayItf, SLuint32 event) {
814 if (SL_PLAYEVENT_HEADATEND & event) {
815 SetEndOfDecoderReached();
816 }
817}