• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 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 //#define LOG_NDEBUG 0
18 #define LOG_TAG "SoundPool"
19 
20 #include <inttypes.h>
21 
22 #include <utils/Log.h>
23 
24 #define USE_SHARED_MEM_BUFFER
25 
26 #include <media/AudioTrack.h>
27 #include <media/IMediaHTTPService.h>
28 #include <media/mediaplayer.h>
29 #include <media/stagefright/MediaExtractor.h>
30 #include "SoundPool.h"
31 #include "SoundPoolThread.h"
32 #include <media/AudioPolicyHelper.h>
33 #include <ndk/NdkMediaCodec.h>
34 #include <ndk/NdkMediaExtractor.h>
35 #include <ndk/NdkMediaFormat.h>
36 
37 namespace android
38 {
39 
40 int kDefaultBufferCount = 4;
41 uint32_t kMaxSampleRate = 48000;
42 uint32_t kDefaultSampleRate = 44100;
43 uint32_t kDefaultFrameCount = 1200;
44 size_t kDefaultHeapSize = 1024 * 1024; // 1MB
45 
46 
SoundPool(int maxChannels,const audio_attributes_t * pAttributes)47 SoundPool::SoundPool(int maxChannels, const audio_attributes_t* pAttributes)
48 {
49     ALOGV("SoundPool constructor: maxChannels=%d, attr.usage=%d, attr.flags=0x%x, attr.tags=%s",
50             maxChannels, pAttributes->usage, pAttributes->flags, pAttributes->tags);
51 
52     // check limits
53     mMaxChannels = maxChannels;
54     if (mMaxChannels < 1) {
55         mMaxChannels = 1;
56     }
57     else if (mMaxChannels > 32) {
58         mMaxChannels = 32;
59     }
60     ALOGW_IF(maxChannels != mMaxChannels, "App requested %d channels", maxChannels);
61 
62     mQuit = false;
63     mDecodeThread = 0;
64     memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
65     mAllocated = 0;
66     mNextSampleID = 0;
67     mNextChannelID = 0;
68 
69     mCallback = 0;
70     mUserData = 0;
71 
72     mChannelPool = new SoundChannel[mMaxChannels];
73     for (int i = 0; i < mMaxChannels; ++i) {
74         mChannelPool[i].init(this);
75         mChannels.push_back(&mChannelPool[i]);
76     }
77 
78     // start decode thread
79     startThreads();
80 }
81 
~SoundPool()82 SoundPool::~SoundPool()
83 {
84     ALOGV("SoundPool destructor");
85     mDecodeThread->quit();
86     quit();
87 
88     Mutex::Autolock lock(&mLock);
89 
90     mChannels.clear();
91     if (mChannelPool)
92         delete [] mChannelPool;
93     // clean up samples
94     ALOGV("clear samples");
95     mSamples.clear();
96 
97     if (mDecodeThread)
98         delete mDecodeThread;
99 }
100 
addToRestartList(SoundChannel * channel)101 void SoundPool::addToRestartList(SoundChannel* channel)
102 {
103     Mutex::Autolock lock(&mRestartLock);
104     if (!mQuit) {
105         mRestart.push_back(channel);
106         mCondition.signal();
107     }
108 }
109 
addToStopList(SoundChannel * channel)110 void SoundPool::addToStopList(SoundChannel* channel)
111 {
112     Mutex::Autolock lock(&mRestartLock);
113     if (!mQuit) {
114         mStop.push_back(channel);
115         mCondition.signal();
116     }
117 }
118 
beginThread(void * arg)119 int SoundPool::beginThread(void* arg)
120 {
121     SoundPool* p = (SoundPool*)arg;
122     return p->run();
123 }
124 
run()125 int SoundPool::run()
126 {
127     mRestartLock.lock();
128     while (!mQuit) {
129         mCondition.wait(mRestartLock);
130         ALOGV("awake");
131         if (mQuit) break;
132 
133         while (!mStop.empty()) {
134             SoundChannel* channel;
135             ALOGV("Getting channel from stop list");
136             List<SoundChannel* >::iterator iter = mStop.begin();
137             channel = *iter;
138             mStop.erase(iter);
139             mRestartLock.unlock();
140             if (channel != 0) {
141                 Mutex::Autolock lock(&mLock);
142                 channel->stop();
143             }
144             mRestartLock.lock();
145             if (mQuit) break;
146         }
147 
148         while (!mRestart.empty()) {
149             SoundChannel* channel;
150             ALOGV("Getting channel from list");
151             List<SoundChannel*>::iterator iter = mRestart.begin();
152             channel = *iter;
153             mRestart.erase(iter);
154             mRestartLock.unlock();
155             if (channel != 0) {
156                 Mutex::Autolock lock(&mLock);
157                 channel->nextEvent();
158             }
159             mRestartLock.lock();
160             if (mQuit) break;
161         }
162     }
163 
164     mStop.clear();
165     mRestart.clear();
166     mCondition.signal();
167     mRestartLock.unlock();
168     ALOGV("goodbye");
169     return 0;
170 }
171 
quit()172 void SoundPool::quit()
173 {
174     mRestartLock.lock();
175     mQuit = true;
176     mCondition.signal();
177     mCondition.wait(mRestartLock);
178     ALOGV("return from quit");
179     mRestartLock.unlock();
180 }
181 
startThreads()182 bool SoundPool::startThreads()
183 {
184     createThreadEtc(beginThread, this, "SoundPool");
185     if (mDecodeThread == NULL)
186         mDecodeThread = new SoundPoolThread(this);
187     return mDecodeThread != NULL;
188 }
189 
findSample(int sampleID)190 sp<Sample> SoundPool::findSample(int sampleID)
191 {
192     Mutex::Autolock lock(&mLock);
193     return findSample_l(sampleID);
194 }
195 
findSample_l(int sampleID)196 sp<Sample> SoundPool::findSample_l(int sampleID)
197 {
198     return mSamples.valueFor(sampleID);
199 }
200 
findChannel(int channelID)201 SoundChannel* SoundPool::findChannel(int channelID)
202 {
203     for (int i = 0; i < mMaxChannels; ++i) {
204         if (mChannelPool[i].channelID() == channelID) {
205             return &mChannelPool[i];
206         }
207     }
208     return NULL;
209 }
210 
findNextChannel(int channelID)211 SoundChannel* SoundPool::findNextChannel(int channelID)
212 {
213     for (int i = 0; i < mMaxChannels; ++i) {
214         if (mChannelPool[i].nextChannelID() == channelID) {
215             return &mChannelPool[i];
216         }
217     }
218     return NULL;
219 }
220 
load(int fd,int64_t offset,int64_t length,int priority __unused)221 int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused)
222 {
223     ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d",
224             fd, offset, length, priority);
225     int sampleID;
226     {
227         Mutex::Autolock lock(&mLock);
228         sampleID = ++mNextSampleID;
229         sp<Sample> sample = new Sample(sampleID, fd, offset, length);
230         mSamples.add(sampleID, sample);
231         sample->startLoad();
232     }
233     // mDecodeThread->loadSample() must be called outside of mLock.
234     // mDecodeThread->loadSample() may block on mDecodeThread message queue space;
235     // the message queue emptying may block on SoundPool::findSample().
236     //
237     // It theoretically possible that sample loads might decode out-of-order.
238     mDecodeThread->loadSample(sampleID);
239     return sampleID;
240 }
241 
unload(int sampleID)242 bool SoundPool::unload(int sampleID)
243 {
244     ALOGV("unload: sampleID=%d", sampleID);
245     Mutex::Autolock lock(&mLock);
246     return mSamples.removeItem(sampleID) >= 0; // removeItem() returns index or BAD_VALUE
247 }
248 
play(int sampleID,float leftVolume,float rightVolume,int priority,int loop,float rate)249 int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
250         int priority, int loop, float rate)
251 {
252     ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
253             sampleID, leftVolume, rightVolume, priority, loop, rate);
254     SoundChannel* channel;
255     int channelID;
256 
257     Mutex::Autolock lock(&mLock);
258 
259     if (mQuit) {
260         return 0;
261     }
262     // is sample ready?
263     sp<Sample> sample(findSample_l(sampleID));
264     if ((sample == 0) || (sample->state() != Sample::READY)) {
265         ALOGW("  sample %d not READY", sampleID);
266         return 0;
267     }
268 
269     dump();
270 
271     // allocate a channel
272     channel = allocateChannel_l(priority, sampleID);
273 
274     // no channel allocated - return 0
275     if (!channel) {
276         ALOGV("No channel allocated");
277         return 0;
278     }
279 
280     channelID = ++mNextChannelID;
281 
282     ALOGV("play channel %p state = %d", channel, channel->state());
283     channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
284     return channelID;
285 }
286 
allocateChannel_l(int priority,int sampleID)287 SoundChannel* SoundPool::allocateChannel_l(int priority, int sampleID)
288 {
289     List<SoundChannel*>::iterator iter;
290     SoundChannel* channel = NULL;
291 
292     // check if channel for given sampleID still available
293     if (!mChannels.empty()) {
294         for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
295             if (sampleID == (*iter)->getPrevSampleID() && (*iter)->state() == SoundChannel::IDLE) {
296                 channel = *iter;
297                 mChannels.erase(iter);
298                 ALOGV("Allocated recycled channel for same sampleID");
299                 break;
300             }
301         }
302     }
303 
304     // allocate any channel
305     if (!channel && !mChannels.empty()) {
306         iter = mChannels.begin();
307         if (priority >= (*iter)->priority()) {
308             channel = *iter;
309             mChannels.erase(iter);
310             ALOGV("Allocated active channel");
311         }
312     }
313 
314     // update priority and put it back in the list
315     if (channel) {
316         channel->setPriority(priority);
317         for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
318             if (priority < (*iter)->priority()) {
319                 break;
320             }
321         }
322         mChannels.insert(iter, channel);
323     }
324     return channel;
325 }
326 
327 // move a channel from its current position to the front of the list
moveToFront_l(SoundChannel * channel)328 void SoundPool::moveToFront_l(SoundChannel* channel)
329 {
330     for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
331         if (*iter == channel) {
332             mChannels.erase(iter);
333             mChannels.push_front(channel);
334             break;
335         }
336     }
337 }
338 
pause(int channelID)339 void SoundPool::pause(int channelID)
340 {
341     ALOGV("pause(%d)", channelID);
342     Mutex::Autolock lock(&mLock);
343     SoundChannel* channel = findChannel(channelID);
344     if (channel) {
345         channel->pause();
346     }
347 }
348 
autoPause()349 void SoundPool::autoPause()
350 {
351     ALOGV("autoPause()");
352     Mutex::Autolock lock(&mLock);
353     for (int i = 0; i < mMaxChannels; ++i) {
354         SoundChannel* channel = &mChannelPool[i];
355         channel->autoPause();
356     }
357 }
358 
resume(int channelID)359 void SoundPool::resume(int channelID)
360 {
361     ALOGV("resume(%d)", channelID);
362     Mutex::Autolock lock(&mLock);
363     SoundChannel* channel = findChannel(channelID);
364     if (channel) {
365         channel->resume();
366     }
367 }
368 
autoResume()369 void SoundPool::autoResume()
370 {
371     ALOGV("autoResume()");
372     Mutex::Autolock lock(&mLock);
373     for (int i = 0; i < mMaxChannels; ++i) {
374         SoundChannel* channel = &mChannelPool[i];
375         channel->autoResume();
376     }
377 }
378 
stop(int channelID)379 void SoundPool::stop(int channelID)
380 {
381     ALOGV("stop(%d)", channelID);
382     Mutex::Autolock lock(&mLock);
383     SoundChannel* channel = findChannel(channelID);
384     if (channel) {
385         channel->stop();
386     } else {
387         channel = findNextChannel(channelID);
388         if (channel)
389             channel->clearNextEvent();
390     }
391 }
392 
setVolume(int channelID,float leftVolume,float rightVolume)393 void SoundPool::setVolume(int channelID, float leftVolume, float rightVolume)
394 {
395     Mutex::Autolock lock(&mLock);
396     SoundChannel* channel = findChannel(channelID);
397     if (channel) {
398         channel->setVolume(leftVolume, rightVolume);
399     }
400 }
401 
setPriority(int channelID,int priority)402 void SoundPool::setPriority(int channelID, int priority)
403 {
404     ALOGV("setPriority(%d, %d)", channelID, priority);
405     Mutex::Autolock lock(&mLock);
406     SoundChannel* channel = findChannel(channelID);
407     if (channel) {
408         channel->setPriority(priority);
409     }
410 }
411 
setLoop(int channelID,int loop)412 void SoundPool::setLoop(int channelID, int loop)
413 {
414     ALOGV("setLoop(%d, %d)", channelID, loop);
415     Mutex::Autolock lock(&mLock);
416     SoundChannel* channel = findChannel(channelID);
417     if (channel) {
418         channel->setLoop(loop);
419     }
420 }
421 
setRate(int channelID,float rate)422 void SoundPool::setRate(int channelID, float rate)
423 {
424     ALOGV("setRate(%d, %f)", channelID, rate);
425     Mutex::Autolock lock(&mLock);
426     SoundChannel* channel = findChannel(channelID);
427     if (channel) {
428         channel->setRate(rate);
429     }
430 }
431 
432 // call with lock held
done_l(SoundChannel * channel)433 void SoundPool::done_l(SoundChannel* channel)
434 {
435     ALOGV("done_l(%d)", channel->channelID());
436     // if "stolen", play next event
437     if (channel->nextChannelID() != 0) {
438         ALOGV("add to restart list");
439         addToRestartList(channel);
440     }
441 
442     // return to idle state
443     else {
444         ALOGV("move to front");
445         moveToFront_l(channel);
446     }
447 }
448 
setCallback(SoundPoolCallback * callback,void * user)449 void SoundPool::setCallback(SoundPoolCallback* callback, void* user)
450 {
451     Mutex::Autolock lock(&mCallbackLock);
452     mCallback = callback;
453     mUserData = user;
454 }
455 
notify(SoundPoolEvent event)456 void SoundPool::notify(SoundPoolEvent event)
457 {
458     Mutex::Autolock lock(&mCallbackLock);
459     if (mCallback != NULL) {
460         mCallback(event, this, mUserData);
461     }
462 }
463 
dump()464 void SoundPool::dump()
465 {
466     for (int i = 0; i < mMaxChannels; ++i) {
467         mChannelPool[i].dump();
468     }
469 }
470 
471 
Sample(int sampleID,int fd,int64_t offset,int64_t length)472 Sample::Sample(int sampleID, int fd, int64_t offset, int64_t length)
473 {
474     init();
475     mSampleID = sampleID;
476     mFd = dup(fd);
477     mOffset = offset;
478     mLength = length;
479     ALOGV("create sampleID=%d, fd=%d, offset=%" PRId64 " length=%" PRId64,
480         mSampleID, mFd, mLength, mOffset);
481 }
482 
init()483 void Sample::init()
484 {
485     mSize = 0;
486     mRefCount = 0;
487     mSampleID = 0;
488     mState = UNLOADED;
489     mFd = -1;
490     mOffset = 0;
491     mLength = 0;
492 }
493 
~Sample()494 Sample::~Sample()
495 {
496     ALOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd);
497     if (mFd > 0) {
498         ALOGV("close(%d)", mFd);
499         ::close(mFd);
500     }
501 }
502 
decode(int fd,int64_t offset,int64_t length,uint32_t * rate,int * numChannels,audio_format_t * audioFormat,sp<MemoryHeapBase> heap,size_t * memsize)503 static status_t decode(int fd, int64_t offset, int64_t length,
504         uint32_t *rate, int *numChannels, audio_format_t *audioFormat,
505         sp<MemoryHeapBase> heap, size_t *memsize) {
506 
507     ALOGV("fd %d, offset %" PRId64 ", size %" PRId64, fd, offset, length);
508     AMediaExtractor *ex = AMediaExtractor_new();
509     status_t err = AMediaExtractor_setDataSourceFd(ex, fd, offset, length);
510 
511     if (err != AMEDIA_OK) {
512         AMediaExtractor_delete(ex);
513         return err;
514     }
515 
516     *audioFormat = AUDIO_FORMAT_PCM_16_BIT;
517 
518     size_t numTracks = AMediaExtractor_getTrackCount(ex);
519     for (size_t i = 0; i < numTracks; i++) {
520         AMediaFormat *format = AMediaExtractor_getTrackFormat(ex, i);
521         const char *mime;
522         if (!AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime)) {
523             AMediaExtractor_delete(ex);
524             AMediaFormat_delete(format);
525             return UNKNOWN_ERROR;
526         }
527         if (strncmp(mime, "audio/", 6) == 0) {
528 
529             AMediaCodec *codec = AMediaCodec_createDecoderByType(mime);
530             if (codec == NULL
531                     || AMediaCodec_configure(codec, format,
532                             NULL /* window */, NULL /* drm */, 0 /* flags */) != AMEDIA_OK
533                     || AMediaCodec_start(codec) != AMEDIA_OK
534                     || AMediaExtractor_selectTrack(ex, i) != AMEDIA_OK) {
535                 AMediaExtractor_delete(ex);
536                 AMediaCodec_delete(codec);
537                 AMediaFormat_delete(format);
538                 return UNKNOWN_ERROR;
539             }
540 
541             bool sawInputEOS = false;
542             bool sawOutputEOS = false;
543             uint8_t* writePos = static_cast<uint8_t*>(heap->getBase());
544             size_t available = heap->getSize();
545             size_t written = 0;
546 
547             AMediaFormat_delete(format);
548             format = AMediaCodec_getOutputFormat(codec);
549 
550             while (!sawOutputEOS) {
551                 if (!sawInputEOS) {
552                     ssize_t bufidx = AMediaCodec_dequeueInputBuffer(codec, 5000);
553                     ALOGV("input buffer %zd", bufidx);
554                     if (bufidx >= 0) {
555                         size_t bufsize;
556                         uint8_t *buf = AMediaCodec_getInputBuffer(codec, bufidx, &bufsize);
557                         int sampleSize = AMediaExtractor_readSampleData(ex, buf, bufsize);
558                         ALOGV("read %d", sampleSize);
559                         if (sampleSize < 0) {
560                             sampleSize = 0;
561                             sawInputEOS = true;
562                             ALOGV("EOS");
563                         }
564                         int64_t presentationTimeUs = AMediaExtractor_getSampleTime(ex);
565 
566                         AMediaCodec_queueInputBuffer(codec, bufidx,
567                                 0 /* offset */, sampleSize, presentationTimeUs,
568                                 sawInputEOS ? AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM : 0);
569                         AMediaExtractor_advance(ex);
570                     }
571                 }
572 
573                 AMediaCodecBufferInfo info;
574                 int status = AMediaCodec_dequeueOutputBuffer(codec, &info, 1);
575                 ALOGV("dequeueoutput returned: %d", status);
576                 if (status >= 0) {
577                     if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) {
578                         ALOGV("output EOS");
579                         sawOutputEOS = true;
580                     }
581                     ALOGV("got decoded buffer size %d", info.size);
582 
583                     uint8_t *buf = AMediaCodec_getOutputBuffer(codec, status, NULL /* out_size */);
584                     size_t dataSize = info.size;
585                     if (dataSize > available) {
586                         dataSize = available;
587                     }
588                     memcpy(writePos, buf + info.offset, dataSize);
589                     writePos += dataSize;
590                     written += dataSize;
591                     available -= dataSize;
592                     AMediaCodec_releaseOutputBuffer(codec, status, false /* render */);
593                     if (available == 0) {
594                         // there might be more data, but there's no space for it
595                         sawOutputEOS = true;
596                     }
597                 } else if (status == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
598                     ALOGV("output buffers changed");
599                 } else if (status == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
600                     AMediaFormat_delete(format);
601                     format = AMediaCodec_getOutputFormat(codec);
602                     ALOGV("format changed to: %s", AMediaFormat_toString(format));
603                 } else if (status == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
604                     ALOGV("no output buffer right now");
605                 } else {
606                     ALOGV("unexpected info code: %d", status);
607                 }
608             }
609 
610             AMediaCodec_stop(codec);
611             AMediaCodec_delete(codec);
612             AMediaExtractor_delete(ex);
613             if (!AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, (int32_t*) rate) ||
614                     !AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, numChannels)) {
615                 AMediaFormat_delete(format);
616                 return UNKNOWN_ERROR;
617             }
618             AMediaFormat_delete(format);
619             *memsize = written;
620             return OK;
621         }
622         AMediaFormat_delete(format);
623     }
624     AMediaExtractor_delete(ex);
625     return UNKNOWN_ERROR;
626 }
627 
doLoad()628 status_t Sample::doLoad()
629 {
630     uint32_t sampleRate;
631     int numChannels;
632     audio_format_t format;
633     status_t status;
634     mHeap = new MemoryHeapBase(kDefaultHeapSize);
635 
636     ALOGV("Start decode");
637     status = decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format,
638                                  mHeap, &mSize);
639     ALOGV("close(%d)", mFd);
640     ::close(mFd);
641     mFd = -1;
642     if (status != NO_ERROR) {
643         ALOGE("Unable to load sample");
644         goto error;
645     }
646     ALOGV("pointer = %p, size = %zu, sampleRate = %u, numChannels = %d",
647           mHeap->getBase(), mSize, sampleRate, numChannels);
648 
649     if (sampleRate > kMaxSampleRate) {
650        ALOGE("Sample rate (%u) out of range", sampleRate);
651        status = BAD_VALUE;
652        goto error;
653     }
654 
655     if ((numChannels < 1) || (numChannels > 8)) {
656         ALOGE("Sample channel count (%d) out of range", numChannels);
657         status = BAD_VALUE;
658         goto error;
659     }
660 
661     mData = new MemoryBase(mHeap, 0, mSize);
662     mSampleRate = sampleRate;
663     mNumChannels = numChannels;
664     mFormat = format;
665     mState = READY;
666     return NO_ERROR;
667 
668 error:
669     mHeap.clear();
670     return status;
671 }
672 
673 
init(SoundPool * soundPool)674 void SoundChannel::init(SoundPool* soundPool)
675 {
676     mSoundPool = soundPool;
677     mPrevSampleID = -1;
678 }
679 
680 // call with sound pool lock held
play(const sp<Sample> & sample,int nextChannelID,float leftVolume,float rightVolume,int priority,int loop,float rate)681 void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
682         float rightVolume, int priority, int loop, float rate)
683 {
684     sp<AudioTrack> oldTrack;
685     sp<AudioTrack> newTrack;
686     status_t status = NO_ERROR;
687 
688     { // scope for the lock
689         Mutex::Autolock lock(&mLock);
690 
691         ALOGV("SoundChannel::play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f,"
692                 " priority=%d, loop=%d, rate=%f",
693                 this, sample->sampleID(), nextChannelID, leftVolume, rightVolume,
694                 priority, loop, rate);
695 
696         // if not idle, this voice is being stolen
697         if (mState != IDLE) {
698             ALOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
699             mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
700             stop_l();
701             return;
702         }
703 
704         // initialize track
705         size_t afFrameCount;
706         uint32_t afSampleRate;
707         audio_stream_type_t streamType = audio_attributes_to_stream_type(mSoundPool->attributes());
708         if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
709             afFrameCount = kDefaultFrameCount;
710         }
711         if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
712             afSampleRate = kDefaultSampleRate;
713         }
714         int numChannels = sample->numChannels();
715         uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
716         size_t frameCount = 0;
717 
718         if (loop) {
719             const audio_format_t format = sample->format();
720             const size_t frameSize = audio_is_linear_pcm(format)
721                     ? numChannels * audio_bytes_per_sample(format) : 1;
722             frameCount = sample->size() / frameSize;
723         }
724 
725 #ifndef USE_SHARED_MEM_BUFFER
726         uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
727         // Ensure minimum audio buffer size in case of short looped sample
728         if(frameCount < totalFrames) {
729             frameCount = totalFrames;
730         }
731 #endif
732 
733         // check if the existing track has the same sample id.
734         if (mAudioTrack != 0 && mPrevSampleID == sample->sampleID()) {
735             // the sample rate may fail to change if the audio track is a fast track.
736             if (mAudioTrack->setSampleRate(sampleRate) == NO_ERROR) {
737                 newTrack = mAudioTrack;
738                 ALOGV("reusing track %p for sample %d", mAudioTrack.get(), sample->sampleID());
739             }
740         }
741         if (newTrack == 0) {
742             // mToggle toggles each time a track is started on a given channel.
743             // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
744             // as callback user data. This enables the detection of callbacks received from the old
745             // audio track while the new one is being started and avoids processing them with
746             // wrong audio audio buffer size  (mAudioBufferSize)
747             unsigned long toggle = mToggle ^ 1;
748             void *userData = (void *)((unsigned long)this | toggle);
749             audio_channel_mask_t channelMask = audio_channel_out_mask_from_count(numChannels);
750 
751             // do not create a new audio track if current track is compatible with sample parameters
752     #ifdef USE_SHARED_MEM_BUFFER
753             newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
754                     channelMask, sample->getIMemory(), AUDIO_OUTPUT_FLAG_FAST, callback, userData,
755                     0 /*default notification frames*/, AUDIO_SESSION_ALLOCATE,
756                     AudioTrack::TRANSFER_DEFAULT,
757                     NULL /*offloadInfo*/, -1 /*uid*/, -1 /*pid*/, mSoundPool->attributes());
758     #else
759             uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
760             newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
761                     channelMask, frameCount, AUDIO_OUTPUT_FLAG_FAST, callback, userData,
762                     bufferFrames, AUDIO_SESSION_ALLOCATE, AudioTrack::TRANSFER_DEFAULT,
763                     NULL /*offloadInfo*/, -1 /*uid*/, -1 /*pid*/, mSoundPool->attributes());
764     #endif
765             oldTrack = mAudioTrack;
766             status = newTrack->initCheck();
767             if (status != NO_ERROR) {
768                 ALOGE("Error creating AudioTrack");
769                 // newTrack goes out of scope, so reference count drops to zero
770                 goto exit;
771             }
772             // From now on, AudioTrack callbacks received with previous toggle value will be ignored.
773             mToggle = toggle;
774             mAudioTrack = newTrack;
775             ALOGV("using new track %p for sample %d", newTrack.get(), sample->sampleID());
776         }
777         newTrack->setVolume(leftVolume, rightVolume);
778         newTrack->setLoop(0, frameCount, loop);
779         mPos = 0;
780         mSample = sample;
781         mChannelID = nextChannelID;
782         mPriority = priority;
783         mLoop = loop;
784         mLeftVolume = leftVolume;
785         mRightVolume = rightVolume;
786         mNumChannels = numChannels;
787         mRate = rate;
788         clearNextEvent();
789         mState = PLAYING;
790         mAudioTrack->start();
791         mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
792     }
793 
794 exit:
795     ALOGV("delete oldTrack %p", oldTrack.get());
796     if (status != NO_ERROR) {
797         mAudioTrack.clear();
798     }
799 }
800 
nextEvent()801 void SoundChannel::nextEvent()
802 {
803     sp<Sample> sample;
804     int nextChannelID;
805     float leftVolume;
806     float rightVolume;
807     int priority;
808     int loop;
809     float rate;
810 
811     // check for valid event
812     {
813         Mutex::Autolock lock(&mLock);
814         nextChannelID = mNextEvent.channelID();
815         if (nextChannelID  == 0) {
816             ALOGV("stolen channel has no event");
817             return;
818         }
819 
820         sample = mNextEvent.sample();
821         leftVolume = mNextEvent.leftVolume();
822         rightVolume = mNextEvent.rightVolume();
823         priority = mNextEvent.priority();
824         loop = mNextEvent.loop();
825         rate = mNextEvent.rate();
826     }
827 
828     ALOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
829     play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
830 }
831 
callback(int event,void * user,void * info)832 void SoundChannel::callback(int event, void* user, void *info)
833 {
834     SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
835 
836     channel->process(event, info, (unsigned long)user & 1);
837 }
838 
process(int event,void * info,unsigned long toggle)839 void SoundChannel::process(int event, void *info, unsigned long toggle)
840 {
841     //ALOGV("process(%d)", mChannelID);
842 
843     Mutex::Autolock lock(&mLock);
844 
845     AudioTrack::Buffer* b = NULL;
846     if (event == AudioTrack::EVENT_MORE_DATA) {
847        b = static_cast<AudioTrack::Buffer *>(info);
848     }
849 
850     if (mToggle != toggle) {
851         ALOGV("process wrong toggle %p channel %d", this, mChannelID);
852         if (b != NULL) {
853             b->size = 0;
854         }
855         return;
856     }
857 
858     sp<Sample> sample = mSample;
859 
860 //    ALOGV("SoundChannel::process event %d", event);
861 
862     if (event == AudioTrack::EVENT_MORE_DATA) {
863 
864         // check for stop state
865         if (b->size == 0) return;
866 
867         if (mState == IDLE) {
868             b->size = 0;
869             return;
870         }
871 
872         if (sample != 0) {
873             // fill buffer
874             uint8_t* q = (uint8_t*) b->i8;
875             size_t count = 0;
876 
877             if (mPos < (int)sample->size()) {
878                 uint8_t* p = sample->data() + mPos;
879                 count = sample->size() - mPos;
880                 if (count > b->size) {
881                     count = b->size;
882                 }
883                 memcpy(q, p, count);
884 //              ALOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size,
885 //                      count);
886             } else if (mPos < mAudioBufferSize) {
887                 count = mAudioBufferSize - mPos;
888                 if (count > b->size) {
889                     count = b->size;
890                 }
891                 memset(q, 0, count);
892 //              ALOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
893             }
894 
895             mPos += count;
896             b->size = count;
897             //ALOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
898         }
899     } else if (event == AudioTrack::EVENT_UNDERRUN || event == AudioTrack::EVENT_BUFFER_END) {
900         ALOGV("process %p channel %d event %s",
901               this, mChannelID, (event == AudioTrack::EVENT_UNDERRUN) ? "UNDERRUN" :
902                       "BUFFER_END");
903         mSoundPool->addToStopList(this);
904     } else if (event == AudioTrack::EVENT_LOOP_END) {
905         ALOGV("End loop %p channel %d", this, mChannelID);
906     } else if (event == AudioTrack::EVENT_NEW_IAUDIOTRACK) {
907         ALOGV("process %p channel %d NEW_IAUDIOTRACK", this, mChannelID);
908     } else {
909         ALOGW("SoundChannel::process unexpected event %d", event);
910     }
911 }
912 
913 
914 // call with lock held
doStop_l()915 bool SoundChannel::doStop_l()
916 {
917     if (mState != IDLE) {
918         setVolume_l(0, 0);
919         ALOGV("stop");
920         mAudioTrack->stop();
921         mPrevSampleID = mSample->sampleID();
922         mSample.clear();
923         mState = IDLE;
924         mPriority = IDLE_PRIORITY;
925         return true;
926     }
927     return false;
928 }
929 
930 // call with lock held and sound pool lock held
stop_l()931 void SoundChannel::stop_l()
932 {
933     if (doStop_l()) {
934         mSoundPool->done_l(this);
935     }
936 }
937 
938 // call with sound pool lock held
stop()939 void SoundChannel::stop()
940 {
941     bool stopped;
942     {
943         Mutex::Autolock lock(&mLock);
944         stopped = doStop_l();
945     }
946 
947     if (stopped) {
948         mSoundPool->done_l(this);
949     }
950 }
951 
952 //FIXME: Pause is a little broken right now
pause()953 void SoundChannel::pause()
954 {
955     Mutex::Autolock lock(&mLock);
956     if (mState == PLAYING) {
957         ALOGV("pause track");
958         mState = PAUSED;
959         mAudioTrack->pause();
960     }
961 }
962 
autoPause()963 void SoundChannel::autoPause()
964 {
965     Mutex::Autolock lock(&mLock);
966     if (mState == PLAYING) {
967         ALOGV("pause track");
968         mState = PAUSED;
969         mAutoPaused = true;
970         mAudioTrack->pause();
971     }
972 }
973 
resume()974 void SoundChannel::resume()
975 {
976     Mutex::Autolock lock(&mLock);
977     if (mState == PAUSED) {
978         ALOGV("resume track");
979         mState = PLAYING;
980         mAutoPaused = false;
981         mAudioTrack->start();
982     }
983 }
984 
autoResume()985 void SoundChannel::autoResume()
986 {
987     Mutex::Autolock lock(&mLock);
988     if (mAutoPaused && (mState == PAUSED)) {
989         ALOGV("resume track");
990         mState = PLAYING;
991         mAutoPaused = false;
992         mAudioTrack->start();
993     }
994 }
995 
setRate(float rate)996 void SoundChannel::setRate(float rate)
997 {
998     Mutex::Autolock lock(&mLock);
999     if (mAudioTrack != NULL && mSample != 0) {
1000         uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5);
1001         mAudioTrack->setSampleRate(sampleRate);
1002         mRate = rate;
1003     }
1004 }
1005 
1006 // call with lock held
setVolume_l(float leftVolume,float rightVolume)1007 void SoundChannel::setVolume_l(float leftVolume, float rightVolume)
1008 {
1009     mLeftVolume = leftVolume;
1010     mRightVolume = rightVolume;
1011     if (mAudioTrack != NULL)
1012         mAudioTrack->setVolume(leftVolume, rightVolume);
1013 }
1014 
setVolume(float leftVolume,float rightVolume)1015 void SoundChannel::setVolume(float leftVolume, float rightVolume)
1016 {
1017     Mutex::Autolock lock(&mLock);
1018     setVolume_l(leftVolume, rightVolume);
1019 }
1020 
setLoop(int loop)1021 void SoundChannel::setLoop(int loop)
1022 {
1023     Mutex::Autolock lock(&mLock);
1024     if (mAudioTrack != NULL && mSample != 0) {
1025         uint32_t loopEnd = mSample->size()/mNumChannels/
1026             ((mSample->format() == AUDIO_FORMAT_PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
1027         mAudioTrack->setLoop(0, loopEnd, loop);
1028         mLoop = loop;
1029     }
1030 }
1031 
~SoundChannel()1032 SoundChannel::~SoundChannel()
1033 {
1034     ALOGV("SoundChannel destructor %p", this);
1035     {
1036         Mutex::Autolock lock(&mLock);
1037         clearNextEvent();
1038         doStop_l();
1039     }
1040     // do not call AudioTrack destructor with mLock held as it will wait for the AudioTrack
1041     // callback thread to exit which may need to execute process() and acquire the mLock.
1042     mAudioTrack.clear();
1043 }
1044 
dump()1045 void SoundChannel::dump()
1046 {
1047     ALOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d",
1048             mState, mChannelID, mNumChannels, mPos, mPriority, mLoop);
1049 }
1050 
set(const sp<Sample> & sample,int channelID,float leftVolume,float rightVolume,int priority,int loop,float rate)1051 void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
1052             float rightVolume, int priority, int loop, float rate)
1053 {
1054     mSample = sample;
1055     mChannelID = channelID;
1056     mLeftVolume = leftVolume;
1057     mRightVolume = rightVolume;
1058     mPriority = priority;
1059     mLoop = loop;
1060     mRate =rate;
1061 }
1062 
1063 } // end namespace android
1064