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