blob: d2e381bf97e600db9e035bad3445e205522cd764 [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
186SoundChannel* SoundPool::findChannel(int channelID)
187{
188 for (int i = 0; i < mMaxChannels; ++i) {
189 if (mChannelPool[i].channelID() == channelID) {
190 return &mChannelPool[i];
191 }
192 }
193 return NULL;
194}
195
196SoundChannel* SoundPool::findNextChannel(int channelID)
197{
198 for (int i = 0; i < mMaxChannels; ++i) {
199 if (mChannelPool[i].nextChannelID() == channelID) {
200 return &mChannelPool[i];
201 }
202 }
203 return NULL;
204}
205
Glenn Kasten7c7be1e2013-12-19 16:34:04 -0800206int SoundPool::load(const char* path, int priority __unused)
Eric Laurent2e66a782012-03-26 10:47:22 -0700207{
208 ALOGV("load: path=%s, priority=%d", path, priority);
209 Mutex::Autolock lock(&mLock);
210 sp<Sample> sample = new Sample(++mNextSampleID, path);
211 mSamples.add(sample->sampleID(), sample);
212 doLoad(sample);
213 return sample->sampleID();
214}
215
Glenn Kasten7c7be1e2013-12-19 16:34:04 -0800216int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused)
Eric Laurent2e66a782012-03-26 10:47:22 -0700217{
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700218 ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d",
Eric Laurent2e66a782012-03-26 10:47:22 -0700219 fd, offset, length, priority);
220 Mutex::Autolock lock(&mLock);
221 sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length);
222 mSamples.add(sample->sampleID(), sample);
223 doLoad(sample);
224 return sample->sampleID();
225}
226
227void SoundPool::doLoad(sp<Sample>& sample)
228{
229 ALOGV("doLoad: loading sample sampleID=%d", sample->sampleID());
230 sample->startLoad();
231 mDecodeThread->loadSample(sample->sampleID());
232}
233
234bool SoundPool::unload(int sampleID)
235{
236 ALOGV("unload: sampleID=%d", sampleID);
237 Mutex::Autolock lock(&mLock);
238 return mSamples.removeItem(sampleID);
239}
240
241int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
242 int priority, int loop, float rate)
243{
244 ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
245 sampleID, leftVolume, rightVolume, priority, loop, rate);
246 sp<Sample> sample;
247 SoundChannel* channel;
248 int channelID;
249
250 Mutex::Autolock lock(&mLock);
251
252 if (mQuit) {
253 return 0;
254 }
255 // is sample ready?
256 sample = findSample(sampleID);
257 if ((sample == 0) || (sample->state() != Sample::READY)) {
258 ALOGW(" sample %d not READY", sampleID);
259 return 0;
260 }
261
262 dump();
263
264 // allocate a channel
265 channel = allocateChannel_l(priority);
266
267 // no channel allocated - return 0
268 if (!channel) {
269 ALOGV("No channel allocated");
270 return 0;
271 }
272
273 channelID = ++mNextChannelID;
274
275 ALOGV("play channel %p state = %d", channel, channel->state());
276 channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
277 return channelID;
278}
279
280SoundChannel* SoundPool::allocateChannel_l(int priority)
281{
282 List<SoundChannel*>::iterator iter;
283 SoundChannel* channel = NULL;
284
285 // allocate a channel
286 if (!mChannels.empty()) {
287 iter = mChannels.begin();
288 if (priority >= (*iter)->priority()) {
289 channel = *iter;
290 mChannels.erase(iter);
291 ALOGV("Allocated active channel");
292 }
293 }
294
295 // update priority and put it back in the list
296 if (channel) {
297 channel->setPriority(priority);
298 for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
299 if (priority < (*iter)->priority()) {
300 break;
301 }
302 }
303 mChannels.insert(iter, channel);
304 }
305 return channel;
306}
307
308// move a channel from its current position to the front of the list
309void SoundPool::moveToFront_l(SoundChannel* channel)
310{
311 for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
312 if (*iter == channel) {
313 mChannels.erase(iter);
314 mChannels.push_front(channel);
315 break;
316 }
317 }
318}
319
320void SoundPool::pause(int channelID)
321{
322 ALOGV("pause(%d)", channelID);
323 Mutex::Autolock lock(&mLock);
324 SoundChannel* channel = findChannel(channelID);
325 if (channel) {
326 channel->pause();
327 }
328}
329
330void SoundPool::autoPause()
331{
332 ALOGV("autoPause()");
333 Mutex::Autolock lock(&mLock);
334 for (int i = 0; i < mMaxChannels; ++i) {
335 SoundChannel* channel = &mChannelPool[i];
336 channel->autoPause();
337 }
338}
339
340void SoundPool::resume(int channelID)
341{
342 ALOGV("resume(%d)", channelID);
343 Mutex::Autolock lock(&mLock);
344 SoundChannel* channel = findChannel(channelID);
345 if (channel) {
346 channel->resume();
347 }
348}
349
350void SoundPool::autoResume()
351{
352 ALOGV("autoResume()");
353 Mutex::Autolock lock(&mLock);
354 for (int i = 0; i < mMaxChannels; ++i) {
355 SoundChannel* channel = &mChannelPool[i];
356 channel->autoResume();
357 }
358}
359
360void SoundPool::stop(int channelID)
361{
362 ALOGV("stop(%d)", channelID);
363 Mutex::Autolock lock(&mLock);
364 SoundChannel* channel = findChannel(channelID);
365 if (channel) {
366 channel->stop();
367 } else {
368 channel = findNextChannel(channelID);
369 if (channel)
370 channel->clearNextEvent();
371 }
372}
373
374void SoundPool::setVolume(int channelID, float leftVolume, float rightVolume)
375{
376 Mutex::Autolock lock(&mLock);
377 SoundChannel* channel = findChannel(channelID);
378 if (channel) {
379 channel->setVolume(leftVolume, rightVolume);
380 }
381}
382
383void SoundPool::setPriority(int channelID, int priority)
384{
385 ALOGV("setPriority(%d, %d)", channelID, priority);
386 Mutex::Autolock lock(&mLock);
387 SoundChannel* channel = findChannel(channelID);
388 if (channel) {
389 channel->setPriority(priority);
390 }
391}
392
393void SoundPool::setLoop(int channelID, int loop)
394{
395 ALOGV("setLoop(%d, %d)", channelID, loop);
396 Mutex::Autolock lock(&mLock);
397 SoundChannel* channel = findChannel(channelID);
398 if (channel) {
399 channel->setLoop(loop);
400 }
401}
402
403void SoundPool::setRate(int channelID, float rate)
404{
405 ALOGV("setRate(%d, %f)", channelID, rate);
406 Mutex::Autolock lock(&mLock);
407 SoundChannel* channel = findChannel(channelID);
408 if (channel) {
409 channel->setRate(rate);
410 }
411}
412
413// call with lock held
414void SoundPool::done_l(SoundChannel* channel)
415{
416 ALOGV("done_l(%d)", channel->channelID());
417 // if "stolen", play next event
418 if (channel->nextChannelID() != 0) {
419 ALOGV("add to restart list");
420 addToRestartList(channel);
421 }
422
423 // return to idle state
424 else {
425 ALOGV("move to front");
426 moveToFront_l(channel);
427 }
428}
429
430void SoundPool::setCallback(SoundPoolCallback* callback, void* user)
431{
432 Mutex::Autolock lock(&mCallbackLock);
433 mCallback = callback;
434 mUserData = user;
435}
436
437void SoundPool::notify(SoundPoolEvent event)
438{
439 Mutex::Autolock lock(&mCallbackLock);
440 if (mCallback != NULL) {
441 mCallback(event, this, mUserData);
442 }
443}
444
445void SoundPool::dump()
446{
447 for (int i = 0; i < mMaxChannels; ++i) {
448 mChannelPool[i].dump();
449 }
450}
451
452
453Sample::Sample(int sampleID, const char* url)
454{
455 init();
456 mSampleID = sampleID;
457 mUrl = strdup(url);
458 ALOGV("create sampleID=%d, url=%s", mSampleID, mUrl);
459}
460
461Sample::Sample(int sampleID, int fd, int64_t offset, int64_t length)
462{
463 init();
464 mSampleID = sampleID;
465 mFd = dup(fd);
466 mOffset = offset;
467 mLength = length;
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700468 ALOGV("create sampleID=%d, fd=%d, offset=%" PRId64 " length=%" PRId64,
469 mSampleID, mFd, mLength, mOffset);
Eric Laurent2e66a782012-03-26 10:47:22 -0700470}
471
472void Sample::init()
473{
Eric Laurent2e66a782012-03-26 10:47:22 -0700474 mSize = 0;
475 mRefCount = 0;
476 mSampleID = 0;
477 mState = UNLOADED;
478 mFd = -1;
479 mOffset = 0;
480 mLength = 0;
481 mUrl = 0;
482}
483
484Sample::~Sample()
485{
486 ALOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd);
487 if (mFd > 0) {
488 ALOGV("close(%d)", mFd);
489 ::close(mFd);
490 }
Marco Nelissena6b47a12012-11-19 09:49:18 -0800491 free(mUrl);
Eric Laurent2e66a782012-03-26 10:47:22 -0700492}
493
494status_t Sample::doLoad()
495{
496 uint32_t sampleRate;
497 int numChannels;
498 audio_format_t format;
Eric Laurent3d00aa62013-09-24 09:53:27 -0700499 status_t status;
500 mHeap = new MemoryHeapBase(kDefaultHeapSize);
501
Eric Laurent2e66a782012-03-26 10:47:22 -0700502 ALOGV("Start decode");
503 if (mUrl) {
Andreas Huber1b86fe02014-01-29 11:13:26 -0800504 status = MediaPlayer::decode(
505 NULL /* httpService */,
506 mUrl,
507 &sampleRate,
508 &numChannels,
509 &format,
510 mHeap,
511 &mSize);
Eric Laurent2e66a782012-03-26 10:47:22 -0700512 } else {
Eric Laurent3d00aa62013-09-24 09:53:27 -0700513 status = MediaPlayer::decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format,
514 mHeap, &mSize);
Eric Laurent2e66a782012-03-26 10:47:22 -0700515 ALOGV("close(%d)", mFd);
516 ::close(mFd);
517 mFd = -1;
518 }
Eric Laurent3d00aa62013-09-24 09:53:27 -0700519 if (status != NO_ERROR) {
Eric Laurent2e66a782012-03-26 10:47:22 -0700520 ALOGE("Unable to load sample: %s", mUrl);
Eric Laurent3d00aa62013-09-24 09:53:27 -0700521 goto error;
Eric Laurent2e66a782012-03-26 10:47:22 -0700522 }
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700523 ALOGV("pointer = %p, size = %zu, sampleRate = %u, numChannels = %d",
Eric Laurent3d00aa62013-09-24 09:53:27 -0700524 mHeap->getBase(), mSize, sampleRate, numChannels);
Eric Laurent2e66a782012-03-26 10:47:22 -0700525
526 if (sampleRate > kMaxSampleRate) {
527 ALOGE("Sample rate (%u) out of range", sampleRate);
Eric Laurent3d00aa62013-09-24 09:53:27 -0700528 status = BAD_VALUE;
529 goto error;
Eric Laurent2e66a782012-03-26 10:47:22 -0700530 }
531
532 if ((numChannels < 1) || (numChannels > 2)) {
533 ALOGE("Sample channel count (%d) out of range", numChannels);
Eric Laurent3d00aa62013-09-24 09:53:27 -0700534 status = BAD_VALUE;
535 goto error;
Eric Laurent2e66a782012-03-26 10:47:22 -0700536 }
537
Eric Laurent3d00aa62013-09-24 09:53:27 -0700538 mData = new MemoryBase(mHeap, 0, mSize);
Eric Laurent2e66a782012-03-26 10:47:22 -0700539 mSampleRate = sampleRate;
540 mNumChannels = numChannels;
541 mFormat = format;
542 mState = READY;
Eric Laurent3d00aa62013-09-24 09:53:27 -0700543 return NO_ERROR;
544
545error:
546 mHeap.clear();
547 return status;
Eric Laurent2e66a782012-03-26 10:47:22 -0700548}
549
550
551void SoundChannel::init(SoundPool* soundPool)
552{
553 mSoundPool = soundPool;
554}
555
556// call with sound pool lock held
557void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
558 float rightVolume, int priority, int loop, float rate)
559{
Glenn Kasten2799d742013-05-30 14:33:29 -0700560 sp<AudioTrack> oldTrack;
561 sp<AudioTrack> newTrack;
Eric Laurent2e66a782012-03-26 10:47:22 -0700562 status_t status;
563
564 { // scope for the lock
565 Mutex::Autolock lock(&mLock);
566
567 ALOGV("SoundChannel::play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f,"
568 " priority=%d, loop=%d, rate=%f",
569 this, sample->sampleID(), nextChannelID, leftVolume, rightVolume,
570 priority, loop, rate);
571
572 // if not idle, this voice is being stolen
573 if (mState != IDLE) {
574 ALOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
575 mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
576 stop_l();
577 return;
578 }
579
580 // initialize track
Glenn Kastene33054e2012-11-14 12:54:39 -0800581 size_t afFrameCount;
Glenn Kasten3b16c762012-11-14 08:44:39 -0800582 uint32_t afSampleRate;
Jean-Michel Trividf813a32014-07-20 17:58:33 -0700583 audio_stream_type_t streamType = audio_attributes_to_stream_type(mSoundPool->attributes());
Eric Laurent2e66a782012-03-26 10:47:22 -0700584 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
585 afFrameCount = kDefaultFrameCount;
586 }
587 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
588 afSampleRate = kDefaultSampleRate;
589 }
590 int numChannels = sample->numChannels();
591 uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
592 uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
593 uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
Glenn Kastenbce50bf2014-02-27 15:29:51 -0800594 size_t frameCount = 0;
Eric Laurent2e66a782012-03-26 10:47:22 -0700595
596 if (loop) {
597 frameCount = sample->size()/numChannels/
598 ((sample->format() == AUDIO_FORMAT_PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
599 }
600
601#ifndef USE_SHARED_MEM_BUFFER
602 // Ensure minimum audio buffer size in case of short looped sample
603 if(frameCount < totalFrames) {
604 frameCount = totalFrames;
605 }
606#endif
607
608 // mToggle toggles each time a track is started on a given channel.
609 // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
610 // as callback user data. This enables the detection of callbacks received from the old
611 // audio track while the new one is being started and avoids processing them with
612 // wrong audio audio buffer size (mAudioBufferSize)
613 unsigned long toggle = mToggle ^ 1;
614 void *userData = (void *)((unsigned long)this | toggle);
Glenn Kasten79c57862013-10-30 09:47:17 -0700615 audio_channel_mask_t channelMask = audio_channel_out_mask_from_count(numChannels);
Eric Laurent2e66a782012-03-26 10:47:22 -0700616
617 // do not create a new audio track if current track is compatible with sample parameters
618#ifdef USE_SHARED_MEM_BUFFER
619 newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
Glenn Kasten79c57862013-10-30 09:47:17 -0700620 channelMask, sample->getIMemory(), AUDIO_OUTPUT_FLAG_FAST, callback, userData);
Eric Laurent2e66a782012-03-26 10:47:22 -0700621#else
622 newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
Glenn Kasten79c57862013-10-30 09:47:17 -0700623 channelMask, frameCount, AUDIO_OUTPUT_FLAG_FAST, callback, userData,
Eric Laurent2e66a782012-03-26 10:47:22 -0700624 bufferFrames);
625#endif
626 oldTrack = mAudioTrack;
627 status = newTrack->initCheck();
628 if (status != NO_ERROR) {
629 ALOGE("Error creating AudioTrack");
630 goto exit;
631 }
Glenn Kasten2799d742013-05-30 14:33:29 -0700632 ALOGV("setVolume %p", newTrack.get());
Eric Laurent2e66a782012-03-26 10:47:22 -0700633 newTrack->setVolume(leftVolume, rightVolume);
634 newTrack->setLoop(0, frameCount, loop);
635
636 // From now on, AudioTrack callbacks received with previous toggle value will be ignored.
637 mToggle = toggle;
638 mAudioTrack = newTrack;
639 mPos = 0;
640 mSample = sample;
641 mChannelID = nextChannelID;
642 mPriority = priority;
643 mLoop = loop;
644 mLeftVolume = leftVolume;
645 mRightVolume = rightVolume;
646 mNumChannels = numChannels;
647 mRate = rate;
648 clearNextEvent();
649 mState = PLAYING;
650 mAudioTrack->start();
651 mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
652 }
653
654exit:
Glenn Kasten2799d742013-05-30 14:33:29 -0700655 ALOGV("delete oldTrack %p", oldTrack.get());
Eric Laurent2e66a782012-03-26 10:47:22 -0700656 if (status != NO_ERROR) {
Glenn Kasten2799d742013-05-30 14:33:29 -0700657 mAudioTrack.clear();
Eric Laurent2e66a782012-03-26 10:47:22 -0700658 }
659}
660
661void SoundChannel::nextEvent()
662{
663 sp<Sample> sample;
664 int nextChannelID;
665 float leftVolume;
666 float rightVolume;
667 int priority;
668 int loop;
669 float rate;
670
671 // check for valid event
672 {
673 Mutex::Autolock lock(&mLock);
674 nextChannelID = mNextEvent.channelID();
675 if (nextChannelID == 0) {
676 ALOGV("stolen channel has no event");
677 return;
678 }
679
680 sample = mNextEvent.sample();
681 leftVolume = mNextEvent.leftVolume();
682 rightVolume = mNextEvent.rightVolume();
683 priority = mNextEvent.priority();
684 loop = mNextEvent.loop();
685 rate = mNextEvent.rate();
686 }
687
688 ALOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID);
689 play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
690}
691
692void SoundChannel::callback(int event, void* user, void *info)
693{
694 SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
695
696 channel->process(event, info, (unsigned long)user & 1);
697}
698
699void SoundChannel::process(int event, void *info, unsigned long toggle)
700{
701 //ALOGV("process(%d)", mChannelID);
702
703 Mutex::Autolock lock(&mLock);
704
705 AudioTrack::Buffer* b = NULL;
706 if (event == AudioTrack::EVENT_MORE_DATA) {
707 b = static_cast<AudioTrack::Buffer *>(info);
708 }
709
710 if (mToggle != toggle) {
711 ALOGV("process wrong toggle %p channel %d", this, mChannelID);
712 if (b != NULL) {
713 b->size = 0;
714 }
715 return;
716 }
717
718 sp<Sample> sample = mSample;
719
720// ALOGV("SoundChannel::process event %d", event);
721
722 if (event == AudioTrack::EVENT_MORE_DATA) {
723
724 // check for stop state
725 if (b->size == 0) return;
726
727 if (mState == IDLE) {
728 b->size = 0;
729 return;
730 }
731
732 if (sample != 0) {
733 // fill buffer
734 uint8_t* q = (uint8_t*) b->i8;
735 size_t count = 0;
736
737 if (mPos < (int)sample->size()) {
738 uint8_t* p = sample->data() + mPos;
739 count = sample->size() - mPos;
740 if (count > b->size) {
741 count = b->size;
742 }
743 memcpy(q, p, count);
Glenn Kasten4944acb2013-08-19 08:39:20 -0700744// ALOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size,
745// count);
Eric Laurent2e66a782012-03-26 10:47:22 -0700746 } else if (mPos < mAudioBufferSize) {
747 count = mAudioBufferSize - mPos;
748 if (count > b->size) {
749 count = b->size;
750 }
751 memset(q, 0, count);
752// ALOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
753 }
754
755 mPos += count;
756 b->size = count;
757 //ALOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
758 }
Eric Laurentb3cb72a2013-10-12 17:05:19 -0700759 } else if (event == AudioTrack::EVENT_UNDERRUN || event == AudioTrack::EVENT_BUFFER_END ||
760 event == AudioTrack::EVENT_NEW_IAUDIOTRACK) {
761 ALOGV("process %p channel %d event %s",
762 this, mChannelID, (event == AudioTrack::EVENT_UNDERRUN) ? "UNDERRUN" :
763 (event == AudioTrack::EVENT_BUFFER_END) ? "BUFFER_END" : "NEW_IAUDIOTRACK");
Eric Laurent2e66a782012-03-26 10:47:22 -0700764 mSoundPool->addToStopList(this);
765 } else if (event == AudioTrack::EVENT_LOOP_END) {
Eric Laurent3d00aa62013-09-24 09:53:27 -0700766 ALOGV("End loop %p channel %d", this, mChannelID);
Eric Laurentb3cb72a2013-10-12 17:05:19 -0700767 } else {
768 ALOGW("SoundChannel::process unexpected event %d", event);
Eric Laurent2e66a782012-03-26 10:47:22 -0700769 }
770}
771
772
773// call with lock held
774bool SoundChannel::doStop_l()
775{
776 if (mState != IDLE) {
777 setVolume_l(0, 0);
778 ALOGV("stop");
779 mAudioTrack->stop();
780 mSample.clear();
781 mState = IDLE;
782 mPriority = IDLE_PRIORITY;
783 return true;
784 }
785 return false;
786}
787
788// call with lock held and sound pool lock held
789void SoundChannel::stop_l()
790{
791 if (doStop_l()) {
792 mSoundPool->done_l(this);
793 }
794}
795
796// call with sound pool lock held
797void SoundChannel::stop()
798{
799 bool stopped;
800 {
801 Mutex::Autolock lock(&mLock);
802 stopped = doStop_l();
803 }
804
805 if (stopped) {
806 mSoundPool->done_l(this);
807 }
808}
809
810//FIXME: Pause is a little broken right now
811void SoundChannel::pause()
812{
813 Mutex::Autolock lock(&mLock);
814 if (mState == PLAYING) {
815 ALOGV("pause track");
816 mState = PAUSED;
817 mAudioTrack->pause();
818 }
819}
820
821void SoundChannel::autoPause()
822{
823 Mutex::Autolock lock(&mLock);
824 if (mState == PLAYING) {
825 ALOGV("pause track");
826 mState = PAUSED;
827 mAutoPaused = true;
828 mAudioTrack->pause();
829 }
830}
831
832void SoundChannel::resume()
833{
834 Mutex::Autolock lock(&mLock);
835 if (mState == PAUSED) {
836 ALOGV("resume track");
837 mState = PLAYING;
838 mAutoPaused = false;
839 mAudioTrack->start();
840 }
841}
842
843void SoundChannel::autoResume()
844{
845 Mutex::Autolock lock(&mLock);
846 if (mAutoPaused && (mState == PAUSED)) {
847 ALOGV("resume track");
848 mState = PLAYING;
849 mAutoPaused = false;
850 mAudioTrack->start();
851 }
852}
853
854void SoundChannel::setRate(float rate)
855{
856 Mutex::Autolock lock(&mLock);
857 if (mAudioTrack != NULL && mSample != 0) {
858 uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5);
859 mAudioTrack->setSampleRate(sampleRate);
860 mRate = rate;
861 }
862}
863
864// call with lock held
865void SoundChannel::setVolume_l(float leftVolume, float rightVolume)
866{
867 mLeftVolume = leftVolume;
868 mRightVolume = rightVolume;
869 if (mAudioTrack != NULL)
870 mAudioTrack->setVolume(leftVolume, rightVolume);
871}
872
873void SoundChannel::setVolume(float leftVolume, float rightVolume)
874{
875 Mutex::Autolock lock(&mLock);
876 setVolume_l(leftVolume, rightVolume);
877}
878
879void SoundChannel::setLoop(int loop)
880{
881 Mutex::Autolock lock(&mLock);
882 if (mAudioTrack != NULL && mSample != 0) {
883 uint32_t loopEnd = mSample->size()/mNumChannels/
884 ((mSample->format() == AUDIO_FORMAT_PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
885 mAudioTrack->setLoop(0, loopEnd, loop);
886 mLoop = loop;
887 }
888}
889
890SoundChannel::~SoundChannel()
891{
892 ALOGV("SoundChannel destructor %p", this);
893 {
894 Mutex::Autolock lock(&mLock);
895 clearNextEvent();
896 doStop_l();
897 }
898 // do not call AudioTrack destructor with mLock held as it will wait for the AudioTrack
899 // callback thread to exit which may need to execute process() and acquire the mLock.
Glenn Kasten2799d742013-05-30 14:33:29 -0700900 mAudioTrack.clear();
Eric Laurent2e66a782012-03-26 10:47:22 -0700901}
902
903void SoundChannel::dump()
904{
905 ALOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d",
906 mState, mChannelID, mNumChannels, mPos, mPriority, mLoop);
907}
908
909void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
910 float rightVolume, int priority, int loop, float rate)
911{
912 mSample = sample;
913 mChannelID = channelID;
914 mLeftVolume = leftVolume;
915 mRightVolume = rightVolume;
916 mPriority = priority;
917 mLoop = loop;
918 mRate =rate;
919}
920
921} // end namespace android