SoundPool.cpp revision c0e3ddf8f2f30dc9593f0a1bfd46335823e25d65
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#include <utils/Log.h>
20
21//#define USE_SHARED_MEM_BUFFER
22
23// XXX needed for timing latency
24#include <utils/Timers.h>
25
26#include <sys/resource.h>
27#include <media/AudioTrack.h>
28#include <media/mediaplayer.h>
29
30#include "SoundPool.h"
31#include "SoundPoolThread.h"
32
33namespace android
34{
35
36int kDefaultBufferCount = 4;
37uint32_t kMaxSampleRate = 48000;
38uint32_t kDefaultSampleRate = 44100;
39uint32_t kDefaultFrameCount = 1200;
40
41SoundPool::SoundPool(int maxChannels, int streamType, int srcQuality)
42{
43    LOGV("SoundPool constructor: maxChannels=%d, streamType=%d, srcQuality=%d",
44            maxChannels, streamType, srcQuality);
45
46    // check limits
47    mMaxChannels = maxChannels;
48    if (mMaxChannels < 1) {
49        mMaxChannels = 1;
50    }
51    else if (mMaxChannels > 32) {
52        mMaxChannels = 32;
53    }
54    LOGW_IF(maxChannels != mMaxChannels, "App requested %d channels", maxChannels);
55
56    mQuit = false;
57    mDecodeThread = 0;
58    mStreamType = streamType;
59    mSrcQuality = srcQuality;
60    mAllocated = 0;
61    mNextSampleID = 0;
62    mNextChannelID = 0;
63
64    mChannelPool = new SoundChannel[mMaxChannels];
65    for (int i = 0; i < mMaxChannels; ++i) {
66        mChannelPool[i].init(this);
67        mChannels.push_back(&mChannelPool[i]);
68    }
69
70    // start decode thread
71    startThreads();
72}
73
74SoundPool::~SoundPool()
75{
76    LOGV("SoundPool destructor");
77    mDecodeThread->quit();
78    quit();
79
80    Mutex::Autolock lock(&mLock);
81    mChannels.clear();
82    if (mChannelPool)
83        delete [] mChannelPool;
84
85    // clean up samples
86    LOGV("clear samples");
87    mSamples.clear();
88
89    if (mDecodeThread)
90        delete mDecodeThread;
91}
92
93void SoundPool::addToRestartList(SoundChannel* channel)
94{
95    Mutex::Autolock lock(&mRestartLock);
96    mRestart.push_back(channel);
97    mCondition.signal();
98}
99
100int SoundPool::beginThread(void* arg)
101{
102    SoundPool* p = (SoundPool*)arg;
103    return p->run();
104}
105
106int SoundPool::run()
107{
108    mRestartLock.lock();
109    while (!mQuit) {
110        mCondition.wait(mRestartLock);
111        LOGV("awake");
112        if (mQuit) break;
113
114        while (!mRestart.empty()) {
115            SoundChannel* channel;
116            LOGV("Getting channel from list");
117            List<SoundChannel*>::iterator iter = mRestart.begin();
118            channel = *iter;
119            mRestart.erase(iter);
120            if (channel) channel->nextEvent();
121            if (mQuit) break;
122        }
123    }
124
125    mRestart.clear();
126    mCondition.signal();
127    mRestartLock.unlock();
128    LOGV("goodbye");
129    return 0;
130}
131
132void SoundPool::quit()
133{
134    mRestartLock.lock();
135    mQuit = true;
136    mCondition.signal();
137    mCondition.wait(mRestartLock);
138    LOGV("return from quit");
139    mRestartLock.unlock();
140}
141
142bool SoundPool::startThreads()
143{
144    createThread(beginThread, this);
145    if (mDecodeThread == NULL)
146        mDecodeThread = new SoundPoolThread(this);
147    return mDecodeThread != NULL;
148}
149
150SoundChannel* SoundPool::findChannel(int channelID)
151{
152    for (int i = 0; i < mMaxChannels; ++i) {
153        if (mChannelPool[i].channelID() == channelID) {
154            return &mChannelPool[i];
155        }
156    }
157    return NULL;
158}
159
160SoundChannel* SoundPool::findNextChannel(int channelID)
161{
162    for (int i = 0; i < mMaxChannels; ++i) {
163        if (mChannelPool[i].nextChannelID() == channelID) {
164            return &mChannelPool[i];
165        }
166    }
167    return NULL;
168}
169
170int SoundPool::load(const char* path, int priority)
171{
172    LOGV("load: path=%s, priority=%d", path, priority);
173    Mutex::Autolock lock(&mLock);
174    sp<Sample> sample = new Sample(++mNextSampleID, path);
175    mSamples.add(sample->sampleID(), sample);
176    doLoad(sample);
177    return sample->sampleID();
178}
179
180int SoundPool::load(int fd, int64_t offset, int64_t length, int priority)
181{
182    LOGV("load: fd=%d, offset=%lld, length=%lld, priority=%d",
183            fd, offset, length, priority);
184    Mutex::Autolock lock(&mLock);
185    sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length);
186    mSamples.add(sample->sampleID(), sample);
187    doLoad(sample);
188    return sample->sampleID();
189}
190
191void SoundPool::doLoad(sp<Sample>& sample)
192{
193    LOGV("doLoad: loading sample sampleID=%d", sample->sampleID());
194    sample->startLoad();
195    mDecodeThread->loadSample(sample->sampleID());
196}
197
198bool SoundPool::unload(int sampleID)
199{
200    LOGV("unload: sampleID=%d", sampleID);
201    Mutex::Autolock lock(&mLock);
202    return mSamples.removeItem(sampleID);
203}
204
205int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
206        int priority, int loop, float rate)
207{
208    LOGV("sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
209            sampleID, leftVolume, rightVolume, priority, loop, rate);
210    sp<Sample> sample;
211    SoundChannel* channel;
212    int channelID;
213
214    // scope for lock
215    {
216        Mutex::Autolock lock(&mLock);
217
218        // is sample ready?
219        sample = findSample(sampleID);
220        if ((sample == 0) || (sample->state() != Sample::READY)) {
221            LOGW("  sample %d not READY", sampleID);
222            return 0;
223        }
224
225        dump();
226
227        // allocate a channel
228        channel = allocateChannel(priority);
229
230        // no channel allocated - return 0
231        if (!channel) {
232            LOGV("No channel allocated");
233            return 0;
234        }
235
236        channelID = ++mNextChannelID;
237    }
238
239    LOGV("channel state = %d", channel->state());
240    channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
241    return channelID;
242}
243
244SoundChannel* SoundPool::allocateChannel(int priority)
245{
246    List<SoundChannel*>::iterator iter;
247    SoundChannel* channel = NULL;
248
249    // allocate a channel
250    if (!mChannels.empty()) {
251        iter = mChannels.begin();
252        if (priority >= (*iter)->priority()) {
253            channel = *iter;
254            mChannels.erase(iter);
255            LOGV("Allocated active channel");
256        }
257    }
258
259    // update priority and put it back in the list
260    if (channel) {
261        channel->setPriority(priority);
262        for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
263            if (priority < (*iter)->priority()) {
264                break;
265            }
266        }
267        mChannels.insert(iter, channel);
268    }
269    return channel;
270}
271
272// move a channel from its current position to the front of the list
273void SoundPool::moveToFront(SoundChannel* channel)
274{
275    for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
276        if (*iter == channel) {
277            mChannels.erase(iter);
278            mChannels.push_front(channel);
279            break;
280        }
281    }
282}
283
284void SoundPool::pause(int channelID)
285{
286    LOGV("pause(%d)", channelID);
287    Mutex::Autolock lock(&mLock);
288    SoundChannel* channel = findChannel(channelID);
289    if (channel) {
290        channel->pause();
291    }
292}
293
294void SoundPool::resume(int channelID)
295{
296    LOGV("resume(%d)", channelID);
297    Mutex::Autolock lock(&mLock);
298    SoundChannel* channel = findChannel(channelID);
299    if (channel) {
300        channel->resume();
301    }
302}
303
304void SoundPool::stop(int channelID)
305{
306    LOGV("stop(%d)", channelID);
307    Mutex::Autolock lock(&mLock);
308    SoundChannel* channel = findChannel(channelID);
309    if (channel) {
310        channel->stop();
311    } else {
312        channel = findNextChannel(channelID);
313        if (channel)
314            channel->clearNextEvent();
315    }
316}
317
318void SoundPool::setVolume(int channelID, float leftVolume, float rightVolume)
319{
320    Mutex::Autolock lock(&mLock);
321    SoundChannel* channel = findChannel(channelID);
322    if (channel) {
323        channel->setVolume(leftVolume, rightVolume);
324    }
325}
326
327void SoundPool::setPriority(int channelID, int priority)
328{
329    LOGV("setPriority(%d, %d)", channelID, priority);
330    Mutex::Autolock lock(&mLock);
331    SoundChannel* channel = findChannel(channelID);
332    if (channel) {
333        channel->setPriority(priority);
334    }
335}
336
337void SoundPool::setLoop(int channelID, int loop)
338{
339    LOGV("setLoop(%d, %d)", channelID, loop);
340    Mutex::Autolock lock(&mLock);
341    SoundChannel* channel = findChannel(channelID);
342    if (channel) {
343        channel->setLoop(loop);
344    }
345}
346
347void SoundPool::setRate(int channelID, float rate)
348{
349    LOGV("setRate(%d, %f)", channelID, rate);
350    Mutex::Autolock lock(&mLock);
351    SoundChannel* channel = findChannel(channelID);
352    if (channel) {
353        channel->setRate(rate);
354    }
355}
356
357// call with lock held
358void SoundPool::done(SoundChannel* channel)
359{
360    LOGV("done(%d)", channel->channelID());
361
362    // if "stolen", play next event
363    if (channel->nextChannelID() != 0) {
364        LOGV("add to restart list");
365        addToRestartList(channel);
366    }
367
368    // return to idle state
369    else {
370        LOGV("move to front");
371        moveToFront(channel);
372    }
373}
374
375void SoundPool::dump()
376{
377    for (int i = 0; i < mMaxChannels; ++i) {
378        mChannelPool[i].dump();
379    }
380}
381
382
383Sample::Sample(int sampleID, const char* url)
384{
385    init();
386    mSampleID = sampleID;
387    mUrl = strdup(url);
388    LOGV("create sampleID=%d, url=%s", mSampleID, mUrl);
389}
390
391Sample::Sample(int sampleID, int fd, int64_t offset, int64_t length)
392{
393    init();
394    mSampleID = sampleID;
395    mFd = dup(fd);
396    mOffset = offset;
397    mLength = length;
398    LOGV("create sampleID=%d, fd=%d, offset=%lld, length=%lld", mSampleID, mFd, mLength, mOffset);
399}
400
401void Sample::init()
402{
403    mData = 0;
404    mSize = 0;
405    mRefCount = 0;
406    mSampleID = 0;
407    mState = UNLOADED;
408    mFd = -1;
409    mOffset = 0;
410    mLength = 0;
411    mUrl = 0;
412}
413
414Sample::~Sample()
415{
416    LOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd);
417    if (mFd > 0) {
418        LOGV("close(%d)", mFd);
419        ::close(mFd);
420    }
421    mData.clear();
422    delete mUrl;
423}
424
425void Sample::doLoad()
426{
427    uint32_t sampleRate;
428    int numChannels;
429    int format;
430    sp<IMemory> p;
431    LOGV("Start decode");
432    if (mUrl) {
433        p = MediaPlayer::decode(mUrl, &sampleRate, &numChannels, &format);
434    } else {
435        p = MediaPlayer::decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format);
436        LOGV("close(%d)", mFd);
437        ::close(mFd);
438        mFd = -1;
439    }
440    if (p == 0) {
441        LOGE("Unable to load sample: %s", mUrl);
442        return;
443    }
444    LOGV("pointer = %p, size = %u, sampleRate = %u, numChannels = %d",
445            p->pointer(), p->size(), sampleRate, numChannels);
446
447    if (sampleRate > kMaxSampleRate) {
448       LOGE("Sample rate (%u) out of range", sampleRate);
449       return;
450    }
451
452    if ((numChannels < 1) || (numChannels > 2)) {
453        LOGE("Sample channel count (%d) out of range", numChannels);
454        return;
455    }
456
457    //_dumpBuffer(p->pointer(), p->size());
458    uint8_t* q = static_cast<uint8_t*>(p->pointer()) + p->size() - 10;
459    //_dumpBuffer(q, 10, 10, false);
460
461    mData = p;
462    mSize = p->size();
463    mSampleRate = sampleRate;
464    mNumChannels = numChannels;
465    mFormat = format;
466    mState = READY;
467}
468
469
470void SoundChannel::init(SoundPool* soundPool)
471{
472    mSoundPool = soundPool;
473}
474
475void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
476        float rightVolume, int priority, int loop, float rate)
477{
478    AudioTrack* oldTrack;
479
480    LOGV("play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
481            this, sample->sampleID(), nextChannelID, leftVolume, rightVolume, priority, loop, rate);
482
483    // if not idle, this voice is being stolen
484    if (mState != IDLE) {
485        LOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
486        mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
487        stop();
488        return;
489    }
490
491    // initialize track
492    int afFrameCount;
493    int afSampleRate;
494    int streamType = mSoundPool->streamType();
495    if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
496        afFrameCount = kDefaultFrameCount;
497    }
498    if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
499        afSampleRate = kDefaultSampleRate;
500    }
501    int numChannels = sample->numChannels();
502    uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
503    uint32_t bufferFrames = (afFrameCount * sampleRate) / afSampleRate;
504    uint32_t frameCount = 0;
505
506    if (loop) {
507        frameCount = sample->size()/numChannels/((sample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
508    }
509
510#ifndef USE_SHARED_MEM_BUFFER
511    // Ensure minimum audio buffer size in case of short looped sample
512    if(frameCount < kDefaultBufferCount * bufferFrames) {
513        frameCount = kDefaultBufferCount * bufferFrames;
514    }
515#endif
516
517    AudioTrack* newTrack;
518
519    // mToggle toggles each time a track is started on a given channel.
520    // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
521    // as callback user data. This enables the detection of callbacks received from the old
522    // audio track while the new one is being started and avoids processing them with
523    // wrong audio audio buffer size  (mAudioBufferSize)
524    unsigned long toggle = mToggle ^ 1;
525    void *userData = (void *)((unsigned long)this | toggle);
526    uint32_t channels = (numChannels == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO;
527
528#ifdef USE_SHARED_MEM_BUFFER
529    newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
530            channels, sample->getIMemory(), 0, callback, userData);
531#else
532    newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
533            channels, frameCount, 0, callback, userData, bufferFrames);
534#endif
535    if (newTrack->initCheck() != NO_ERROR) {
536        LOGE("Error creating AudioTrack");
537        delete newTrack;
538        return;
539    }
540    LOGV("setVolume %p", newTrack);
541    newTrack->setVolume(leftVolume, rightVolume);
542    newTrack->setLoop(0, frameCount, loop);
543
544    {
545        Mutex::Autolock lock(&mLock);
546        // From now on, AudioTrack callbacks recevieved with previous toggle value will be ignored.
547        mToggle = toggle;
548        oldTrack = mAudioTrack;
549        mAudioTrack = newTrack;
550        mPos = 0;
551        mSample = sample;
552        mChannelID = nextChannelID;
553        mPriority = priority;
554        mLoop = loop;
555        mLeftVolume = leftVolume;
556        mRightVolume = rightVolume;
557        mNumChannels = numChannels;
558        mRate = rate;
559        clearNextEvent();
560        mState = PLAYING;
561        mAudioTrack->start();
562        mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
563    }
564
565    LOGV("delete oldTrack %p", oldTrack);
566    delete oldTrack;
567}
568
569void SoundChannel::nextEvent()
570{
571    sp<Sample> sample;
572    int nextChannelID;
573    float leftVolume;
574    float rightVolume;
575    int priority;
576    int loop;
577    float rate;
578
579    // check for valid event
580    {
581        Mutex::Autolock lock(&mLock);
582        nextChannelID = mNextEvent.channelID();
583        if (nextChannelID  == 0) {
584            LOGV("stolen channel has no event");
585            return;
586        }
587
588        sample = mNextEvent.sample();
589        leftVolume = mNextEvent.leftVolume();
590        rightVolume = mNextEvent.rightVolume();
591        priority = mNextEvent.priority();
592        loop = mNextEvent.loop();
593        rate = mNextEvent.rate();
594    }
595
596    LOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
597    play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
598}
599
600void SoundChannel::callback(int event, void* user, void *info)
601{
602    unsigned long toggle = (unsigned long)user & 1;
603    SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
604
605    if (channel->mToggle != toggle) {
606        LOGV("callback with wrong toggle");
607        return;
608    }
609    channel->process(event, info);
610}
611
612void SoundChannel::process(int event, void *info)
613{
614    //LOGV("process(%d)", mChannelID);
615    sp<Sample> sample = mSample;
616
617//    LOGV("SoundChannel::process event %d", event);
618
619    if (event == AudioTrack::EVENT_MORE_DATA) {
620       AudioTrack::Buffer* b = static_cast<AudioTrack::Buffer *>(info);
621
622        // check for stop state
623        if (b->size == 0) return;
624
625        if (sample != 0) {
626            // fill buffer
627            uint8_t* q = (uint8_t*) b->i8;
628            size_t count = 0;
629
630            if (mPos < (int)sample->size()) {
631                uint8_t* p = sample->data() + mPos;
632                count = sample->size() - mPos;
633                if (count > b->size) {
634                    count = b->size;
635                }
636                memcpy(q, p, count);
637                LOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size, count);
638            } else if (mPos < mAudioBufferSize) {
639                count = mAudioBufferSize - mPos;
640                if (count > b->size) {
641                    count = b->size;
642                }
643                memset(q, 0, count);
644                LOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
645            }
646
647            mPos += count;
648            b->size = count;
649            //LOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
650        }
651    } else if (event == AudioTrack::EVENT_UNDERRUN) {
652        LOGV("stopping track");
653        stop();
654    } else if (event == AudioTrack::EVENT_LOOP_END) {
655        LOGV("End loop: %d", *(int *)info);
656    }
657}
658
659
660// call with lock held
661void SoundChannel::stop_l()
662{
663    if (mState != IDLE) {
664        setVolume_l(0, 0);
665        LOGV("stop");
666        mAudioTrack->stop();
667        mSample.clear();
668        mState = IDLE;
669        mPriority = IDLE_PRIORITY;
670    }
671}
672
673void SoundChannel::stop()
674{
675    {
676        Mutex::Autolock lock(&mLock);
677        stop_l();
678    }
679    mSoundPool->done(this);
680}
681
682//FIXME: Pause is a little broken right now
683void SoundChannel::pause()
684{
685    Mutex::Autolock lock(&mLock);
686    if (mState == PLAYING) {
687        LOGV("pause track");
688        mState = PAUSED;
689        mAudioTrack->pause();
690    }
691}
692
693void SoundChannel::resume()
694{
695    Mutex::Autolock lock(&mLock);
696    if (mState == PAUSED) {
697        LOGV("resume track");
698        mState = PLAYING;
699        mAudioTrack->start();
700    }
701}
702
703void SoundChannel::setRate(float rate)
704{
705    Mutex::Autolock lock(&mLock);
706    if (mAudioTrack != 0 && mSample.get() != 0) {
707        uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5);
708        mAudioTrack->setSampleRate(sampleRate);
709        mRate = rate;
710    }
711}
712
713// call with lock held
714void SoundChannel::setVolume_l(float leftVolume, float rightVolume)
715{
716    mLeftVolume = leftVolume;
717    mRightVolume = rightVolume;
718    if (mAudioTrack != 0) mAudioTrack->setVolume(leftVolume, rightVolume);
719}
720
721void SoundChannel::setVolume(float leftVolume, float rightVolume)
722{
723    Mutex::Autolock lock(&mLock);
724    setVolume_l(leftVolume, rightVolume);
725}
726
727void SoundChannel::setLoop(int loop)
728{
729    Mutex::Autolock lock(&mLock);
730    if (mAudioTrack != 0 && mSample.get() != 0) {
731        mAudioTrack->setLoop(0, mSample->size()/mNumChannels/((mSample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t)), loop);
732        mLoop = loop;
733    }
734}
735
736SoundChannel::~SoundChannel()
737{
738    LOGV("SoundChannel destructor");
739    if (mAudioTrack) {
740        LOGV("stop track");
741        mAudioTrack->stop();
742        delete mAudioTrack;
743    }
744    clearNextEvent();
745    mSample.clear();
746}
747
748void SoundChannel::dump()
749{
750    LOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d",
751            mState, mChannelID, mNumChannels, mPos, mPriority, mLoop);
752}
753
754void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
755            float rightVolume, int priority, int loop, float rate)
756{
757    mSample =sample;
758    mChannelID = channelID;
759    mLeftVolume = leftVolume;
760    mRightVolume = rightVolume;
761    mPriority = priority;
762    mLoop = loop;
763    mRate =rate;
764}
765
766} // end namespace android
767
768