SoundPool.cpp revision 9648e4b6774910afde095be94b8359ae80cd3dcb
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// 22#define USE_SHARED_MEM_BUFFER 23 24// XXX needed for timing latency 25#include <utils/Timers.h> 26 27#include <sys/resource.h> 28#include <media/AudioTrack.h> 29#include <media/mediaplayer.h> 30 31#include "SoundPool.h" 32#include "SoundPoolThread.h" 33 34namespace android 35{ 36 37int kDefaultBufferCount = 4; 38uint32_t kMaxSampleRate = 48000; 39uint32_t kDefaultSampleRate = 44100; 40uint32_t kDefaultFrameCount = 1200; 41 42SoundPool::SoundPool(jobject soundPoolRef, int maxChannels, int streamType, int srcQuality) 43{ 44 LOGV("SoundPool constructor: maxChannels=%d, streamType=%d, srcQuality=%d", 45 maxChannels, streamType, srcQuality); 46 47 if (maxChannels > 32) { 48 LOGW("App requested %d channels, capped at 32", maxChannels); 49 maxChannels = 32; 50 } 51 52 mQuit = false; 53 mSoundPoolRef = soundPoolRef; 54 mDecodeThread = 0; 55 mMaxChannels = maxChannels; 56 mStreamType = streamType; 57 mSrcQuality = srcQuality; 58 mAllocated = 0; 59 mNextSampleID = 0; 60 mNextChannelID = 0; 61 62 mChannelPool = new SoundChannel[maxChannels]; 63 for (int i = 0; i < maxChannels; ++i) { 64 mChannelPool[i].init(this); 65 mChannels.push_back(&mChannelPool[i]); 66 } 67 68 // start decode thread 69 startThreads(); 70} 71 72SoundPool::~SoundPool() 73{ 74 LOGV("SoundPool destructor"); 75 mDecodeThread->quit(); 76 quit(); 77 78 Mutex::Autolock lock(&mLock); 79 mChannels.clear(); 80 if (mChannelPool) 81 delete [] mChannelPool; 82 83 // clean up samples 84 LOGV("clear samples"); 85 mSamples.clear(); 86 87 if (mDecodeThread) 88 delete mDecodeThread; 89} 90 91void SoundPool::addToRestartList(SoundChannel* channel) 92{ 93 Mutex::Autolock lock(&mLock); 94 mRestart.push_back(channel); 95 mCondition.signal(); 96} 97 98int SoundPool::beginThread(void* arg) 99{ 100 SoundPool* p = (SoundPool*)arg; 101 return p->run(); 102} 103 104int SoundPool::run() 105{ 106 mLock.lock(); 107 while (!mQuit) { 108 mCondition.wait(mLock); 109 LOGV("awake"); 110 if (mQuit) break; 111 112 while (!mRestart.empty()) { 113 SoundChannel* channel; 114 LOGV("Getting channel from list"); 115 List<SoundChannel*>::iterator iter = mRestart.begin(); 116 channel = *iter; 117 mRestart.erase(iter); 118 if (channel) channel->nextEvent(); 119 if (mQuit) break; 120 } 121 } 122 123 mRestart.clear(); 124 mCondition.signal(); 125 mLock.unlock(); 126 LOGV("goodbye"); 127 return 0; 128} 129 130void SoundPool::quit() 131{ 132 mLock.lock(); 133 mQuit = true; 134 mCondition.signal(); 135 mCondition.wait(mLock); 136 LOGV("return from quit"); 137 mLock.unlock(); 138} 139 140bool SoundPool::startThreads() 141{ 142 createThread(beginThread, this); 143 if (mDecodeThread == NULL) 144 mDecodeThread = new SoundPoolThread(this); 145 return mDecodeThread != NULL; 146} 147 148SoundChannel* SoundPool::findChannel(int channelID) 149{ 150 for (int i = 0; i < mMaxChannels; ++i) { 151 if (mChannelPool[i].channelID() == channelID) { 152 return &mChannelPool[i]; 153 } 154 } 155 return NULL; 156} 157 158SoundChannel* SoundPool::findNextChannel(int channelID) 159{ 160 for (int i = 0; i < mMaxChannels; ++i) { 161 if (mChannelPool[i].nextChannelID() == channelID) { 162 return &mChannelPool[i]; 163 } 164 } 165 return NULL; 166} 167 168int SoundPool::load(const char* path, int priority) 169{ 170 LOGV("load: path=%s, priority=%d", path, priority); 171 Mutex::Autolock lock(&mLock); 172 sp<Sample> sample = new Sample(++mNextSampleID, path); 173 mSamples.add(sample->sampleID(), sample); 174 doLoad(sample); 175 return sample->sampleID(); 176} 177 178int SoundPool::load(int fd, int64_t offset, int64_t length, int priority) 179{ 180 LOGV("load: fd=%d, offset=%lld, length=%lld, priority=%d", 181 fd, offset, length, priority); 182 Mutex::Autolock lock(&mLock); 183 sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length); 184 mSamples.add(sample->sampleID(), sample); 185 doLoad(sample); 186 return sample->sampleID(); 187} 188 189void SoundPool::doLoad(sp<Sample>& sample) 190{ 191 LOGV("doLoad: loading sample sampleID=%d", sample->sampleID()); 192 sample->startLoad(); 193 mDecodeThread->loadSample(sample->sampleID()); 194} 195 196bool SoundPool::unload(int sampleID) 197{ 198 LOGV("unload: sampleID=%d", sampleID); 199 Mutex::Autolock lock(&mLock); 200 return mSamples.removeItem(sampleID); 201} 202 203int SoundPool::play(int sampleID, float leftVolume, float rightVolume, 204 int priority, int loop, float rate) 205{ 206 LOGV("sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f", 207 sampleID, leftVolume, rightVolume, priority, loop, rate); 208 sp<Sample> sample; 209 SoundChannel* channel; 210 int channelID; 211 212 // scope for lock 213 { 214 Mutex::Autolock lock(&mLock); 215 216 // is sample ready? 217 sample = findSample(sampleID); 218 if ((sample == 0) || (sample->state() != Sample::READY)) { 219 LOGW(" sample %d not READY", sampleID); 220 return 0; 221 } 222 223 dump(); 224 225 // allocate a channel 226 channel = allocateChannel(priority); 227 228 // no channel allocated - return 0 229 if (!channel) { 230 LOGV("No channel allocated"); 231 return 0; 232 } 233 234 channelID = ++mNextChannelID; 235 } 236 237 LOGV("channel state = %d", channel->state()); 238 channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate); 239 return channelID; 240} 241 242SoundChannel* SoundPool::allocateChannel(int priority) 243{ 244 List<SoundChannel*>::iterator iter; 245 SoundChannel* channel = NULL; 246 247 // allocate a channel 248 if (!mChannels.empty()) { 249 iter = mChannels.begin(); 250 if (priority >= (*iter)->priority()) { 251 channel = *iter; 252 mChannels.erase(iter); 253 LOGV("Allocated active channel"); 254 } 255 } 256 257 // update priority and put it back in the list 258 if (channel) { 259 channel->setPriority(priority); 260 for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) { 261 if (priority < (*iter)->priority()) { 262 break; 263 } 264 } 265 mChannels.insert(iter, channel); 266 } 267 return channel; 268} 269 270// move a channel from its current position to the front of the list 271void SoundPool::moveToFront(SoundChannel* channel) 272{ 273 for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) { 274 if (*iter == channel) { 275 mChannels.erase(iter); 276 mChannels.push_front(channel); 277 break; 278 } 279 } 280} 281 282void SoundPool::pause(int channelID) 283{ 284 LOGV("pause(%d)", channelID); 285 Mutex::Autolock lock(&mLock); 286 SoundChannel* channel = findChannel(channelID); 287 if (channel) { 288 channel->pause(); 289 } 290} 291 292void SoundPool::resume(int channelID) 293{ 294 LOGV("resume(%d)", channelID); 295 Mutex::Autolock lock(&mLock); 296 SoundChannel* channel = findChannel(channelID); 297 if (channel) { 298 channel->resume(); 299 } 300} 301 302void SoundPool::stop(int channelID) 303{ 304 LOGV("stop(%d)", channelID); 305 Mutex::Autolock lock(&mLock); 306 SoundChannel* channel = findChannel(channelID); 307 if (channel) { 308 channel->stop(); 309 } else { 310 channel = findNextChannel(channelID); 311 if (channel) 312 channel->clearNextEvent(); 313 } 314} 315 316void SoundPool::setVolume(int channelID, float leftVolume, float rightVolume) 317{ 318 Mutex::Autolock lock(&mLock); 319 SoundChannel* channel = findChannel(channelID); 320 if (channel) { 321 channel->setVolume(leftVolume, rightVolume); 322 } 323} 324 325void SoundPool::setPriority(int channelID, int priority) 326{ 327 LOGV("setPriority(%d, %d)", channelID, priority); 328 Mutex::Autolock lock(&mLock); 329 SoundChannel* channel = findChannel(channelID); 330 if (channel) { 331 channel->setPriority(priority); 332 } 333} 334 335void SoundPool::setLoop(int channelID, int loop) 336{ 337 LOGV("setLoop(%d, %d)", channelID, loop); 338 Mutex::Autolock lock(&mLock); 339 SoundChannel* channel = findChannel(channelID); 340 if (channel) { 341 channel->setLoop(loop); 342 } 343} 344 345void SoundPool::setRate(int channelID, float rate) 346{ 347 LOGV("setRate(%d, %f)", channelID, rate); 348 Mutex::Autolock lock(&mLock); 349 SoundChannel* channel = findChannel(channelID); 350 if (channel) { 351 channel->setRate(rate); 352 } 353} 354 355// call with lock held 356void SoundPool::done(SoundChannel* channel) 357{ 358 LOGV("done(%d)", channel->channelID()); 359 360 // if "stolen", play next event 361 if (channel->nextChannelID() != 0) { 362 LOGV("add to restart list"); 363 addToRestartList(channel); 364 } 365 366 // return to idle state 367 else { 368 LOGV("move to front"); 369 moveToFront(channel); 370 } 371} 372 373void SoundPool::dump() 374{ 375 for (int i = 0; i < mMaxChannels; ++i) { 376 mChannelPool[i].dump(); 377 } 378} 379 380 381Sample::Sample(int sampleID, const char* url) 382{ 383 init(); 384 mSampleID = sampleID; 385 mUrl = strdup(url); 386 LOGV("create sampleID=%d, url=%s", mSampleID, mUrl); 387} 388 389Sample::Sample(int sampleID, int fd, int64_t offset, int64_t length) 390{ 391 init(); 392 mSampleID = sampleID; 393 mFd = dup(fd); 394 mOffset = offset; 395 mLength = length; 396 LOGV("create sampleID=%d, fd=%d, offset=%lld, length=%lld", mSampleID, mFd, mLength, mOffset); 397} 398 399void Sample::init() 400{ 401 mData = 0; 402 mSize = 0; 403 mRefCount = 0; 404 mSampleID = 0; 405 mState = UNLOADED; 406 mFd = -1; 407 mOffset = 0; 408 mLength = 0; 409 mUrl = 0; 410} 411 412Sample::~Sample() 413{ 414 LOGV("Sample::destructor sampleID=%d, fd=%d", mSampleID, mFd); 415 if (mFd > 0) { 416 LOGV("close(%d)", mFd); 417 ::close(mFd); 418 } 419 mData.clear(); 420 delete mUrl; 421} 422 423void Sample::doLoad() 424{ 425 uint32_t sampleRate; 426 int numChannels; 427 int format; 428 sp<IMemory> p; 429 LOGV("Start decode"); 430 if (mUrl) { 431 p = MediaPlayer::decode(mUrl, &sampleRate, &numChannels, &format); 432 } else { 433 p = MediaPlayer::decode(mFd, mOffset, mLength, &sampleRate, &numChannels, &format); 434 LOGV("close(%d)", mFd); 435 ::close(mFd); 436 mFd = -1; 437 } 438 if (p == 0) { 439 LOGE("Unable to load sample: %s", mUrl); 440 return; 441 } 442 LOGV("pointer = %p, size = %u, sampleRate = %u, numChannels = %d", 443 p->pointer(), p->size(), sampleRate, numChannels); 444 445 if (sampleRate > kMaxSampleRate) { 446 LOGE("Sample rate (%u) out of range", sampleRate); 447 return; 448 } 449 450 if ((numChannels < 1) || (numChannels > 2)) { 451 LOGE("Sample channel count (%d) out of range", numChannels); 452 return; 453 } 454 455 //_dumpBuffer(p->pointer(), p->size()); 456 uint8_t* q = static_cast<uint8_t*>(p->pointer()) + p->size() - 10; 457 //_dumpBuffer(q, 10, 10, false); 458 459 mData = p; 460 mSize = p->size(); 461 mSampleRate = sampleRate; 462 mNumChannels = numChannels; 463 mFormat = format; 464 mState = READY; 465} 466 467 468void SoundChannel::init(SoundPool* soundPool) 469{ 470 mSoundPool = soundPool; 471} 472 473void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume, 474 float rightVolume, int priority, int loop, float rate) 475{ 476 AudioTrack* oldTrack; 477 478 LOGV("play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f", 479 this, sample->sampleID(), nextChannelID, leftVolume, rightVolume, priority, loop, rate); 480 481 // if not idle, this voice is being stolen 482 if (mState != IDLE) { 483 LOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID); 484 stop_l(); 485 mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate); 486#ifdef USE_SHARED_MEM_BUFFER 487 mSoundPool->done(this); 488#endif 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