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