AudioTrack.cpp revision 5e07b5774c8b376776caa4f5b0a193767697e97e
1/* //device/extlibs/pv/android/AudioTrack.cpp 2** 3** Copyright 2007, The Android Open Source Project 4** 5** Licensed under the Apache License, Version 2.0 (the "License"); 6** you may not use this file except in compliance with the License. 7** You may obtain a copy of the License at 8** 9** http://www.apache.org/licenses/LICENSE-2.0 10** 11** Unless required by applicable law or agreed to in writing, software 12** distributed under the License is distributed on an "AS IS" BASIS, 13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14** See the License for the specific language governing permissions and 15** limitations under the License. 16*/ 17 18 19//#define LOG_NDEBUG 0 20#define LOG_TAG "AudioTrack" 21 22#include <stdint.h> 23#include <sys/types.h> 24#include <limits.h> 25 26#include <sched.h> 27#include <sys/resource.h> 28 29#include <private/media/AudioTrackShared.h> 30 31#include <media/AudioSystem.h> 32#include <media/AudioTrack.h> 33 34#include <utils/Log.h> 35#include <utils/MemoryDealer.h> 36#include <utils/Parcel.h> 37#include <utils/IPCThreadState.h> 38#include <utils/Timers.h> 39#include <cutils/atomic.h> 40 41#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true )) 42#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false )) 43 44namespace android { 45 46// --------------------------------------------------------------------------- 47 48AudioTrack::AudioTrack() 49 : mStatus(NO_INIT) 50{ 51} 52 53AudioTrack::AudioTrack( 54 int streamType, 55 uint32_t sampleRate, 56 int format, 57 int channelCount, 58 int frameCount, 59 uint32_t flags, 60 callback_t cbf, 61 void* user, 62 int notificationFrames) 63 : mStatus(NO_INIT) 64{ 65 mStatus = set(streamType, sampleRate, format, channelCount, 66 frameCount, flags, cbf, user, notificationFrames, 0); 67} 68 69AudioTrack::AudioTrack( 70 int streamType, 71 uint32_t sampleRate, 72 int format, 73 int channelCount, 74 const sp<IMemory>& sharedBuffer, 75 uint32_t flags, 76 callback_t cbf, 77 void* user, 78 int notificationFrames) 79 : mStatus(NO_INIT) 80{ 81 mStatus = set(streamType, sampleRate, format, channelCount, 82 0, flags, cbf, user, notificationFrames, sharedBuffer); 83} 84 85AudioTrack::~AudioTrack() 86{ 87 LOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer()); 88 89 if (mStatus == NO_ERROR) { 90 // Make sure that callback function exits in the case where 91 // it is looping on buffer full condition in obtainBuffer(). 92 // Otherwise the callback thread will never exit. 93 stop(); 94 if (mAudioTrackThread != 0) { 95 mCblk->cv.signal(); 96 mAudioTrackThread->requestExitAndWait(); 97 mAudioTrackThread.clear(); 98 } 99 mAudioTrack.clear(); 100 IPCThreadState::self()->flushCommands(); 101 } 102} 103 104status_t AudioTrack::set( 105 int streamType, 106 uint32_t sampleRate, 107 int format, 108 int channelCount, 109 int frameCount, 110 uint32_t flags, 111 callback_t cbf, 112 void* user, 113 int notificationFrames, 114 const sp<IMemory>& sharedBuffer, 115 bool threadCanCallJava) 116{ 117 118 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size()); 119 120 if (mAudioFlinger != 0) { 121 LOGE("Track already in use"); 122 return INVALID_OPERATION; 123 } 124 125 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger(); 126 if (audioFlinger == 0) { 127 LOGE("Could not get audioflinger"); 128 return NO_INIT; 129 } 130 int afSampleRate; 131 if (AudioSystem::getOutputSamplingRate(&afSampleRate) != NO_ERROR) { 132 return NO_INIT; 133 } 134 int afFrameCount; 135 if (AudioSystem::getOutputFrameCount(&afFrameCount) != NO_ERROR) { 136 return NO_INIT; 137 } 138 uint32_t afLatency; 139 if (AudioSystem::getOutputLatency(&afLatency) != NO_ERROR) { 140 return NO_INIT; 141 } 142 143 144 // handle default values first. 145 if (streamType == DEFAULT) { 146 streamType = MUSIC; 147 } 148 if (sampleRate == 0) { 149 sampleRate = afSampleRate; 150 } 151 // these below should probably come from the audioFlinger too... 152 if (format == 0) { 153 format = AudioSystem::PCM_16_BIT; 154 } 155 if (channelCount == 0) { 156 channelCount = 2; 157 } 158 159 // validate parameters 160 if (((format != AudioSystem::PCM_8_BIT) || mSharedBuffer != 0) && 161 (format != AudioSystem::PCM_16_BIT)) { 162 LOGE("Invalid format"); 163 return BAD_VALUE; 164 } 165 if (channelCount != 1 && channelCount != 2) { 166 LOGE("Invalid channel number"); 167 return BAD_VALUE; 168 } 169 170 // Ensure that buffer depth covers at least audio hardware latency 171 uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate); 172 // When playing from shared buffer, playback will start even if last audioflinger 173 // block is partly filled. 174 if (sharedBuffer != 0 && minBufCount > 1) { 175 minBufCount--; 176 } 177 178 int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate; 179 180 if (sharedBuffer == 0) { 181 if (frameCount == 0) { 182 frameCount = minFrameCount; 183 } 184 if (notificationFrames == 0) { 185 notificationFrames = frameCount/2; 186 } 187 // Make sure that application is notified with sufficient margin 188 // before underrun 189 if (notificationFrames > frameCount/2) { 190 notificationFrames = frameCount/2; 191 } 192 } else { 193 // Ensure that buffer alignment matches channelcount 194 if (((uint32_t)sharedBuffer->pointer() & (channelCount | 1)) != 0) { 195 LOGE("Invalid buffer alignement: address %p, channelCount %d", sharedBuffer->pointer(), channelCount); 196 return BAD_VALUE; 197 } 198 frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t); 199 } 200 201 if (frameCount < minFrameCount) { 202 LOGE("Invalid buffer size: minFrameCount %d, frameCount %d", minFrameCount, frameCount); 203 return BAD_VALUE; 204 } 205 206 // create the track 207 status_t status; 208 sp<IAudioTrack> track = audioFlinger->createTrack(getpid(), 209 streamType, sampleRate, format, channelCount, frameCount, flags, sharedBuffer, &status); 210 211 if (track == 0) { 212 LOGE("AudioFlinger could not create track, status: %d", status); 213 return status; 214 } 215 sp<IMemory> cblk = track->getCblk(); 216 if (cblk == 0) { 217 LOGE("Could not get control block"); 218 return NO_INIT; 219 } 220 if (cbf != 0) { 221 mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava); 222 if (mAudioTrackThread == 0) { 223 LOGE("Could not create callback thread"); 224 return NO_INIT; 225 } 226 } 227 228 mStatus = NO_ERROR; 229 230 mAudioFlinger = audioFlinger; 231 mAudioTrack = track; 232 mCblkMemory = cblk; 233 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer()); 234 mCblk->out = 1; 235 // Update buffer size in case it has been limited by AudioFlinger during track creation 236 mFrameCount = mCblk->frameCount; 237 if (sharedBuffer == 0) { 238 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t); 239 } else { 240 mCblk->buffers = sharedBuffer->pointer(); 241 // Force buffer full condition as data is already present in shared memory 242 mCblk->stepUser(mFrameCount); 243 } 244 mCblk->volume[0] = mCblk->volume[1] = 0x1000; 245 mVolume[LEFT] = 1.0f; 246 mVolume[RIGHT] = 1.0f; 247 mSampleRate = sampleRate; 248 mStreamType = streamType; 249 mFormat = format; 250 mChannelCount = channelCount; 251 mSharedBuffer = sharedBuffer; 252 mMuted = false; 253 mActive = 0; 254 mCbf = cbf; 255 mNotificationFrames = notificationFrames; 256 mRemainingFrames = notificationFrames; 257 mUserData = user; 258 mLatency = afLatency + (1000*mFrameCount) / mSampleRate; 259 mLoopCount = 0; 260 mMarkerPosition = 0; 261 mNewPosition = 0; 262 mUpdatePeriod = 0; 263 264 return NO_ERROR; 265} 266 267status_t AudioTrack::initCheck() const 268{ 269 return mStatus; 270} 271 272// ------------------------------------------------------------------------- 273 274uint32_t AudioTrack::latency() const 275{ 276 return mLatency; 277} 278 279int AudioTrack::streamType() const 280{ 281 return mStreamType; 282} 283 284uint32_t AudioTrack::sampleRate() const 285{ 286 return mSampleRate; 287} 288 289int AudioTrack::format() const 290{ 291 return mFormat; 292} 293 294int AudioTrack::channelCount() const 295{ 296 return mChannelCount; 297} 298 299uint32_t AudioTrack::frameCount() const 300{ 301 return mFrameCount; 302} 303 304int AudioTrack::frameSize() const 305{ 306 return channelCount()*((format() == AudioSystem::PCM_8_BIT) ? sizeof(uint8_t) : sizeof(int16_t)); 307} 308 309sp<IMemory>& AudioTrack::sharedBuffer() 310{ 311 return mSharedBuffer; 312} 313 314// ------------------------------------------------------------------------- 315 316void AudioTrack::start() 317{ 318 sp<AudioTrackThread> t = mAudioTrackThread; 319 320 LOGV("start"); 321 if (t != 0) { 322 if (t->exitPending()) { 323 if (t->requestExitAndWait() == WOULD_BLOCK) { 324 LOGE("AudioTrack::start called from thread"); 325 return; 326 } 327 } 328 t->mLock.lock(); 329 } 330 331 if (android_atomic_or(1, &mActive) == 0) { 332 mNewPosition = mCblk->server + mUpdatePeriod; 333 mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS; 334 mCblk->waitTimeMs = 0; 335 if (t != 0) { 336 t->run("AudioTrackThread", THREAD_PRIORITY_AUDIO_CLIENT); 337 } else { 338 setpriority(PRIO_PROCESS, 0, THREAD_PRIORITY_AUDIO_CLIENT); 339 } 340 mAudioTrack->start(); 341 } 342 343 if (t != 0) { 344 t->mLock.unlock(); 345 } 346} 347 348void AudioTrack::stop() 349{ 350 sp<AudioTrackThread> t = mAudioTrackThread; 351 352 LOGV("stop"); 353 if (t != 0) { 354 t->mLock.lock(); 355 } 356 357 if (android_atomic_and(~1, &mActive) == 1) { 358 mAudioTrack->stop(); 359 // Cancel loops (If we are in the middle of a loop, playback 360 // would not stop until loopCount reaches 0). 361 setLoop(0, 0, 0); 362 // Force flush if a shared buffer is used otherwise audioflinger 363 // will not stop before end of buffer is reached. 364 if (mSharedBuffer != 0) { 365 flush(); 366 } 367 if (t != 0) { 368 t->requestExit(); 369 } else { 370 setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL); 371 } 372 } 373 374 if (t != 0) { 375 t->mLock.unlock(); 376 } 377} 378 379bool AudioTrack::stopped() const 380{ 381 return !mActive; 382} 383 384void AudioTrack::flush() 385{ 386 LOGV("flush"); 387 388 if (!mActive) { 389 mCblk->lock.lock(); 390 mAudioTrack->flush(); 391 // Release AudioTrack callback thread in case it was waiting for new buffers 392 // in AudioTrack::obtainBuffer() 393 mCblk->cv.signal(); 394 mCblk->lock.unlock(); 395 } 396} 397 398void AudioTrack::pause() 399{ 400 LOGV("pause"); 401 if (android_atomic_and(~1, &mActive) == 1) { 402 mActive = 0; 403 mAudioTrack->pause(); 404 } 405} 406 407void AudioTrack::mute(bool e) 408{ 409 mAudioTrack->mute(e); 410 mMuted = e; 411} 412 413bool AudioTrack::muted() const 414{ 415 return mMuted; 416} 417 418void AudioTrack::setVolume(float left, float right) 419{ 420 mVolume[LEFT] = left; 421 mVolume[RIGHT] = right; 422 423 // write must be atomic 424 mCblk->volumeLR = (int32_t(int16_t(left * 0x1000)) << 16) | int16_t(right * 0x1000); 425} 426 427void AudioTrack::getVolume(float* left, float* right) 428{ 429 *left = mVolume[LEFT]; 430 *right = mVolume[RIGHT]; 431} 432 433void AudioTrack::setSampleRate(int rate) 434{ 435 int afSamplingRate; 436 437 if (AudioSystem::getOutputSamplingRate(&afSamplingRate) != NO_ERROR) { 438 return; 439 } 440 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 441 if (rate > afSamplingRate*2) rate = afSamplingRate*2; 442 443 if (rate > MAX_SAMPLE_RATE) rate = MAX_SAMPLE_RATE; 444 445 mCblk->sampleRate = rate; 446} 447 448uint32_t AudioTrack::getSampleRate() 449{ 450 return uint32_t(mCblk->sampleRate); 451} 452 453status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount) 454{ 455 audio_track_cblk_t* cblk = mCblk; 456 457 458 Mutex::Autolock _l(cblk->lock); 459 460 if (loopCount == 0) { 461 cblk->loopStart = UINT_MAX; 462 cblk->loopEnd = UINT_MAX; 463 cblk->loopCount = 0; 464 mLoopCount = 0; 465 return NO_ERROR; 466 } 467 468 if (loopStart >= loopEnd || 469 loopEnd - loopStart > mFrameCount) { 470 LOGW("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, user %d", loopStart, loopEnd, loopCount, mFrameCount, cblk->user); 471 return BAD_VALUE; 472 } 473 // TODO handle shared buffer here: limit loop end to framecount 474 475 cblk->loopStart = loopStart; 476 cblk->loopEnd = loopEnd; 477 cblk->loopCount = loopCount; 478 mLoopCount = loopCount; 479 480 return NO_ERROR; 481} 482 483status_t AudioTrack::getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount) 484{ 485 if (loopStart != 0) { 486 *loopStart = mCblk->loopStart; 487 } 488 if (loopEnd != 0) { 489 *loopEnd = mCblk->loopEnd; 490 } 491 if (loopCount != 0) { 492 if (mCblk->loopCount < 0) { 493 *loopCount = -1; 494 } else { 495 *loopCount = mCblk->loopCount; 496 } 497 } 498 499 return NO_ERROR; 500} 501 502status_t AudioTrack::setMarkerPosition(uint32_t marker) 503{ 504 if (mCbf == 0) return INVALID_OPERATION; 505 506 mMarkerPosition = marker; 507 508 return NO_ERROR; 509} 510 511status_t AudioTrack::getMarkerPosition(uint32_t *marker) 512{ 513 if (marker == 0) return BAD_VALUE; 514 515 *marker = mMarkerPosition; 516 517 return NO_ERROR; 518} 519 520status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod) 521{ 522 if (mCbf == 0) return INVALID_OPERATION; 523 524 uint32_t curPosition; 525 getPosition(&curPosition); 526 mNewPosition = curPosition + updatePeriod; 527 mUpdatePeriod = updatePeriod; 528 529 return NO_ERROR; 530} 531 532status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) 533{ 534 if (updatePeriod == 0) return BAD_VALUE; 535 536 *updatePeriod = mUpdatePeriod; 537 538 return NO_ERROR; 539} 540 541status_t AudioTrack::setPosition(uint32_t position) 542{ 543 Mutex::Autolock _l(mCblk->lock); 544 545 if (!stopped()) return INVALID_OPERATION; 546 547 if (position > mCblk->user) return BAD_VALUE; 548 549 mCblk->server = position; 550 mCblk->forceReady = 1; 551 552 return NO_ERROR; 553} 554 555status_t AudioTrack::getPosition(uint32_t *position) 556{ 557 if (position == 0) return BAD_VALUE; 558 559 *position = mCblk->server; 560 561 return NO_ERROR; 562} 563 564status_t AudioTrack::reload() 565{ 566 if (!stopped()) return INVALID_OPERATION; 567 568 flush(); 569 570 mCblk->stepUser(mFrameCount); 571 572 return NO_ERROR; 573} 574 575// ------------------------------------------------------------------------- 576 577status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount) 578{ 579 int active; 580 int timeout = 0; 581 status_t result; 582 audio_track_cblk_t* cblk = mCblk; 583 uint32_t framesReq = audioBuffer->frameCount; 584 585 audioBuffer->frameCount = 0; 586 audioBuffer->size = 0; 587 588 uint32_t framesAvail = cblk->framesAvailable(); 589 590 if (framesAvail == 0) { 591 Mutex::Autolock _l(cblk->lock); 592 goto start_loop_here; 593 while (framesAvail == 0) { 594 active = mActive; 595 if (UNLIKELY(!active)) { 596 LOGV("Not active and NO_MORE_BUFFERS"); 597 return NO_MORE_BUFFERS; 598 } 599 if (UNLIKELY(!waitCount)) 600 return WOULD_BLOCK; 601 timeout = 0; 602 result = cblk->cv.waitRelative(cblk->lock, milliseconds(WAIT_PERIOD_MS)); 603 if (__builtin_expect(result!=NO_ERROR, false)) { 604 cblk->waitTimeMs += WAIT_PERIOD_MS; 605 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) { 606 // timing out when a loop has been set and we have already written upto loop end 607 // is a normal condition: no need to wake AudioFlinger up. 608 if (cblk->user < cblk->loopEnd) { 609 LOGW( "obtainBuffer timed out (is the CPU pegged?) " 610 "user=%08x, server=%08x", cblk->user, cblk->server); 611 mAudioFlinger->wakeUp(); 612 timeout = 1; 613 } 614 cblk->waitTimeMs = 0; 615 } 616 617 if (--waitCount == 0) { 618 return TIMED_OUT; 619 } 620 } 621 // read the server count again 622 start_loop_here: 623 framesAvail = cblk->framesAvailable_l(); 624 } 625 } 626 627 cblk->waitTimeMs = 0; 628 629 if (framesReq > framesAvail) { 630 framesReq = framesAvail; 631 } 632 633 uint32_t u = cblk->user; 634 uint32_t bufferEnd = cblk->userBase + cblk->frameCount; 635 636 if (u + framesReq > bufferEnd) { 637 framesReq = bufferEnd - u; 638 } 639 640 LOGW_IF(timeout, 641 "*** SERIOUS WARNING *** obtainBuffer() timed out " 642 "but didn't need to be locked. We recovered, but " 643 "this shouldn't happen (user=%08x, server=%08x)", cblk->user, cblk->server); 644 645 audioBuffer->flags = mMuted ? Buffer::MUTE : 0; 646 audioBuffer->channelCount= mChannelCount; 647 audioBuffer->format = AudioSystem::PCM_16_BIT; 648 audioBuffer->frameCount = framesReq; 649 audioBuffer->size = framesReq*mChannelCount*sizeof(int16_t); 650 audioBuffer->raw = (int8_t *)cblk->buffer(u); 651 active = mActive; 652 return active ? status_t(NO_ERROR) : status_t(STOPPED); 653} 654 655void AudioTrack::releaseBuffer(Buffer* audioBuffer) 656{ 657 audio_track_cblk_t* cblk = mCblk; 658 cblk->stepUser(audioBuffer->frameCount); 659} 660 661// ------------------------------------------------------------------------- 662 663ssize_t AudioTrack::write(const void* buffer, size_t userSize) 664{ 665 666 if (mSharedBuffer != 0) return INVALID_OPERATION; 667 668 if (ssize_t(userSize) < 0) { 669 // sanity-check. user is most-likely passing an error code. 670 LOGE("AudioTrack::write(buffer=%p, size=%u (%d)", 671 buffer, userSize, userSize); 672 return BAD_VALUE; 673 } 674 675 LOGV("write %d bytes, mActive=%d", userSize, mActive); 676 677 ssize_t written = 0; 678 const int8_t *src = (const int8_t *)buffer; 679 Buffer audioBuffer; 680 681 do { 682 audioBuffer.frameCount = userSize/mChannelCount; 683 if (mFormat == AudioSystem::PCM_16_BIT) { 684 audioBuffer.frameCount >>= 1; 685 } 686 // Calling obtainBuffer() with a negative wait count causes 687 // an (almost) infinite wait time. 688 status_t err = obtainBuffer(&audioBuffer, -1); 689 if (err < 0) { 690 // out of buffers, return #bytes written 691 if (err == status_t(NO_MORE_BUFFERS)) 692 break; 693 return ssize_t(err); 694 } 695 696 size_t toWrite; 697 if (mFormat == AudioSystem::PCM_8_BIT) { 698 // Divide capacity by 2 to take expansion into account 699 toWrite = audioBuffer.size>>1; 700 // 8 to 16 bit conversion 701 int count = toWrite; 702 int16_t *dst = (int16_t *)(audioBuffer.i8); 703 while(count--) { 704 *dst++ = (int16_t)(*src++^0x80) << 8; 705 } 706 }else { 707 toWrite = audioBuffer.size; 708 memcpy(audioBuffer.i8, src, toWrite); 709 src += toWrite; 710 } 711 userSize -= toWrite; 712 written += toWrite; 713 714 releaseBuffer(&audioBuffer); 715 } while (userSize); 716 717 return written; 718} 719 720// ------------------------------------------------------------------------- 721 722bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread) 723{ 724 Buffer audioBuffer; 725 uint32_t frames; 726 size_t writtenSize; 727 728 // Manage underrun callback 729 if (mActive && (mCblk->framesReady() == 0)) { 730 LOGV("Underrun user: %x, server: %x, flowControlFlag %d", mCblk->user, mCblk->server, mCblk->flowControlFlag); 731 if (mCblk->flowControlFlag == 0) { 732 mCbf(EVENT_UNDERRUN, mUserData, 0); 733 if (mCblk->server == mCblk->frameCount) { 734 mCbf(EVENT_BUFFER_END, mUserData, 0); 735 } 736 mCblk->flowControlFlag = 1; 737 if (mSharedBuffer != 0) return false; 738 } 739 } 740 741 // Manage loop end callback 742 while (mLoopCount > mCblk->loopCount) { 743 int loopCount = -1; 744 mLoopCount--; 745 if (mLoopCount >= 0) loopCount = mLoopCount; 746 747 mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount); 748 } 749 750 // Manage marker callback 751 if(mMarkerPosition > 0) { 752 if (mCblk->server >= mMarkerPosition) { 753 mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition); 754 mMarkerPosition = 0; 755 } 756 } 757 758 // Manage new position callback 759 if(mUpdatePeriod > 0) { 760 while (mCblk->server >= mNewPosition) { 761 mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition); 762 mNewPosition += mUpdatePeriod; 763 } 764 } 765 766 // If Shared buffer is used, no data is requested from client. 767 if (mSharedBuffer != 0) { 768 frames = 0; 769 } else { 770 frames = mRemainingFrames; 771 } 772 773 do { 774 775 audioBuffer.frameCount = frames; 776 777 // Calling obtainBuffer() with a wait count of 1 778 // limits wait time to WAIT_PERIOD_MS. This prevents from being 779 // stuck here not being able to handle timed events (position, markers, loops). 780 status_t err = obtainBuffer(&audioBuffer, 1); 781 if (err < NO_ERROR) { 782 if (err != TIMED_OUT) { 783 LOGE("Error obtaining an audio buffer, giving up."); 784 return false; 785 } 786 break; 787 } 788 if (err == status_t(STOPPED)) return false; 789 790 // Divide buffer size by 2 to take into account the expansion 791 // due to 8 to 16 bit conversion: the callback must fill only half 792 // of the destination buffer 793 if (mFormat == AudioSystem::PCM_8_BIT) { 794 audioBuffer.size >>= 1; 795 } 796 797 size_t reqSize = audioBuffer.size; 798 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer); 799 writtenSize = audioBuffer.size; 800 801 // Sanity check on returned size 802 if (ssize_t(writtenSize) <= 0) break; 803 if (writtenSize > reqSize) writtenSize = reqSize; 804 805 if (mFormat == AudioSystem::PCM_8_BIT) { 806 // 8 to 16 bit conversion 807 const int8_t *src = audioBuffer.i8 + writtenSize-1; 808 int count = writtenSize; 809 int16_t *dst = audioBuffer.i16 + writtenSize-1; 810 while(count--) { 811 *dst-- = (int16_t)(*src--^0x80) << 8; 812 } 813 writtenSize <<= 1; 814 } 815 816 audioBuffer.size = writtenSize; 817 audioBuffer.frameCount = writtenSize/mChannelCount/sizeof(int16_t); 818 frames -= audioBuffer.frameCount; 819 820 releaseBuffer(&audioBuffer); 821 } 822 while (frames); 823 824 if (frames == 0) { 825 mRemainingFrames = mNotificationFrames; 826 } else { 827 mRemainingFrames = frames; 828 } 829 return true; 830} 831 832status_t AudioTrack::dump(int fd, const Vector<String16>& args) const 833{ 834 835 const size_t SIZE = 256; 836 char buffer[SIZE]; 837 String8 result; 838 839 result.append(" AudioTrack::dump\n"); 840 snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mVolume[0], mVolume[1]); 841 result.append(buffer); 842 snprintf(buffer, 255, " format(%d), channel count(%d), frame count(%d)\n", mFormat, mChannelCount, mFrameCount); 843 result.append(buffer); 844 snprintf(buffer, 255, " sample rate(%d), status(%d), muted(%d)\n", mSampleRate, mStatus, mMuted); 845 result.append(buffer); 846 snprintf(buffer, 255, " active(%d), latency (%d)\n", mActive, mLatency); 847 result.append(buffer); 848 ::write(fd, result.string(), result.size()); 849 return NO_ERROR; 850} 851 852// ========================================================================= 853 854AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava) 855 : Thread(bCanCallJava), mReceiver(receiver) 856{ 857} 858 859bool AudioTrack::AudioTrackThread::threadLoop() 860{ 861 return mReceiver.processAudioBuffer(this); 862} 863 864status_t AudioTrack::AudioTrackThread::readyToRun() 865{ 866 return NO_ERROR; 867} 868 869void AudioTrack::AudioTrackThread::onFirstRef() 870{ 871} 872 873// ========================================================================= 874 875audio_track_cblk_t::audio_track_cblk_t() 876 : user(0), server(0), userBase(0), serverBase(0), buffers(0), frameCount(0), 877 loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0), flowControlFlag(1), forceReady(0) 878{ 879} 880 881uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount) 882{ 883 uint32_t u = this->user; 884 885 u += frameCount; 886 // Ensure that user is never ahead of server for AudioRecord 887 if (out) { 888 // If stepServer() has been called once, switch to normal obtainBuffer() timeout period 889 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) { 890 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS; 891 } 892 } else if (u > this->server) { 893 LOGW("stepServer occured after track reset"); 894 u = this->server; 895 } 896 897 if (u >= userBase + this->frameCount) { 898 userBase += this->frameCount; 899 } 900 901 this->user = u; 902 903 // Clear flow control error condition as new data has been written/read to/from buffer. 904 flowControlFlag = 0; 905 906 return u; 907} 908 909bool audio_track_cblk_t::stepServer(uint32_t frameCount) 910{ 911 // the code below simulates lock-with-timeout 912 // we MUST do this to protect the AudioFlinger server 913 // as this lock is shared with the client. 914 status_t err; 915 916 err = lock.tryLock(); 917 if (err == -EBUSY) { // just wait a bit 918 usleep(1000); 919 err = lock.tryLock(); 920 } 921 if (err != NO_ERROR) { 922 // probably, the client just died. 923 return false; 924 } 925 926 uint32_t s = this->server; 927 928 s += frameCount; 929 if (out) { 930 // Mark that we have read the first buffer so that next time stepUser() is called 931 // we switch to normal obtainBuffer() timeout period 932 if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) { 933 bufferTimeoutMs = MAX_RUN_TIMEOUT_MS - 1; 934 } 935 // It is possible that we receive a flush() 936 // while the mixer is processing a block: in this case, 937 // stepServer() is called After the flush() has reset u & s and 938 // we have s > u 939 if (s > this->user) { 940 LOGW("stepServer occured after track reset"); 941 s = this->user; 942 } 943 } 944 945 if (s >= loopEnd) { 946 LOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd); 947 s = loopStart; 948 if (--loopCount == 0) { 949 loopEnd = UINT_MAX; 950 loopStart = UINT_MAX; 951 } 952 } 953 if (s >= serverBase + this->frameCount) { 954 serverBase += this->frameCount; 955 } 956 957 this->server = s; 958 959 cv.signal(); 960 lock.unlock(); 961 return true; 962} 963 964void* audio_track_cblk_t::buffer(uint32_t offset) const 965{ 966 return (int16_t *)this->buffers + (offset-userBase)*this->channels; 967} 968 969uint32_t audio_track_cblk_t::framesAvailable() 970{ 971 Mutex::Autolock _l(lock); 972 return framesAvailable_l(); 973} 974 975uint32_t audio_track_cblk_t::framesAvailable_l() 976{ 977 uint32_t u = this->user; 978 uint32_t s = this->server; 979 980 if (out) { 981 uint32_t limit = (s < loopStart) ? s : loopStart; 982 return limit + frameCount - u; 983 } else { 984 return frameCount + u - s; 985 } 986} 987 988uint32_t audio_track_cblk_t::framesReady() 989{ 990 uint32_t u = this->user; 991 uint32_t s = this->server; 992 993 if (out) { 994 if (u < loopEnd) { 995 return u - s; 996 } else { 997 Mutex::Autolock _l(lock); 998 if (loopCount >= 0) { 999 return (loopEnd - loopStart)*loopCount + u - s; 1000 } else { 1001 return UINT_MAX; 1002 } 1003 } 1004 } else { 1005 return s - u; 1006 } 1007} 1008 1009// ------------------------------------------------------------------------- 1010 1011}; // namespace android 1012 1013