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