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