blob: 70d651f2c24a3ee35cd3147d5c3daa7a5b9a5995 [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
Andy Hung0275a982015-11-30 16:09:55 -0800190sp<Sample> SoundPool::findSample(int sampleID)
191{
192 Mutex::Autolock lock(&mLock);
193 return findSample_l(sampleID);
194}
195
196sp<Sample> SoundPool::findSample_l(int sampleID)
197{
198 return mSamples.valueFor(sampleID);
199}
200
Marco Nelissen372be892014-12-04 08:59:22 -0800201SoundChannel* SoundPool::findChannel(int channelID)
202{
203 for (int i = 0; i < mMaxChannels; ++i) {
204 if (mChannelPool[i].channelID() == channelID) {
205 return &mChannelPool[i];
206 }
207 }
208 return NULL;
209}
210
211SoundChannel* SoundPool::findNextChannel(int channelID)
212{
213 for (int i = 0; i < mMaxChannels; ++i) {
214 if (mChannelPool[i].nextChannelID() == channelID) {
215 return &mChannelPool[i];
216 }
217 }
218 return NULL;
219}
220
221int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused)
222{
223 ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d",
224 fd, offset, length, priority);
Andy Hung0275a982015-11-30 16:09:55 -0800225 int sampleID;
226 {
227 Mutex::Autolock lock(&mLock);
228 sampleID = ++mNextSampleID;
229 sp<Sample> sample = new Sample(sampleID, fd, offset, length);
230 mSamples.add(sampleID, sample);
231 sample->startLoad();
232 }
233 // mDecodeThread->loadSample() must be called outside of mLock.
234 // mDecodeThread->loadSample() may block on mDecodeThread message queue space;
235 // the message queue emptying may block on SoundPool::findSample().
236 //
237 // It theoretically possible that sample loads might decode out-of-order.
238 mDecodeThread->loadSample(sampleID);
239 return sampleID;
Marco Nelissen372be892014-12-04 08:59:22 -0800240}
241
242bool SoundPool::unload(int sampleID)
243{
244 ALOGV("unload: sampleID=%d", sampleID);
245 Mutex::Autolock lock(&mLock);
Andy Hunga6238ef2015-05-15 18:39:09 -0700246 return mSamples.removeItem(sampleID) >= 0; // removeItem() returns index or BAD_VALUE
Marco Nelissen372be892014-12-04 08:59:22 -0800247}
248
249int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
250 int priority, int loop, float rate)
251{
252 ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
253 sampleID, leftVolume, rightVolume, priority, loop, rate);
Marco Nelissen372be892014-12-04 08:59:22 -0800254 SoundChannel* channel;
255 int channelID;
256
257 Mutex::Autolock lock(&mLock);
258
259 if (mQuit) {
260 return 0;
261 }
262 // is sample ready?
Andy Hung0275a982015-11-30 16:09:55 -0800263 sp<Sample> sample(findSample_l(sampleID));
Marco Nelissen372be892014-12-04 08:59:22 -0800264 if ((sample == 0) || (sample->state() != Sample::READY)) {
265 ALOGW(" sample %d not READY", sampleID);
266 return 0;
267 }
268
269 dump();
270
271 // allocate a channel
Andy Hung0c4b81b2015-03-17 23:02:00 +0000272 channel = allocateChannel_l(priority, sampleID);
Marco Nelissen372be892014-12-04 08:59:22 -0800273
274 // no channel allocated - return 0
275 if (!channel) {
276 ALOGV("No channel allocated");
277 return 0;
278 }
279
280 channelID = ++mNextChannelID;
281
282 ALOGV("play channel %p state = %d", channel, channel->state());
283 channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
284 return channelID;
285}
286
Andy Hung0c4b81b2015-03-17 23:02:00 +0000287SoundChannel* SoundPool::allocateChannel_l(int priority, int sampleID)
Marco Nelissen372be892014-12-04 08:59:22 -0800288{
289 List<SoundChannel*>::iterator iter;
290 SoundChannel* channel = NULL;
291
Andy Hung0c4b81b2015-03-17 23:02:00 +0000292 // check if channel for given sampleID still available
Marco Nelissen372be892014-12-04 08:59:22 -0800293 if (!mChannels.empty()) {
Andy Hung0c4b81b2015-03-17 23:02:00 +0000294 for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
295 if (sampleID == (*iter)->getPrevSampleID() && (*iter)->state() == SoundChannel::IDLE) {
296 channel = *iter;
297 mChannels.erase(iter);
298 ALOGV("Allocated recycled channel for same sampleID");
299 break;
300 }
301 }
302 }
303
304 // allocate any channel
305 if (!channel && !mChannels.empty()) {
Marco Nelissen372be892014-12-04 08:59:22 -0800306 iter = mChannels.begin();
307 if (priority >= (*iter)->priority()) {
308 channel = *iter;
309 mChannels.erase(iter);
310 ALOGV("Allocated active channel");
311 }
312 }
313
314 // update priority and put it back in the list
315 if (channel) {
316 channel->setPriority(priority);
317 for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
318 if (priority < (*iter)->priority()) {
319 break;
320 }
321 }
322 mChannels.insert(iter, channel);
323 }
324 return channel;
325}
326
327// move a channel from its current position to the front of the list
328void SoundPool::moveToFront_l(SoundChannel* channel)
329{
330 for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
331 if (*iter == channel) {
332 mChannels.erase(iter);
333 mChannels.push_front(channel);
334 break;
335 }
336 }
337}
338
339void SoundPool::pause(int channelID)
340{
341 ALOGV("pause(%d)", channelID);
342 Mutex::Autolock lock(&mLock);
343 SoundChannel* channel = findChannel(channelID);
344 if (channel) {
345 channel->pause();
346 }
347}
348
349void SoundPool::autoPause()
350{
351 ALOGV("autoPause()");
352 Mutex::Autolock lock(&mLock);
353 for (int i = 0; i < mMaxChannels; ++i) {
354 SoundChannel* channel = &mChannelPool[i];
355 channel->autoPause();
356 }
357}
358
359void SoundPool::resume(int channelID)
360{
361 ALOGV("resume(%d)", channelID);
362 Mutex::Autolock lock(&mLock);
363 SoundChannel* channel = findChannel(channelID);
364 if (channel) {
365 channel->resume();
366 }
367}
368
369void SoundPool::autoResume()
370{
371 ALOGV("autoResume()");
372 Mutex::Autolock lock(&mLock);
373 for (int i = 0; i < mMaxChannels; ++i) {
374 SoundChannel* channel = &mChannelPool[i];
375 channel->autoResume();
376 }
377}
378
379void SoundPool::stop(int channelID)
380{
381 ALOGV("stop(%d)", channelID);
382 Mutex::Autolock lock(&mLock);
383 SoundChannel* channel = findChannel(channelID);
384 if (channel) {
385 channel->stop();
386 } else {
387 channel = findNextChannel(channelID);
388 if (channel)
389 channel->clearNextEvent();
390 }
391}
392
393void SoundPool::setVolume(int channelID, float leftVolume, float rightVolume)
394{
395 Mutex::Autolock lock(&mLock);
396 SoundChannel* channel = findChannel(channelID);
397 if (channel) {
398 channel->setVolume(leftVolume, rightVolume);
399 }
400}
401
402void SoundPool::setPriority(int channelID, int priority)
403{
404 ALOGV("setPriority(%d, %d)", channelID, priority);
405 Mutex::Autolock lock(&mLock);
406 SoundChannel* channel = findChannel(channelID);
407 if (channel) {
408 channel->setPriority(priority);
409 }
410}
411
412void SoundPool::setLoop(int channelID, int loop)
413{
414 ALOGV("setLoop(%d, %d)", channelID, loop);
415 Mutex::Autolock lock(&mLock);
416 SoundChannel* channel = findChannel(channelID);
417 if (channel) {
418 channel->setLoop(loop);
419 }
420}
421
422void SoundPool::setRate(int channelID, float rate)
423{
424 ALOGV("setRate(%d, %f)", channelID, rate);
425 Mutex::Autolock lock(&mLock);
426 SoundChannel* channel = findChannel(channelID);
427 if (channel) {
428 channel->setRate(rate);
429 }
430}
431
432// call with lock held
433void SoundPool::done_l(SoundChannel* channel)
434{
435 ALOGV("done_l(%d)", channel->channelID());
436 // if "stolen", play next event
437 if (channel->nextChannelID() != 0) {
438 ALOGV("add to restart list");
439 addToRestartList(channel);
440 }
441
442 // return to idle state
443 else {
444 ALOGV("move to front");
445 moveToFront_l(channel);
446 }
447}
448
449void SoundPool::setCallback(SoundPoolCallback* callback, void* user)
450{
451 Mutex::Autolock lock(&mCallbackLock);
452 mCallback = callback;
453 mUserData = user;
454}
455
456void SoundPool::notify(SoundPoolEvent event)
457{
458 Mutex::Autolock lock(&mCallbackLock);
459 if (mCallback != NULL) {
460 mCallback(event, this, mUserData);
461 }
462}
463
464void SoundPool::dump()
465{
466 for (int i = 0; i < mMaxChannels; ++i) {
467 mChannelPool[i].dump();
468 }
469}
470
471
472Sample::Sample(int sampleID, int fd, int64_t offset, int64_t length)
473{
474 init();
475 mSampleID = sampleID;
476 mFd = dup(fd);
477 mOffset = offset;
478 mLength = length;
479 ALOGV("create sampleID=%d, fd=%d, offset=%" PRId64 " length=%" PRId64,
480 mSampleID, mFd, mLength, mOffset);
481}
482
483void Sample::init()
484{
485 mSize = 0;
486 mRefCount = 0;
487 mSampleID = 0;
488 mState = UNLOADED;
489 mFd = -1;
490 mOffset = 0;
491 mLength = 0;
492}
493
494Sample::~Sample()
495{
496 ALOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd);
497 if (mFd > 0) {
498 ALOGV("close(%d)", mFd);
499 ::close(mFd);
500 }
501}
502
503static status_t decode(int fd, int64_t offset, int64_t length,
504 uint32_t *rate, int *numChannels, audio_format_t *audioFormat,
505 sp<MemoryHeapBase> heap, size_t *memsize) {
506
Marco Nelissen6cd61102015-01-27 12:17:48 -0800507 ALOGV("fd %d, offset %" PRId64 ", size %" PRId64, fd, offset, length);
Marco Nelissen372be892014-12-04 08:59:22 -0800508 AMediaExtractor *ex = AMediaExtractor_new();
509 status_t err = AMediaExtractor_setDataSourceFd(ex, fd, offset, length);
510
511 if (err != AMEDIA_OK) {
Marco Nelissen06524dc2015-02-10 15:45:23 -0800512 AMediaExtractor_delete(ex);
Marco Nelissen372be892014-12-04 08:59:22 -0800513 return err;
514 }
515
516 *audioFormat = AUDIO_FORMAT_PCM_16_BIT;
517
518 size_t numTracks = AMediaExtractor_getTrackCount(ex);
519 for (size_t i = 0; i < numTracks; i++) {
520 AMediaFormat *format = AMediaExtractor_getTrackFormat(ex, i);
521 const char *mime;
522 if (!AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime)) {
523 AMediaExtractor_delete(ex);
524 AMediaFormat_delete(format);
525 return UNKNOWN_ERROR;
526 }
527 if (strncmp(mime, "audio/", 6) == 0) {
528
529 AMediaCodec *codec = AMediaCodec_createDecoderByType(mime);
Andy Hung26eca012015-04-28 18:43:03 -0700530 if (codec == NULL
531 || AMediaCodec_configure(codec, format,
532 NULL /* window */, NULL /* drm */, 0 /* flags */) != AMEDIA_OK
533 || AMediaCodec_start(codec) != AMEDIA_OK
534 || AMediaExtractor_selectTrack(ex, i) != AMEDIA_OK) {
Marco Nelissen372be892014-12-04 08:59:22 -0800535 AMediaExtractor_delete(ex);
536 AMediaCodec_delete(codec);
537 AMediaFormat_delete(format);
538 return UNKNOWN_ERROR;
539 }
540
541 bool sawInputEOS = false;
542 bool sawOutputEOS = false;
543 uint8_t* writePos = static_cast<uint8_t*>(heap->getBase());
544 size_t available = heap->getSize();
545 size_t written = 0;
546
547 AMediaFormat_delete(format);
548 format = AMediaCodec_getOutputFormat(codec);
549
550 while (!sawOutputEOS) {
551 if (!sawInputEOS) {
552 ssize_t bufidx = AMediaCodec_dequeueInputBuffer(codec, 5000);
Marco Nelissen6cd61102015-01-27 12:17:48 -0800553 ALOGV("input buffer %zd", bufidx);
Marco Nelissen372be892014-12-04 08:59:22 -0800554 if (bufidx >= 0) {
555 size_t bufsize;
556 uint8_t *buf = AMediaCodec_getInputBuffer(codec, bufidx, &bufsize);
557 int sampleSize = AMediaExtractor_readSampleData(ex, buf, bufsize);
558 ALOGV("read %d", sampleSize);
559 if (sampleSize < 0) {
560 sampleSize = 0;
561 sawInputEOS = true;
562 ALOGV("EOS");
563 }
564 int64_t presentationTimeUs = AMediaExtractor_getSampleTime(ex);
565
566 AMediaCodec_queueInputBuffer(codec, bufidx,
567 0 /* offset */, sampleSize, presentationTimeUs,
568 sawInputEOS ? AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM : 0);
569 AMediaExtractor_advance(ex);
570 }
571 }
572
573 AMediaCodecBufferInfo info;
574 int status = AMediaCodec_dequeueOutputBuffer(codec, &info, 1);
575 ALOGV("dequeueoutput returned: %d", status);
576 if (status >= 0) {
577 if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) {
578 ALOGV("output EOS");
579 sawOutputEOS = true;
580 }
581 ALOGV("got decoded buffer size %d", info.size);
582
583 uint8_t *buf = AMediaCodec_getOutputBuffer(codec, status, NULL /* out_size */);
584 size_t dataSize = info.size;
585 if (dataSize > available) {
586 dataSize = available;
587 }
588 memcpy(writePos, buf + info.offset, dataSize);
589 writePos += dataSize;
590 written += dataSize;
591 available -= dataSize;
592 AMediaCodec_releaseOutputBuffer(codec, status, false /* render */);
593 if (available == 0) {
594 // there might be more data, but there's no space for it
595 sawOutputEOS = true;
596 }
597 } else if (status == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
598 ALOGV("output buffers changed");
599 } else if (status == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
600 AMediaFormat_delete(format);
601 format = AMediaCodec_getOutputFormat(codec);
602 ALOGV("format changed to: %s", AMediaFormat_toString(format));
603 } else if (status == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
604 ALOGV("no output buffer right now");
Marco Nelissen2f01c802015-09-15 12:49:07 -0700605 } else if (status <= AMEDIA_ERROR_BASE) {
606 ALOGE("decode error: %d", status);
607 break;
Marco Nelissen372be892014-12-04 08:59:22 -0800608 } else {
609 ALOGV("unexpected info code: %d", status);
610 }
611 }
612
613 AMediaCodec_stop(codec);
614 AMediaCodec_delete(codec);
615 AMediaExtractor_delete(ex);
616 if (!AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, (int32_t*) rate) ||
617 !AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, numChannels)) {
618 AMediaFormat_delete(format);
619 return UNKNOWN_ERROR;
620 }
621 AMediaFormat_delete(format);
622 *memsize = written;
623 return OK;
624 }
625 AMediaFormat_delete(format);
626 }
627 AMediaExtractor_delete(ex);
628 return UNKNOWN_ERROR;
629}
630
631status_t Sample::doLoad()
632{
633 uint32_t sampleRate;
634 int numChannels;
635 audio_format_t format;
636 status_t status;
637 mHeap = new MemoryHeapBase(kDefaultHeapSize);
638
639 ALOGV("Start decode");
640 status = decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format,
641 mHeap, &mSize);
642 ALOGV("close(%d)", mFd);
643 ::close(mFd);
644 mFd = -1;
645 if (status != NO_ERROR) {
646 ALOGE("Unable to load sample");
647 goto error;
648 }
649 ALOGV("pointer = %p, size = %zu, sampleRate = %u, numChannels = %d",
650 mHeap->getBase(), mSize, sampleRate, numChannels);
651
652 if (sampleRate > kMaxSampleRate) {
653 ALOGE("Sample rate (%u) out of range", sampleRate);
654 status = BAD_VALUE;
655 goto error;
656 }
657
Andy Hunga1c35162015-03-06 15:00:42 -0800658 if ((numChannels < 1) || (numChannels > 8)) {
Marco Nelissen372be892014-12-04 08:59:22 -0800659 ALOGE("Sample channel count (%d) out of range", numChannels);
660 status = BAD_VALUE;
661 goto error;
662 }
663
664 mData = new MemoryBase(mHeap, 0, mSize);
665 mSampleRate = sampleRate;
666 mNumChannels = numChannels;
667 mFormat = format;
668 mState = READY;
669 return NO_ERROR;
670
671error:
672 mHeap.clear();
673 return status;
674}
675
676
677void SoundChannel::init(SoundPool* soundPool)
678{
679 mSoundPool = soundPool;
Andy Hung0c4b81b2015-03-17 23:02:00 +0000680 mPrevSampleID = -1;
Marco Nelissen372be892014-12-04 08:59:22 -0800681}
682
683// call with sound pool lock held
684void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
685 float rightVolume, int priority, int loop, float rate)
686{
687 sp<AudioTrack> oldTrack;
688 sp<AudioTrack> newTrack;
Andy Hung0c4b81b2015-03-17 23:02:00 +0000689 status_t status = NO_ERROR;
Marco Nelissen372be892014-12-04 08:59:22 -0800690
691 { // scope for the lock
692 Mutex::Autolock lock(&mLock);
693
694 ALOGV("SoundChannel::play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f,"
695 " priority=%d, loop=%d, rate=%f",
696 this, sample->sampleID(), nextChannelID, leftVolume, rightVolume,
697 priority, loop, rate);
698
699 // if not idle, this voice is being stolen
700 if (mState != IDLE) {
701 ALOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
702 mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
703 stop_l();
704 return;
705 }
706
707 // initialize track
708 size_t afFrameCount;
709 uint32_t afSampleRate;
710 audio_stream_type_t streamType = audio_attributes_to_stream_type(mSoundPool->attributes());
711 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
712 afFrameCount = kDefaultFrameCount;
713 }
714 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
715 afSampleRate = kDefaultSampleRate;
716 }
717 int numChannels = sample->numChannels();
718 uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
719 size_t frameCount = 0;
720
721 if (loop) {
Andy Hunga1c35162015-03-06 15:00:42 -0800722 const audio_format_t format = sample->format();
723 const size_t frameSize = audio_is_linear_pcm(format)
724 ? numChannels * audio_bytes_per_sample(format) : 1;
725 frameCount = sample->size() / frameSize;
Marco Nelissen372be892014-12-04 08:59:22 -0800726 }
727
728#ifndef USE_SHARED_MEM_BUFFER
729 uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
730 // Ensure minimum audio buffer size in case of short looped sample
731 if(frameCount < totalFrames) {
732 frameCount = totalFrames;
733 }
734#endif
735
Andy Hung32ccb692015-03-27 18:27:27 -0700736 // check if the existing track has the same sample id.
737 if (mAudioTrack != 0 && mPrevSampleID == sample->sampleID()) {
738 // the sample rate may fail to change if the audio track is a fast track.
739 if (mAudioTrack->setSampleRate(sampleRate) == NO_ERROR) {
740 newTrack = mAudioTrack;
741 ALOGV("reusing track %p for sample %d", mAudioTrack.get(), sample->sampleID());
742 }
743 }
744 if (newTrack == 0) {
Andy Hung0c4b81b2015-03-17 23:02:00 +0000745 // mToggle toggles each time a track is started on a given channel.
746 // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
747 // as callback user data. This enables the detection of callbacks received from the old
748 // audio track while the new one is being started and avoids processing them with
749 // wrong audio audio buffer size (mAudioBufferSize)
750 unsigned long toggle = mToggle ^ 1;
751 void *userData = (void *)((unsigned long)this | toggle);
752 audio_channel_mask_t channelMask = audio_channel_out_mask_from_count(numChannels);
Marco Nelissen372be892014-12-04 08:59:22 -0800753
Andy Hung0c4b81b2015-03-17 23:02:00 +0000754 // do not create a new audio track if current track is compatible with sample parameters
755 #ifdef USE_SHARED_MEM_BUFFER
756 newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
Jean-Michel Trivi6c307872015-05-13 19:03:21 -0700757 channelMask, sample->getIMemory(), AUDIO_OUTPUT_FLAG_FAST, callback, userData,
758 0 /*default notification frames*/, AUDIO_SESSION_ALLOCATE,
759 AudioTrack::TRANSFER_DEFAULT,
760 NULL /*offloadInfo*/, -1 /*uid*/, -1 /*pid*/, mSoundPool->attributes());
Andy Hung0c4b81b2015-03-17 23:02:00 +0000761 #else
762 uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
763 newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
764 channelMask, frameCount, AUDIO_OUTPUT_FLAG_FAST, callback, userData,
Jean-Michel Trivi6c307872015-05-13 19:03:21 -0700765 bufferFrames, AUDIO_SESSION_ALLOCATE, AudioTrack::TRANSFER_DEFAULT,
766 NULL /*offloadInfo*/, -1 /*uid*/, -1 /*pid*/, mSoundPool->attributes());
Andy Hung0c4b81b2015-03-17 23:02:00 +0000767 #endif
768 oldTrack = mAudioTrack;
769 status = newTrack->initCheck();
770 if (status != NO_ERROR) {
771 ALOGE("Error creating AudioTrack");
Glenn Kasten14d226a2015-05-18 13:53:39 -0700772 // newTrack goes out of scope, so reference count drops to zero
Andy Hung0c4b81b2015-03-17 23:02:00 +0000773 goto exit;
774 }
775 // From now on, AudioTrack callbacks received with previous toggle value will be ignored.
776 mToggle = toggle;
777 mAudioTrack = newTrack;
Andy Hungbc453732015-03-17 23:05:12 +0000778 ALOGV("using new track %p for sample %d", newTrack.get(), sample->sampleID());
Marco Nelissen372be892014-12-04 08:59:22 -0800779 }
Marco Nelissen372be892014-12-04 08:59:22 -0800780 newTrack->setVolume(leftVolume, rightVolume);
781 newTrack->setLoop(0, frameCount, loop);
Marco Nelissen372be892014-12-04 08:59:22 -0800782 mPos = 0;
783 mSample = sample;
784 mChannelID = nextChannelID;
785 mPriority = priority;
786 mLoop = loop;
787 mLeftVolume = leftVolume;
788 mRightVolume = rightVolume;
789 mNumChannels = numChannels;
790 mRate = rate;
791 clearNextEvent();
792 mState = PLAYING;
793 mAudioTrack->start();
794 mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
795 }
796
797exit:
798 ALOGV("delete oldTrack %p", oldTrack.get());
799 if (status != NO_ERROR) {
800 mAudioTrack.clear();
801 }
802}
803
804void SoundChannel::nextEvent()
805{
806 sp<Sample> sample;
807 int nextChannelID;
808 float leftVolume;
809 float rightVolume;
810 int priority;
811 int loop;
812 float rate;
813
814 // check for valid event
815 {
816 Mutex::Autolock lock(&mLock);
817 nextChannelID = mNextEvent.channelID();
818 if (nextChannelID == 0) {
819 ALOGV("stolen channel has no event");
820 return;
821 }
822
823 sample = mNextEvent.sample();
824 leftVolume = mNextEvent.leftVolume();
825 rightVolume = mNextEvent.rightVolume();
826 priority = mNextEvent.priority();
827 loop = mNextEvent.loop();
828 rate = mNextEvent.rate();
829 }
830
831 ALOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
832 play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
833}
834
835void SoundChannel::callback(int event, void* user, void *info)
836{
837 SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
838
839 channel->process(event, info, (unsigned long)user & 1);
840}
841
842void SoundChannel::process(int event, void *info, unsigned long toggle)
843{
844 //ALOGV("process(%d)", mChannelID);
845
846 Mutex::Autolock lock(&mLock);
847
848 AudioTrack::Buffer* b = NULL;
849 if (event == AudioTrack::EVENT_MORE_DATA) {
850 b = static_cast<AudioTrack::Buffer *>(info);
851 }
852
853 if (mToggle != toggle) {
854 ALOGV("process wrong toggle %p channel %d", this, mChannelID);
855 if (b != NULL) {
856 b->size = 0;
857 }
858 return;
859 }
860
861 sp<Sample> sample = mSample;
862
863// ALOGV("SoundChannel::process event %d", event);
864
865 if (event == AudioTrack::EVENT_MORE_DATA) {
866
867 // check for stop state
868 if (b->size == 0) return;
869
870 if (mState == IDLE) {
871 b->size = 0;
872 return;
873 }
874
875 if (sample != 0) {
876 // fill buffer
877 uint8_t* q = (uint8_t*) b->i8;
878 size_t count = 0;
879
880 if (mPos < (int)sample->size()) {
881 uint8_t* p = sample->data() + mPos;
882 count = sample->size() - mPos;
883 if (count > b->size) {
884 count = b->size;
885 }
886 memcpy(q, p, count);
887// ALOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size,
888// count);
889 } else if (mPos < mAudioBufferSize) {
890 count = mAudioBufferSize - mPos;
891 if (count > b->size) {
892 count = b->size;
893 }
894 memset(q, 0, count);
895// ALOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
896 }
897
898 mPos += count;
899 b->size = count;
900 //ALOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
901 }
902 } else if (event == AudioTrack::EVENT_UNDERRUN || event == AudioTrack::EVENT_BUFFER_END) {
903 ALOGV("process %p channel %d event %s",
904 this, mChannelID, (event == AudioTrack::EVENT_UNDERRUN) ? "UNDERRUN" :
905 "BUFFER_END");
906 mSoundPool->addToStopList(this);
907 } else if (event == AudioTrack::EVENT_LOOP_END) {
908 ALOGV("End loop %p channel %d", this, mChannelID);
909 } else if (event == AudioTrack::EVENT_NEW_IAUDIOTRACK) {
910 ALOGV("process %p channel %d NEW_IAUDIOTRACK", this, mChannelID);
911 } else {
912 ALOGW("SoundChannel::process unexpected event %d", event);
913 }
914}
915
916
917// call with lock held
918bool SoundChannel::doStop_l()
919{
920 if (mState != IDLE) {
921 setVolume_l(0, 0);
922 ALOGV("stop");
923 mAudioTrack->stop();
Andy Hung0c4b81b2015-03-17 23:02:00 +0000924 mPrevSampleID = mSample->sampleID();
Marco Nelissen372be892014-12-04 08:59:22 -0800925 mSample.clear();
926 mState = IDLE;
927 mPriority = IDLE_PRIORITY;
928 return true;
929 }
930 return false;
931}
932
933// call with lock held and sound pool lock held
934void SoundChannel::stop_l()
935{
936 if (doStop_l()) {
937 mSoundPool->done_l(this);
938 }
939}
940
941// call with sound pool lock held
942void SoundChannel::stop()
943{
944 bool stopped;
945 {
946 Mutex::Autolock lock(&mLock);
947 stopped = doStop_l();
948 }
949
950 if (stopped) {
951 mSoundPool->done_l(this);
952 }
953}
954
955//FIXME: Pause is a little broken right now
956void SoundChannel::pause()
957{
958 Mutex::Autolock lock(&mLock);
959 if (mState == PLAYING) {
960 ALOGV("pause track");
961 mState = PAUSED;
962 mAudioTrack->pause();
963 }
964}
965
966void SoundChannel::autoPause()
967{
968 Mutex::Autolock lock(&mLock);
969 if (mState == PLAYING) {
970 ALOGV("pause track");
971 mState = PAUSED;
972 mAutoPaused = true;
973 mAudioTrack->pause();
974 }
975}
976
977void SoundChannel::resume()
978{
979 Mutex::Autolock lock(&mLock);
980 if (mState == PAUSED) {
981 ALOGV("resume track");
982 mState = PLAYING;
983 mAutoPaused = false;
984 mAudioTrack->start();
985 }
986}
987
988void SoundChannel::autoResume()
989{
990 Mutex::Autolock lock(&mLock);
991 if (mAutoPaused && (mState == PAUSED)) {
992 ALOGV("resume track");
993 mState = PLAYING;
994 mAutoPaused = false;
995 mAudioTrack->start();
996 }
997}
998
999void SoundChannel::setRate(float rate)
1000{
1001 Mutex::Autolock lock(&mLock);
1002 if (mAudioTrack != NULL && mSample != 0) {
1003 uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5);
1004 mAudioTrack->setSampleRate(sampleRate);
1005 mRate = rate;
1006 }
1007}
1008
1009// call with lock held
1010void SoundChannel::setVolume_l(float leftVolume, float rightVolume)
1011{
1012 mLeftVolume = leftVolume;
1013 mRightVolume = rightVolume;
1014 if (mAudioTrack != NULL)
1015 mAudioTrack->setVolume(leftVolume, rightVolume);
1016}
1017
1018void SoundChannel::setVolume(float leftVolume, float rightVolume)
1019{
1020 Mutex::Autolock lock(&mLock);
1021 setVolume_l(leftVolume, rightVolume);
1022}
1023
1024void SoundChannel::setLoop(int loop)
1025{
1026 Mutex::Autolock lock(&mLock);
1027 if (mAudioTrack != NULL && mSample != 0) {
1028 uint32_t loopEnd = mSample->size()/mNumChannels/
1029 ((mSample->format() == AUDIO_FORMAT_PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
1030 mAudioTrack->setLoop(0, loopEnd, loop);
1031 mLoop = loop;
1032 }
1033}
1034
1035SoundChannel::~SoundChannel()
1036{
1037 ALOGV("SoundChannel destructor %p", this);
1038 {
1039 Mutex::Autolock lock(&mLock);
1040 clearNextEvent();
1041 doStop_l();
1042 }
1043 // do not call AudioTrack destructor with mLock held as it will wait for the AudioTrack
1044 // callback thread to exit which may need to execute process() and acquire the mLock.
1045 mAudioTrack.clear();
1046}
1047
1048void SoundChannel::dump()
1049{
1050 ALOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d",
1051 mState, mChannelID, mNumChannels, mPos, mPriority, mLoop);
1052}
1053
1054void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
1055 float rightVolume, int priority, int loop, float rate)
1056{
1057 mSample = sample;
1058 mChannelID = channelID;
1059 mLeftVolume = leftVolume;
1060 mRightVolume = rightVolume;
1061 mPriority = priority;
1062 mLoop = loop;
1063 mRate =rate;
1064}
1065
1066} // end namespace android