blob: a2b5e306f0b3cd977322b1e9721a9e40d9b1b150 [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"
19#include <utils/Log.h>
20
Glenn Kasten8973c042013-09-11 14:35:16 -070021#define USE_SHARED_MEM_BUFFER
Eric Laurent2e66a782012-03-26 10:47:22 -070022
Eric Laurent2e66a782012-03-26 10:47:22 -070023#include <media/AudioTrack.h>
24#include <media/mediaplayer.h>
James Dong559bf282012-03-28 10:29:14 -070025#include <media/SoundPool.h>
Eric Laurent2e66a782012-03-26 10:47:22 -070026#include "SoundPoolThread.h"
27
28namespace android
29{
30
31int kDefaultBufferCount = 4;
32uint32_t kMaxSampleRate = 48000;
33uint32_t kDefaultSampleRate = 44100;
34uint32_t kDefaultFrameCount = 1200;
Eric Laurent3d00aa62013-09-24 09:53:27 -070035size_t kDefaultHeapSize = 1024 * 1024; // 1MB
36
Eric Laurent2e66a782012-03-26 10:47:22 -070037
38SoundPool::SoundPool(int maxChannels, audio_stream_type_t streamType, int srcQuality)
39{
40 ALOGV("SoundPool constructor: maxChannels=%d, streamType=%d, srcQuality=%d",
41 maxChannels, streamType, srcQuality);
42
43 // check limits
44 mMaxChannels = maxChannels;
45 if (mMaxChannels < 1) {
46 mMaxChannels = 1;
47 }
48 else if (mMaxChannels > 32) {
49 mMaxChannels = 32;
50 }
51 ALOGW_IF(maxChannels != mMaxChannels, "App requested %d channels", maxChannels);
52
53 mQuit = false;
54 mDecodeThread = 0;
55 mStreamType = streamType;
56 mSrcQuality = srcQuality;
57 mAllocated = 0;
58 mNextSampleID = 0;
59 mNextChannelID = 0;
60
61 mCallback = 0;
62 mUserData = 0;
63
64 mChannelPool = new SoundChannel[mMaxChannels];
65 for (int i = 0; i < mMaxChannels; ++i) {
66 mChannelPool[i].init(this);
67 mChannels.push_back(&mChannelPool[i]);
68 }
69
70 // start decode thread
71 startThreads();
72}
73
74SoundPool::~SoundPool()
75{
76 ALOGV("SoundPool destructor");
77 mDecodeThread->quit();
78 quit();
79
80 Mutex::Autolock lock(&mLock);
81
82 mChannels.clear();
83 if (mChannelPool)
84 delete [] mChannelPool;
85 // clean up samples
86 ALOGV("clear samples");
87 mSamples.clear();
88
89 if (mDecodeThread)
90 delete mDecodeThread;
91}
92
93void SoundPool::addToRestartList(SoundChannel* channel)
94{
95 Mutex::Autolock lock(&mRestartLock);
96 if (!mQuit) {
97 mRestart.push_back(channel);
98 mCondition.signal();
99 }
100}
101
102void SoundPool::addToStopList(SoundChannel* channel)
103{
104 Mutex::Autolock lock(&mRestartLock);
105 if (!mQuit) {
106 mStop.push_back(channel);
107 mCondition.signal();
108 }
109}
110
111int SoundPool::beginThread(void* arg)
112{
113 SoundPool* p = (SoundPool*)arg;
114 return p->run();
115}
116
117int SoundPool::run()
118{
119 mRestartLock.lock();
120 while (!mQuit) {
121 mCondition.wait(mRestartLock);
122 ALOGV("awake");
123 if (mQuit) break;
124
125 while (!mStop.empty()) {
126 SoundChannel* channel;
127 ALOGV("Getting channel from stop list");
128 List<SoundChannel* >::iterator iter = mStop.begin();
129 channel = *iter;
130 mStop.erase(iter);
131 mRestartLock.unlock();
132 if (channel != 0) {
133 Mutex::Autolock lock(&mLock);
134 channel->stop();
135 }
136 mRestartLock.lock();
137 if (mQuit) break;
138 }
139
140 while (!mRestart.empty()) {
141 SoundChannel* channel;
142 ALOGV("Getting channel from list");
143 List<SoundChannel*>::iterator iter = mRestart.begin();
144 channel = *iter;
145 mRestart.erase(iter);
146 mRestartLock.unlock();
147 if (channel != 0) {
148 Mutex::Autolock lock(&mLock);
149 channel->nextEvent();
150 }
151 mRestartLock.lock();
152 if (mQuit) break;
153 }
154 }
155
156 mStop.clear();
157 mRestart.clear();
158 mCondition.signal();
159 mRestartLock.unlock();
160 ALOGV("goodbye");
161 return 0;
162}
163
164void SoundPool::quit()
165{
166 mRestartLock.lock();
167 mQuit = true;
168 mCondition.signal();
169 mCondition.wait(mRestartLock);
170 ALOGV("return from quit");
171 mRestartLock.unlock();
172}
173
174bool SoundPool::startThreads()
175{
176 createThreadEtc(beginThread, this, "SoundPool");
177 if (mDecodeThread == NULL)
178 mDecodeThread = new SoundPoolThread(this);
179 return mDecodeThread != NULL;
180}
181
Andy Hung3d6a7142015-12-02 15:55:23 -0800182sp<Sample> SoundPool::findSample(int sampleID)
183{
184 Mutex::Autolock lock(&mLock);
185 return findSample_l(sampleID);
186}
187
188sp<Sample> SoundPool::findSample_l(int sampleID)
189{
190 return mSamples.valueFor(sampleID);
191}
192
Eric Laurent2e66a782012-03-26 10:47:22 -0700193SoundChannel* SoundPool::findChannel(int channelID)
194{
195 for (int i = 0; i < mMaxChannels; ++i) {
196 if (mChannelPool[i].channelID() == channelID) {
197 return &mChannelPool[i];
198 }
199 }
200 return NULL;
201}
202
203SoundChannel* SoundPool::findNextChannel(int channelID)
204{
205 for (int i = 0; i < mMaxChannels; ++i) {
206 if (mChannelPool[i].nextChannelID() == channelID) {
207 return &mChannelPool[i];
208 }
209 }
210 return NULL;
211}
212
213int SoundPool::load(const char* path, int priority)
214{
215 ALOGV("load: path=%s, priority=%d", path, priority);
Andy Hung3d6a7142015-12-02 15:55:23 -0800216 int sampleID;
217 {
218 Mutex::Autolock lock(&mLock);
219 sampleID = ++mNextSampleID;
220 sp<Sample> sample = new Sample(sampleID, path);
221 mSamples.add(sampleID, sample);
222 sample->startLoad();
223 }
224 // mDecodeThread->loadSample() must be called outside of mLock.
225 // mDecodeThread->loadSample() may block on mDecodeThread message queue space;
226 // the message queue emptying may block on SoundPool::findSample().
227 //
228 // It theoretically possible that sample loads might decode out-of-order.
229 mDecodeThread->loadSample(sampleID);
230 return sampleID;
Eric Laurent2e66a782012-03-26 10:47:22 -0700231}
232
233int SoundPool::load(int fd, int64_t offset, int64_t length, int priority)
234{
235 ALOGV("load: fd=%d, offset=%lld, length=%lld, priority=%d",
236 fd, offset, length, priority);
Andy Hung3d6a7142015-12-02 15:55:23 -0800237 int sampleID;
238 {
239 Mutex::Autolock lock(&mLock);
240 sampleID = ++mNextSampleID;
241 sp<Sample> sample = new Sample(sampleID, fd, offset, length);
242 mSamples.add(sampleID, sample);
243 sample->startLoad();
244 }
245 // mDecodeThread->loadSample() must be called outside of mLock.
246 // mDecodeThread->loadSample() may block on mDecodeThread message queue space;
247 // the message queue emptying may block on SoundPool::findSample().
248 //
249 // It theoretically possible that sample loads might decode out-of-order.
250 mDecodeThread->loadSample(sampleID);
251 return sampleID;
Eric Laurent2e66a782012-03-26 10:47:22 -0700252}
253
254bool SoundPool::unload(int sampleID)
255{
256 ALOGV("unload: sampleID=%d", sampleID);
257 Mutex::Autolock lock(&mLock);
258 return mSamples.removeItem(sampleID);
259}
260
261int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
262 int priority, int loop, float rate)
263{
264 ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
265 sampleID, leftVolume, rightVolume, priority, loop, rate);
Eric Laurent2e66a782012-03-26 10:47:22 -0700266 SoundChannel* channel;
267 int channelID;
268
269 Mutex::Autolock lock(&mLock);
270
271 if (mQuit) {
272 return 0;
273 }
274 // is sample ready?
Andy Hung3d6a7142015-12-02 15:55:23 -0800275 sp<Sample> sample(findSample_l(sampleID));
Eric Laurent2e66a782012-03-26 10:47:22 -0700276 if ((sample == 0) || (sample->state() != Sample::READY)) {
277 ALOGW(" sample %d not READY", sampleID);
278 return 0;
279 }
280
281 dump();
282
283 // allocate a channel
284 channel = allocateChannel_l(priority);
285
286 // no channel allocated - return 0
287 if (!channel) {
288 ALOGV("No channel allocated");
289 return 0;
290 }
291
292 channelID = ++mNextChannelID;
293
294 ALOGV("play channel %p state = %d", channel, channel->state());
295 channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
296 return channelID;
297}
298
299SoundChannel* SoundPool::allocateChannel_l(int priority)
300{
301 List<SoundChannel*>::iterator iter;
302 SoundChannel* channel = NULL;
303
304 // allocate a channel
305 if (!mChannels.empty()) {
306 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, const char* url)
473{
474 init();
475 mSampleID = sampleID;
476 mUrl = strdup(url);
477 ALOGV("create sampleID=%d, url=%s", mSampleID, mUrl);
478}
479
480Sample::Sample(int sampleID, int fd, int64_t offset, int64_t length)
481{
482 init();
483 mSampleID = sampleID;
484 mFd = dup(fd);
485 mOffset = offset;
486 mLength = length;
487 ALOGV("create sampleID=%d, fd=%d, offset=%lld, length=%lld", mSampleID, mFd, mLength, mOffset);
488}
489
490void Sample::init()
491{
Eric Laurent2e66a782012-03-26 10:47:22 -0700492 mSize = 0;
493 mRefCount = 0;
494 mSampleID = 0;
495 mState = UNLOADED;
496 mFd = -1;
497 mOffset = 0;
498 mLength = 0;
499 mUrl = 0;
500}
501
502Sample::~Sample()
503{
504 ALOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd);
505 if (mFd > 0) {
506 ALOGV("close(%d)", mFd);
507 ::close(mFd);
508 }
Marco Nelissena6b47a12012-11-19 09:49:18 -0800509 free(mUrl);
Eric Laurent2e66a782012-03-26 10:47:22 -0700510}
511
512status_t Sample::doLoad()
513{
514 uint32_t sampleRate;
515 int numChannels;
516 audio_format_t format;
Eric Laurent3d00aa62013-09-24 09:53:27 -0700517 status_t status;
518 mHeap = new MemoryHeapBase(kDefaultHeapSize);
519
Eric Laurent2e66a782012-03-26 10:47:22 -0700520 ALOGV("Start decode");
521 if (mUrl) {
Eric Laurent3d00aa62013-09-24 09:53:27 -0700522 status = MediaPlayer::decode(mUrl, &sampleRate, &numChannels, &format, mHeap, &mSize);
Eric Laurent2e66a782012-03-26 10:47:22 -0700523 } else {
Eric Laurent3d00aa62013-09-24 09:53:27 -0700524 status = MediaPlayer::decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format,
525 mHeap, &mSize);
Eric Laurent2e66a782012-03-26 10:47:22 -0700526 ALOGV("close(%d)", mFd);
527 ::close(mFd);
528 mFd = -1;
529 }
Eric Laurent3d00aa62013-09-24 09:53:27 -0700530 if (status != NO_ERROR) {
Eric Laurent2e66a782012-03-26 10:47:22 -0700531 ALOGE("Unable to load sample: %s", mUrl);
Eric Laurent3d00aa62013-09-24 09:53:27 -0700532 goto error;
Eric Laurent2e66a782012-03-26 10:47:22 -0700533 }
534 ALOGV("pointer = %p, size = %u, sampleRate = %u, numChannels = %d",
Eric Laurent3d00aa62013-09-24 09:53:27 -0700535 mHeap->getBase(), mSize, sampleRate, numChannels);
Eric Laurent2e66a782012-03-26 10:47:22 -0700536
537 if (sampleRate > kMaxSampleRate) {
538 ALOGE("Sample rate (%u) out of range", sampleRate);
Eric Laurent3d00aa62013-09-24 09:53:27 -0700539 status = BAD_VALUE;
540 goto error;
Eric Laurent2e66a782012-03-26 10:47:22 -0700541 }
542
543 if ((numChannels < 1) || (numChannels > 2)) {
544 ALOGE("Sample channel count (%d) out of range", numChannels);
Eric Laurent3d00aa62013-09-24 09:53:27 -0700545 status = BAD_VALUE;
546 goto error;
Eric Laurent2e66a782012-03-26 10:47:22 -0700547 }
548
Eric Laurent3d00aa62013-09-24 09:53:27 -0700549 mData = new MemoryBase(mHeap, 0, mSize);
Eric Laurent2e66a782012-03-26 10:47:22 -0700550 mSampleRate = sampleRate;
551 mNumChannels = numChannels;
552 mFormat = format;
553 mState = READY;
Eric Laurent3d00aa62013-09-24 09:53:27 -0700554 return NO_ERROR;
555
556error:
557 mHeap.clear();
558 return status;
Eric Laurent2e66a782012-03-26 10:47:22 -0700559}
560
561
562void SoundChannel::init(SoundPool* soundPool)
563{
564 mSoundPool = soundPool;
565}
566
567// call with sound pool lock held
568void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
569 float rightVolume, int priority, int loop, float rate)
570{
Glenn Kasten2799d742013-05-30 14:33:29 -0700571 sp<AudioTrack> oldTrack;
572 sp<AudioTrack> newTrack;
Eric Laurent2e66a782012-03-26 10:47:22 -0700573 status_t status;
574
575 { // scope for the lock
576 Mutex::Autolock lock(&mLock);
577
578 ALOGV("SoundChannel::play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f,"
579 " priority=%d, loop=%d, rate=%f",
580 this, sample->sampleID(), nextChannelID, leftVolume, rightVolume,
581 priority, loop, rate);
582
583 // if not idle, this voice is being stolen
584 if (mState != IDLE) {
585 ALOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
586 mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
587 stop_l();
588 return;
589 }
590
591 // initialize track
Glenn Kastene33054e2012-11-14 12:54:39 -0800592 size_t afFrameCount;
Glenn Kasten3b16c762012-11-14 08:44:39 -0800593 uint32_t afSampleRate;
Eric Laurent2e66a782012-03-26 10:47:22 -0700594 audio_stream_type_t streamType = mSoundPool->streamType();
595 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
596 afFrameCount = kDefaultFrameCount;
597 }
598 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
599 afSampleRate = kDefaultSampleRate;
600 }
601 int numChannels = sample->numChannels();
602 uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
603 uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
604 uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
605 uint32_t frameCount = 0;
606
607 if (loop) {
608 frameCount = sample->size()/numChannels/
609 ((sample->format() == AUDIO_FORMAT_PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
610 }
611
612#ifndef USE_SHARED_MEM_BUFFER
613 // Ensure minimum audio buffer size in case of short looped sample
614 if(frameCount < totalFrames) {
615 frameCount = totalFrames;
616 }
617#endif
618
619 // mToggle toggles each time a track is started on a given channel.
620 // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
621 // as callback user data. This enables the detection of callbacks received from the old
622 // audio track while the new one is being started and avoids processing them with
623 // wrong audio audio buffer size (mAudioBufferSize)
624 unsigned long toggle = mToggle ^ 1;
625 void *userData = (void *)((unsigned long)this | toggle);
626 uint32_t channels = (numChannels == 2) ?
627 AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO;
628
629 // do not create a new audio track if current track is compatible with sample parameters
630#ifdef USE_SHARED_MEM_BUFFER
631 newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
Glenn Kasten8973c042013-09-11 14:35:16 -0700632 channels, sample->getIMemory(), AUDIO_OUTPUT_FLAG_FAST, callback, userData);
Eric Laurent2e66a782012-03-26 10:47:22 -0700633#else
634 newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
Glenn Kasten1477e922012-05-01 10:59:31 -0700635 channels, frameCount, AUDIO_OUTPUT_FLAG_FAST, callback, userData,
Eric Laurent2e66a782012-03-26 10:47:22 -0700636 bufferFrames);
637#endif
638 oldTrack = mAudioTrack;
639 status = newTrack->initCheck();
640 if (status != NO_ERROR) {
641 ALOGE("Error creating AudioTrack");
642 goto exit;
643 }
Glenn Kasten2799d742013-05-30 14:33:29 -0700644 ALOGV("setVolume %p", newTrack.get());
Eric Laurent2e66a782012-03-26 10:47:22 -0700645 newTrack->setVolume(leftVolume, rightVolume);
646 newTrack->setLoop(0, frameCount, loop);
647
648 // From now on, AudioTrack callbacks received with previous toggle value will be ignored.
649 mToggle = toggle;
650 mAudioTrack = newTrack;
651 mPos = 0;
652 mSample = sample;
653 mChannelID = nextChannelID;
654 mPriority = priority;
655 mLoop = loop;
656 mLeftVolume = leftVolume;
657 mRightVolume = rightVolume;
658 mNumChannels = numChannels;
659 mRate = rate;
660 clearNextEvent();
661 mState = PLAYING;
662 mAudioTrack->start();
663 mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
664 }
665
666exit:
Glenn Kasten2799d742013-05-30 14:33:29 -0700667 ALOGV("delete oldTrack %p", oldTrack.get());
Eric Laurent2e66a782012-03-26 10:47:22 -0700668 if (status != NO_ERROR) {
Glenn Kasten2799d742013-05-30 14:33:29 -0700669 mAudioTrack.clear();
Eric Laurent2e66a782012-03-26 10:47:22 -0700670 }
671}
672
673void SoundChannel::nextEvent()
674{
675 sp<Sample> sample;
676 int nextChannelID;
677 float leftVolume;
678 float rightVolume;
679 int priority;
680 int loop;
681 float rate;
682
683 // check for valid event
684 {
685 Mutex::Autolock lock(&mLock);
686 nextChannelID = mNextEvent.channelID();
687 if (nextChannelID == 0) {
688 ALOGV("stolen channel has no event");
689 return;
690 }
691
692 sample = mNextEvent.sample();
693 leftVolume = mNextEvent.leftVolume();
694 rightVolume = mNextEvent.rightVolume();
695 priority = mNextEvent.priority();
696 loop = mNextEvent.loop();
697 rate = mNextEvent.rate();
698 }
699
700 ALOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
701 play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
702}
703
704void SoundChannel::callback(int event, void* user, void *info)
705{
706 SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
707
708 channel->process(event, info, (unsigned long)user & 1);
709}
710
711void SoundChannel::process(int event, void *info, unsigned long toggle)
712{
713 //ALOGV("process(%d)", mChannelID);
714
715 Mutex::Autolock lock(&mLock);
716
717 AudioTrack::Buffer* b = NULL;
718 if (event == AudioTrack::EVENT_MORE_DATA) {
719 b = static_cast<AudioTrack::Buffer *>(info);
720 }
721
722 if (mToggle != toggle) {
723 ALOGV("process wrong toggle %p channel %d", this, mChannelID);
724 if (b != NULL) {
725 b->size = 0;
726 }
727 return;
728 }
729
730 sp<Sample> sample = mSample;
731
732// ALOGV("SoundChannel::process event %d", event);
733
734 if (event == AudioTrack::EVENT_MORE_DATA) {
735
736 // check for stop state
737 if (b->size == 0) return;
738
739 if (mState == IDLE) {
740 b->size = 0;
741 return;
742 }
743
744 if (sample != 0) {
745 // fill buffer
746 uint8_t* q = (uint8_t*) b->i8;
747 size_t count = 0;
748
749 if (mPos < (int)sample->size()) {
750 uint8_t* p = sample->data() + mPos;
751 count = sample->size() - mPos;
752 if (count > b->size) {
753 count = b->size;
754 }
755 memcpy(q, p, count);
756// ALOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size, count);
757 } else if (mPos < mAudioBufferSize) {
758 count = mAudioBufferSize - mPos;
759 if (count > b->size) {
760 count = b->size;
761 }
762 memset(q, 0, count);
763// ALOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
764 }
765
766 mPos += count;
767 b->size = count;
768 //ALOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
769 }
Eric Laurentb3cb72a2013-10-12 17:05:19 -0700770 } else if (event == AudioTrack::EVENT_UNDERRUN || event == AudioTrack::EVENT_BUFFER_END ||
771 event == AudioTrack::EVENT_NEW_IAUDIOTRACK) {
772 ALOGV("process %p channel %d event %s",
773 this, mChannelID, (event == AudioTrack::EVENT_UNDERRUN) ? "UNDERRUN" :
774 (event == AudioTrack::EVENT_BUFFER_END) ? "BUFFER_END" : "NEW_IAUDIOTRACK");
Eric Laurent2e66a782012-03-26 10:47:22 -0700775 mSoundPool->addToStopList(this);
776 } else if (event == AudioTrack::EVENT_LOOP_END) {
Eric Laurent3d00aa62013-09-24 09:53:27 -0700777 ALOGV("End loop %p channel %d", this, mChannelID);
Eric Laurentb3cb72a2013-10-12 17:05:19 -0700778 } else {
779 ALOGW("SoundChannel::process unexpected event %d", event);
Eric Laurent2e66a782012-03-26 10:47:22 -0700780 }
781}
782
783
784// call with lock held
785bool SoundChannel::doStop_l()
786{
787 if (mState != IDLE) {
788 setVolume_l(0, 0);
789 ALOGV("stop");
790 mAudioTrack->stop();
791 mSample.clear();
792 mState = IDLE;
793 mPriority = IDLE_PRIORITY;
794 return true;
795 }
796 return false;
797}
798
799// call with lock held and sound pool lock held
800void SoundChannel::stop_l()
801{
802 if (doStop_l()) {
803 mSoundPool->done_l(this);
804 }
805}
806
807// call with sound pool lock held
808void SoundChannel::stop()
809{
810 bool stopped;
811 {
812 Mutex::Autolock lock(&mLock);
813 stopped = doStop_l();
814 }
815
816 if (stopped) {
817 mSoundPool->done_l(this);
818 }
819}
820
821//FIXME: Pause is a little broken right now
822void SoundChannel::pause()
823{
824 Mutex::Autolock lock(&mLock);
825 if (mState == PLAYING) {
826 ALOGV("pause track");
827 mState = PAUSED;
828 mAudioTrack->pause();
829 }
830}
831
832void SoundChannel::autoPause()
833{
834 Mutex::Autolock lock(&mLock);
835 if (mState == PLAYING) {
836 ALOGV("pause track");
837 mState = PAUSED;
838 mAutoPaused = true;
839 mAudioTrack->pause();
840 }
841}
842
843void SoundChannel::resume()
844{
845 Mutex::Autolock lock(&mLock);
846 if (mState == PAUSED) {
847 ALOGV("resume track");
848 mState = PLAYING;
849 mAutoPaused = false;
850 mAudioTrack->start();
851 }
852}
853
854void SoundChannel::autoResume()
855{
856 Mutex::Autolock lock(&mLock);
857 if (mAutoPaused && (mState == PAUSED)) {
858 ALOGV("resume track");
859 mState = PLAYING;
860 mAutoPaused = false;
861 mAudioTrack->start();
862 }
863}
864
865void SoundChannel::setRate(float rate)
866{
867 Mutex::Autolock lock(&mLock);
868 if (mAudioTrack != NULL && mSample != 0) {
869 uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5);
870 mAudioTrack->setSampleRate(sampleRate);
871 mRate = rate;
872 }
873}
874
875// call with lock held
876void SoundChannel::setVolume_l(float leftVolume, float rightVolume)
877{
878 mLeftVolume = leftVolume;
879 mRightVolume = rightVolume;
880 if (mAudioTrack != NULL)
881 mAudioTrack->setVolume(leftVolume, rightVolume);
882}
883
884void SoundChannel::setVolume(float leftVolume, float rightVolume)
885{
886 Mutex::Autolock lock(&mLock);
887 setVolume_l(leftVolume, rightVolume);
888}
889
890void SoundChannel::setLoop(int loop)
891{
892 Mutex::Autolock lock(&mLock);
893 if (mAudioTrack != NULL && mSample != 0) {
894 uint32_t loopEnd = mSample->size()/mNumChannels/
895 ((mSample->format() == AUDIO_FORMAT_PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
896 mAudioTrack->setLoop(0, loopEnd, loop);
897 mLoop = loop;
898 }
899}
900
901SoundChannel::~SoundChannel()
902{
903 ALOGV("SoundChannel destructor %p", this);
904 {
905 Mutex::Autolock lock(&mLock);
906 clearNextEvent();
907 doStop_l();
908 }
909 // do not call AudioTrack destructor with mLock held as it will wait for the AudioTrack
910 // callback thread to exit which may need to execute process() and acquire the mLock.
Glenn Kasten2799d742013-05-30 14:33:29 -0700911 mAudioTrack.clear();
Eric Laurent2e66a782012-03-26 10:47:22 -0700912}
913
914void SoundChannel::dump()
915{
916 ALOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d",
917 mState, mChannelID, mNumChannels, mPos, mPriority, mLoop);
918}
919
920void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
921 float rightVolume, int priority, int loop, float rate)
922{
923 mSample = sample;
924 mChannelID = channelID;
925 mLeftVolume = leftVolume;
926 mRightVolume = rightVolume;
927 mPriority = priority;
928 mLoop = loop;
929 mRate =rate;
930}
931
932} // end namespace android