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