blob: 29ad7ea5db7197748df6205eab6d58a3ba3466aa [file] [log] [blame]
Eric Laurent2e66a782012-03-26 10:47:22 -07001/*
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"
Mark Salyzyn34fb2962014-06-18 16:30:56 -070019
20#include <inttypes.h>
21
Eric Laurent2e66a782012-03-26 10:47:22 -070022#include <utils/Log.h>
23
Glenn Kasten8973c042013-09-11 14:35:16 -070024#define USE_SHARED_MEM_BUFFER
Eric Laurent2e66a782012-03-26 10:47:22 -070025
Eric Laurent2e66a782012-03-26 10:47:22 -070026#include <media/AudioTrack.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080027#include <media/IMediaHTTPService.h>
Eric Laurent2e66a782012-03-26 10:47:22 -070028#include <media/mediaplayer.h>
James Dong559bf282012-03-28 10:29:14 -070029#include <media/SoundPool.h>
Eric Laurent2e66a782012-03-26 10:47:22 -070030#include "SoundPoolThread.h"
Jean-Michel Trividf813a32014-07-20 17:58:33 -070031#include <media/AudioPolicyHelper.h>
Eric Laurent2e66a782012-03-26 10:47:22 -070032
33namespace android
34{
35
36int kDefaultBufferCount = 4;
37uint32_t kMaxSampleRate = 48000;
38uint32_t kDefaultSampleRate = 44100;
39uint32_t kDefaultFrameCount = 1200;
Eric Laurent3d00aa62013-09-24 09:53:27 -070040size_t kDefaultHeapSize = 1024 * 1024; // 1MB
41
Eric Laurent2e66a782012-03-26 10:47:22 -070042
Jean-Michel Trividf813a32014-07-20 17:58:33 -070043SoundPool::SoundPool(int maxChannels, const audio_attributes_t* pAttributes)
Eric Laurent2e66a782012-03-26 10:47:22 -070044{
Jean-Michel Trividf813a32014-07-20 17:58:33 -070045 ALOGV("SoundPool constructor: maxChannels=%d, attr.usage=%d, attr.flags=0x%x, attr.tags=%s",
46 maxChannels, pAttributes->usage, pAttributes->flags, pAttributes->tags);
Eric Laurent2e66a782012-03-26 10:47:22 -070047
48 // check limits
49 mMaxChannels = maxChannels;
50 if (mMaxChannels < 1) {
51 mMaxChannels = 1;
52 }
53 else if (mMaxChannels > 32) {
54 mMaxChannels = 32;
55 }
56 ALOGW_IF(maxChannels != mMaxChannels, "App requested %d channels", maxChannels);
57
58 mQuit = false;
59 mDecodeThread = 0;
Jean-Michel Trividf813a32014-07-20 17:58:33 -070060 memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
Eric Laurent2e66a782012-03-26 10:47:22 -070061 mAllocated = 0;
62 mNextSampleID = 0;
63 mNextChannelID = 0;
64
65 mCallback = 0;
66 mUserData = 0;
67
68 mChannelPool = new SoundChannel[mMaxChannels];
69 for (int i = 0; i < mMaxChannels; ++i) {
70 mChannelPool[i].init(this);
71 mChannels.push_back(&mChannelPool[i]);
72 }
73
74 // start decode thread
75 startThreads();
76}
77
78SoundPool::~SoundPool()
79{
80 ALOGV("SoundPool destructor");
81 mDecodeThread->quit();
82 quit();
83
84 Mutex::Autolock lock(&mLock);
85
86 mChannels.clear();
87 if (mChannelPool)
88 delete [] mChannelPool;
89 // clean up samples
90 ALOGV("clear samples");
91 mSamples.clear();
92
93 if (mDecodeThread)
94 delete mDecodeThread;
95}
96
97void SoundPool::addToRestartList(SoundChannel* channel)
98{
99 Mutex::Autolock lock(&mRestartLock);
100 if (!mQuit) {
101 mRestart.push_back(channel);
102 mCondition.signal();
103 }
104}
105
106void SoundPool::addToStopList(SoundChannel* channel)
107{
108 Mutex::Autolock lock(&mRestartLock);
109 if (!mQuit) {
110 mStop.push_back(channel);
111 mCondition.signal();
112 }
113}
114
115int SoundPool::beginThread(void* arg)
116{
117 SoundPool* p = (SoundPool*)arg;
118 return p->run();
119}
120
121int SoundPool::run()
122{
123 mRestartLock.lock();
124 while (!mQuit) {
125 mCondition.wait(mRestartLock);
126 ALOGV("awake");
127 if (mQuit) break;
128
129 while (!mStop.empty()) {
130 SoundChannel* channel;
131 ALOGV("Getting channel from stop list");
132 List<SoundChannel* >::iterator iter = mStop.begin();
133 channel = *iter;
134 mStop.erase(iter);
135 mRestartLock.unlock();
136 if (channel != 0) {
137 Mutex::Autolock lock(&mLock);
138 channel->stop();
139 }
140 mRestartLock.lock();
141 if (mQuit) break;
142 }
143
144 while (!mRestart.empty()) {
145 SoundChannel* channel;
146 ALOGV("Getting channel from list");
147 List<SoundChannel*>::iterator iter = mRestart.begin();
148 channel = *iter;
149 mRestart.erase(iter);
150 mRestartLock.unlock();
151 if (channel != 0) {
152 Mutex::Autolock lock(&mLock);
153 channel->nextEvent();
154 }
155 mRestartLock.lock();
156 if (mQuit) break;
157 }
158 }
159
160 mStop.clear();
161 mRestart.clear();
162 mCondition.signal();
163 mRestartLock.unlock();
164 ALOGV("goodbye");
165 return 0;
166}
167
168void SoundPool::quit()
169{
170 mRestartLock.lock();
171 mQuit = true;
172 mCondition.signal();
173 mCondition.wait(mRestartLock);
174 ALOGV("return from quit");
175 mRestartLock.unlock();
176}
177
178bool SoundPool::startThreads()
179{
180 createThreadEtc(beginThread, this, "SoundPool");
181 if (mDecodeThread == NULL)
182 mDecodeThread = new SoundPoolThread(this);
183 return mDecodeThread != NULL;
184}
185
Andy Hung19c47af2015-12-02 15:55:23 -0800186sp<Sample> SoundPool::findSample(int sampleID)
187{
188 Mutex::Autolock lock(&mLock);
189 return findSample_l(sampleID);
190}
191
192sp<Sample> SoundPool::findSample_l(int sampleID)
193{
194 return mSamples.valueFor(sampleID);
195}
196
Eric Laurent2e66a782012-03-26 10:47:22 -0700197SoundChannel* SoundPool::findChannel(int channelID)
198{
199 for (int i = 0; i < mMaxChannels; ++i) {
200 if (mChannelPool[i].channelID() == channelID) {
201 return &mChannelPool[i];
202 }
203 }
204 return NULL;
205}
206
207SoundChannel* SoundPool::findNextChannel(int channelID)
208{
209 for (int i = 0; i < mMaxChannels; ++i) {
210 if (mChannelPool[i].nextChannelID() == channelID) {
211 return &mChannelPool[i];
212 }
213 }
214 return NULL;
215}
216
Glenn Kasten7c7be1e2013-12-19 16:34:04 -0800217int SoundPool::load(const char* path, int priority __unused)
Eric Laurent2e66a782012-03-26 10:47:22 -0700218{
219 ALOGV("load: path=%s, priority=%d", path, priority);
Andy Hung19c47af2015-12-02 15:55:23 -0800220 int sampleID;
221 {
222 Mutex::Autolock lock(&mLock);
223 sampleID = ++mNextSampleID;
224 sp<Sample> sample = new Sample(sampleID, path);
225 mSamples.add(sampleID, sample);
226 sample->startLoad();
227 }
228 // mDecodeThread->loadSample() must be called outside of mLock.
229 // mDecodeThread->loadSample() may block on mDecodeThread message queue space;
230 // the message queue emptying may block on SoundPool::findSample().
231 //
232 // It theoretically possible that sample loads might decode out-of-order.
233 mDecodeThread->loadSample(sampleID);
234 return sampleID;
Eric Laurent2e66a782012-03-26 10:47:22 -0700235}
236
Glenn Kasten7c7be1e2013-12-19 16:34:04 -0800237int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused)
Eric Laurent2e66a782012-03-26 10:47:22 -0700238{
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700239 ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d",
Eric Laurent2e66a782012-03-26 10:47:22 -0700240 fd, offset, length, priority);
Andy Hung19c47af2015-12-02 15:55:23 -0800241 int sampleID;
242 {
243 Mutex::Autolock lock(&mLock);
244 sampleID = ++mNextSampleID;
245 sp<Sample> sample = new Sample(sampleID, fd, offset, length);
246 mSamples.add(sampleID, sample);
247 sample->startLoad();
248 }
249 // mDecodeThread->loadSample() must be called outside of mLock.
250 // mDecodeThread->loadSample() may block on mDecodeThread message queue space;
251 // the message queue emptying may block on SoundPool::findSample().
252 //
253 // It theoretically possible that sample loads might decode out-of-order.
254 mDecodeThread->loadSample(sampleID);
255 return sampleID;
Eric Laurent2e66a782012-03-26 10:47:22 -0700256}
257
258bool SoundPool::unload(int sampleID)
259{
260 ALOGV("unload: sampleID=%d", sampleID);
261 Mutex::Autolock lock(&mLock);
262 return mSamples.removeItem(sampleID);
263}
264
265int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
266 int priority, int loop, float rate)
267{
268 ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
269 sampleID, leftVolume, rightVolume, priority, loop, rate);
Eric Laurent2e66a782012-03-26 10:47:22 -0700270 SoundChannel* channel;
271 int channelID;
272
273 Mutex::Autolock lock(&mLock);
274
275 if (mQuit) {
276 return 0;
277 }
278 // is sample ready?
Andy Hung19c47af2015-12-02 15:55:23 -0800279 sp<Sample> sample(findSample_l(sampleID));
Eric Laurent2e66a782012-03-26 10:47:22 -0700280 if ((sample == 0) || (sample->state() != Sample::READY)) {
281 ALOGW(" sample %d not READY", sampleID);
282 return 0;
283 }
284
285 dump();
286
287 // allocate a channel
288 channel = allocateChannel_l(priority);
289
290 // no channel allocated - return 0
291 if (!channel) {
292 ALOGV("No channel allocated");
293 return 0;
294 }
295
296 channelID = ++mNextChannelID;
297
298 ALOGV("play channel %p state = %d", channel, channel->state());
299 channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
300 return channelID;
301}
302
303SoundChannel* SoundPool::allocateChannel_l(int priority)
304{
305 List<SoundChannel*>::iterator iter;
306 SoundChannel* channel = NULL;
307
308 // allocate a channel
309 if (!mChannels.empty()) {
310 iter = mChannels.begin();
311 if (priority >= (*iter)->priority()) {
312 channel = *iter;
313 mChannels.erase(iter);
314 ALOGV("Allocated active channel");
315 }
316 }
317
318 // update priority and put it back in the list
319 if (channel) {
320 channel->setPriority(priority);
321 for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
322 if (priority < (*iter)->priority()) {
323 break;
324 }
325 }
326 mChannels.insert(iter, channel);
327 }
328 return channel;
329}
330
331// move a channel from its current position to the front of the list
332void SoundPool::moveToFront_l(SoundChannel* channel)
333{
334 for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
335 if (*iter == channel) {
336 mChannels.erase(iter);
337 mChannels.push_front(channel);
338 break;
339 }
340 }
341}
342
343void SoundPool::pause(int channelID)
344{
345 ALOGV("pause(%d)", channelID);
346 Mutex::Autolock lock(&mLock);
347 SoundChannel* channel = findChannel(channelID);
348 if (channel) {
349 channel->pause();
350 }
351}
352
353void SoundPool::autoPause()
354{
355 ALOGV("autoPause()");
356 Mutex::Autolock lock(&mLock);
357 for (int i = 0; i < mMaxChannels; ++i) {
358 SoundChannel* channel = &mChannelPool[i];
359 channel->autoPause();
360 }
361}
362
363void SoundPool::resume(int channelID)
364{
365 ALOGV("resume(%d)", channelID);
366 Mutex::Autolock lock(&mLock);
367 SoundChannel* channel = findChannel(channelID);
368 if (channel) {
369 channel->resume();
370 }
371}
372
373void SoundPool::autoResume()
374{
375 ALOGV("autoResume()");
376 Mutex::Autolock lock(&mLock);
377 for (int i = 0; i < mMaxChannels; ++i) {
378 SoundChannel* channel = &mChannelPool[i];
379 channel->autoResume();
380 }
381}
382
383void SoundPool::stop(int channelID)
384{
385 ALOGV("stop(%d)", channelID);
386 Mutex::Autolock lock(&mLock);
387 SoundChannel* channel = findChannel(channelID);
388 if (channel) {
389 channel->stop();
390 } else {
391 channel = findNextChannel(channelID);
392 if (channel)
393 channel->clearNextEvent();
394 }
395}
396
397void SoundPool::setVolume(int channelID, float leftVolume, float rightVolume)
398{
399 Mutex::Autolock lock(&mLock);
400 SoundChannel* channel = findChannel(channelID);
401 if (channel) {
402 channel->setVolume(leftVolume, rightVolume);
403 }
404}
405
406void SoundPool::setPriority(int channelID, int priority)
407{
408 ALOGV("setPriority(%d, %d)", channelID, priority);
409 Mutex::Autolock lock(&mLock);
410 SoundChannel* channel = findChannel(channelID);
411 if (channel) {
412 channel->setPriority(priority);
413 }
414}
415
416void SoundPool::setLoop(int channelID, int loop)
417{
418 ALOGV("setLoop(%d, %d)", channelID, loop);
419 Mutex::Autolock lock(&mLock);
420 SoundChannel* channel = findChannel(channelID);
421 if (channel) {
422 channel->setLoop(loop);
423 }
424}
425
426void SoundPool::setRate(int channelID, float rate)
427{
428 ALOGV("setRate(%d, %f)", channelID, rate);
429 Mutex::Autolock lock(&mLock);
430 SoundChannel* channel = findChannel(channelID);
431 if (channel) {
432 channel->setRate(rate);
433 }
434}
435
436// call with lock held
437void SoundPool::done_l(SoundChannel* channel)
438{
439 ALOGV("done_l(%d)", channel->channelID());
440 // if "stolen", play next event
441 if (channel->nextChannelID() != 0) {
442 ALOGV("add to restart list");
443 addToRestartList(channel);
444 }
445
446 // return to idle state
447 else {
448 ALOGV("move to front");
449 moveToFront_l(channel);
450 }
451}
452
453void SoundPool::setCallback(SoundPoolCallback* callback, void* user)
454{
455 Mutex::Autolock lock(&mCallbackLock);
456 mCallback = callback;
457 mUserData = user;
458}
459
460void SoundPool::notify(SoundPoolEvent event)
461{
462 Mutex::Autolock lock(&mCallbackLock);
463 if (mCallback != NULL) {
464 mCallback(event, this, mUserData);
465 }
466}
467
468void SoundPool::dump()
469{
470 for (int i = 0; i < mMaxChannels; ++i) {
471 mChannelPool[i].dump();
472 }
473}
474
475
476Sample::Sample(int sampleID, const char* url)
477{
478 init();
479 mSampleID = sampleID;
480 mUrl = strdup(url);
481 ALOGV("create sampleID=%d, url=%s", mSampleID, mUrl);
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;
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700491 ALOGV("create sampleID=%d, fd=%d, offset=%" PRId64 " length=%" PRId64,
492 mSampleID, mFd, mLength, mOffset);
Eric Laurent2e66a782012-03-26 10:47:22 -0700493}
494
495void Sample::init()
496{
Eric Laurent2e66a782012-03-26 10:47:22 -0700497 mSize = 0;
498 mRefCount = 0;
499 mSampleID = 0;
500 mState = UNLOADED;
501 mFd = -1;
502 mOffset = 0;
503 mLength = 0;
504 mUrl = 0;
505}
506
507Sample::~Sample()
508{
509 ALOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd);
510 if (mFd > 0) {
511 ALOGV("close(%d)", mFd);
512 ::close(mFd);
513 }
Marco Nelissena6b47a12012-11-19 09:49:18 -0800514 free(mUrl);
Eric Laurent2e66a782012-03-26 10:47:22 -0700515}
516
517status_t Sample::doLoad()
518{
519 uint32_t sampleRate;
520 int numChannels;
521 audio_format_t format;
Eric Laurent3d00aa62013-09-24 09:53:27 -0700522 status_t status;
523 mHeap = new MemoryHeapBase(kDefaultHeapSize);
524
Eric Laurent2e66a782012-03-26 10:47:22 -0700525 ALOGV("Start decode");
526 if (mUrl) {
Andreas Huber1b86fe02014-01-29 11:13:26 -0800527 status = MediaPlayer::decode(
528 NULL /* httpService */,
529 mUrl,
530 &sampleRate,
531 &numChannels,
532 &format,
533 mHeap,
534 &mSize);
Eric Laurent2e66a782012-03-26 10:47:22 -0700535 } else {
Eric Laurent3d00aa62013-09-24 09:53:27 -0700536 status = MediaPlayer::decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format,
537 mHeap, &mSize);
Eric Laurent2e66a782012-03-26 10:47:22 -0700538 ALOGV("close(%d)", mFd);
539 ::close(mFd);
540 mFd = -1;
541 }
Eric Laurent3d00aa62013-09-24 09:53:27 -0700542 if (status != NO_ERROR) {
Eric Laurent2e66a782012-03-26 10:47:22 -0700543 ALOGE("Unable to load sample: %s", mUrl);
Eric Laurent3d00aa62013-09-24 09:53:27 -0700544 goto error;
Eric Laurent2e66a782012-03-26 10:47:22 -0700545 }
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700546 ALOGV("pointer = %p, size = %zu, sampleRate = %u, numChannels = %d",
Eric Laurent3d00aa62013-09-24 09:53:27 -0700547 mHeap->getBase(), mSize, sampleRate, numChannels);
Eric Laurent2e66a782012-03-26 10:47:22 -0700548
549 if (sampleRate > kMaxSampleRate) {
550 ALOGE("Sample rate (%u) out of range", sampleRate);
Eric Laurent3d00aa62013-09-24 09:53:27 -0700551 status = BAD_VALUE;
552 goto error;
Eric Laurent2e66a782012-03-26 10:47:22 -0700553 }
554
555 if ((numChannels < 1) || (numChannels > 2)) {
556 ALOGE("Sample channel count (%d) out of range", numChannels);
Eric Laurent3d00aa62013-09-24 09:53:27 -0700557 status = BAD_VALUE;
558 goto error;
Eric Laurent2e66a782012-03-26 10:47:22 -0700559 }
560
Eric Laurent3d00aa62013-09-24 09:53:27 -0700561 mData = new MemoryBase(mHeap, 0, mSize);
Eric Laurent2e66a782012-03-26 10:47:22 -0700562 mSampleRate = sampleRate;
563 mNumChannels = numChannels;
564 mFormat = format;
565 mState = READY;
Eric Laurent3d00aa62013-09-24 09:53:27 -0700566 return NO_ERROR;
567
568error:
569 mHeap.clear();
570 return status;
Eric Laurent2e66a782012-03-26 10:47:22 -0700571}
572
573
574void SoundChannel::init(SoundPool* soundPool)
575{
576 mSoundPool = soundPool;
577}
578
579// call with sound pool lock held
580void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
581 float rightVolume, int priority, int loop, float rate)
582{
Glenn Kasten2799d742013-05-30 14:33:29 -0700583 sp<AudioTrack> oldTrack;
584 sp<AudioTrack> newTrack;
Eric Laurent2e66a782012-03-26 10:47:22 -0700585 status_t status;
586
587 { // scope for the lock
588 Mutex::Autolock lock(&mLock);
589
590 ALOGV("SoundChannel::play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f,"
591 " priority=%d, loop=%d, rate=%f",
592 this, sample->sampleID(), nextChannelID, leftVolume, rightVolume,
593 priority, loop, rate);
594
595 // if not idle, this voice is being stolen
596 if (mState != IDLE) {
597 ALOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
598 mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
599 stop_l();
600 return;
601 }
602
603 // initialize track
Glenn Kastene33054e2012-11-14 12:54:39 -0800604 size_t afFrameCount;
Glenn Kasten3b16c762012-11-14 08:44:39 -0800605 uint32_t afSampleRate;
Jean-Michel Trividf813a32014-07-20 17:58:33 -0700606 audio_stream_type_t streamType = audio_attributes_to_stream_type(mSoundPool->attributes());
Eric Laurent2e66a782012-03-26 10:47:22 -0700607 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
608 afFrameCount = kDefaultFrameCount;
609 }
610 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
611 afSampleRate = kDefaultSampleRate;
612 }
613 int numChannels = sample->numChannels();
614 uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
615 uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
616 uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800617 size_t frameCount = 0;
Eric Laurent2e66a782012-03-26 10:47:22 -0700618
619 if (loop) {
620 frameCount = sample->size()/numChannels/
621 ((sample->format() == AUDIO_FORMAT_PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
622 }
623
624#ifndef USE_SHARED_MEM_BUFFER
625 // Ensure minimum audio buffer size in case of short looped sample
626 if(frameCount < totalFrames) {
627 frameCount = totalFrames;
628 }
629#endif
630
631 // mToggle toggles each time a track is started on a given channel.
632 // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
633 // as callback user data. This enables the detection of callbacks received from the old
634 // audio track while the new one is being started and avoids processing them with
635 // wrong audio audio buffer size (mAudioBufferSize)
636 unsigned long toggle = mToggle ^ 1;
637 void *userData = (void *)((unsigned long)this | toggle);
Glenn Kasten79c57862013-10-30 09:47:17 -0700638 audio_channel_mask_t channelMask = audio_channel_out_mask_from_count(numChannels);
Eric Laurent2e66a782012-03-26 10:47:22 -0700639
640 // do not create a new audio track if current track is compatible with sample parameters
641#ifdef USE_SHARED_MEM_BUFFER
642 newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
Glenn Kasten79c57862013-10-30 09:47:17 -0700643 channelMask, sample->getIMemory(), AUDIO_OUTPUT_FLAG_FAST, callback, userData);
Eric Laurent2e66a782012-03-26 10:47:22 -0700644#else
645 newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
Glenn Kasten79c57862013-10-30 09:47:17 -0700646 channelMask, frameCount, AUDIO_OUTPUT_FLAG_FAST, callback, userData,
Eric Laurent2e66a782012-03-26 10:47:22 -0700647 bufferFrames);
648#endif
649 oldTrack = mAudioTrack;
650 status = newTrack->initCheck();
651 if (status != NO_ERROR) {
652 ALOGE("Error creating AudioTrack");
653 goto exit;
654 }
Glenn Kasten2799d742013-05-30 14:33:29 -0700655 ALOGV("setVolume %p", newTrack.get());
Eric Laurent2e66a782012-03-26 10:47:22 -0700656 newTrack->setVolume(leftVolume, rightVolume);
657 newTrack->setLoop(0, frameCount, loop);
658
659 // From now on, AudioTrack callbacks received with previous toggle value will be ignored.
660 mToggle = toggle;
661 mAudioTrack = newTrack;
662 mPos = 0;
663 mSample = sample;
664 mChannelID = nextChannelID;
665 mPriority = priority;
666 mLoop = loop;
667 mLeftVolume = leftVolume;
668 mRightVolume = rightVolume;
669 mNumChannels = numChannels;
670 mRate = rate;
671 clearNextEvent();
672 mState = PLAYING;
673 mAudioTrack->start();
674 mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
675 }
676
677exit:
Glenn Kasten2799d742013-05-30 14:33:29 -0700678 ALOGV("delete oldTrack %p", oldTrack.get());
Eric Laurent2e66a782012-03-26 10:47:22 -0700679 if (status != NO_ERROR) {
Glenn Kasten2799d742013-05-30 14:33:29 -0700680 mAudioTrack.clear();
Eric Laurent2e66a782012-03-26 10:47:22 -0700681 }
682}
683
684void SoundChannel::nextEvent()
685{
686 sp<Sample> sample;
687 int nextChannelID;
688 float leftVolume;
689 float rightVolume;
690 int priority;
691 int loop;
692 float rate;
693
694 // check for valid event
695 {
696 Mutex::Autolock lock(&mLock);
697 nextChannelID = mNextEvent.channelID();
698 if (nextChannelID == 0) {
699 ALOGV("stolen channel has no event");
700 return;
701 }
702
703 sample = mNextEvent.sample();
704 leftVolume = mNextEvent.leftVolume();
705 rightVolume = mNextEvent.rightVolume();
706 priority = mNextEvent.priority();
707 loop = mNextEvent.loop();
708 rate = mNextEvent.rate();
709 }
710
711 ALOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
712 play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
713}
714
715void SoundChannel::callback(int event, void* user, void *info)
716{
717 SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
718
719 channel->process(event, info, (unsigned long)user & 1);
720}
721
722void SoundChannel::process(int event, void *info, unsigned long toggle)
723{
724 //ALOGV("process(%d)", mChannelID);
725
726 Mutex::Autolock lock(&mLock);
727
728 AudioTrack::Buffer* b = NULL;
729 if (event == AudioTrack::EVENT_MORE_DATA) {
730 b = static_cast<AudioTrack::Buffer *>(info);
731 }
732
733 if (mToggle != toggle) {
734 ALOGV("process wrong toggle %p channel %d", this, mChannelID);
735 if (b != NULL) {
736 b->size = 0;
737 }
738 return;
739 }
740
741 sp<Sample> sample = mSample;
742
743// ALOGV("SoundChannel::process event %d", event);
744
745 if (event == AudioTrack::EVENT_MORE_DATA) {
746
747 // check for stop state
748 if (b->size == 0) return;
749
750 if (mState == IDLE) {
751 b->size = 0;
752 return;
753 }
754
755 if (sample != 0) {
756 // fill buffer
757 uint8_t* q = (uint8_t*) b->i8;
758 size_t count = 0;
759
760 if (mPos < (int)sample->size()) {
761 uint8_t* p = sample->data() + mPos;
762 count = sample->size() - mPos;
763 if (count > b->size) {
764 count = b->size;
765 }
766 memcpy(q, p, count);
Glenn Kasten4944acb2013-08-19 08:39:20 -0700767// ALOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size,
768// count);
Eric Laurent2e66a782012-03-26 10:47:22 -0700769 } else if (mPos < mAudioBufferSize) {
770 count = mAudioBufferSize - mPos;
771 if (count > b->size) {
772 count = b->size;
773 }
774 memset(q, 0, count);
775// ALOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
776 }
777
778 mPos += count;
779 b->size = count;
780 //ALOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
781 }
Eric Laurentb3cb72a2013-10-12 17:05:19 -0700782 } else if (event == AudioTrack::EVENT_UNDERRUN || event == AudioTrack::EVENT_BUFFER_END ||
783 event == AudioTrack::EVENT_NEW_IAUDIOTRACK) {
784 ALOGV("process %p channel %d event %s",
785 this, mChannelID, (event == AudioTrack::EVENT_UNDERRUN) ? "UNDERRUN" :
786 (event == AudioTrack::EVENT_BUFFER_END) ? "BUFFER_END" : "NEW_IAUDIOTRACK");
Eric Laurent2e66a782012-03-26 10:47:22 -0700787 mSoundPool->addToStopList(this);
788 } else if (event == AudioTrack::EVENT_LOOP_END) {
Eric Laurent3d00aa62013-09-24 09:53:27 -0700789 ALOGV("End loop %p channel %d", this, mChannelID);
Eric Laurentb3cb72a2013-10-12 17:05:19 -0700790 } else {
791 ALOGW("SoundChannel::process unexpected event %d", event);
Eric Laurent2e66a782012-03-26 10:47:22 -0700792 }
793}
794
795
796// call with lock held
797bool SoundChannel::doStop_l()
798{
799 if (mState != IDLE) {
800 setVolume_l(0, 0);
801 ALOGV("stop");
802 mAudioTrack->stop();
803 mSample.clear();
804 mState = IDLE;
805 mPriority = IDLE_PRIORITY;
806 return true;
807 }
808 return false;
809}
810
811// call with lock held and sound pool lock held
812void SoundChannel::stop_l()
813{
814 if (doStop_l()) {
815 mSoundPool->done_l(this);
816 }
817}
818
819// call with sound pool lock held
820void SoundChannel::stop()
821{
822 bool stopped;
823 {
824 Mutex::Autolock lock(&mLock);
825 stopped = doStop_l();
826 }
827
828 if (stopped) {
829 mSoundPool->done_l(this);
830 }
831}
832
833//FIXME: Pause is a little broken right now
834void SoundChannel::pause()
835{
836 Mutex::Autolock lock(&mLock);
837 if (mState == PLAYING) {
838 ALOGV("pause track");
839 mState = PAUSED;
840 mAudioTrack->pause();
841 }
842}
843
844void SoundChannel::autoPause()
845{
846 Mutex::Autolock lock(&mLock);
847 if (mState == PLAYING) {
848 ALOGV("pause track");
849 mState = PAUSED;
850 mAutoPaused = true;
851 mAudioTrack->pause();
852 }
853}
854
855void SoundChannel::resume()
856{
857 Mutex::Autolock lock(&mLock);
858 if (mState == PAUSED) {
859 ALOGV("resume track");
860 mState = PLAYING;
861 mAutoPaused = false;
862 mAudioTrack->start();
863 }
864}
865
866void SoundChannel::autoResume()
867{
868 Mutex::Autolock lock(&mLock);
869 if (mAutoPaused && (mState == PAUSED)) {
870 ALOGV("resume track");
871 mState = PLAYING;
872 mAutoPaused = false;
873 mAudioTrack->start();
874 }
875}
876
877void SoundChannel::setRate(float rate)
878{
879 Mutex::Autolock lock(&mLock);
880 if (mAudioTrack != NULL && mSample != 0) {
881 uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5);
882 mAudioTrack->setSampleRate(sampleRate);
883 mRate = rate;
884 }
885}
886
887// call with lock held
888void SoundChannel::setVolume_l(float leftVolume, float rightVolume)
889{
890 mLeftVolume = leftVolume;
891 mRightVolume = rightVolume;
892 if (mAudioTrack != NULL)
893 mAudioTrack->setVolume(leftVolume, rightVolume);
894}
895
896void SoundChannel::setVolume(float leftVolume, float rightVolume)
897{
898 Mutex::Autolock lock(&mLock);
899 setVolume_l(leftVolume, rightVolume);
900}
901
902void SoundChannel::setLoop(int loop)
903{
904 Mutex::Autolock lock(&mLock);
905 if (mAudioTrack != NULL && mSample != 0) {
906 uint32_t loopEnd = mSample->size()/mNumChannels/
907 ((mSample->format() == AUDIO_FORMAT_PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
908 mAudioTrack->setLoop(0, loopEnd, loop);
909 mLoop = loop;
910 }
911}
912
913SoundChannel::~SoundChannel()
914{
915 ALOGV("SoundChannel destructor %p", this);
916 {
917 Mutex::Autolock lock(&mLock);
918 clearNextEvent();
919 doStop_l();
920 }
921 // do not call AudioTrack destructor with mLock held as it will wait for the AudioTrack
922 // callback thread to exit which may need to execute process() and acquire the mLock.
Glenn Kasten2799d742013-05-30 14:33:29 -0700923 mAudioTrack.clear();
Eric Laurent2e66a782012-03-26 10:47:22 -0700924}
925
926void SoundChannel::dump()
927{
928 ALOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d",
929 mState, mChannelID, mNumChannels, mPos, mPriority, mLoop);
930}
931
932void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
933 float rightVolume, int priority, int loop, float rate)
934{
935 mSample = sample;
936 mChannelID = channelID;
937 mLeftVolume = leftVolume;
938 mRightVolume = rightVolume;
939 mPriority = priority;
940 mLoop = loop;
941 mRate =rate;
942}
943
944} // end namespace android