2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "SoundPool"
19 #include <utils/Log.h>
21 //#define USE_SHARED_MEM_BUFFER
23 // XXX needed for timing latency
24 #include <utils/Timers.h>
26 #include <sys/resource.h>
27 #include <media/AudioTrack.h>
28 #include <media/mediaplayer.h>
30 #include "SoundPool.h"
31 #include "SoundPoolThread.h"
36 int kDefaultBufferCount = 4;
37 uint32_t kMaxSampleRate = 48000;
38 uint32_t kDefaultSampleRate = 44100;
39 uint32_t kDefaultFrameCount = 1200;
41 SoundPool::SoundPool(int maxChannels, int streamType, int srcQuality)
43 LOGV("SoundPool constructor: maxChannels=%d, streamType=%d, srcQuality=%d",
44 maxChannels, streamType, srcQuality);
47 mMaxChannels = maxChannels;
48 if (mMaxChannels < 1) {
51 else if (mMaxChannels > 32) {
54 LOGW_IF(maxChannels != mMaxChannels, "App requested %d channels", maxChannels);
58 mStreamType = streamType;
59 mSrcQuality = srcQuality;
67 mChannelPool = new SoundChannel[mMaxChannels];
68 for (int i = 0; i < mMaxChannels; ++i) {
69 mChannelPool[i].init(this);
70 mChannels.push_back(&mChannelPool[i]);
73 // start decode thread
77 SoundPool::~SoundPool()
79 LOGV("SoundPool destructor");
80 mDecodeThread->quit();
83 Mutex::Autolock lock(&mLock);
86 delete [] mChannelPool;
89 LOGV("clear samples");
96 void SoundPool::addToRestartList(SoundChannel* channel)
98 Mutex::Autolock lock(&mRestartLock);
99 mRestart.push_back(channel);
103 int SoundPool::beginThread(void* arg)
105 SoundPool* p = (SoundPool*)arg;
113 mCondition.wait(mRestartLock);
117 while (!mRestart.empty()) {
118 SoundChannel* channel;
119 LOGV("Getting channel from list");
120 List<SoundChannel*>::iterator iter = mRestart.begin();
122 mRestart.erase(iter);
123 if (channel) channel->nextEvent();
130 mRestartLock.unlock();
135 void SoundPool::quit()
140 mCondition.wait(mRestartLock);
141 LOGV("return from quit");
142 mRestartLock.unlock();
145 bool SoundPool::startThreads()
147 createThreadEtc(beginThread, this, "SoundPool");
148 if (mDecodeThread == NULL)
149 mDecodeThread = new SoundPoolThread(this);
150 return mDecodeThread != NULL;
153 SoundChannel* SoundPool::findChannel(int channelID)
155 for (int i = 0; i < mMaxChannels; ++i) {
156 if (mChannelPool[i].channelID() == channelID) {
157 return &mChannelPool[i];
163 SoundChannel* SoundPool::findNextChannel(int channelID)
165 for (int i = 0; i < mMaxChannels; ++i) {
166 if (mChannelPool[i].nextChannelID() == channelID) {
167 return &mChannelPool[i];
173 int SoundPool::load(const char* path, int priority)
175 LOGV("load: path=%s, priority=%d", path, priority);
176 Mutex::Autolock lock(&mLock);
177 sp<Sample> sample = new Sample(++mNextSampleID, path);
178 mSamples.add(sample->sampleID(), sample);
180 return sample->sampleID();
183 int SoundPool::load(int fd, int64_t offset, int64_t length, int priority)
185 LOGV("load: fd=%d, offset=%lld, length=%lld, priority=%d",
186 fd, offset, length, priority);
187 Mutex::Autolock lock(&mLock);
188 sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length);
189 mSamples.add(sample->sampleID(), sample);
191 return sample->sampleID();
194 void SoundPool::doLoad(sp<Sample>& sample)
196 LOGV("doLoad: loading sample sampleID=%d", sample->sampleID());
198 mDecodeThread->loadSample(sample->sampleID());
201 bool SoundPool::unload(int sampleID)
203 LOGV("unload: sampleID=%d", sampleID);
204 Mutex::Autolock lock(&mLock);
205 return mSamples.removeItem(sampleID);
208 int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
209 int priority, int loop, float rate)
211 LOGV("sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
212 sampleID, leftVolume, rightVolume, priority, loop, rate);
214 SoundChannel* channel;
219 Mutex::Autolock lock(&mLock);
222 sample = findSample(sampleID);
223 if ((sample == 0) || (sample->state() != Sample::READY)) {
224 LOGW(" sample %d not READY", sampleID);
230 // allocate a channel
231 channel = allocateChannel(priority);
233 // no channel allocated - return 0
235 LOGV("No channel allocated");
239 channelID = ++mNextChannelID;
242 LOGV("channel state = %d", channel->state());
243 channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
247 SoundChannel* SoundPool::allocateChannel(int priority)
249 List<SoundChannel*>::iterator iter;
250 SoundChannel* channel = NULL;
252 // allocate a channel
253 if (!mChannels.empty()) {
254 iter = mChannels.begin();
255 if (priority >= (*iter)->priority()) {
257 mChannels.erase(iter);
258 LOGV("Allocated active channel");
262 // update priority and put it back in the list
264 channel->setPriority(priority);
265 for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
266 if (priority < (*iter)->priority()) {
270 mChannels.insert(iter, channel);
275 // move a channel from its current position to the front of the list
276 void SoundPool::moveToFront(SoundChannel* channel)
278 for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
279 if (*iter == channel) {
280 mChannels.erase(iter);
281 mChannels.push_front(channel);
287 void SoundPool::pause(int channelID)
289 LOGV("pause(%d)", channelID);
290 Mutex::Autolock lock(&mLock);
291 SoundChannel* channel = findChannel(channelID);
297 void SoundPool::autoPause()
300 Mutex::Autolock lock(&mLock);
301 for (int i = 0; i < mMaxChannels; ++i) {
302 SoundChannel* channel = &mChannelPool[i];
303 channel->autoPause();
307 void SoundPool::resume(int channelID)
309 LOGV("resume(%d)", channelID);
310 Mutex::Autolock lock(&mLock);
311 SoundChannel* channel = findChannel(channelID);
317 void SoundPool::autoResume()
319 LOGV("autoResume()");
320 Mutex::Autolock lock(&mLock);
321 for (int i = 0; i < mMaxChannels; ++i) {
322 SoundChannel* channel = &mChannelPool[i];
323 channel->autoResume();
327 void SoundPool::stop(int channelID)
329 LOGV("stop(%d)", channelID);
330 Mutex::Autolock lock(&mLock);
331 SoundChannel* channel = findChannel(channelID);
335 channel = findNextChannel(channelID);
337 channel->clearNextEvent();
341 void SoundPool::setVolume(int channelID, float leftVolume, float rightVolume)
343 Mutex::Autolock lock(&mLock);
344 SoundChannel* channel = findChannel(channelID);
346 channel->setVolume(leftVolume, rightVolume);
350 void SoundPool::setPriority(int channelID, int priority)
352 LOGV("setPriority(%d, %d)", channelID, priority);
353 Mutex::Autolock lock(&mLock);
354 SoundChannel* channel = findChannel(channelID);
356 channel->setPriority(priority);
360 void SoundPool::setLoop(int channelID, int loop)
362 LOGV("setLoop(%d, %d)", channelID, loop);
363 Mutex::Autolock lock(&mLock);
364 SoundChannel* channel = findChannel(channelID);
366 channel->setLoop(loop);
370 void SoundPool::setRate(int channelID, float rate)
372 LOGV("setRate(%d, %f)", channelID, rate);
373 Mutex::Autolock lock(&mLock);
374 SoundChannel* channel = findChannel(channelID);
376 channel->setRate(rate);
380 // call with lock held
381 void SoundPool::done(SoundChannel* channel)
383 LOGV("done(%d)", channel->channelID());
385 // if "stolen", play next event
386 if (channel->nextChannelID() != 0) {
387 LOGV("add to restart list");
388 addToRestartList(channel);
391 // return to idle state
393 LOGV("move to front");
394 moveToFront(channel);
398 void SoundPool::setCallback(SoundPoolCallback* callback, void* user)
400 Mutex::Autolock lock(&mCallbackLock);
401 mCallback = callback;
405 void SoundPool::notify(SoundPoolEvent event)
407 Mutex::Autolock lock(&mCallbackLock);
408 if (mCallback != NULL) {
409 mCallback(event, this, mUserData);
413 void SoundPool::dump()
415 for (int i = 0; i < mMaxChannels; ++i) {
416 mChannelPool[i].dump();
421 Sample::Sample(int sampleID, const char* url)
424 mSampleID = sampleID;
426 LOGV("create sampleID=%d, url=%s", mSampleID, mUrl);
429 Sample::Sample(int sampleID, int fd, int64_t offset, int64_t length)
432 mSampleID = sampleID;
436 LOGV("create sampleID=%d, fd=%d, offset=%lld, length=%lld", mSampleID, mFd, mLength, mOffset);
454 LOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd);
456 LOGV("close(%d)", mFd);
463 status_t Sample::doLoad()
469 LOGV("Start decode");
471 p = MediaPlayer::decode(mUrl, &sampleRate, &numChannels, &format);
473 p = MediaPlayer::decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format);
474 LOGV("close(%d)", mFd);
479 LOGE("Unable to load sample: %s", mUrl);
482 LOGV("pointer = %p, size = %u, sampleRate = %u, numChannels = %d",
483 p->pointer(), p->size(), sampleRate, numChannels);
485 if (sampleRate > kMaxSampleRate) {
486 LOGE("Sample rate (%u) out of range", sampleRate);
490 if ((numChannels < 1) || (numChannels > 2)) {
491 LOGE("Sample channel count (%d) out of range", numChannels);
495 //_dumpBuffer(p->pointer(), p->size());
496 uint8_t* q = static_cast<uint8_t*>(p->pointer()) + p->size() - 10;
497 //_dumpBuffer(q, 10, 10, false);
501 mSampleRate = sampleRate;
502 mNumChannels = numChannels;
509 void SoundChannel::init(SoundPool* soundPool)
511 mSoundPool = soundPool;
514 void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
515 float rightVolume, int priority, int loop, float rate)
517 AudioTrack* oldTrack;
519 LOGV("play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
520 this, sample->sampleID(), nextChannelID, leftVolume, rightVolume, priority, loop, rate);
522 // if not idle, this voice is being stolen
523 if (mState != IDLE) {
524 LOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
525 mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
533 int streamType = mSoundPool->streamType();
534 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
535 afFrameCount = kDefaultFrameCount;
537 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
538 afSampleRate = kDefaultSampleRate;
540 int numChannels = sample->numChannels();
541 uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
542 uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
543 uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
544 uint32_t frameCount = 0;
547 frameCount = sample->size()/numChannels/((sample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
550 #ifndef USE_SHARED_MEM_BUFFER
551 // Ensure minimum audio buffer size in case of short looped sample
552 if(frameCount < totalFrames) {
553 frameCount = totalFrames;
557 AudioTrack* newTrack;
559 // mToggle toggles each time a track is started on a given channel.
560 // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
561 // as callback user data. This enables the detection of callbacks received from the old
562 // audio track while the new one is being started and avoids processing them with
563 // wrong audio audio buffer size (mAudioBufferSize)
564 unsigned long toggle = mToggle ^ 1;
565 void *userData = (void *)((unsigned long)this | toggle);
566 uint32_t channels = (numChannels == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO;
568 #ifdef USE_SHARED_MEM_BUFFER
569 newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
570 channels, sample->getIMemory(), 0, callback, userData);
572 newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
573 channels, frameCount, 0, callback, userData, bufferFrames);
575 if (newTrack->initCheck() != NO_ERROR) {
576 LOGE("Error creating AudioTrack");
580 LOGV("setVolume %p", newTrack);
581 newTrack->setVolume(leftVolume, rightVolume);
582 newTrack->setLoop(0, frameCount, loop);
585 Mutex::Autolock lock(&mLock);
586 // From now on, AudioTrack callbacks recevieved with previous toggle value will be ignored.
588 oldTrack = mAudioTrack;
589 mAudioTrack = newTrack;
592 mChannelID = nextChannelID;
593 mPriority = priority;
595 mLeftVolume = leftVolume;
596 mRightVolume = rightVolume;
597 mNumChannels = numChannels;
601 mAudioTrack->start();
602 mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
605 LOGV("delete oldTrack %p", oldTrack);
609 void SoundChannel::nextEvent()
619 // check for valid event
621 Mutex::Autolock lock(&mLock);
622 nextChannelID = mNextEvent.channelID();
623 if (nextChannelID == 0) {
624 LOGV("stolen channel has no event");
628 sample = mNextEvent.sample();
629 leftVolume = mNextEvent.leftVolume();
630 rightVolume = mNextEvent.rightVolume();
631 priority = mNextEvent.priority();
632 loop = mNextEvent.loop();
633 rate = mNextEvent.rate();
636 LOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
637 play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
640 void SoundChannel::callback(int event, void* user, void *info)
642 unsigned long toggle = (unsigned long)user & 1;
643 SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
645 if (channel->mToggle != toggle) {
646 LOGV("callback with wrong toggle");
649 channel->process(event, info);
652 void SoundChannel::process(int event, void *info)
654 //LOGV("process(%d)", mChannelID);
655 sp<Sample> sample = mSample;
657 // LOGV("SoundChannel::process event %d", event);
659 if (event == AudioTrack::EVENT_MORE_DATA) {
660 AudioTrack::Buffer* b = static_cast<AudioTrack::Buffer *>(info);
662 // check for stop state
663 if (b->size == 0) return;
667 uint8_t* q = (uint8_t*) b->i8;
670 if (mPos < (int)sample->size()) {
671 uint8_t* p = sample->data() + mPos;
672 count = sample->size() - mPos;
673 if (count > b->size) {
677 LOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size, count);
678 } else if (mPos < mAudioBufferSize) {
679 count = mAudioBufferSize - mPos;
680 if (count > b->size) {
684 LOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
689 //LOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
691 } else if (event == AudioTrack::EVENT_UNDERRUN) {
692 LOGV("stopping track");
694 } else if (event == AudioTrack::EVENT_LOOP_END) {
695 LOGV("End loop: %d", *(int *)info);
700 // call with lock held
701 void SoundChannel::stop_l()
703 if (mState != IDLE) {
709 mPriority = IDLE_PRIORITY;
713 void SoundChannel::stop()
716 Mutex::Autolock lock(&mLock);
719 mSoundPool->done(this);
722 //FIXME: Pause is a little broken right now
723 void SoundChannel::pause()
725 Mutex::Autolock lock(&mLock);
726 if (mState == PLAYING) {
729 mAudioTrack->pause();
733 void SoundChannel::autoPause()
735 Mutex::Autolock lock(&mLock);
736 if (mState == PLAYING) {
740 mAudioTrack->pause();
744 void SoundChannel::resume()
746 Mutex::Autolock lock(&mLock);
747 if (mState == PAUSED) {
748 LOGV("resume track");
751 mAudioTrack->start();
755 void SoundChannel::autoResume()
757 Mutex::Autolock lock(&mLock);
758 if (mAutoPaused && (mState == PAUSED)) {
759 LOGV("resume track");
762 mAudioTrack->start();
766 void SoundChannel::setRate(float rate)
768 Mutex::Autolock lock(&mLock);
769 if (mAudioTrack != 0 && mSample.get() != 0) {
770 uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5);
771 mAudioTrack->setSampleRate(sampleRate);
776 // call with lock held
777 void SoundChannel::setVolume_l(float leftVolume, float rightVolume)
779 mLeftVolume = leftVolume;
780 mRightVolume = rightVolume;
781 if (mAudioTrack != 0) mAudioTrack->setVolume(leftVolume, rightVolume);
784 void SoundChannel::setVolume(float leftVolume, float rightVolume)
786 Mutex::Autolock lock(&mLock);
787 setVolume_l(leftVolume, rightVolume);
790 void SoundChannel::setLoop(int loop)
792 Mutex::Autolock lock(&mLock);
793 if (mAudioTrack != 0 && mSample.get() != 0) {
794 mAudioTrack->setLoop(0, mSample->size()/mNumChannels/((mSample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t)), loop);
799 SoundChannel::~SoundChannel()
801 LOGV("SoundChannel destructor");
811 void SoundChannel::dump()
813 LOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d",
814 mState, mChannelID, mNumChannels, mPos, mPriority, mLoop);
817 void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
818 float rightVolume, int priority, int loop, float rate)
821 mChannelID = channelID;
822 mLeftVolume = leftVolume;
823 mRightVolume = rightVolume;
824 mPriority = priority;
829 } // end namespace android