blob: 49eddbe07134d57b50fc982219fa72f5fe4bf211 [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
47// When calculating play buffer size before pushing to audio player.
48const size_t kNumberOfBytesPerInt16 = 2;
49
50// How long to sleep during the main play loop and the decoding callback loop.
51// In due course this should be replaced with the better signal and wait on
52// condition rather than busy-looping.
53const int kSleepTimeMicros = 1000;
54
55// Used in detecting errors with the OpenSL ES framework.
56const SLuint32 kPrefetchErrorCandidate =
57 SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE;
58
59// Structure used when we perform a decoding callback.
60typedef struct CallbackContext_ {
61 SLPlayItf decoderPlay;
62 // Pointer to local storage buffers for decoded audio data.
63 int8_t* pDataBase;
64 // Pointer to the current buffer within local storage.
65 int8_t* pData;
66} CallbackContext;
67
68// Local storage for decoded audio data.
69int8_t pcmData[kNumberOfBuffersInQueue * kBufferSizeInBytes];
70
71#define CheckSLResult(message, result) \
72 CheckSLResult_Real(message, result, __LINE__)
73
74// Helper function for debugging - checks the OpenSL result for success.
75void CheckSLResult_Real(const char* message, SLresult result, int line) {
76 // This can be helpful when debugging.
77 // LOGD("sl result %d for %s", result, message);
78 if (SL_RESULT_SUCCESS != result) {
79 LOGE("slresult was %d at %s file variablespeed line %d",
80 static_cast<int>(result), message, line);
81 }
82 CHECK(SL_RESULT_SUCCESS == result);
83}
84
85} // namespace
86
87// ****************************************************************************
88// Static instance of audio engine, and methods for getting, setting and
89// deleting it.
90
91// The single global audio engine instance.
92AudioEngine* AudioEngine::audioEngine_ = NULL;
93android::Mutex publishEngineLock_;
94
95AudioEngine* AudioEngine::GetEngine() {
96 android::Mutex::Autolock autoLock(publishEngineLock_);
97 if (audioEngine_ == NULL) {
98 LOGE("you haven't initialized the audio engine");
99 CHECK(false);
100 return NULL;
101 }
102 return audioEngine_;
103}
104
105void AudioEngine::SetEngine(AudioEngine* engine) {
106 if (audioEngine_ != NULL) {
107 LOGE("you have already set the audio engine");
108 CHECK(false);
109 return;
110 }
111 audioEngine_ = engine;
112}
113
114void AudioEngine::DeleteEngine() {
115 if (audioEngine_ == NULL) {
116 LOGE("you haven't initialized the audio engine");
117 CHECK(false);
118 return;
119 }
120 delete audioEngine_;
121 audioEngine_ = NULL;
122}
123
124// ****************************************************************************
125// The callbacks from the engine require static callback functions.
126// Here are the static functions - they just delegate to instance methods on
127// the engine.
128
129static void PlayingBufferQueueCb(SLAndroidSimpleBufferQueueItf, void*) {
130 AudioEngine::GetEngine()->PlayingBufferQueueCallback();
131}
132
133static void PrefetchEventCb(SLPrefetchStatusItf caller, void*, SLuint32 event) {
134 AudioEngine::GetEngine()->PrefetchEventCallback(caller, event);
135}
136
137static void DecodingBufferQueueCb(SLAndroidSimpleBufferQueueItf queueItf,
138 void *context) {
139 AudioEngine::GetEngine()->DecodingBufferQueueCallback(queueItf, context);
140}
141
142static void DecodingEventCb(SLPlayItf caller, void*, SLuint32 event) {
143 AudioEngine::GetEngine()->DecodingEventCallback(caller, event);
144}
145
146// ****************************************************************************
147// Static utility methods.
148
149static void PausePlaying(SLPlayItf playItf) {
150 SLresult result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PAUSED);
151 CheckSLResult("pause playing", result);
152}
153
154static void StartPlaying(SLPlayItf playItf) {
155 SLresult result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING);
156 CheckSLResult("start playing", result);
157}
158
159static void StopPlaying(SLPlayItf playItf) {
160 SLresult result = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
161 CheckSLResult("stop playing", result);
162}
163
164static void ExtractMetadataFromDecoder(SLObjectItf decoder) {
165 SLMetadataExtractionItf decoderMetadata;
166 SLresult result = (*decoder)->GetInterface(decoder,
167 SL_IID_METADATAEXTRACTION, &decoderMetadata);
168 CheckSLResult("getting metadata interface", result);
169 SLuint32 itemCount;
170 result = (*decoderMetadata)->GetItemCount(decoderMetadata, &itemCount);
171 CheckSLResult("getting item count", result);
172 SLuint32 i, keySize, valueSize;
173 SLMetadataInfo *keyInfo, *value;
174 for (i = 0; i < itemCount ; ++i) {
175 keyInfo = NULL;
176 keySize = 0;
177 value = NULL;
178 valueSize = 0;
179 result = (*decoderMetadata)->GetKeySize(decoderMetadata, i, &keySize);
180 CheckSLResult("get key size", result);
181 keyInfo = static_cast<SLMetadataInfo*>(malloc(keySize));
182 if (keyInfo) {
183 result = (*decoderMetadata)->GetKey(
184 decoderMetadata, i, keySize, keyInfo);
185 CheckSLResult("get key", result);
186 if (keyInfo->encoding == SL_CHARACTERENCODING_ASCII
187 || keyInfo->encoding == SL_CHARACTERENCODING_UTF8) {
188 result = (*decoderMetadata)->GetValueSize(
189 decoderMetadata, i, &valueSize);
190 CheckSLResult("get value size", result);
191 value = static_cast<SLMetadataInfo*>(malloc(valueSize));
192 if (value) {
193 result = (*decoderMetadata)->GetValue(
194 decoderMetadata, i, valueSize, value);
195 CheckSLResult("get value", result);
196 if (value->encoding == SL_CHARACTERENCODING_BINARY) {
197 LOGD("key[%d] size=%d, name=%s value size=%d value=%d",
198 i, keyInfo->size, keyInfo->data, value->size,
199 *(reinterpret_cast<SLuint32*>(value->data)));
200 }
201 free(value);
202 }
203 }
204 free(keyInfo);
205 }
206 }
207}
208
209static void SeekToPosition(SLSeekItf seekItf, size_t startPositionMillis) {
210 SLresult result = (*seekItf)->SetPosition(
211 seekItf, startPositionMillis, SL_SEEKMODE_ACCURATE);
212 CheckSLResult("seek to position", result);
213}
214
215static void RegisterCallbackContextAndAddEnqueueBuffersToDecoder(
216 SLAndroidSimpleBufferQueueItf decoderQueue, SLPlayItf player,
217 android::Mutex &callbackLock) {
218 android::Mutex::Autolock autoLock(callbackLock);
219 // Initialize the callback structure, used during the decoding.
220 // Then register a callback on the decoder queue, so that we will be called
221 // throughout the decoding process (and can then extract the decoded audio
222 // for the next bit of the pipeline).
223 CallbackContext cntxt;
224 cntxt.decoderPlay = player;
225 cntxt.pDataBase = pcmData;
226 cntxt.pData = pcmData;
227 {
228 SLresult result = (*decoderQueue)->RegisterCallback(
229 decoderQueue, DecodingBufferQueueCb, &cntxt);
230 CheckSLResult("decode callback", result);
231 }
232
233 // Enqueue buffers to map the region of memory allocated to store the
234 // decoded data.
235 for (size_t i = 0; i < kNumberOfBuffersInQueue; i++) {
236 SLresult result = (*decoderQueue)->Enqueue(
237 decoderQueue, cntxt.pData, kBufferSizeInBytes);
238 CheckSLResult("enqueue something", result);
239 cntxt.pData += kBufferSizeInBytes;
240 }
241 cntxt.pData = cntxt.pDataBase;
242}
243
244// ****************************************************************************
245// Constructor and Destructor.
246
247AudioEngine::AudioEngine(size_t channels, size_t sampleRate,
248 size_t targetFrames, float windowDuration, float windowOverlapDuration,
249 size_t maxPlayBufferCount, float initialRate, size_t decodeInitialSize,
250 size_t decodeMaxSize, size_t startPositionMillis)
251 : decodeBuffer_(decodeInitialSize, decodeMaxSize),
252 playingBuffers_(), freeBuffers_(), timeScaler_(NULL),
253 floatBuffer_(NULL), injectBuffer_(NULL),
254 channels_(channels), sampleRate_(sampleRate), slSampleRate_(0),
255 slOutputChannels_(0),
256 targetFrames_(targetFrames),
257 windowDuration_(windowDuration),
258 windowOverlapDuration_(windowOverlapDuration),
259 maxPlayBufferCount_(maxPlayBufferCount), initialRate_(initialRate),
260 startPositionMillis_(startPositionMillis),
261 totalDurationMs_(0), startRequested_(false),
262 stopRequested_(false), finishedDecoding_(false) {
263 if (sampleRate_ == 44100) {
264 slSampleRate_ = SL_SAMPLINGRATE_44_1;
265 } else if (sampleRate_ == 8000) {
266 slSampleRate_ = SL_SAMPLINGRATE_8;
267 } else if (sampleRate_ == 11025) {
268 slSampleRate_ = SL_SAMPLINGRATE_11_025;
269 } else {
270 LOGE("unknown sample rate, not changing");
271 CHECK(false);
272 }
273 if (channels_ == 2) {
274 slOutputChannels_ = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
275 } else if (channels_ == 1) {
276 slOutputChannels_ = SL_SPEAKER_FRONT_LEFT;
277 } else {
278 LOGE("unknown channels, not changing");
279 }
280}
281
282AudioEngine::~AudioEngine() {
283 // destroy the time scaler
284 if (timeScaler_ != NULL) {
285 delete timeScaler_;
286 timeScaler_ = NULL;
287 }
288
289 // delete all outstanding playing and free buffers
290 android::Mutex::Autolock autoLock(playBufferLock_);
291 while (playingBuffers_.size() > 0) {
292 delete[] playingBuffers_.front();
293 playingBuffers_.pop();
294 }
295 while (freeBuffers_.size() > 0) {
296 delete[] freeBuffers_.top();
297 freeBuffers_.pop();
298 }
299
300 delete[] floatBuffer_;
301 floatBuffer_ = NULL;
302 delete[] injectBuffer_;
303 injectBuffer_ = NULL;
304}
305
306// ****************************************************************************
307// Regular AudioEngine class methods.
308
309void AudioEngine::SetVariableSpeed(float speed) {
310 GetTimeScaler()->set_speed(speed);
311}
312
313void AudioEngine::RequestStart() {
314 android::Mutex::Autolock autoLock(lock_);
315 startRequested_ = true;
316}
317
318void AudioEngine::ClearRequestStart() {
319 android::Mutex::Autolock autoLock(lock_);
320 startRequested_ = false;
321}
322
323bool AudioEngine::GetWasStartRequested() {
324 android::Mutex::Autolock autoLock(lock_);
325 return startRequested_;
326}
327
328void AudioEngine::RequestStop() {
329 android::Mutex::Autolock autoLock(lock_);
330 stopRequested_ = true;
331}
332
333int AudioEngine::GetCurrentPosition() {
334 android::Mutex::Autolock autoLock(decodeBufferLock_);
335 double result = decodeBuffer_.GetTotalAdvancedCount();
336 return static_cast<int>(
337 (result * 1000) / sampleRate_ / channels_ + startPositionMillis_);
338}
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) {
347 timeScaler_ = new video_editing::SolaTimeScaler();
348 timeScaler_->Init(sampleRate_, channels_, initialRate_, windowDuration_,
349 windowOverlapDuration_);
350 }
351 return timeScaler_;
352}
353
354void AudioEngine::PrefetchDurationSampleRateAndChannels(
355 SLPlayItf playItf, SLPrefetchStatusItf prefetchItf) {
356 // Set play state to pause, to begin the prefetching.
357 PausePlaying(playItf);
358
359 // Wait until the data has been prefetched.
360 // TODO(hugohudson): 0. Not dealing with error just yet.
361 {
362 SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
363 android::Mutex::Autolock autoLock(prefetchLock_);
364 while (prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) {
365 LOGI("waiting for condition");
366 // prefetchCondition_.waitRelative(prefetchLock, 1000 * 1000 * 10);
367 usleep(10 * 1000);
368 LOGI("getting the value");
369 (*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
370 }
371 LOGI("done with wait");
372 }
373
374 SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
375 SLresult result = (*playItf)->GetDuration(playItf, &durationInMsec);
376 CheckSLResult("getting duration", result);
377 CHECK(durationInMsec != SL_TIME_UNKNOWN);
378 LOGD("duration: %d", static_cast<int>(durationInMsec));
379 android::Mutex::Autolock autoLock(lock_);
380 totalDurationMs_ = durationInMsec;
381}
382
383bool AudioEngine::EnqueueNextBufferOfAudio(
384 SLAndroidSimpleBufferQueueItf audioPlayerQueue) {
385 size_t frameSizeInBytes = kSampleSizeInBytes * channels_;
386 size_t frameCount = 0;
387 while (frameCount < targetFrames_) {
388 size_t framesLeft = targetFrames_ - frameCount;
389 // If there is data already in the time scaler, retrieve it.
390 if (GetTimeScaler()->available() > 0) {
391 size_t retrieveCount = min(GetTimeScaler()->available(), framesLeft);
392 int count = GetTimeScaler()->RetrieveSamples(
393 floatBuffer_ + frameCount * channels_, retrieveCount);
394 if (count <= 0) {
395 LOGD("ERROR: Count was %d", count);
396 break;
397 }
398 frameCount += count;
399 continue;
400 }
401 // If there is no data in the time scaler, then feed some into it.
402 android::Mutex::Autolock autoLock(decodeBufferLock_);
403 size_t framesInDecodeBuffer =
404 decodeBuffer_.GetSizeInBytes() / frameSizeInBytes;
405 size_t framesScalerCanHandle = GetTimeScaler()->input_limit();
406 size_t framesToInject = min(framesInDecodeBuffer,
407 min(targetFrames_, framesScalerCanHandle));
408 if (framesToInject <= 0) {
409 // No more frames left to inject.
410 break;
411 }
412 for (size_t i = 0; i < framesToInject * channels_ ; ++i) {
413 injectBuffer_[i] = decodeBuffer_.GetAtIndex(i);
414 }
415 int count = GetTimeScaler()->InjectSamples(injectBuffer_, framesToInject);
416 if (count <= 0) {
417 LOGD("ERROR: Count was %d", count);
418 break;
419 }
420 decodeBuffer_.AdvanceHeadPointerShorts(count * channels_);
421 }
422 if (frameCount <= 0) {
423 // We must have finished playback.
424 if (GetEndOfDecoderReached()) {
425 // If we've finished decoding, clear the buffer - so we will terminate.
426 ClearDecodeBuffer();
427 }
428 return false;
429 }
430
431 // Get a free playing buffer.
432 int16* playBuffer;
433 {
434 android::Mutex::Autolock autoLock(playBufferLock_);
435 if (freeBuffers_.size() > 0) {
436 // If we have a free buffer, recycle it.
437 playBuffer = freeBuffers_.top();
438 freeBuffers_.pop();
439 } else {
440 // Otherwise allocate a new one.
441 playBuffer = new int16[targetFrames_ * channels_];
442 }
443 }
444
445 // Try to play the buffer.
446 for (size_t i = 0; i < frameCount * channels_ ; ++i) {
447 playBuffer[i] = floatBuffer_[i];
448 }
449 size_t sizeOfPlayBufferInBytes =
450 frameCount * channels_ * kNumberOfBytesPerInt16;
451 SLresult result = (*audioPlayerQueue)->Enqueue(audioPlayerQueue, playBuffer,
452 sizeOfPlayBufferInBytes);
453 CheckSLResult("enqueue prebuilt audio", result);
454 if (result == SL_RESULT_SUCCESS) {
455 android::Mutex::Autolock autoLock(playBufferLock_);
456 playingBuffers_.push(playBuffer);
457 } else {
458 LOGE("could not enqueue audio buffer");
459 delete[] playBuffer;
460 }
461
462 return (result == SL_RESULT_SUCCESS);
463}
464
465bool AudioEngine::GetEndOfDecoderReached() {
466 android::Mutex::Autolock autoLock(lock_);
467 return finishedDecoding_;
468}
469
470void AudioEngine::SetEndOfDecoderReached() {
471 android::Mutex::Autolock autoLock(lock_);
472 finishedDecoding_ = true;
473}
474
475bool AudioEngine::PlayFileDescriptor(int fd, int64 offset, int64 length) {
476 SLDataLocator_AndroidFD loc_fd = {
477 SL_DATALOCATOR_ANDROIDFD, fd, offset, length };
478 SLDataFormat_MIME format_mime = {
479 SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED };
480 SLDataSource audioSrc = { &loc_fd, &format_mime };
481 return PlayFromThisSource(audioSrc);
482}
483
484bool AudioEngine::PlayUri(const char* uri) {
485 // Source of audio data for the decoding
486 SLDataLocator_URI decUri = { SL_DATALOCATOR_URI,
487 const_cast<SLchar*>(reinterpret_cast<const SLchar*>(uri)) };
488 SLDataFormat_MIME decMime = {
489 SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED };
490 SLDataSource decSource = { &decUri, &decMime };
491 return PlayFromThisSource(decSource);
492}
493
494bool AudioEngine::IsDecodeBufferEmpty() {
495 android::Mutex::Autolock autoLock(decodeBufferLock_);
496 return decodeBuffer_.GetSizeInBytes() <= 0;
497}
498
499void AudioEngine::ClearDecodeBuffer() {
500 android::Mutex::Autolock autoLock(decodeBufferLock_);
501 decodeBuffer_.Clear();
502}
503
504bool AudioEngine::PlayFromThisSource(const SLDataSource& audioSrc) {
505 ClearDecodeBuffer();
506 floatBuffer_ = new float[targetFrames_ * channels_];
507 injectBuffer_ = new float[targetFrames_ * channels_];
508
509 // Create the engine.
510 SLEngineOption EngineOption[] = { {
511 SL_ENGINEOPTION_THREADSAFE, SL_BOOLEAN_TRUE } };
512 SLObjectItf engine;
513 SLresult result = slCreateEngine(&engine, 1, EngineOption, 0, NULL, NULL);
514 CheckSLResult("create engine", result);
515 result = (*engine)->Realize(engine, SL_BOOLEAN_FALSE);
516 CheckSLResult("realise engine", result);
517 SLEngineItf engineInterface;
518 result = (*engine)->GetInterface(engine, SL_IID_ENGINE, &engineInterface);
519 CheckSLResult("get interface", result);
520
521 // Create the output mix for playing.
522 SLObjectItf outputMix;
523 result = (*engineInterface)->CreateOutputMix(
524 engineInterface, &outputMix, 0, NULL, NULL);
525 CheckSLResult("create output mix", result);
526 result = (*outputMix)->Realize(outputMix, SL_BOOLEAN_FALSE);
527 CheckSLResult("realize", result);
528
529 // Define the source and sink for the audio player: comes from a buffer queue
530 // and goes to the output mix.
531 SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {
532 SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2 };
533 SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, channels_, slSampleRate_,
534 SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16,
535 slOutputChannels_, SL_BYTEORDER_LITTLEENDIAN};
536 SLDataSource playingSrc = {&loc_bufq, &format_pcm};
537 SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMix};
538 SLDataSink audioSnk = {&loc_outmix, NULL};
539
540 // Create the audio player, which will play from the buffer queue and send to
541 // the output mix.
542 const size_t playerInterfaceCount = 1;
543 const SLInterfaceID iids[playerInterfaceCount] = {
544 SL_IID_ANDROIDSIMPLEBUFFERQUEUE };
545 const SLboolean reqs[playerInterfaceCount] = { SL_BOOLEAN_TRUE };
546 SLObjectItf audioPlayer;
547 result = (*engineInterface)->CreateAudioPlayer(engineInterface, &audioPlayer,
548 &playingSrc, &audioSnk, playerInterfaceCount, iids, reqs);
549 CheckSLResult("create audio player", result);
550 result = (*audioPlayer)->Realize(audioPlayer, SL_BOOLEAN_FALSE);
551 CheckSLResult("realize buffer queue", result);
552
553 // Get the play interface from the player, as well as the buffer queue
554 // interface from its source.
555 // Register for callbacks during play.
556 SLPlayItf audioPlayerPlay;
557 result = (*audioPlayer)->GetInterface(
558 audioPlayer, SL_IID_PLAY, &audioPlayerPlay);
559 CheckSLResult("get interface", result);
560 SLAndroidSimpleBufferQueueItf audioPlayerQueue;
561 result = (*audioPlayer)->GetInterface(audioPlayer,
562 SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &audioPlayerQueue);
563 CheckSLResult("get interface again", result);
564 result = (*audioPlayerQueue)->RegisterCallback(
565 audioPlayerQueue, PlayingBufferQueueCb, NULL);
566 CheckSLResult("register callback", result);
567
568 // Define the source and sink for the decoding player: comes from the source
569 // this method was called with, is sent to another buffer queue.
570 SLDataLocator_AndroidSimpleBufferQueue decBuffQueue;
571 decBuffQueue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
572 decBuffQueue.numBuffers = kNumberOfBuffersInQueue;
573 // A valid value seems required here but is currently ignored.
574 SLDataFormat_PCM pcm = {SL_DATAFORMAT_PCM, 1, slSampleRate_,
575 SL_PCMSAMPLEFORMAT_FIXED_16, 16,
576 SL_SPEAKER_FRONT_LEFT, SL_BYTEORDER_LITTLEENDIAN};
577 SLDataSink decDest = { &decBuffQueue, &pcm };
578
579 // Create the decoder with the given source and sink.
580 const size_t decoderInterfaceCount = 4;
581 SLObjectItf decoder;
582 const SLInterfaceID decodePlayerInterfaces[decoderInterfaceCount] = {
583 SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_PREFETCHSTATUS, SL_IID_SEEK,
584 SL_IID_METADATAEXTRACTION };
585 const SLboolean decodePlayerRequired[decoderInterfaceCount] = {
586 SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };
587 SLDataSource sourceCopy(audioSrc);
588 result = (*engineInterface)->CreateAudioPlayer(engineInterface, &decoder,
589 &sourceCopy, &decDest, decoderInterfaceCount, decodePlayerInterfaces,
590 decodePlayerRequired);
591 CheckSLResult("create audio player", result);
592 result = (*decoder)->Realize(decoder, SL_BOOLEAN_FALSE);
593 CheckSLResult("realize in sync mode", result);
594
595 // Get the play interface from the decoder, and register event callbacks.
596 // Get the buffer queue, prefetch and seek interfaces.
597 SLPlayItf decoderPlay;
598 result = (*decoder)->GetInterface(decoder, SL_IID_PLAY, &decoderPlay);
599 CheckSLResult("get play interface, implicit", result);
600 result = (*decoderPlay)->SetCallbackEventsMask(
601 decoderPlay, SL_PLAYEVENT_HEADATEND);
602 CheckSLResult("set the event mask", result);
603 result = (*decoderPlay)->RegisterCallback(
604 decoderPlay, DecodingEventCb, NULL);
605 CheckSLResult("register decoding event callback", result);
606 SLAndroidSimpleBufferQueueItf decoderQueue;
607 result = (*decoder)->GetInterface(
608 decoder, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &decoderQueue);
609 CheckSLResult("get decoder buffer queue", result);
610 SLPrefetchStatusItf decoderPrefetch;
611 result = (*decoder)->GetInterface(
612 decoder, SL_IID_PREFETCHSTATUS, &decoderPrefetch);
613 CheckSLResult("get prefetch status interface", result);
614 SLSeekItf decoderSeek;
615 result = (*decoder)->GetInterface(decoder, SL_IID_SEEK, &decoderSeek);
616 CheckSLResult("get seek interface", result);
617
618 RegisterCallbackContextAndAddEnqueueBuffersToDecoder(
619 decoderQueue, decoderPlay, callbackLock_);
620
621 // Initialize the callback for prefetch errors, if we can't open the
622 // resource to decode.
623 result = (*decoderPrefetch)->SetCallbackEventsMask(
624 decoderPrefetch, kPrefetchErrorCandidate);
625 CheckSLResult("set prefetch callback mask", result);
626 result = (*decoderPrefetch)->RegisterCallback(
627 decoderPrefetch, PrefetchEventCb, &decoderPrefetch);
628 CheckSLResult("set prefetch callback", result);
629
630 SeekToPosition(decoderSeek, startPositionMillis_);
631
632 PrefetchDurationSampleRateAndChannels(decoderPlay, decoderPrefetch);
633
634 ExtractMetadataFromDecoder(decoder);
635
636 StartPlaying(decoderPlay);
637
638 // 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()) {
642 if (GetWasStartRequested()) {
643 ClearRequestStart();
644 StartPlaying(audioPlayerPlay);
645 }
646 EnqueueMoreAudioIfNecessary(audioPlayerQueue);
647 usleep(kSleepTimeMicros);
648 }
649
650 StopPlaying(audioPlayerPlay);
651 StopPlaying(decoderPlay);
652
653 // Delete the audio player.
654 result = (*audioPlayerQueue)->Clear(audioPlayerQueue);
655 CheckSLResult("clear audio player queue", result);
656 result = (*audioPlayerQueue)->RegisterCallback(audioPlayerQueue, NULL, NULL);
657 CheckSLResult("clear callback", result);
658 (*audioPlayer)->AbortAsyncOperation(audioPlayer);
659 audioPlayerPlay = NULL;
660 audioPlayerQueue = NULL;
661 (*audioPlayer)->Destroy(audioPlayer);
662
663 // Delete the decoder.
664 result = (*decoderPrefetch)->RegisterCallback(decoderPrefetch, NULL, NULL);
665 CheckSLResult("clearing prefetch error callback", result);
666 // TODO(hugohudson): 0. This is returning slresult 13 if I do no playback.
667 // Repro is to comment out all before this line, and all after enqueueing
668 // my buffers.
669 // result = (*decoderQueue)->Clear(decoderQueue);
670 // CheckSLResult("clearing decode buffer queue", result);
671 result = (*decoderQueue)->RegisterCallback(decoderQueue, NULL, NULL);
672 CheckSLResult("clearing decode callback", result);
673 decoderSeek = NULL;
674 decoderPrefetch = NULL;
675 decoderQueue = NULL;
676 result = (*decoderPlay)->RegisterCallback(decoderPlay, NULL, NULL);
677 CheckSLResult("clear decoding event callback", result);
678 (*decoder)->AbortAsyncOperation(decoder);
679 decoderPlay = NULL;
680 (*decoder)->Destroy(decoder);
681
682 // Delete the output mix, then the engine.
683 (*outputMix)->Destroy(outputMix);
684 engineInterface = NULL;
685 (*engine)->Destroy(engine);
686
687 return true;
688}
689
690bool AudioEngine::Finished() {
691 if (GetWasStopRequested()) {
692 return true;
693 }
694 android::Mutex::Autolock autoLock(playBufferLock_);
695 return playingBuffers_.size() <= 0 &&
696 IsDecodeBufferEmpty() &&
697 GetEndOfDecoderReached();
698}
699
700bool AudioEngine::GetWasStopRequested() {
701 android::Mutex::Autolock autoLock(lock_);
702 return stopRequested_;
703}
704
705bool AudioEngine::GetHasReachedPlayingBuffersLimit() {
706 android::Mutex::Autolock autoLock(playBufferLock_);
707 return playingBuffers_.size() >= maxPlayBufferCount_;
708}
709
710void AudioEngine::EnqueueMoreAudioIfNecessary(
711 SLAndroidSimpleBufferQueueItf audioPlayerQueue) {
712 bool keepEnqueueing = true;
713 while (!GetWasStopRequested() &&
714 !IsDecodeBufferEmpty() &&
715 !GetHasReachedPlayingBuffersLimit() &&
716 keepEnqueueing) {
717 keepEnqueueing = EnqueueNextBufferOfAudio(audioPlayerQueue);
718 }
719}
720
721bool AudioEngine::DecodeBufferTooFull() {
722 android::Mutex::Autolock autoLock(decodeBufferLock_);
723 return decodeBuffer_.IsTooLarge();
724}
725
726// ****************************************************************************
727// Code for handling the static callbacks.
728
729void AudioEngine::PlayingBufferQueueCallback() {
730 // The head playing buffer is done, move it to the free list.
731 android::Mutex::Autolock autoLock(playBufferLock_);
732 if (playingBuffers_.size() > 0) {
733 freeBuffers_.push(playingBuffers_.front());
734 playingBuffers_.pop();
735 }
736}
737
738void AudioEngine::PrefetchEventCallback(
739 SLPrefetchStatusItf caller, SLuint32 event) {
740 // If there was a problem during decoding, then signal the end.
741 LOGI("in the prefetch callback");
742 SLpermille level = 0;
743 SLresult result = (*caller)->GetFillLevel(caller, &level);
744 CheckSLResult("get fill level", result);
745 SLuint32 status;
746 result = (*caller)->GetPrefetchStatus(caller, &status);
747 CheckSLResult("get prefetch status", result);
748 if ((kPrefetchErrorCandidate == (event & kPrefetchErrorCandidate)) &&
749 (level == 0) &&
750 (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
751 LOGI("PrefetchEventCallback error while prefetching data");
752 SetEndOfDecoderReached();
753 }
754 if (SL_PREFETCHSTATUS_SUFFICIENTDATA == event) {
755 LOGI("looks like our event...");
756 // android::Mutex::Autolock autoLock(prefetchLock_);
757 // prefetchCondition_.broadcast();
758 LOGI("just sent a broadcast");
759 }
760}
761
762void AudioEngine::DecodingBufferQueueCallback(
763 SLAndroidSimpleBufferQueueItf queueItf, void *context) {
764 if (GetWasStopRequested()) {
765 return;
766 }
767
768 CallbackContext *pCntxt;
769 {
770 android::Mutex::Autolock autoLock(callbackLock_);
771 pCntxt = reinterpret_cast<CallbackContext*>(context);
772 }
773 {
774 android::Mutex::Autolock autoLock(decodeBufferLock_);
775 decodeBuffer_.AddData(pCntxt->pDataBase, kBufferSizeInBytes);
776 }
777
778 // Increase data pointer by buffer size
779 pCntxt->pData += kBufferSizeInBytes;
780 if (pCntxt->pData >= pCntxt->pDataBase +
781 (kNumberOfBuffersInQueue * kBufferSizeInBytes)) {
782 pCntxt->pData = pCntxt->pDataBase;
783 }
784
785 SLresult result = (*queueItf)->Enqueue(
786 queueItf, pCntxt->pDataBase, kBufferSizeInBytes);
787 CheckSLResult("enqueue something else", result);
788
789 // If we get too much data into the decoder,
790 // sleep until the playback catches up.
791 while (!GetWasStopRequested() && DecodeBufferTooFull()) {
792 usleep(kSleepTimeMicros);
793 }
794}
795
796void AudioEngine::DecodingEventCallback(SLPlayItf, SLuint32 event) {
797 if (SL_PLAYEVENT_HEADATEND & event) {
798 SetEndOfDecoderReached();
799 }
800}