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