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