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/stagefright/MediaExtractor.h>
30#include "SoundPool.h"
31#include "SoundPoolThread.h"
32#include <media/AudioPolicyHelper.h>
33#include <ndk/NdkMediaCodec.h>
34#include <ndk/NdkMediaExtractor.h>
35#include <ndk/NdkMediaFormat.h>
36
37namespace android
38{
39
40int kDefaultBufferCount = 4;
41uint32_t kMaxSampleRate = 48000;
42uint32_t kDefaultSampleRate = 44100;
43uint32_t kDefaultFrameCount = 1200;
44size_t kDefaultHeapSize = 1024 * 1024; // 1MB
45
46
47SoundPool::SoundPool(int maxChannels, const audio_attributes_t* pAttributes)
48{
49    ALOGV("SoundPool constructor: maxChannels=%d, attr.usage=%d, attr.flags=0x%x, attr.tags=%s",
50            maxChannels, pAttributes->usage, pAttributes->flags, pAttributes->tags);
51
52    // check limits
53    mMaxChannels = maxChannels;
54    if (mMaxChannels < 1) {
55        mMaxChannels = 1;
56    }
57    else if (mMaxChannels > 32) {
58        mMaxChannels = 32;
59    }
60    ALOGW_IF(maxChannels != mMaxChannels, "App requested %d channels", maxChannels);
61
62    mQuit = false;
63    mMuted = false;
64    mDecodeThread = 0;
65    memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
66    mAllocated = 0;
67    mNextSampleID = 0;
68    mNextChannelID = 0;
69
70    mCallback = 0;
71    mUserData = 0;
72
73    mChannelPool = new SoundChannel[mMaxChannels];
74    for (int i = 0; i < mMaxChannels; ++i) {
75        mChannelPool[i].init(this);
76        mChannels.push_back(&mChannelPool[i]);
77    }
78
79    // start decode thread
80    startThreads();
81}
82
83SoundPool::~SoundPool()
84{
85    ALOGV("SoundPool destructor");
86    mDecodeThread->quit();
87    quit();
88
89    Mutex::Autolock lock(&mLock);
90
91    mChannels.clear();
92    if (mChannelPool)
93        delete [] mChannelPool;
94    // clean up samples
95    ALOGV("clear samples");
96    mSamples.clear();
97
98    if (mDecodeThread)
99        delete mDecodeThread;
100}
101
102void SoundPool::addToRestartList(SoundChannel* channel)
103{
104    Mutex::Autolock lock(&mRestartLock);
105    if (!mQuit) {
106        mRestart.push_back(channel);
107        mCondition.signal();
108    }
109}
110
111void SoundPool::addToStopList(SoundChannel* channel)
112{
113    Mutex::Autolock lock(&mRestartLock);
114    if (!mQuit) {
115        mStop.push_back(channel);
116        mCondition.signal();
117    }
118}
119
120int SoundPool::beginThread(void* arg)
121{
122    SoundPool* p = (SoundPool*)arg;
123    return p->run();
124}
125
126int SoundPool::run()
127{
128    mRestartLock.lock();
129    while (!mQuit) {
130        mCondition.wait(mRestartLock);
131        ALOGV("awake");
132        if (mQuit) break;
133
134        while (!mStop.empty()) {
135            SoundChannel* channel;
136            ALOGV("Getting channel from stop list");
137            List<SoundChannel* >::iterator iter = mStop.begin();
138            channel = *iter;
139            mStop.erase(iter);
140            mRestartLock.unlock();
141            if (channel != 0) {
142                Mutex::Autolock lock(&mLock);
143                channel->stop();
144            }
145            mRestartLock.lock();
146            if (mQuit) break;
147        }
148
149        while (!mRestart.empty()) {
150            SoundChannel* channel;
151            ALOGV("Getting channel from list");
152            List<SoundChannel*>::iterator iter = mRestart.begin();
153            channel = *iter;
154            mRestart.erase(iter);
155            mRestartLock.unlock();
156            if (channel != 0) {
157                Mutex::Autolock lock(&mLock);
158                channel->nextEvent();
159            }
160            mRestartLock.lock();
161            if (mQuit) break;
162        }
163    }
164
165    mStop.clear();
166    mRestart.clear();
167    mCondition.signal();
168    mRestartLock.unlock();
169    ALOGV("goodbye");
170    return 0;
171}
172
173void SoundPool::quit()
174{
175    mRestartLock.lock();
176    mQuit = true;
177    mCondition.signal();
178    mCondition.wait(mRestartLock);
179    ALOGV("return from quit");
180    mRestartLock.unlock();
181}
182
183bool SoundPool::startThreads()
184{
185    createThreadEtc(beginThread, this, "SoundPool");
186    if (mDecodeThread == NULL)
187        mDecodeThread = new SoundPoolThread(this);
188    return mDecodeThread != NULL;
189}
190
191sp<Sample> SoundPool::findSample(int sampleID)
192{
193    Mutex::Autolock lock(&mLock);
194    return findSample_l(sampleID);
195}
196
197sp<Sample> SoundPool::findSample_l(int sampleID)
198{
199    return mSamples.valueFor(sampleID);
200}
201
202SoundChannel* SoundPool::findChannel(int channelID)
203{
204    for (int i = 0; i < mMaxChannels; ++i) {
205        if (mChannelPool[i].channelID() == channelID) {
206            return &mChannelPool[i];
207        }
208    }
209    return NULL;
210}
211
212SoundChannel* SoundPool::findNextChannel(int channelID)
213{
214    for (int i = 0; i < mMaxChannels; ++i) {
215        if (mChannelPool[i].nextChannelID() == channelID) {
216            return &mChannelPool[i];
217        }
218    }
219    return NULL;
220}
221
222int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused)
223{
224    ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d",
225            fd, offset, length, priority);
226    int sampleID;
227    {
228        Mutex::Autolock lock(&mLock);
229        sampleID = ++mNextSampleID;
230        sp<Sample> sample = new Sample(sampleID, fd, offset, length);
231        mSamples.add(sampleID, sample);
232        sample->startLoad();
233    }
234    // mDecodeThread->loadSample() must be called outside of mLock.
235    // mDecodeThread->loadSample() may block on mDecodeThread message queue space;
236    // the message queue emptying may block on SoundPool::findSample().
237    //
238    // It theoretically possible that sample loads might decode out-of-order.
239    mDecodeThread->loadSample(sampleID);
240    return sampleID;
241}
242
243bool SoundPool::unload(int sampleID)
244{
245    ALOGV("unload: sampleID=%d", sampleID);
246    Mutex::Autolock lock(&mLock);
247    return mSamples.removeItem(sampleID) >= 0; // removeItem() returns index or BAD_VALUE
248}
249
250int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
251        int priority, int loop, float rate)
252{
253    ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
254            sampleID, leftVolume, rightVolume, priority, loop, rate);
255    SoundChannel* channel;
256    int channelID;
257
258    Mutex::Autolock lock(&mLock);
259
260    if (mQuit) {
261        return 0;
262    }
263    // is sample ready?
264    sp<Sample> sample(findSample_l(sampleID));
265    if ((sample == 0) || (sample->state() != Sample::READY)) {
266        ALOGW("  sample %d not READY", sampleID);
267        return 0;
268    }
269
270    dump();
271
272    // allocate a channel
273    channel = allocateChannel_l(priority, sampleID);
274
275    // no channel allocated - return 0
276    if (!channel) {
277        ALOGV("No channel allocated");
278        return 0;
279    }
280
281    channelID = ++mNextChannelID;
282
283    ALOGV("play channel %p state = %d", channel, channel->state());
284    channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
285    return channelID;
286}
287
288SoundChannel* SoundPool::allocateChannel_l(int priority, int sampleID)
289{
290    List<SoundChannel*>::iterator iter;
291    SoundChannel* channel = NULL;
292
293    // check if channel for given sampleID still available
294    if (!mChannels.empty()) {
295        for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
296            if (sampleID == (*iter)->getPrevSampleID() && (*iter)->state() == SoundChannel::IDLE) {
297                channel = *iter;
298                mChannels.erase(iter);
299                ALOGV("Allocated recycled channel for same sampleID");
300                break;
301            }
302        }
303    }
304
305    // allocate any channel
306    if (!channel && !mChannels.empty()) {
307        iter = mChannels.begin();
308        if (priority >= (*iter)->priority()) {
309            channel = *iter;
310            mChannels.erase(iter);
311            ALOGV("Allocated active channel");
312        }
313    }
314
315    // update priority and put it back in the list
316    if (channel) {
317        channel->setPriority(priority);
318        for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
319            if (priority < (*iter)->priority()) {
320                break;
321            }
322        }
323        mChannels.insert(iter, channel);
324    }
325    return channel;
326}
327
328// move a channel from its current position to the front of the list
329void SoundPool::moveToFront_l(SoundChannel* channel)
330{
331    for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
332        if (*iter == channel) {
333            mChannels.erase(iter);
334            mChannels.push_front(channel);
335            break;
336        }
337    }
338}
339
340void SoundPool::pause(int channelID)
341{
342    ALOGV("pause(%d)", channelID);
343    Mutex::Autolock lock(&mLock);
344    SoundChannel* channel = findChannel(channelID);
345    if (channel) {
346        channel->pause();
347    }
348}
349
350void SoundPool::autoPause()
351{
352    ALOGV("autoPause()");
353    Mutex::Autolock lock(&mLock);
354    for (int i = 0; i < mMaxChannels; ++i) {
355        SoundChannel* channel = &mChannelPool[i];
356        channel->autoPause();
357    }
358}
359
360void SoundPool::resume(int channelID)
361{
362    ALOGV("resume(%d)", channelID);
363    Mutex::Autolock lock(&mLock);
364    SoundChannel* channel = findChannel(channelID);
365    if (channel) {
366        channel->resume();
367    }
368}
369
370void SoundPool::mute(bool muting)
371{
372    ALOGV("mute(%d)", muting);
373    Mutex::Autolock lock(&mLock);
374    mMuted = muting;
375    if (!mChannels.empty()) {
376            for (List<SoundChannel*>::iterator iter = mChannels.begin();
377                    iter != mChannels.end(); ++iter) {
378                (*iter)->mute(muting);
379            }
380        }
381}
382
383void SoundPool::autoResume()
384{
385    ALOGV("autoResume()");
386    Mutex::Autolock lock(&mLock);
387    for (int i = 0; i < mMaxChannels; ++i) {
388        SoundChannel* channel = &mChannelPool[i];
389        channel->autoResume();
390    }
391}
392
393void SoundPool::stop(int channelID)
394{
395    ALOGV("stop(%d)", channelID);
396    Mutex::Autolock lock(&mLock);
397    SoundChannel* channel = findChannel(channelID);
398    if (channel) {
399        channel->stop();
400    } else {
401        channel = findNextChannel(channelID);
402        if (channel)
403            channel->clearNextEvent();
404    }
405}
406
407void SoundPool::setVolume(int channelID, float leftVolume, float rightVolume)
408{
409    Mutex::Autolock lock(&mLock);
410    SoundChannel* channel = findChannel(channelID);
411    if (channel) {
412        channel->setVolume(leftVolume, rightVolume);
413    }
414}
415
416void SoundPool::setPriority(int channelID, int priority)
417{
418    ALOGV("setPriority(%d, %d)", channelID, priority);
419    Mutex::Autolock lock(&mLock);
420    SoundChannel* channel = findChannel(channelID);
421    if (channel) {
422        channel->setPriority(priority);
423    }
424}
425
426void SoundPool::setLoop(int channelID, int loop)
427{
428    ALOGV("setLoop(%d, %d)", channelID, loop);
429    Mutex::Autolock lock(&mLock);
430    SoundChannel* channel = findChannel(channelID);
431    if (channel) {
432        channel->setLoop(loop);
433    }
434}
435
436void SoundPool::setRate(int channelID, float rate)
437{
438    ALOGV("setRate(%d, %f)", channelID, rate);
439    Mutex::Autolock lock(&mLock);
440    SoundChannel* channel = findChannel(channelID);
441    if (channel) {
442        channel->setRate(rate);
443    }
444}
445
446// call with lock held
447void SoundPool::done_l(SoundChannel* channel)
448{
449    ALOGV("done_l(%d)", channel->channelID());
450    // if "stolen", play next event
451    if (channel->nextChannelID() != 0) {
452        ALOGV("add to restart list");
453        addToRestartList(channel);
454    }
455
456    // return to idle state
457    else {
458        ALOGV("move to front");
459        moveToFront_l(channel);
460    }
461}
462
463void SoundPool::setCallback(SoundPoolCallback* callback, void* user)
464{
465    Mutex::Autolock lock(&mCallbackLock);
466    mCallback = callback;
467    mUserData = user;
468}
469
470void SoundPool::notify(SoundPoolEvent event)
471{
472    Mutex::Autolock lock(&mCallbackLock);
473    if (mCallback != NULL) {
474        mCallback(event, this, mUserData);
475    }
476}
477
478void SoundPool::dump()
479{
480    for (int i = 0; i < mMaxChannels; ++i) {
481        mChannelPool[i].dump();
482    }
483}
484
485
486Sample::Sample(int sampleID, int fd, int64_t offset, int64_t length)
487{
488    init();
489    mSampleID = sampleID;
490    mFd = dup(fd);
491    mOffset = offset;
492    mLength = length;
493    ALOGV("create sampleID=%d, fd=%d, offset=%" PRId64 " length=%" PRId64,
494        mSampleID, mFd, mLength, mOffset);
495}
496
497void Sample::init()
498{
499    mSize = 0;
500    mRefCount = 0;
501    mSampleID = 0;
502    mState = UNLOADED;
503    mFd = -1;
504    mOffset = 0;
505    mLength = 0;
506}
507
508Sample::~Sample()
509{
510    ALOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd);
511    if (mFd > 0) {
512        ALOGV("close(%d)", mFd);
513        ::close(mFd);
514    }
515}
516
517static status_t decode(int fd, int64_t offset, int64_t length,
518        uint32_t *rate, int *numChannels, audio_format_t *audioFormat,
519        sp<MemoryHeapBase> heap, size_t *memsize) {
520
521    ALOGV("fd %d, offset %" PRId64 ", size %" PRId64, fd, offset, length);
522    AMediaExtractor *ex = AMediaExtractor_new();
523    status_t err = AMediaExtractor_setDataSourceFd(ex, fd, offset, length);
524
525    if (err != AMEDIA_OK) {
526        AMediaExtractor_delete(ex);
527        return err;
528    }
529
530    *audioFormat = AUDIO_FORMAT_PCM_16_BIT;
531
532    size_t numTracks = AMediaExtractor_getTrackCount(ex);
533    for (size_t i = 0; i < numTracks; i++) {
534        AMediaFormat *format = AMediaExtractor_getTrackFormat(ex, i);
535        const char *mime;
536        if (!AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime)) {
537            AMediaExtractor_delete(ex);
538            AMediaFormat_delete(format);
539            return UNKNOWN_ERROR;
540        }
541        if (strncmp(mime, "audio/", 6) == 0) {
542
543            AMediaCodec *codec = AMediaCodec_createDecoderByType(mime);
544            if (codec == NULL
545                    || AMediaCodec_configure(codec, format,
546                            NULL /* window */, NULL /* drm */, 0 /* flags */) != AMEDIA_OK
547                    || AMediaCodec_start(codec) != AMEDIA_OK
548                    || AMediaExtractor_selectTrack(ex, i) != AMEDIA_OK) {
549                AMediaExtractor_delete(ex);
550                AMediaCodec_delete(codec);
551                AMediaFormat_delete(format);
552                return UNKNOWN_ERROR;
553            }
554
555            bool sawInputEOS = false;
556            bool sawOutputEOS = false;
557            uint8_t* writePos = static_cast<uint8_t*>(heap->getBase());
558            size_t available = heap->getSize();
559            size_t written = 0;
560
561            AMediaFormat_delete(format);
562            format = AMediaCodec_getOutputFormat(codec);
563
564            while (!sawOutputEOS) {
565                if (!sawInputEOS) {
566                    ssize_t bufidx = AMediaCodec_dequeueInputBuffer(codec, 5000);
567                    ALOGV("input buffer %zd", bufidx);
568                    if (bufidx >= 0) {
569                        size_t bufsize;
570                        uint8_t *buf = AMediaCodec_getInputBuffer(codec, bufidx, &bufsize);
571                        if (buf == nullptr) {
572                            ALOGE("AMediaCodec_getInputBuffer returned nullptr, short decode");
573                            break;
574                        }
575                        int sampleSize = AMediaExtractor_readSampleData(ex, buf, bufsize);
576                        ALOGV("read %d", sampleSize);
577                        if (sampleSize < 0) {
578                            sampleSize = 0;
579                            sawInputEOS = true;
580                            ALOGV("EOS");
581                        }
582                        int64_t presentationTimeUs = AMediaExtractor_getSampleTime(ex);
583
584                        media_status_t mstatus = AMediaCodec_queueInputBuffer(codec, bufidx,
585                                0 /* offset */, sampleSize, presentationTimeUs,
586                                sawInputEOS ? AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM : 0);
587                        if (mstatus != AMEDIA_OK) {
588                            // AMEDIA_ERROR_UNKNOWN == { -ERANGE -EINVAL -EACCES }
589                            ALOGE("AMediaCodec_queueInputBuffer returned status %d, short decode",
590                                    (int)mstatus);
591                            break;
592                        }
593                        (void)AMediaExtractor_advance(ex);
594                    }
595                }
596
597                AMediaCodecBufferInfo info;
598                int status = AMediaCodec_dequeueOutputBuffer(codec, &info, 1);
599                ALOGV("dequeueoutput returned: %d", status);
600                if (status >= 0) {
601                    if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) {
602                        ALOGV("output EOS");
603                        sawOutputEOS = true;
604                    }
605                    ALOGV("got decoded buffer size %d", info.size);
606
607                    uint8_t *buf = AMediaCodec_getOutputBuffer(codec, status, NULL /* out_size */);
608                    if (buf == nullptr) {
609                        ALOGE("AMediaCodec_getOutputBuffer returned nullptr, short decode");
610                        break;
611                    }
612                    size_t dataSize = info.size;
613                    if (dataSize > available) {
614                        dataSize = available;
615                    }
616                    memcpy(writePos, buf + info.offset, dataSize);
617                    writePos += dataSize;
618                    written += dataSize;
619                    available -= dataSize;
620                    media_status_t mstatus = AMediaCodec_releaseOutputBuffer(
621                            codec, status, false /* render */);
622                    if (mstatus != AMEDIA_OK) {
623                        // AMEDIA_ERROR_UNKNOWN == { -ERANGE -EINVAL -EACCES }
624                        ALOGE("AMediaCodec_releaseOutputBuffer returned status %d, short decode",
625                                (int)mstatus);
626                        break;
627                    }
628                    if (available == 0) {
629                        // there might be more data, but there's no space for it
630                        sawOutputEOS = true;
631                    }
632                } else if (status == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
633                    ALOGV("output buffers changed");
634                } else if (status == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
635                    AMediaFormat_delete(format);
636                    format = AMediaCodec_getOutputFormat(codec);
637                    ALOGV("format changed to: %s", AMediaFormat_toString(format));
638                } else if (status == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
639                    ALOGV("no output buffer right now");
640                } else if (status <= AMEDIA_ERROR_BASE) {
641                    ALOGE("decode error: %d", status);
642                    break;
643                } else {
644                    ALOGV("unexpected info code: %d", status);
645                }
646            }
647
648            (void)AMediaCodec_stop(codec);
649            (void)AMediaCodec_delete(codec);
650            (void)AMediaExtractor_delete(ex);
651            if (!AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, (int32_t*) rate) ||
652                    !AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, numChannels)) {
653                (void)AMediaFormat_delete(format);
654                return UNKNOWN_ERROR;
655            }
656            (void)AMediaFormat_delete(format);
657            *memsize = written;
658            return OK;
659        }
660        (void)AMediaFormat_delete(format);
661    }
662    (void)AMediaExtractor_delete(ex);
663    return UNKNOWN_ERROR;
664}
665
666status_t Sample::doLoad()
667{
668    uint32_t sampleRate;
669    int numChannels;
670    audio_format_t format;
671    status_t status;
672    mHeap = new MemoryHeapBase(kDefaultHeapSize);
673
674    ALOGV("Start decode");
675    status = decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format,
676                                 mHeap, &mSize);
677    ALOGV("close(%d)", mFd);
678    ::close(mFd);
679    mFd = -1;
680    if (status != NO_ERROR) {
681        ALOGE("Unable to load sample");
682        goto error;
683    }
684    ALOGV("pointer = %p, size = %zu, sampleRate = %u, numChannels = %d",
685          mHeap->getBase(), mSize, sampleRate, numChannels);
686
687    if (sampleRate > kMaxSampleRate) {
688       ALOGE("Sample rate (%u) out of range", sampleRate);
689       status = BAD_VALUE;
690       goto error;
691    }
692
693    if ((numChannels < 1) || (numChannels > FCC_8)) {
694        ALOGE("Sample channel count (%d) out of range", numChannels);
695        status = BAD_VALUE;
696        goto error;
697    }
698
699    mData = new MemoryBase(mHeap, 0, mSize);
700    mSampleRate = sampleRate;
701    mNumChannels = numChannels;
702    mFormat = format;
703    mState = READY;
704    return NO_ERROR;
705
706error:
707    mHeap.clear();
708    return status;
709}
710
711
712void SoundChannel::init(SoundPool* soundPool)
713{
714    mSoundPool = soundPool;
715    mPrevSampleID = -1;
716}
717
718// call with sound pool lock held
719void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
720        float rightVolume, int priority, int loop, float rate)
721{
722    sp<AudioTrack> oldTrack;
723    sp<AudioTrack> newTrack;
724    status_t status = NO_ERROR;
725
726    { // scope for the lock
727        Mutex::Autolock lock(&mLock);
728
729        ALOGV("SoundChannel::play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f,"
730                " priority=%d, loop=%d, rate=%f",
731                this, sample->sampleID(), nextChannelID, leftVolume, rightVolume,
732                priority, loop, rate);
733
734        // if not idle, this voice is being stolen
735        if (mState != IDLE) {
736            ALOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
737            mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
738            stop_l();
739            return;
740        }
741
742        // initialize track
743        size_t afFrameCount;
744        uint32_t afSampleRate;
745        audio_stream_type_t streamType = audio_attributes_to_stream_type(mSoundPool->attributes());
746        if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
747            afFrameCount = kDefaultFrameCount;
748        }
749        if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
750            afSampleRate = kDefaultSampleRate;
751        }
752        int numChannels = sample->numChannels();
753        uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
754        size_t frameCount = 0;
755
756        if (loop) {
757            const audio_format_t format = sample->format();
758            const size_t frameSize = audio_is_linear_pcm(format)
759                    ? numChannels * audio_bytes_per_sample(format) : 1;
760            frameCount = sample->size() / frameSize;
761        }
762
763#ifndef USE_SHARED_MEM_BUFFER
764        uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
765        // Ensure minimum audio buffer size in case of short looped sample
766        if(frameCount < totalFrames) {
767            frameCount = totalFrames;
768        }
769#endif
770
771        // check if the existing track has the same sample id.
772        if (mAudioTrack != 0 && mPrevSampleID == sample->sampleID()) {
773            // the sample rate may fail to change if the audio track is a fast track.
774            if (mAudioTrack->setSampleRate(sampleRate) == NO_ERROR) {
775                newTrack = mAudioTrack;
776                ALOGV("reusing track %p for sample %d", mAudioTrack.get(), sample->sampleID());
777            }
778        }
779        if (newTrack == 0) {
780            // mToggle toggles each time a track is started on a given channel.
781            // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
782            // as callback user data. This enables the detection of callbacks received from the old
783            // audio track while the new one is being started and avoids processing them with
784            // wrong audio audio buffer size  (mAudioBufferSize)
785            unsigned long toggle = mToggle ^ 1;
786            void *userData = (void *)((unsigned long)this | toggle);
787            audio_channel_mask_t channelMask = audio_channel_out_mask_from_count(numChannels);
788
789            // do not create a new audio track if current track is compatible with sample parameters
790    #ifdef USE_SHARED_MEM_BUFFER
791            newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
792                    channelMask, sample->getIMemory(), AUDIO_OUTPUT_FLAG_FAST, callback, userData,
793                    0 /*default notification frames*/, AUDIO_SESSION_ALLOCATE,
794                    AudioTrack::TRANSFER_DEFAULT,
795                    NULL /*offloadInfo*/, -1 /*uid*/, -1 /*pid*/, mSoundPool->attributes());
796    #else
797            uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
798            newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
799                    channelMask, frameCount, AUDIO_OUTPUT_FLAG_FAST, callback, userData,
800                    bufferFrames, AUDIO_SESSION_ALLOCATE, AudioTrack::TRANSFER_DEFAULT,
801                    NULL /*offloadInfo*/, -1 /*uid*/, -1 /*pid*/, mSoundPool->attributes());
802    #endif
803            oldTrack = mAudioTrack;
804            status = newTrack->initCheck();
805            if (status != NO_ERROR) {
806                ALOGE("Error creating AudioTrack");
807                // newTrack goes out of scope, so reference count drops to zero
808                goto exit;
809            }
810            // From now on, AudioTrack callbacks received with previous toggle value will be ignored.
811            mToggle = toggle;
812            mAudioTrack = newTrack;
813            ALOGV("using new track %p for sample %d", newTrack.get(), sample->sampleID());
814        }
815        newTrack->setVolume(leftVolume, rightVolume);
816        newTrack->setLoop(0, frameCount, loop);
817        mPos = 0;
818        mSample = sample;
819        mChannelID = nextChannelID;
820        mPriority = priority;
821        mLoop = loop;
822        mLeftVolume = leftVolume;
823        mRightVolume = rightVolume;
824        mNumChannels = numChannels;
825        mRate = rate;
826        clearNextEvent();
827        mState = PLAYING;
828        mAudioTrack->start();
829        mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
830    }
831
832exit:
833    ALOGV("delete oldTrack %p", oldTrack.get());
834    if (status != NO_ERROR) {
835        mAudioTrack.clear();
836    }
837}
838
839void SoundChannel::nextEvent()
840{
841    sp<Sample> sample;
842    int nextChannelID;
843    float leftVolume;
844    float rightVolume;
845    int priority;
846    int loop;
847    float rate;
848
849    // check for valid event
850    {
851        Mutex::Autolock lock(&mLock);
852        nextChannelID = mNextEvent.channelID();
853        if (nextChannelID  == 0) {
854            ALOGV("stolen channel has no event");
855            return;
856        }
857
858        sample = mNextEvent.sample();
859        leftVolume = mNextEvent.leftVolume();
860        rightVolume = mNextEvent.rightVolume();
861        priority = mNextEvent.priority();
862        loop = mNextEvent.loop();
863        rate = mNextEvent.rate();
864    }
865
866    ALOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
867    play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
868}
869
870void SoundChannel::callback(int event, void* user, void *info)
871{
872    SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
873
874    channel->process(event, info, (unsigned long)user & 1);
875}
876
877void SoundChannel::process(int event, void *info, unsigned long toggle)
878{
879    //ALOGV("process(%d)", mChannelID);
880
881    Mutex::Autolock lock(&mLock);
882
883    AudioTrack::Buffer* b = NULL;
884    if (event == AudioTrack::EVENT_MORE_DATA) {
885       b = static_cast<AudioTrack::Buffer *>(info);
886    }
887
888    if (mToggle != toggle) {
889        ALOGV("process wrong toggle %p channel %d", this, mChannelID);
890        if (b != NULL) {
891            b->size = 0;
892        }
893        return;
894    }
895
896    sp<Sample> sample = mSample;
897
898//    ALOGV("SoundChannel::process event %d", event);
899
900    if (event == AudioTrack::EVENT_MORE_DATA) {
901
902        // check for stop state
903        if (b->size == 0) return;
904
905        if (mState == IDLE) {
906            b->size = 0;
907            return;
908        }
909
910        if (sample != 0) {
911            // fill buffer
912            uint8_t* q = (uint8_t*) b->i8;
913            size_t count = 0;
914
915            if (mPos < (int)sample->size()) {
916                uint8_t* p = sample->data() + mPos;
917                count = sample->size() - mPos;
918                if (count > b->size) {
919                    count = b->size;
920                }
921                memcpy(q, p, count);
922//              ALOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size,
923//                      count);
924            } else if (mPos < mAudioBufferSize) {
925                count = mAudioBufferSize - mPos;
926                if (count > b->size) {
927                    count = b->size;
928                }
929                memset(q, 0, count);
930//              ALOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
931            }
932
933            mPos += count;
934            b->size = count;
935            //ALOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
936        }
937    } else if (event == AudioTrack::EVENT_UNDERRUN || event == AudioTrack::EVENT_BUFFER_END) {
938        ALOGV("process %p channel %d event %s",
939              this, mChannelID, (event == AudioTrack::EVENT_UNDERRUN) ? "UNDERRUN" :
940                      "BUFFER_END");
941        mSoundPool->addToStopList(this);
942    } else if (event == AudioTrack::EVENT_LOOP_END) {
943        ALOGV("End loop %p channel %d", this, mChannelID);
944    } else if (event == AudioTrack::EVENT_NEW_IAUDIOTRACK) {
945        ALOGV("process %p channel %d NEW_IAUDIOTRACK", this, mChannelID);
946    } else {
947        ALOGW("SoundChannel::process unexpected event %d", event);
948    }
949}
950
951
952// call with lock held
953bool SoundChannel::doStop_l()
954{
955    if (mState != IDLE) {
956        setVolume_l(0, 0);
957        ALOGV("stop");
958        mAudioTrack->stop();
959        mPrevSampleID = mSample->sampleID();
960        mSample.clear();
961        mState = IDLE;
962        mPriority = IDLE_PRIORITY;
963        return true;
964    }
965    return false;
966}
967
968// call with lock held and sound pool lock held
969void SoundChannel::stop_l()
970{
971    if (doStop_l()) {
972        mSoundPool->done_l(this);
973    }
974}
975
976// call with sound pool lock held
977void SoundChannel::stop()
978{
979    bool stopped;
980    {
981        Mutex::Autolock lock(&mLock);
982        stopped = doStop_l();
983    }
984
985    if (stopped) {
986        mSoundPool->done_l(this);
987    }
988}
989
990//FIXME: Pause is a little broken right now
991void SoundChannel::pause()
992{
993    Mutex::Autolock lock(&mLock);
994    if (mState == PLAYING) {
995        ALOGV("pause track");
996        mState = PAUSED;
997        mAudioTrack->pause();
998    }
999}
1000
1001void SoundChannel::autoPause()
1002{
1003    Mutex::Autolock lock(&mLock);
1004    if (mState == PLAYING) {
1005        ALOGV("pause track");
1006        mState = PAUSED;
1007        mAutoPaused = true;
1008        mAudioTrack->pause();
1009    }
1010}
1011
1012void SoundChannel::resume()
1013{
1014    Mutex::Autolock lock(&mLock);
1015    if (mState == PAUSED) {
1016        ALOGV("resume track");
1017        mState = PLAYING;
1018        mAutoPaused = false;
1019        mAudioTrack->start();
1020    }
1021}
1022
1023void SoundChannel::autoResume()
1024{
1025    Mutex::Autolock lock(&mLock);
1026    if (mAutoPaused && (mState == PAUSED)) {
1027        ALOGV("resume track");
1028        mState = PLAYING;
1029        mAutoPaused = false;
1030        mAudioTrack->start();
1031    }
1032}
1033
1034void SoundChannel::setRate(float rate)
1035{
1036    Mutex::Autolock lock(&mLock);
1037    if (mAudioTrack != NULL && mSample != 0) {
1038        uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5);
1039        mAudioTrack->setSampleRate(sampleRate);
1040        mRate = rate;
1041    }
1042}
1043
1044// call with lock held
1045void SoundChannel::setVolume_l(float leftVolume, float rightVolume)
1046{
1047    mLeftVolume = leftVolume;
1048    mRightVolume = rightVolume;
1049    if (mAudioTrack != NULL && !mMuted)
1050        mAudioTrack->setVolume(leftVolume, rightVolume);
1051}
1052
1053void SoundChannel::setVolume(float leftVolume, float rightVolume)
1054{
1055    Mutex::Autolock lock(&mLock);
1056    setVolume_l(leftVolume, rightVolume);
1057}
1058
1059void SoundChannel::mute(bool muting)
1060{
1061    Mutex::Autolock lock(&mLock);
1062    mMuted = muting;
1063    if (mAudioTrack != NULL) {
1064        if (mMuted) {
1065            mAudioTrack->setVolume(0.0f, 0.0f);
1066        } else {
1067            mAudioTrack->setVolume(mLeftVolume, mRightVolume);
1068        }
1069    }
1070}
1071
1072void SoundChannel::setLoop(int loop)
1073{
1074    Mutex::Autolock lock(&mLock);
1075    if (mAudioTrack != NULL && mSample != 0) {
1076        uint32_t loopEnd = mSample->size()/mNumChannels/
1077            ((mSample->format() == AUDIO_FORMAT_PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
1078        mAudioTrack->setLoop(0, loopEnd, loop);
1079        mLoop = loop;
1080    }
1081}
1082
1083SoundChannel::~SoundChannel()
1084{
1085    ALOGV("SoundChannel destructor %p", this);
1086    {
1087        Mutex::Autolock lock(&mLock);
1088        clearNextEvent();
1089        doStop_l();
1090    }
1091    // do not call AudioTrack destructor with mLock held as it will wait for the AudioTrack
1092    // callback thread to exit which may need to execute process() and acquire the mLock.
1093    mAudioTrack.clear();
1094}
1095
1096void SoundChannel::dump()
1097{
1098    ALOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d",
1099            mState, mChannelID, mNumChannels, mPos, mPriority, mLoop);
1100}
1101
1102void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
1103            float rightVolume, int priority, int loop, float rate)
1104{
1105    mSample = sample;
1106    mChannelID = channelID;
1107    mLeftVolume = leftVolume;
1108    mRightVolume = rightVolume;
1109    mPriority = priority;
1110    mLoop = loop;
1111    mRate =rate;
1112}
1113
1114} // end namespace android
1115