SoundPool.cpp revision 1b0efec3473134fb7de226f3e1fdade5b3529ad9
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 uint32_t channels = (numChannels == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO; 528 529#ifdef USE_SHARED_MEM_BUFFER 530 newTrack = new AudioTrack(streamType, sampleRate, sample->format(), 531 channels, sample->getIMemory(), 0, callback, userData); 532#else 533 newTrack = new AudioTrack(streamType, sampleRate, sample->format(), 534 channels, frameCount, 0, callback, userData, bufferFrames); 535#endif 536 if (newTrack->initCheck() != NO_ERROR) { 537 LOGE("Error creating AudioTrack"); 538 delete newTrack; 539 return; 540 } 541 LOGV("setVolume %p", newTrack); 542 newTrack->setVolume(leftVolume, rightVolume); 543 newTrack->setLoop(0, frameCount, loop); 544 545 { 546 Mutex::Autolock lock(&mLock); 547 // From now on, AudioTrack callbacks recevieved with previous toggle value will be ignored. 548 mToggle = toggle; 549 oldTrack = mAudioTrack; 550 mAudioTrack = newTrack; 551 mPos = 0; 552 mSample = sample; 553 mChannelID = nextChannelID; 554 mPriority = priority; 555 mLoop = loop; 556 mLeftVolume = leftVolume; 557 mRightVolume = rightVolume; 558 mNumChannels = numChannels; 559 mRate = rate; 560 clearNextEvent(); 561 mState = PLAYING; 562 mAudioTrack->start(); 563 mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize(); 564 } 565 566 LOGV("delete oldTrack %p", oldTrack); 567 delete oldTrack; 568} 569 570void SoundChannel::nextEvent() 571{ 572 sp<Sample> sample; 573 int nextChannelID; 574 float leftVolume; 575 float rightVolume; 576 int priority; 577 int loop; 578 float rate; 579 580 // check for valid event 581 { 582 Mutex::Autolock lock(&mLock); 583 nextChannelID = mNextEvent.channelID(); 584 if (nextChannelID == 0) { 585 LOGV("stolen channel has no event"); 586 return; 587 } 588 589 sample = mNextEvent.sample(); 590 leftVolume = mNextEvent.leftVolume(); 591 rightVolume = mNextEvent.rightVolume(); 592 priority = mNextEvent.priority(); 593 loop = mNextEvent.loop(); 594 rate = mNextEvent.rate(); 595 } 596 597 LOGV("Starting stolen channel %d -> %d", channelID(), nextChannelID); 598 play(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate); 599} 600 601void SoundChannel::callback(int event, void* user, void *info) 602{ 603 unsigned long toggle = (unsigned long)user & 1; 604 SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1)); 605 606 if (channel->mToggle != toggle) { 607 LOGV("callback with wrong toggle"); 608 return; 609 } 610 channel->process(event, info); 611} 612 613void SoundChannel::process(int event, void *info) 614{ 615 //LOGV("process(%d)", mChannelID); 616 sp<Sample> sample = mSample; 617 618// LOGV("SoundChannel::process event %d", event); 619 620 if (event == AudioTrack::EVENT_MORE_DATA) { 621 AudioTrack::Buffer* b = static_cast<AudioTrack::Buffer *>(info); 622 623 // check for stop state 624 if (b->size == 0) return; 625 626 if (sample != 0) { 627 // fill buffer 628 uint8_t* q = (uint8_t*) b->i8; 629 size_t count = 0; 630 631 if (mPos < (int)sample->size()) { 632 uint8_t* p = sample->data() + mPos; 633 count = sample->size() - mPos; 634 if (count > b->size) { 635 count = b->size; 636 } 637 memcpy(q, p, count); 638 LOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size, count); 639 } else if (mPos < mAudioBufferSize) { 640 count = mAudioBufferSize - mPos; 641 if (count > b->size) { 642 count = b->size; 643 } 644 memset(q, 0, count); 645 LOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count); 646 } 647 648 mPos += count; 649 b->size = count; 650 //LOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]); 651 } 652 } else if (event == AudioTrack::EVENT_UNDERRUN) { 653 LOGV("stopping track"); 654 stop(); 655 } else if (event == AudioTrack::EVENT_LOOP_END) { 656 LOGV("End loop: %d", *(int *)info); 657 } 658} 659 660 661// call with lock held 662void SoundChannel::stop_l() 663{ 664 if (mState != IDLE) { 665 setVolume_l(0, 0); 666 LOGV("stop"); 667 mAudioTrack->stop(); 668 mSample.clear(); 669 mState = IDLE; 670 mPriority = IDLE_PRIORITY; 671 } 672} 673 674void SoundChannel::stop() 675{ 676 { 677 Mutex::Autolock lock(&mLock); 678 stop_l(); 679 } 680 mSoundPool->done(this); 681} 682 683//FIXME: Pause is a little broken right now 684void SoundChannel::pause() 685{ 686 Mutex::Autolock lock(&mLock); 687 if (mState == PLAYING) { 688 LOGV("pause track"); 689 mState = PAUSED; 690 mAudioTrack->pause(); 691 } 692} 693 694void SoundChannel::resume() 695{ 696 Mutex::Autolock lock(&mLock); 697 if (mState == PAUSED) { 698 LOGV("resume track"); 699 mState = PLAYING; 700 mAudioTrack->start(); 701 } 702} 703 704void SoundChannel::setRate(float rate) 705{ 706 Mutex::Autolock lock(&mLock); 707 if (mAudioTrack != 0 && mSample.get() != 0) { 708 uint32_t sampleRate = uint32_t(float(mSample->sampleRate()) * rate + 0.5); 709 mAudioTrack->setSampleRate(sampleRate); 710 mRate = rate; 711 } 712} 713 714// call with lock held 715void SoundChannel::setVolume_l(float leftVolume, float rightVolume) 716{ 717 mLeftVolume = leftVolume; 718 mRightVolume = rightVolume; 719 if (mAudioTrack != 0) mAudioTrack->setVolume(leftVolume, rightVolume); 720} 721 722void SoundChannel::setVolume(float leftVolume, float rightVolume) 723{ 724 Mutex::Autolock lock(&mLock); 725 setVolume_l(leftVolume, rightVolume); 726} 727 728void SoundChannel::setLoop(int loop) 729{ 730 Mutex::Autolock lock(&mLock); 731 if (mAudioTrack != 0 && mSample.get() != 0) { 732 mAudioTrack->setLoop(0, mSample->size()/mNumChannels/((mSample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t)), loop); 733 mLoop = loop; 734 } 735} 736 737SoundChannel::~SoundChannel() 738{ 739 LOGV("SoundChannel destructor"); 740 if (mAudioTrack) { 741 LOGV("stop track"); 742 mAudioTrack->stop(); 743 delete mAudioTrack; 744 } 745 clearNextEvent(); 746 mSample.clear(); 747} 748 749void SoundChannel::dump() 750{ 751 LOGV("mState = %d mChannelID=%d, mNumChannels=%d, mPos = %d, mPriority=%d, mLoop=%d", 752 mState, mChannelID, mNumChannels, mPos, mPriority, mLoop); 753} 754 755void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume, 756 float rightVolume, int priority, int loop, float rate) 757{ 758 mSample =sample; 759 mChannelID = channelID; 760 mLeftVolume = leftVolume; 761 mRightVolume = rightVolume; 762 mPriority = priority; 763 mLoop = loop; 764 mRate =rate; 765} 766 767} // end namespace android 768 769