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