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