• 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 <chrono>
21 #include <inttypes.h>
22 #include <thread>
23 #include <utils/Log.h>
24 
25 #define USE_SHARED_MEM_BUFFER
26 
27 #include <media/AudioTrack.h>
28 #include "SoundPool.h"
29 #include "SoundPoolThread.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,audio_channel_mask_t * channelMask,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         audio_channel_mask_t *channelMask, sp<MemoryHeapBase> heap,
517         size_t *memsize) {
518 
519     ALOGV("fd %d, offset %" PRId64 ", size %" PRId64, fd, offset, length);
520     AMediaExtractor *ex = AMediaExtractor_new();
521     status_t err = AMediaExtractor_setDataSourceFd(ex, fd, offset, length);
522 
523     if (err != AMEDIA_OK) {
524         AMediaExtractor_delete(ex);
525         return err;
526     }
527 
528     *audioFormat = AUDIO_FORMAT_PCM_16_BIT;
529 
530     size_t numTracks = AMediaExtractor_getTrackCount(ex);
531     for (size_t i = 0; i < numTracks; i++) {
532         AMediaFormat *format = AMediaExtractor_getTrackFormat(ex, i);
533         const char *mime;
534         if (!AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime)) {
535             AMediaExtractor_delete(ex);
536             AMediaFormat_delete(format);
537             return UNKNOWN_ERROR;
538         }
539         if (strncmp(mime, "audio/", 6) == 0) {
540 
541             AMediaCodec *codec = AMediaCodec_createDecoderByType(mime);
542             if (codec == NULL
543                     || AMediaCodec_configure(codec, format,
544                             NULL /* window */, NULL /* drm */, 0 /* flags */) != AMEDIA_OK
545                     || AMediaCodec_start(codec) != AMEDIA_OK
546                     || AMediaExtractor_selectTrack(ex, i) != AMEDIA_OK) {
547                 AMediaExtractor_delete(ex);
548                 AMediaCodec_delete(codec);
549                 AMediaFormat_delete(format);
550                 return UNKNOWN_ERROR;
551             }
552 
553             bool sawInputEOS = false;
554             bool sawOutputEOS = false;
555             uint8_t* writePos = static_cast<uint8_t*>(heap->getBase());
556             size_t available = heap->getSize();
557             size_t written = 0;
558 
559             AMediaFormat_delete(format);
560             format = AMediaCodec_getOutputFormat(codec);
561 
562             while (!sawOutputEOS) {
563                 if (!sawInputEOS) {
564                     ssize_t bufidx = AMediaCodec_dequeueInputBuffer(codec, 5000);
565                     ALOGV("input buffer %zd", bufidx);
566                     if (bufidx >= 0) {
567                         size_t bufsize;
568                         uint8_t *buf = AMediaCodec_getInputBuffer(codec, bufidx, &bufsize);
569                         if (buf == nullptr) {
570                             ALOGE("AMediaCodec_getInputBuffer returned nullptr, short decode");
571                             break;
572                         }
573                         int sampleSize = AMediaExtractor_readSampleData(ex, buf, bufsize);
574                         ALOGV("read %d", sampleSize);
575                         if (sampleSize < 0) {
576                             sampleSize = 0;
577                             sawInputEOS = true;
578                             ALOGV("EOS");
579                         }
580                         int64_t presentationTimeUs = AMediaExtractor_getSampleTime(ex);
581 
582                         media_status_t mstatus = AMediaCodec_queueInputBuffer(codec, bufidx,
583                                 0 /* offset */, sampleSize, presentationTimeUs,
584                                 sawInputEOS ? AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM : 0);
585                         if (mstatus != AMEDIA_OK) {
586                             // AMEDIA_ERROR_UNKNOWN == { -ERANGE -EINVAL -EACCES }
587                             ALOGE("AMediaCodec_queueInputBuffer returned status %d, short decode",
588                                     (int)mstatus);
589                             break;
590                         }
591                         (void)AMediaExtractor_advance(ex);
592                     }
593                 }
594 
595                 AMediaCodecBufferInfo info;
596                 int status = AMediaCodec_dequeueOutputBuffer(codec, &info, 1);
597                 ALOGV("dequeueoutput returned: %d", status);
598                 if (status >= 0) {
599                     if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) {
600                         ALOGV("output EOS");
601                         sawOutputEOS = true;
602                     }
603                     ALOGV("got decoded buffer size %d", info.size);
604 
605                     uint8_t *buf = AMediaCodec_getOutputBuffer(codec, status, NULL /* out_size */);
606                     if (buf == nullptr) {
607                         ALOGE("AMediaCodec_getOutputBuffer returned nullptr, short decode");
608                         break;
609                     }
610                     size_t dataSize = info.size;
611                     if (dataSize > available) {
612                         dataSize = available;
613                     }
614                     memcpy(writePos, buf + info.offset, dataSize);
615                     writePos += dataSize;
616                     written += dataSize;
617                     available -= dataSize;
618                     media_status_t mstatus = AMediaCodec_releaseOutputBuffer(
619                             codec, status, false /* render */);
620                     if (mstatus != AMEDIA_OK) {
621                         // AMEDIA_ERROR_UNKNOWN == { -ERANGE -EINVAL -EACCES }
622                         ALOGE("AMediaCodec_releaseOutputBuffer returned status %d, short decode",
623                                 (int)mstatus);
624                         break;
625                     }
626                     if (available == 0) {
627                         // there might be more data, but there's no space for it
628                         sawOutputEOS = true;
629                     }
630                 } else if (status == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
631                     ALOGV("output buffers changed");
632                 } else if (status == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
633                     AMediaFormat_delete(format);
634                     format = AMediaCodec_getOutputFormat(codec);
635                     ALOGV("format changed to: %s", AMediaFormat_toString(format));
636                 } else if (status == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
637                     ALOGV("no output buffer right now");
638                 } else if (status <= AMEDIA_ERROR_BASE) {
639                     ALOGE("decode error: %d", status);
640                     break;
641                 } else {
642                     ALOGV("unexpected info code: %d", status);
643                 }
644             }
645 
646             (void)AMediaCodec_stop(codec);
647             (void)AMediaCodec_delete(codec);
648             (void)AMediaExtractor_delete(ex);
649             if (!AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, (int32_t*) rate) ||
650                     !AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, numChannels)) {
651                 (void)AMediaFormat_delete(format);
652                 return UNKNOWN_ERROR;
653             }
654             if (!AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_MASK,
655                     (int32_t*) channelMask)) {
656                 *channelMask = AUDIO_CHANNEL_NONE;
657             }
658             (void)AMediaFormat_delete(format);
659             *memsize = written;
660             return OK;
661         }
662         (void)AMediaFormat_delete(format);
663     }
664     (void)AMediaExtractor_delete(ex);
665     return UNKNOWN_ERROR;
666 }
667 
doLoad()668 status_t Sample::doLoad()
669 {
670     uint32_t sampleRate;
671     int numChannels;
672     audio_format_t format;
673     audio_channel_mask_t channelMask;
674     status_t status;
675     mHeap = new MemoryHeapBase(kDefaultHeapSize);
676 
677     ALOGV("Start decode");
678     status = decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format,
679                     &channelMask, mHeap, &mSize);
680     ALOGV("close(%d)", mFd);
681     ::close(mFd);
682     mFd = -1;
683     if (status != NO_ERROR) {
684         ALOGE("Unable to load sample");
685         goto error;
686     }
687     ALOGV("pointer = %p, size = %zu, sampleRate = %u, numChannels = %d",
688           mHeap->getBase(), mSize, sampleRate, numChannels);
689 
690     if (sampleRate > kMaxSampleRate) {
691        ALOGE("Sample rate (%u) out of range", sampleRate);
692        status = BAD_VALUE;
693        goto error;
694     }
695 
696     if ((numChannels < 1) || (numChannels > FCC_8)) {
697         ALOGE("Sample channel count (%d) out of range", numChannels);
698         status = BAD_VALUE;
699         goto error;
700     }
701 
702     mData = new MemoryBase(mHeap, 0, mSize);
703     mSampleRate = sampleRate;
704     mNumChannels = numChannels;
705     mFormat = format;
706     mChannelMask = channelMask;
707     mState = READY;
708     return NO_ERROR;
709 
710 error:
711     mHeap.clear();
712     return status;
713 }
714 
715 
init(SoundPool * soundPool)716 void SoundChannel::init(SoundPool* soundPool)
717 {
718     mSoundPool = soundPool;
719     mPrevSampleID = -1;
720 }
721 
722 // call with sound pool lock held
play(const sp<Sample> & sample,int nextChannelID,float leftVolume,float rightVolume,int priority,int loop,float rate)723 void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
724         float rightVolume, int priority, int loop, float rate)
725 {
726     sp<AudioTrack> oldTrack;
727     sp<AudioTrack> newTrack;
728     status_t status = NO_ERROR;
729 
730     { // scope for the lock
731         Mutex::Autolock lock(&mLock);
732 
733         ALOGV("SoundChannel::play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f,"
734                 " priority=%d, loop=%d, rate=%f",
735                 this, sample->sampleID(), nextChannelID, leftVolume, rightVolume,
736                 priority, loop, rate);
737 
738         // if not idle, this voice is being stolen
739         if (mState != IDLE) {
740             ALOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
741             mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
742             stop_l();
743             return;
744         }
745 
746         // initialize track
747         size_t afFrameCount;
748         uint32_t afSampleRate;
749         audio_stream_type_t streamType =
750                 AudioSystem::attributesToStreamType(*mSoundPool->attributes());
751         if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
752             afFrameCount = kDefaultFrameCount;
753         }
754         if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
755             afSampleRate = kDefaultSampleRate;
756         }
757         int numChannels = sample->numChannels();
758         uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
759         size_t frameCount = 0;
760 
761         if (loop) {
762             const audio_format_t format = sample->format();
763             const size_t frameSize = audio_is_linear_pcm(format)
764                     ? numChannels * audio_bytes_per_sample(format) : 1;
765             frameCount = sample->size() / frameSize;
766         }
767 
768 #ifndef USE_SHARED_MEM_BUFFER
769         uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
770         // Ensure minimum audio buffer size in case of short looped sample
771         if(frameCount < totalFrames) {
772             frameCount = totalFrames;
773         }
774 #endif
775 
776         // check if the existing track has the same sample id.
777         if (mAudioTrack != 0 && mPrevSampleID == sample->sampleID()) {
778             // the sample rate may fail to change if the audio track is a fast track.
779             if (mAudioTrack->setSampleRate(sampleRate) == NO_ERROR) {
780                 newTrack = mAudioTrack;
781                 ALOGV("reusing track %p for sample %d", mAudioTrack.get(), sample->sampleID());
782             }
783         }
784         if (newTrack == 0) {
785             // mToggle toggles each time a track is started on a given channel.
786             // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
787             // as callback user data. This enables the detection of callbacks received from the old
788             // audio track while the new one is being started and avoids processing them with
789             // wrong audio audio buffer size  (mAudioBufferSize)
790             unsigned long toggle = mToggle ^ 1;
791             void *userData = (void *)((unsigned long)this | toggle);
792             audio_channel_mask_t sampleChannelMask = sample->channelMask();
793             // When sample contains a not none channel mask, use it as is.
794             // Otherwise, use channel count to calculate channel mask.
795             audio_channel_mask_t channelMask = sampleChannelMask != AUDIO_CHANNEL_NONE
796                     ? sampleChannelMask : audio_channel_out_mask_from_count(numChannels);
797 
798             // do not create a new audio track if current track is compatible with sample parameters
799     #ifdef USE_SHARED_MEM_BUFFER
800             newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
801                     channelMask, sample->getIMemory(), AUDIO_OUTPUT_FLAG_FAST, callback, userData,
802                     0 /*default notification frames*/, AUDIO_SESSION_ALLOCATE,
803                     AudioTrack::TRANSFER_DEFAULT,
804                     NULL /*offloadInfo*/, -1 /*uid*/, -1 /*pid*/, mSoundPool->attributes());
805     #else
806             uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
807             newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
808                     channelMask, frameCount, AUDIO_OUTPUT_FLAG_FAST, callback, userData,
809                     bufferFrames, AUDIO_SESSION_ALLOCATE, AudioTrack::TRANSFER_DEFAULT,
810                     NULL /*offloadInfo*/, -1 /*uid*/, -1 /*pid*/, mSoundPool->attributes());
811     #endif
812             oldTrack = mAudioTrack;
813             status = newTrack->initCheck();
814             if (status != NO_ERROR) {
815                 ALOGE("Error creating AudioTrack");
816                 // newTrack goes out of scope, so reference count drops to zero
817                 goto exit;
818             }
819             // From now on, AudioTrack callbacks received with previous toggle value will be ignored.
820             mToggle = toggle;
821             mAudioTrack = newTrack;
822             ALOGV("using new track %p for sample %d", newTrack.get(), sample->sampleID());
823         }
824         if (mMuted) {
825             newTrack->setVolume(0.0f, 0.0f);
826         } else {
827             newTrack->setVolume(leftVolume, rightVolume);
828         }
829         newTrack->setLoop(0, frameCount, loop);
830         mPos = 0;
831         mSample = sample;
832         mChannelID = nextChannelID;
833         mPriority = priority;
834         mLoop = loop;
835         mLeftVolume = leftVolume;
836         mRightVolume = rightVolume;
837         mNumChannels = numChannels;
838         mRate = rate;
839         clearNextEvent();
840         mState = PLAYING;
841         mAudioTrack->start();
842         mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
843     }
844 
845 exit:
846     ALOGV("delete oldTrack %p", oldTrack.get());
847     if (status != NO_ERROR) {
848         mAudioTrack.clear();
849     }
850 }
851 
nextEvent()852 void SoundChannel::nextEvent()
853 {
854     sp<Sample> sample;
855     int nextChannelID;
856     float leftVolume;
857     float rightVolume;
858     int priority;
859     int loop;
860     float rate;
861 
862     // check for valid event
863     {
864         Mutex::Autolock lock(&mLock);
865         nextChannelID = mNextEvent.channelID();
866         if (nextChannelID  == 0) {
867             ALOGV("stolen channel has no event");
868             return;
869         }
870 
871         sample = mNextEvent.sample();
872         leftVolume = mNextEvent.leftVolume();
873         rightVolume = mNextEvent.rightVolume();
874         priority = mNextEvent.priority();
875         loop = mNextEvent.loop();
876         rate = mNextEvent.rate();
877     }
878 
879     ALOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
880     play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
881 }
882 
callback(int event,void * user,void * info)883 void SoundChannel::callback(int event, void* user, void *info)
884 {
885     SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
886 
887     channel->process(event, info, (unsigned long)user & 1);
888 }
889 
process(int event,void * info,unsigned long toggle)890 void SoundChannel::process(int event, void *info, unsigned long toggle)
891 {
892     //ALOGV("process(%d)", mChannelID);
893 
894     Mutex::Autolock lock(&mLock);
895 
896     AudioTrack::Buffer* b = NULL;
897     if (event == AudioTrack::EVENT_MORE_DATA) {
898        b = static_cast<AudioTrack::Buffer *>(info);
899     }
900 
901     if (mToggle != toggle) {
902         ALOGV("process wrong toggle %p channel %d", this, mChannelID);
903         if (b != NULL) {
904             b->size = 0;
905         }
906         return;
907     }
908 
909     sp<Sample> sample = mSample;
910 
911 //    ALOGV("SoundChannel::process event %d", event);
912 
913     if (event == AudioTrack::EVENT_MORE_DATA) {
914 
915         // check for stop state
916         if (b->size == 0) return;
917 
918         if (mState == IDLE) {
919             b->size = 0;
920             return;
921         }
922 
923         if (sample != 0) {
924             // fill buffer
925             uint8_t* q = (uint8_t*) b->i8;
926             size_t count = 0;
927 
928             if (mPos < (int)sample->size()) {
929                 uint8_t* p = sample->data() + mPos;
930                 count = sample->size() - mPos;
931                 if (count > b->size) {
932                     count = b->size;
933                 }
934                 memcpy(q, p, count);
935 //              ALOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size,
936 //                      count);
937             } else if (mPos < mAudioBufferSize) {
938                 count = mAudioBufferSize - mPos;
939                 if (count > b->size) {
940                     count = b->size;
941                 }
942                 memset(q, 0, count);
943 //              ALOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
944             }
945 
946             mPos += count;
947             b->size = count;
948             //ALOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
949         }
950     } else if (event == AudioTrack::EVENT_UNDERRUN || event == AudioTrack::EVENT_BUFFER_END) {
951         ALOGV("process %p channel %d event %s",
952               this, mChannelID, (event == AudioTrack::EVENT_UNDERRUN) ? "UNDERRUN" :
953                       "BUFFER_END");
954         mSoundPool->addToStopList(this);
955     } else if (event == AudioTrack::EVENT_LOOP_END) {
956         ALOGV("End loop %p channel %d", this, mChannelID);
957     } else if (event == AudioTrack::EVENT_NEW_IAUDIOTRACK) {
958         ALOGV("process %p channel %d NEW_IAUDIOTRACK", this, mChannelID);
959     } else {
960         ALOGW("SoundChannel::process unexpected event %d", event);
961     }
962 }
963 
964 
965 // call with lock held
doStop_l()966 bool SoundChannel::doStop_l()
967 {
968     if (mState != IDLE) {
969         setVolume_l(0, 0);
970         ALOGV("stop");
971         // Since we're forcibly halting the previously playing content,
972         // we sleep here to ensure the volume is ramped down before we stop the track.
973         // Ideally the sleep time is the mixer period, or an approximation thereof
974         // (Fast vs Normal tracks are different).
975         // TODO: consider pausing instead of stop here.
976         std::this_thread::sleep_for(std::chrono::milliseconds(20));
977         mAudioTrack->stop();
978         mPrevSampleID = mSample->sampleID();
979         mSample.clear();
980         mState = IDLE;
981         mPriority = IDLE_PRIORITY;
982         return true;
983     }
984     return false;
985 }
986 
987 // call with lock held and sound pool lock held
stop_l()988 void SoundChannel::stop_l()
989 {
990     if (doStop_l()) {
991         mSoundPool->done_l(this);
992     }
993 }
994 
995 // call with sound pool lock held
stop()996 void SoundChannel::stop()
997 {
998     bool stopped;
999     {
1000         Mutex::Autolock lock(&mLock);
1001         stopped = doStop_l();
1002     }
1003 
1004     if (stopped) {
1005         mSoundPool->done_l(this);
1006     }
1007 }
1008 
1009 //FIXME: Pause is a little broken right now
pause()1010 void SoundChannel::pause()
1011 {
1012     Mutex::Autolock lock(&mLock);
1013     if (mState == PLAYING) {
1014         ALOGV("pause track");
1015         mState = PAUSED;
1016         mAudioTrack->pause();
1017     }
1018 }
1019 
autoPause()1020 void SoundChannel::autoPause()
1021 {
1022     Mutex::Autolock lock(&mLock);
1023     if (mState == PLAYING) {
1024         ALOGV("pause track");
1025         mState = PAUSED;
1026         mAutoPaused = true;
1027         mAudioTrack->pause();
1028     }
1029 }
1030 
resume()1031 void SoundChannel::resume()
1032 {
1033     Mutex::Autolock lock(&mLock);
1034     if (mState == PAUSED) {
1035         ALOGV("resume track");
1036         mState = PLAYING;
1037         mAutoPaused = false;
1038         mAudioTrack->start();
1039     }
1040 }
1041 
autoResume()1042 void SoundChannel::autoResume()
1043 {
1044     Mutex::Autolock lock(&mLock);
1045     if (mAutoPaused && (mState == PAUSED)) {
1046         ALOGV("resume track");
1047         mState = PLAYING;
1048         mAutoPaused = false;
1049         mAudioTrack->start();
1050     }
1051 }
1052 
setRate(float rate)1053 void SoundChannel::setRate(float rate)
1054 {
1055     Mutex::Autolock lock(&mLock);
1056     if (mAudioTrack != NULL && mSample != 0) {
1057         uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5);
1058         mAudioTrack->setSampleRate(sampleRate);
1059         mRate = rate;
1060     }
1061 }
1062 
1063 // call with lock held
setVolume_l(float leftVolume,float rightVolume)1064 void SoundChannel::setVolume_l(float leftVolume, float rightVolume)
1065 {
1066     mLeftVolume = leftVolume;
1067     mRightVolume = rightVolume;
1068     if (mAudioTrack != NULL && !mMuted)
1069         mAudioTrack->setVolume(leftVolume, rightVolume);
1070 }
1071 
setVolume(float leftVolume,float rightVolume)1072 void SoundChannel::setVolume(float leftVolume, float rightVolume)
1073 {
1074     Mutex::Autolock lock(&mLock);
1075     setVolume_l(leftVolume, rightVolume);
1076 }
1077 
mute(bool muting)1078 void SoundChannel::mute(bool muting)
1079 {
1080     Mutex::Autolock lock(&mLock);
1081     mMuted = muting;
1082     if (mAudioTrack != NULL) {
1083         if (mMuted) {
1084             mAudioTrack->setVolume(0.0f, 0.0f);
1085         } else {
1086             mAudioTrack->setVolume(mLeftVolume, mRightVolume);
1087         }
1088     }
1089 }
1090 
setLoop(int loop)1091 void SoundChannel::setLoop(int loop)
1092 {
1093     Mutex::Autolock lock(&mLock);
1094     if (mAudioTrack != NULL && mSample != 0) {
1095         uint32_t loopEnd = mSample->size()/mNumChannels/
1096             ((mSample->format() == AUDIO_FORMAT_PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
1097         mAudioTrack->setLoop(0, loopEnd, loop);
1098         mLoop = loop;
1099     }
1100 }
1101 
~SoundChannel()1102 SoundChannel::~SoundChannel()
1103 {
1104     ALOGV("SoundChannel destructor %p", this);
1105     {
1106         Mutex::Autolock lock(&mLock);
1107         clearNextEvent();
1108         doStop_l();
1109     }
1110     // do not call AudioTrack destructor with mLock held as it will wait for the AudioTrack
1111     // callback thread to exit which may need to execute process() and acquire the mLock.
1112     mAudioTrack.clear();
1113 }
1114 
dump()1115 void SoundChannel::dump()
1116 {
1117     ALOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d",
1118             mState, mChannelID, mNumChannels, mPos, mPriority, mLoop);
1119 }
1120 
set(const sp<Sample> & sample,int channelID,float leftVolume,float rightVolume,int priority,int loop,float rate)1121 void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
1122             float rightVolume, int priority, int loop, float rate)
1123 {
1124     mSample = sample;
1125     mChannelID = channelID;
1126     mLeftVolume = leftVolume;
1127     mRightVolume = rightVolume;
1128     mPriority = priority;
1129     mLoop = loop;
1130     mRate =rate;
1131 }
1132 
1133 } // end namespace android
1134