SoundPool.cpp revision fd8c0e1ff8ef781ba169c0164458ec1ce95ee35c
1/* 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 21//#define USE_SHARED_MEM_BUFFER 22 23// XXX needed for timing latency 24#include <utils/Timers.h> 25 26#include <sys/resource.h> 27#include <media/AudioTrack.h> 28#include <media/mediaplayer.h> 29 30#include "SoundPool.h" 31#include "SoundPoolThread.h" 32 33namespace android 34{ 35 36int kDefaultBufferCount = 4; 37uint32_t kMaxSampleRate = 48000; 38uint32_t kDefaultSampleRate = 44100; 39uint32_t kDefaultFrameCount = 1200; 40 41SoundPool::SoundPool(jobject soundPoolRef, int maxChannels, int streamType, int srcQuality) 42{ 43 LOGV("SoundPool constructor: maxChannels=%d, streamType=%d, srcQuality=%d", 44 maxChannels, streamType, srcQuality); 45 46 // check limits 47 mMaxChannels = maxChannels; 48 if (mMaxChannels < 1) { 49 mMaxChannels = 1; 50 } 51 else if (mMaxChannels > 32) { 52 mMaxChannels = 32; 53 } 54 LOGW_IF(maxChannels != mMaxChannels, "App requested %d channels", maxChannels); 55 56 mQuit = false; 57 mSoundPoolRef = soundPoolRef; 58 mDecodeThread = 0; 59 mStreamType = streamType; 60 mSrcQuality = srcQuality; 61 mAllocated = 0; 62 mNextSampleID = 0; 63 mNextChannelID = 0; 64 65 mChannelPool = new SoundChannel[mMaxChannels]; 66 for (int i = 0; i < mMaxChannels; ++i) { 67 mChannelPool[i].init(this); 68 mChannels.push_back(&mChannelPool[i]); 69 } 70 71 // start decode thread 72 startThreads(); 73} 74 75SoundPool::~SoundPool() 76{ 77 LOGV("SoundPool destructor"); 78 mDecodeThread->quit(); 79 quit(); 80 81 Mutex::Autolock lock(&mLock); 82 mChannels.clear(); 83 if (mChannelPool) 84 delete [] mChannelPool; 85 86 // clean up samples 87 LOGV("clear samples"); 88 mSamples.clear(); 89 90 if (mDecodeThread) 91 delete mDecodeThread; 92} 93 94void SoundPool::addToRestartList(SoundChannel* channel) 95{ 96 Mutex::Autolock lock(&mRestartLock); 97 mRestart.push_back(channel); 98 mCondition.signal(); 99} 100 101int SoundPool::beginThread(void* arg) 102{ 103 SoundPool* p = (SoundPool*)arg; 104 return p->run(); 105} 106 107int SoundPool::run() 108{ 109 mRestartLock.lock(); 110 while (!mQuit) { 111 mCondition.wait(mRestartLock); 112 LOGV("awake"); 113 if (mQuit) break; 114 115 while (!mRestart.empty()) { 116 SoundChannel* channel; 117 LOGV("Getting channel from list"); 118 List<SoundChannel*>::iterator iter = mRestart.begin(); 119 channel = *iter; 120 mRestart.erase(iter); 121 if (channel) channel->nextEvent(); 122 if (mQuit) break; 123 } 124 } 125 126 mRestart.clear(); 127 mCondition.signal(); 128 mRestartLock.unlock(); 129 LOGV("goodbye"); 130 return 0; 131} 132 133void SoundPool::quit() 134{ 135 mRestartLock.lock(); 136 mQuit = true; 137 mCondition.signal(); 138 mCondition.wait(mRestartLock); 139 LOGV("return from quit"); 140 mRestartLock.unlock(); 141} 142 143bool SoundPool::startThreads() 144{ 145 createThread(beginThread, this); 146 if (mDecodeThread == NULL) 147 mDecodeThread = new SoundPoolThread(this); 148 return mDecodeThread != NULL; 149} 150 151SoundChannel* SoundPool::findChannel(int channelID) 152{ 153 for (int i = 0; i < mMaxChannels; ++i) { 154 if (mChannelPool[i].channelID() == channelID) { 155 return &mChannelPool[i]; 156 } 157 } 158 return NULL; 159} 160 161SoundChannel* SoundPool::findNextChannel(int channelID) 162{ 163 for (int i = 0; i < mMaxChannels; ++i) { 164 if (mChannelPool[i].nextChannelID() == channelID) { 165 return &mChannelPool[i]; 166 } 167 } 168 return NULL; 169} 170 171int SoundPool::load(const char* path, int priority) 172{ 173 LOGV("load: path=%s, priority=%d", path, priority); 174 Mutex::Autolock lock(&mLock); 175 sp<Sample> sample = new Sample(++mNextSampleID, path); 176 mSamples.add(sample->sampleID(), sample); 177 doLoad(sample); 178 return sample->sampleID(); 179} 180 181int SoundPool::load(int fd, int64_t offset, int64_t length, int priority) 182{ 183 LOGV("load: fd=%d, offset=%lld, length=%lld, priority=%d", 184 fd, offset, length, priority); 185 Mutex::Autolock lock(&mLock); 186 sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length); 187 mSamples.add(sample->sampleID(), sample); 188 doLoad(sample); 189 return sample->sampleID(); 190} 191 192void SoundPool::doLoad(sp<Sample>& sample) 193{ 194 LOGV("doLoad: loading sample sampleID=%d", sample->sampleID()); 195 sample->startLoad(); 196 mDecodeThread->loadSample(sample->sampleID()); 197} 198 199bool SoundPool::unload(int sampleID) 200{ 201 LOGV("unload: sampleID=%d", sampleID); 202 Mutex::Autolock lock(&mLock); 203 return mSamples.removeItem(sampleID); 204} 205 206int SoundPool::play(int sampleID, float leftVolume, float rightVolume, 207 int priority, int loop, float rate) 208{ 209 LOGV("sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f", 210 sampleID, leftVolume, rightVolume, priority, loop, rate); 211 sp<Sample> sample; 212 SoundChannel* channel; 213 int channelID; 214 215 // scope for lock 216 { 217 Mutex::Autolock lock(&mLock); 218 219 // is sample ready? 220 sample = findSample(sampleID); 221 if ((sample == 0) || (sample->state() != Sample::READY)) { 222 LOGW(" sample %d not READY", sampleID); 223 return 0; 224 } 225 226 dump(); 227 228 // allocate a channel 229 channel = allocateChannel(priority); 230 231 // no channel allocated - return 0 232 if (!channel) { 233 LOGV("No channel allocated"); 234 return 0; 235 } 236 237 channelID = ++mNextChannelID; 238 } 239 240 LOGV("channel state = %d", channel->state()); 241 channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate); 242 return channelID; 243} 244 245SoundChannel* SoundPool::allocateChannel(int priority) 246{ 247 List<SoundChannel*>::iterator iter; 248 SoundChannel* channel = NULL; 249 250 // allocate a channel 251 if (!mChannels.empty()) { 252 iter = mChannels.begin(); 253 if (priority >= (*iter)->priority()) { 254 channel = *iter; 255 mChannels.erase(iter); 256 LOGV("Allocated active channel"); 257 } 258 } 259 260 // update priority and put it back in the list 261 if (channel) { 262 channel->setPriority(priority); 263 for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) { 264 if (priority < (*iter)->priority()) { 265 break; 266 } 267 } 268 mChannels.insert(iter, channel); 269 } 270 return channel; 271} 272 273// move a channel from its current position to the front of the list 274void SoundPool::moveToFront(SoundChannel* channel) 275{ 276 for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) { 277 if (*iter == channel) { 278 mChannels.erase(iter); 279 mChannels.push_front(channel); 280 break; 281 } 282 } 283} 284 285void SoundPool::pause(int channelID) 286{ 287 LOGV("pause(%d)", channelID); 288 Mutex::Autolock lock(&mLock); 289 SoundChannel* channel = findChannel(channelID); 290 if (channel) { 291 channel->pause(); 292 } 293} 294 295void SoundPool::resume(int channelID) 296{ 297 LOGV("resume(%d)", channelID); 298 Mutex::Autolock lock(&mLock); 299 SoundChannel* channel = findChannel(channelID); 300 if (channel) { 301 channel->resume(); 302 } 303} 304 305void SoundPool::stop(int channelID) 306{ 307 LOGV("stop(%d)", channelID); 308 Mutex::Autolock lock(&mLock); 309 SoundChannel* channel = findChannel(channelID); 310 if (channel) { 311 channel->stop(); 312 } else { 313 channel = findNextChannel(channelID); 314 if (channel) 315 channel->clearNextEvent(); 316 } 317} 318 319void SoundPool::setVolume(int channelID, float leftVolume, float rightVolume) 320{ 321 Mutex::Autolock lock(&mLock); 322 SoundChannel* channel = findChannel(channelID); 323 if (channel) { 324 channel->setVolume(leftVolume, rightVolume); 325 } 326} 327 328void SoundPool::setPriority(int channelID, int priority) 329{ 330 LOGV("setPriority(%d, %d)", channelID, priority); 331 Mutex::Autolock lock(&mLock); 332 SoundChannel* channel = findChannel(channelID); 333 if (channel) { 334 channel->setPriority(priority); 335 } 336} 337 338void SoundPool::setLoop(int channelID, int loop) 339{ 340 LOGV("setLoop(%d, %d)", channelID, loop); 341 Mutex::Autolock lock(&mLock); 342 SoundChannel* channel = findChannel(channelID); 343 if (channel) { 344 channel->setLoop(loop); 345 } 346} 347 348void SoundPool::setRate(int channelID, float rate) 349{ 350 LOGV("setRate(%d, %f)", channelID, rate); 351 Mutex::Autolock lock(&mLock); 352 SoundChannel* channel = findChannel(channelID); 353 if (channel) { 354 channel->setRate(rate); 355 } 356} 357 358// call with lock held 359void SoundPool::done(SoundChannel* channel) 360{ 361 LOGV("done(%d)", channel->channelID()); 362 363 // if "stolen", play next event 364 if (channel->nextChannelID() != 0) { 365 LOGV("add to restart list"); 366 addToRestartList(channel); 367 } 368 369 // return to idle state 370 else { 371 LOGV("move to front"); 372 moveToFront(channel); 373 } 374} 375 376void SoundPool::dump() 377{ 378 for (int i = 0; i < mMaxChannels; ++i) { 379 mChannelPool[i].dump(); 380 } 381} 382 383 384Sample::Sample(int sampleID, const char* url) 385{ 386 init(); 387 mSampleID = sampleID; 388 mUrl = strdup(url); 389 LOGV("create sampleID=%d, url=%s", mSampleID, mUrl); 390} 391 392Sample::Sample(int sampleID, int fd, int64_t offset, int64_t length) 393{ 394 init(); 395 mSampleID = sampleID; 396 mFd = dup(fd); 397 mOffset = offset; 398 mLength = length; 399 LOGV("create sampleID=%d, fd=%d, offset=%lld, length=%lld", mSampleID, mFd, mLength, mOffset); 400} 401 402void Sample::init() 403{ 404 mData = 0; 405 mSize = 0; 406 mRefCount = 0; 407 mSampleID = 0; 408 mState = UNLOADED; 409 mFd = -1; 410 mOffset = 0; 411 mLength = 0; 412 mUrl = 0; 413} 414 415Sample::~Sample() 416{ 417 LOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd); 418 if (mFd > 0) { 419 LOGV("close(%d)", mFd); 420 ::close(mFd); 421 } 422 mData.clear(); 423 delete mUrl; 424} 425 426void Sample::doLoad() 427{ 428 uint32_t sampleRate; 429 int numChannels; 430 int format; 431 sp<IMemory> p; 432 LOGV("Start decode"); 433 if (mUrl) { 434 p = MediaPlayer::decode(mUrl, &sampleRate, &numChannels, &format); 435 } else { 436 p = MediaPlayer::decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format); 437 LOGV("close(%d)", mFd); 438 ::close(mFd); 439 mFd = -1; 440 } 441 if (p == 0) { 442 LOGE("Unable to load sample: %s", mUrl); 443 return; 444 } 445 LOGV("pointer = %p, size = %u, sampleRate = %u, numChannels = %d", 446 p->pointer(), p->size(), sampleRate, numChannels); 447 448 if (sampleRate > kMaxSampleRate) { 449 LOGE("Sample rate (%u) out of range", sampleRate); 450 return; 451 } 452 453 if ((numChannels < 1) || (numChannels > 2)) { 454 LOGE("Sample channel count (%d) out of range", numChannels); 455 return; 456 } 457 458 //_dumpBuffer(p->pointer(), p->size()); 459 uint8_t* q = static_cast<uint8_t*>(p->pointer()) + p->size() - 10; 460 //_dumpBuffer(q, 10, 10, false); 461 462 mData = p; 463 mSize = p->size(); 464 mSampleRate = sampleRate; 465 mNumChannels = numChannels; 466 mFormat = format; 467 mState = READY; 468} 469 470 471void SoundChannel::init(SoundPool* soundPool) 472{ 473 mSoundPool = soundPool; 474} 475 476void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume, 477 float rightVolume, int priority, int loop, float rate) 478{ 479 AudioTrack* oldTrack; 480 481 LOGV("play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f", 482 this, sample->sampleID(), nextChannelID, leftVolume, rightVolume, priority, loop, rate); 483 484 // if not idle, this voice is being stolen 485 if (mState != IDLE) { 486 LOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID); 487 mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate); 488 stop(); 489 return; 490 } 491 492 // initialize track 493 int afFrameCount; 494 int afSampleRate; 495 int streamType = mSoundPool->streamType(); 496 if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) { 497 afFrameCount = kDefaultFrameCount; 498 } 499 if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) { 500 afSampleRate = kDefaultSampleRate; 501 } 502 int numChannels = sample->numChannels(); 503 uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5); 504 uint32_t bufferFrames = (afFrameCount * sampleRate) / afSampleRate; 505 uint32_t frameCount = 0; 506 507 if (loop) { 508 frameCount = sample->size()/numChannels/((sample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t)); 509 } 510 511#ifndef USE_SHARED_MEM_BUFFER 512 // Ensure minimum audio buffer size in case of short looped sample 513 if(frameCount < kDefaultBufferCount * bufferFrames) { 514 frameCount = kDefaultBufferCount * bufferFrames; 515 } 516#endif 517 518 AudioTrack* newTrack; 519 520 // mToggle toggles each time a track is started on a given channel. 521 // The toggle is concatenated with the SoundChannel address and passed to AudioTrack 522 // as callback user data. This enables the detection of callbacks received from the old 523 // audio track while the new one is being started and avoids processing them with 524 // wrong audio audio buffer size (mAudioBufferSize) 525 unsigned long toggle = mToggle ^ 1; 526 void *userData = (void *)((unsigned long)this | toggle); 527 528#ifdef USE_SHARED_MEM_BUFFER 529 newTrack = new AudioTrack(streamType, sampleRate, sample->format(), 530 numChannels, sample->getIMemory(), 0, callback, userData); 531#else 532 newTrack = new AudioTrack(streamType, sampleRate, sample->format(), 533 numChannels, frameCount, 0, callback, userData, bufferFrames); 534#endif 535 if (newTrack->initCheck() != NO_ERROR) { 536 LOGE("Error creating AudioTrack"); 537 delete newTrack; 538 return; 539 } 540 LOGV("setVolume %p", newTrack); 541 newTrack->setVolume(leftVolume, rightVolume); 542 newTrack->setLoop(0, frameCount, loop); 543 544 { 545 Mutex::Autolock lock(&mLock); 546 // From now on, AudioTrack callbacks recevieved with previous toggle value will be ignored. 547 mToggle = toggle; 548 oldTrack = mAudioTrack; 549 mAudioTrack = newTrack; 550 mPos = 0; 551 mSample = sample; 552 mChannelID = nextChannelID; 553 mPriority = priority; 554 mLoop = loop; 555 mLeftVolume = leftVolume; 556 mRightVolume = rightVolume; 557 mNumChannels = numChannels; 558 mRate = rate; 559 clearNextEvent(); 560 mState = PLAYING; 561 mAudioTrack->start(); 562 mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize(); 563 } 564 565 LOGV("delete oldTrack %p", oldTrack); 566 delete oldTrack; 567} 568 569void SoundChannel::nextEvent() 570{ 571 sp<Sample> sample; 572 int nextChannelID; 573 float leftVolume; 574 float rightVolume; 575 int priority; 576 int loop; 577 float rate; 578 579 // check for valid event 580 { 581 Mutex::Autolock lock(&mLock); 582 nextChannelID = mNextEvent.channelID(); 583 if (nextChannelID == 0) { 584 LOGV("stolen channel has no event"); 585 return; 586 } 587 588 sample = mNextEvent.sample(); 589 leftVolume = mNextEvent.leftVolume(); 590 rightVolume = mNextEvent.rightVolume(); 591 priority = mNextEvent.priority(); 592 loop = mNextEvent.loop(); 593 rate = mNextEvent.rate(); 594 } 595 596 LOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID); 597 play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate); 598} 599 600void SoundChannel::callback(int event, void* user, void *info) 601{ 602 unsigned long toggle = (unsigned long)user & 1; 603 SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1)); 604 605 if (channel->mToggle != toggle) { 606 LOGV("callback with wrong toggle"); 607 return; 608 } 609 channel->process(event, info); 610} 611 612void SoundChannel::process(int event, void *info) 613{ 614 //LOGV("process(%d)", mChannelID); 615 sp<Sample> sample = mSample; 616 617// LOGV("SoundChannel::process event %d", event); 618 619 if (event == AudioTrack::EVENT_MORE_DATA) { 620 AudioTrack::Buffer* b = static_cast<AudioTrack::Buffer *>(info); 621 622 // check for stop state 623 if (b->size == 0) return; 624 625 if (sample != 0) { 626 // fill buffer 627 uint8_t* q = (uint8_t*) b->i8; 628 size_t count = 0; 629 630 if (mPos < (int)sample->size()) { 631 uint8_t* p = sample->data() + mPos; 632 count = sample->size() - mPos; 633 if (count > b->size) { 634 count = b->size; 635 } 636 memcpy(q, p, count); 637 LOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size, count); 638 } else if (mPos < mAudioBufferSize) { 639 count = mAudioBufferSize - mPos; 640 if (count > b->size) { 641 count = b->size; 642 } 643 memset(q, 0, count); 644 LOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count); 645 } 646 647 mPos += count; 648 b->size = count; 649 //LOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]); 650 } 651 } else if (event == AudioTrack::EVENT_UNDERRUN) { 652 LOGV("stopping track"); 653 stop(); 654 } else if (event == AudioTrack::EVENT_LOOP_END) { 655 LOGV("End loop: %d", *(int *)info); 656 } 657} 658 659 660// call with lock held 661void SoundChannel::stop_l() 662{ 663 if (mState != IDLE) { 664 setVolume_l(0, 0); 665 LOGV("stop"); 666 mAudioTrack->stop(); 667 mSample.clear(); 668 mState = IDLE; 669 mPriority = IDLE_PRIORITY; 670 } 671} 672 673void SoundChannel::stop() 674{ 675 { 676 Mutex::Autolock lock(&mLock); 677 stop_l(); 678 } 679 mSoundPool->done(this); 680} 681 682//FIXME: Pause is a little broken right now 683void SoundChannel::pause() 684{ 685 Mutex::Autolock lock(&mLock); 686 if (mState == PLAYING) { 687 LOGV("pause track"); 688 mState = PAUSED; 689 mAudioTrack->pause(); 690 } 691} 692 693void SoundChannel::resume() 694{ 695 Mutex::Autolock lock(&mLock); 696 if (mState == PAUSED) { 697 LOGV("resume track"); 698 mState = PLAYING; 699 mAudioTrack->start(); 700 } 701} 702 703void SoundChannel::setRate(float rate) 704{ 705 Mutex::Autolock lock(&mLock); 706 if (mAudioTrack != 0 && mSample.get() != 0) { 707 uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5); 708 mAudioTrack->setSampleRate(sampleRate); 709 mRate = rate; 710 } 711} 712 713// call with lock held 714void SoundChannel::setVolume_l(float leftVolume, float rightVolume) 715{ 716 mLeftVolume = leftVolume; 717 mRightVolume = rightVolume; 718 if (mAudioTrack != 0) mAudioTrack->setVolume(leftVolume, rightVolume); 719} 720 721void SoundChannel::setVolume(float leftVolume, float rightVolume) 722{ 723 Mutex::Autolock lock(&mLock); 724 setVolume_l(leftVolume, rightVolume); 725} 726 727void SoundChannel::setLoop(int loop) 728{ 729 Mutex::Autolock lock(&mLock); 730 if (mAudioTrack != 0 && mSample.get() != 0) { 731 mAudioTrack->setLoop(0, mSample->size()/mNumChannels/((mSample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t)), loop); 732 mLoop = loop; 733 } 734} 735 736SoundChannel::~SoundChannel() 737{ 738 LOGV("SoundChannel destructor"); 739 if (mAudioTrack) { 740 LOGV("stop track"); 741 mAudioTrack->stop(); 742 delete mAudioTrack; 743 } 744 clearNextEvent(); 745 mSample.clear(); 746} 747 748void SoundChannel::dump() 749{ 750 LOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d", 751 mState, mChannelID, mNumChannels, mPos, mPriority, mLoop); 752} 753 754void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume, 755 float rightVolume, int priority, int loop, float rate) 756{ 757 mSample =sample; 758 mChannelID = channelID; 759 mLeftVolume = leftVolume; 760 mRightVolume = rightVolume; 761 mPriority = priority; 762 mLoop = loop; 763 mRate =rate; 764} 765 766} // end namespace android 767 768