AudioRecord.cpp revision 34fb29696b0f3abf61b10f8d053b1f33d501de0a
1/* 2** 3** Copyright 2008, 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//#define LOG_NDEBUG 0 19#define LOG_TAG "AudioRecord" 20 21#include <inttypes.h> 22#include <sys/resource.h> 23 24#include <binder/IPCThreadState.h> 25#include <media/AudioRecord.h> 26#include <utils/Log.h> 27#include <private/media/AudioTrackShared.h> 28#include <media/IAudioFlinger.h> 29 30#define WAIT_PERIOD_MS 10 31 32namespace android { 33// --------------------------------------------------------------------------- 34 35// static 36status_t AudioRecord::getMinFrameCount( 37 size_t* frameCount, 38 uint32_t sampleRate, 39 audio_format_t format, 40 audio_channel_mask_t channelMask) 41{ 42 if (frameCount == NULL) { 43 return BAD_VALUE; 44 } 45 46 size_t size; 47 status_t status = AudioSystem::getInputBufferSize(sampleRate, format, channelMask, &size); 48 if (status != NO_ERROR) { 49 ALOGE("AudioSystem could not query the input buffer size for sampleRate %u, format %#x, " 50 "channelMask %#x; status %d", sampleRate, format, channelMask, status); 51 return status; 52 } 53 54 // We double the size of input buffer for ping pong use of record buffer. 55 // Assumes audio_is_linear_pcm(format) 56 if ((*frameCount = (size * 2) / (audio_channel_count_from_in_mask(channelMask) * 57 audio_bytes_per_sample(format))) == 0) { 58 ALOGE("Unsupported configuration: sampleRate %u, format %#x, channelMask %#x", 59 sampleRate, format, channelMask); 60 return BAD_VALUE; 61 } 62 63 return NO_ERROR; 64} 65 66// --------------------------------------------------------------------------- 67 68AudioRecord::AudioRecord() 69 : mStatus(NO_INIT), mSessionId(AUDIO_SESSION_ALLOCATE), 70 mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT) 71{ 72} 73 74AudioRecord::AudioRecord( 75 audio_source_t inputSource, 76 uint32_t sampleRate, 77 audio_format_t format, 78 audio_channel_mask_t channelMask, 79 size_t frameCount, 80 callback_t cbf, 81 void* user, 82 uint32_t notificationFrames, 83 int sessionId, 84 transfer_type transferType, 85 audio_input_flags_t flags) 86 : mStatus(NO_INIT), mSessionId(AUDIO_SESSION_ALLOCATE), 87 mPreviousPriority(ANDROID_PRIORITY_NORMAL), 88 mPreviousSchedulingGroup(SP_DEFAULT), 89 mProxy(NULL) 90{ 91 mStatus = set(inputSource, sampleRate, format, channelMask, frameCount, cbf, user, 92 notificationFrames, false /*threadCanCallJava*/, sessionId, transferType, flags); 93} 94 95AudioRecord::~AudioRecord() 96{ 97 if (mStatus == NO_ERROR) { 98 // Make sure that callback function exits in the case where 99 // it is looping on buffer empty condition in obtainBuffer(). 100 // Otherwise the callback thread will never exit. 101 stop(); 102 if (mAudioRecordThread != 0) { 103 mProxy->interrupt(); 104 mAudioRecordThread->requestExit(); // see comment in AudioRecord.h 105 mAudioRecordThread->requestExitAndWait(); 106 mAudioRecordThread.clear(); 107 } 108 mAudioRecord->asBinder()->unlinkToDeath(mDeathNotifier, this); 109 mAudioRecord.clear(); 110 mCblkMemory.clear(); 111 mBufferMemory.clear(); 112 IPCThreadState::self()->flushCommands(); 113 AudioSystem::releaseAudioSessionId(mSessionId, -1); 114 } 115} 116 117status_t AudioRecord::set( 118 audio_source_t inputSource, 119 uint32_t sampleRate, 120 audio_format_t format, 121 audio_channel_mask_t channelMask, 122 size_t frameCount, 123 callback_t cbf, 124 void* user, 125 uint32_t notificationFrames, 126 bool threadCanCallJava, 127 int sessionId, 128 transfer_type transferType, 129 audio_input_flags_t flags) 130{ 131 ALOGV("set(): inputSource %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, " 132 "notificationFrames %u, sessionId %d, transferType %d, flags %#x", 133 inputSource, sampleRate, format, channelMask, frameCount, notificationFrames, 134 sessionId, transferType, flags); 135 136 switch (transferType) { 137 case TRANSFER_DEFAULT: 138 if (cbf == NULL || threadCanCallJava) { 139 transferType = TRANSFER_SYNC; 140 } else { 141 transferType = TRANSFER_CALLBACK; 142 } 143 break; 144 case TRANSFER_CALLBACK: 145 if (cbf == NULL) { 146 ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL"); 147 return BAD_VALUE; 148 } 149 break; 150 case TRANSFER_OBTAIN: 151 case TRANSFER_SYNC: 152 break; 153 default: 154 ALOGE("Invalid transfer type %d", transferType); 155 return BAD_VALUE; 156 } 157 mTransfer = transferType; 158 159 AutoMutex lock(mLock); 160 161 // invariant that mAudioRecord != 0 is true only after set() returns successfully 162 if (mAudioRecord != 0) { 163 ALOGE("Track already in use"); 164 return INVALID_OPERATION; 165 } 166 167 // handle default values first. 168 if (inputSource == AUDIO_SOURCE_DEFAULT) { 169 inputSource = AUDIO_SOURCE_MIC; 170 } 171 mInputSource = inputSource; 172 173 if (sampleRate == 0) { 174 ALOGE("Invalid sample rate %u", sampleRate); 175 return BAD_VALUE; 176 } 177 mSampleRate = sampleRate; 178 179 // these below should probably come from the audioFlinger too... 180 if (format == AUDIO_FORMAT_DEFAULT) { 181 format = AUDIO_FORMAT_PCM_16_BIT; 182 } 183 184 // validate parameters 185 if (!audio_is_valid_format(format)) { 186 ALOGE("Invalid format %#x", format); 187 return BAD_VALUE; 188 } 189 // Temporary restriction: AudioFlinger currently supports 16-bit PCM only 190 if (format != AUDIO_FORMAT_PCM_16_BIT) { 191 ALOGE("Format %#x is not supported", format); 192 return BAD_VALUE; 193 } 194 mFormat = format; 195 196 if (!audio_is_input_channel(channelMask)) { 197 ALOGE("Invalid channel mask %#x", channelMask); 198 return BAD_VALUE; 199 } 200 mChannelMask = channelMask; 201 uint32_t channelCount = audio_channel_count_from_in_mask(channelMask); 202 mChannelCount = channelCount; 203 204 if (audio_is_linear_pcm(format)) { 205 mFrameSize = channelCount * audio_bytes_per_sample(format); 206 } else { 207 mFrameSize = sizeof(uint8_t); 208 } 209 210 // mFrameCount is initialized in openRecord_l 211 mReqFrameCount = frameCount; 212 213 mNotificationFramesReq = notificationFrames; 214 mNotificationFramesAct = 0; 215 216 if (sessionId == AUDIO_SESSION_ALLOCATE) { 217 mSessionId = AudioSystem::newAudioSessionId(); 218 } else { 219 mSessionId = sessionId; 220 } 221 ALOGV("set(): mSessionId %d", mSessionId); 222 223 mFlags = flags; 224 mCbf = cbf; 225 226 if (cbf != NULL) { 227 mAudioRecordThread = new AudioRecordThread(*this, threadCanCallJava); 228 mAudioRecordThread->run("AudioRecord", ANDROID_PRIORITY_AUDIO); 229 } 230 231 // create the IAudioRecord 232 status_t status = openRecord_l(0 /*epoch*/); 233 234 if (status != NO_ERROR) { 235 if (mAudioRecordThread != 0) { 236 mAudioRecordThread->requestExit(); // see comment in AudioRecord.h 237 mAudioRecordThread->requestExitAndWait(); 238 mAudioRecordThread.clear(); 239 } 240 return status; 241 } 242 243 mStatus = NO_ERROR; 244 mActive = false; 245 mUserData = user; 246 // TODO: add audio hardware input latency here 247 mLatency = (1000*mFrameCount) / sampleRate; 248 mMarkerPosition = 0; 249 mMarkerReached = false; 250 mNewPosition = 0; 251 mUpdatePeriod = 0; 252 AudioSystem::acquireAudioSessionId(mSessionId, -1); 253 mSequence = 1; 254 mObservedSequence = mSequence; 255 mInOverrun = false; 256 257 return NO_ERROR; 258} 259 260// ------------------------------------------------------------------------- 261 262status_t AudioRecord::start(AudioSystem::sync_event_t event, int triggerSession) 263{ 264 ALOGV("start, sync event %d trigger session %d", event, triggerSession); 265 266 AutoMutex lock(mLock); 267 if (mActive) { 268 return NO_ERROR; 269 } 270 271 // reset current position as seen by client to 0 272 mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition()); 273 // force refresh of remaining frames by processAudioBuffer() as last 274 // read before stop could be partial. 275 mRefreshRemaining = true; 276 277 mNewPosition = mProxy->getPosition() + mUpdatePeriod; 278 int32_t flags = android_atomic_acquire_load(&mCblk->mFlags); 279 280 status_t status = NO_ERROR; 281 if (!(flags & CBLK_INVALID)) { 282 ALOGV("mAudioRecord->start()"); 283 status = mAudioRecord->start(event, triggerSession); 284 if (status == DEAD_OBJECT) { 285 flags |= CBLK_INVALID; 286 } 287 } 288 if (flags & CBLK_INVALID) { 289 status = restoreRecord_l("start"); 290 } 291 292 if (status != NO_ERROR) { 293 ALOGE("start() status %d", status); 294 } else { 295 mActive = true; 296 sp<AudioRecordThread> t = mAudioRecordThread; 297 if (t != 0) { 298 t->resume(); 299 } else { 300 mPreviousPriority = getpriority(PRIO_PROCESS, 0); 301 get_sched_policy(0, &mPreviousSchedulingGroup); 302 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO); 303 } 304 } 305 306 return status; 307} 308 309void AudioRecord::stop() 310{ 311 AutoMutex lock(mLock); 312 if (!mActive) { 313 return; 314 } 315 316 mActive = false; 317 mProxy->interrupt(); 318 mAudioRecord->stop(); 319 // the record head position will reset to 0, so if a marker is set, we need 320 // to activate it again 321 mMarkerReached = false; 322 sp<AudioRecordThread> t = mAudioRecordThread; 323 if (t != 0) { 324 t->pause(); 325 } else { 326 setpriority(PRIO_PROCESS, 0, mPreviousPriority); 327 set_sched_policy(0, mPreviousSchedulingGroup); 328 } 329} 330 331bool AudioRecord::stopped() const 332{ 333 AutoMutex lock(mLock); 334 return !mActive; 335} 336 337status_t AudioRecord::setMarkerPosition(uint32_t marker) 338{ 339 // The only purpose of setting marker position is to get a callback 340 if (mCbf == NULL) { 341 return INVALID_OPERATION; 342 } 343 344 AutoMutex lock(mLock); 345 mMarkerPosition = marker; 346 mMarkerReached = false; 347 348 return NO_ERROR; 349} 350 351status_t AudioRecord::getMarkerPosition(uint32_t *marker) const 352{ 353 if (marker == NULL) { 354 return BAD_VALUE; 355 } 356 357 AutoMutex lock(mLock); 358 *marker = mMarkerPosition; 359 360 return NO_ERROR; 361} 362 363status_t AudioRecord::setPositionUpdatePeriod(uint32_t updatePeriod) 364{ 365 // The only purpose of setting position update period is to get a callback 366 if (mCbf == NULL) { 367 return INVALID_OPERATION; 368 } 369 370 AutoMutex lock(mLock); 371 mNewPosition = mProxy->getPosition() + updatePeriod; 372 mUpdatePeriod = updatePeriod; 373 374 return NO_ERROR; 375} 376 377status_t AudioRecord::getPositionUpdatePeriod(uint32_t *updatePeriod) const 378{ 379 if (updatePeriod == NULL) { 380 return BAD_VALUE; 381 } 382 383 AutoMutex lock(mLock); 384 *updatePeriod = mUpdatePeriod; 385 386 return NO_ERROR; 387} 388 389status_t AudioRecord::getPosition(uint32_t *position) const 390{ 391 if (position == NULL) { 392 return BAD_VALUE; 393 } 394 395 AutoMutex lock(mLock); 396 *position = mProxy->getPosition(); 397 398 return NO_ERROR; 399} 400 401uint32_t AudioRecord::getInputFramesLost() const 402{ 403 // no need to check mActive, because if inactive this will return 0, which is what we want 404 return AudioSystem::getInputFramesLost(getInput()); 405} 406 407// ------------------------------------------------------------------------- 408 409// must be called with mLock held 410status_t AudioRecord::openRecord_l(size_t epoch) 411{ 412 status_t status; 413 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger(); 414 if (audioFlinger == 0) { 415 ALOGE("Could not get audioflinger"); 416 return NO_INIT; 417 } 418 419 // Fast tracks must be at the primary _output_ [sic] sampling rate, 420 // because there is currently no concept of a primary input sampling rate 421 uint32_t afSampleRate = AudioSystem::getPrimaryOutputSamplingRate(); 422 if (afSampleRate == 0) { 423 ALOGW("getPrimaryOutputSamplingRate failed"); 424 } 425 426 // Client can only express a preference for FAST. Server will perform additional tests. 427 if ((mFlags & AUDIO_INPUT_FLAG_FAST) && !( 428 // use case: callback transfer mode 429 (mTransfer == TRANSFER_CALLBACK) && 430 // matching sample rate 431 (mSampleRate == afSampleRate))) { 432 ALOGW("AUDIO_INPUT_FLAG_FAST denied by client"); 433 // once denied, do not request again if IAudioRecord is re-created 434 mFlags = (audio_input_flags_t) (mFlags & ~AUDIO_INPUT_FLAG_FAST); 435 } 436 437 IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT; 438 439 pid_t tid = -1; 440 if (mFlags & AUDIO_INPUT_FLAG_FAST) { 441 trackFlags |= IAudioFlinger::TRACK_FAST; 442 if (mAudioRecordThread != 0) { 443 tid = mAudioRecordThread->getTid(); 444 } 445 } 446 447 // FIXME Assume double buffering, because we don't know the true HAL sample rate 448 const uint32_t nBuffering = 2; 449 450 mNotificationFramesAct = mNotificationFramesReq; 451 size_t frameCount = mReqFrameCount; 452 453 if (!(mFlags & AUDIO_INPUT_FLAG_FAST)) { 454 // validate framecount 455 // If fast track was not requested, this preserves 456 // the old behavior of validating on client side. 457 // FIXME Eventually the validation should be done on server side 458 // regardless of whether it's a fast or normal track. It's debatable 459 // whether to account for the input latency to provision buffers appropriately. 460 size_t minFrameCount; 461 status = AudioRecord::getMinFrameCount(&minFrameCount, 462 mSampleRate, mFormat, mChannelMask); 463 if (status != NO_ERROR) { 464 ALOGE("getMinFrameCount() failed for sampleRate %u, format %#x, channelMask %#x; " 465 "status %d", 466 mSampleRate, mFormat, mChannelMask, status); 467 return status; 468 } 469 470 if (frameCount == 0) { 471 frameCount = minFrameCount; 472 } else if (frameCount < minFrameCount) { 473 ALOGE("frameCount %zu < minFrameCount %zu", frameCount, minFrameCount); 474 return BAD_VALUE; 475 } 476 477 // Make sure that application is notified with sufficient margin before overrun 478 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/2) { 479 mNotificationFramesAct = frameCount/2; 480 } 481 } 482 483 audio_io_handle_t input = AudioSystem::getInput(mInputSource, mSampleRate, mFormat, 484 mChannelMask, mSessionId); 485 if (input == AUDIO_IO_HANDLE_NONE) { 486 ALOGE("Could not get audio input for record source %d, sample rate %u, format %#x, " 487 "channel mask %#x, session %d", 488 mInputSource, mSampleRate, mFormat, mChannelMask, mSessionId); 489 return BAD_VALUE; 490 } 491 { 492 // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger, 493 // we must release it ourselves if anything goes wrong. 494 495 size_t temp = frameCount; // temp may be replaced by a revised value of frameCount, 496 // but we will still need the original value also 497 int originalSessionId = mSessionId; 498 sp<IMemory> iMem; // for cblk 499 sp<IMemory> bufferMem; 500 sp<IAudioRecord> record = audioFlinger->openRecord(input, 501 mSampleRate, mFormat, 502 mChannelMask, 503 &temp, 504 &trackFlags, 505 tid, 506 &mSessionId, 507 iMem, 508 bufferMem, 509 &status); 510 ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId, 511 "session ID changed from %d to %d", originalSessionId, mSessionId); 512 513 if (status != NO_ERROR) { 514 ALOGE("AudioFlinger could not create record track, status: %d", status); 515 goto release; 516 } 517 ALOG_ASSERT(record != 0); 518 519 // AudioFlinger now owns the reference to the I/O handle, 520 // so we are no longer responsible for releasing it. 521 522 if (iMem == 0) { 523 ALOGE("Could not get control block"); 524 return NO_INIT; 525 } 526 void *iMemPointer = iMem->pointer(); 527 if (iMemPointer == NULL) { 528 ALOGE("Could not get control block pointer"); 529 return NO_INIT; 530 } 531 audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer); 532 533 // Starting address of buffers in shared memory. 534 // The buffers are either immediately after the control block, 535 // or in a separate area at discretion of server. 536 void *buffers; 537 if (bufferMem == 0) { 538 buffers = cblk + 1; 539 } else { 540 buffers = bufferMem->pointer(); 541 if (buffers == NULL) { 542 ALOGE("Could not get buffer pointer"); 543 return NO_INIT; 544 } 545 } 546 547 // invariant that mAudioRecord != 0 is true only after set() returns successfully 548 if (mAudioRecord != 0) { 549 mAudioRecord->asBinder()->unlinkToDeath(mDeathNotifier, this); 550 mDeathNotifier.clear(); 551 } 552 mAudioRecord = record; 553 mCblkMemory = iMem; 554 mBufferMemory = bufferMem; 555 IPCThreadState::self()->flushCommands(); 556 557 mCblk = cblk; 558 // note that temp is the (possibly revised) value of frameCount 559 if (temp < frameCount || (frameCount == 0 && temp == 0)) { 560 ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp); 561 } 562 frameCount = temp; 563 564 mAwaitBoost = false; 565 if (mFlags & AUDIO_INPUT_FLAG_FAST) { 566 if (trackFlags & IAudioFlinger::TRACK_FAST) { 567 ALOGV("AUDIO_INPUT_FLAG_FAST successful; frameCount %zu", frameCount); 568 mAwaitBoost = true; 569 } else { 570 ALOGV("AUDIO_INPUT_FLAG_FAST denied by server; frameCount %zu", frameCount); 571 // once denied, do not request again if IAudioRecord is re-created 572 mFlags = (audio_input_flags_t) (mFlags & ~AUDIO_INPUT_FLAG_FAST); 573 } 574 // Theoretically double-buffering is not required for fast tracks, 575 // due to tighter scheduling. But in practice, to accomodate kernels with 576 // scheduling jitter, and apps with computation jitter, we use double-buffering. 577 if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) { 578 mNotificationFramesAct = frameCount/nBuffering; 579 } 580 } 581 582 // We retain a copy of the I/O handle, but don't own the reference 583 mInput = input; 584 mRefreshRemaining = true; 585 586 mFrameCount = frameCount; 587 // If IAudioRecord is re-created, don't let the requested frameCount 588 // decrease. This can confuse clients that cache frameCount(). 589 if (frameCount > mReqFrameCount) { 590 mReqFrameCount = frameCount; 591 } 592 593 // update proxy 594 mProxy = new AudioRecordClientProxy(cblk, buffers, mFrameCount, mFrameSize); 595 mProxy->setEpoch(epoch); 596 mProxy->setMinimum(mNotificationFramesAct); 597 598 mDeathNotifier = new DeathNotifier(this); 599 mAudioRecord->asBinder()->linkToDeath(mDeathNotifier, this); 600 601 return NO_ERROR; 602 } 603 604release: 605 AudioSystem::releaseInput(input); 606 if (status == NO_ERROR) { 607 status = NO_INIT; 608 } 609 return status; 610} 611 612status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount) 613{ 614 if (audioBuffer == NULL) { 615 return BAD_VALUE; 616 } 617 if (mTransfer != TRANSFER_OBTAIN) { 618 audioBuffer->frameCount = 0; 619 audioBuffer->size = 0; 620 audioBuffer->raw = NULL; 621 return INVALID_OPERATION; 622 } 623 624 const struct timespec *requested; 625 struct timespec timeout; 626 if (waitCount == -1) { 627 requested = &ClientProxy::kForever; 628 } else if (waitCount == 0) { 629 requested = &ClientProxy::kNonBlocking; 630 } else if (waitCount > 0) { 631 long long ms = WAIT_PERIOD_MS * (long long) waitCount; 632 timeout.tv_sec = ms / 1000; 633 timeout.tv_nsec = (int) (ms % 1000) * 1000000; 634 requested = &timeout; 635 } else { 636 ALOGE("%s invalid waitCount %d", __func__, waitCount); 637 requested = NULL; 638 } 639 return obtainBuffer(audioBuffer, requested); 640} 641 642status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested, 643 struct timespec *elapsed, size_t *nonContig) 644{ 645 // previous and new IAudioRecord sequence numbers are used to detect track re-creation 646 uint32_t oldSequence = 0; 647 uint32_t newSequence; 648 649 Proxy::Buffer buffer; 650 status_t status = NO_ERROR; 651 652 static const int32_t kMaxTries = 5; 653 int32_t tryCounter = kMaxTries; 654 655 do { 656 // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to 657 // keep them from going away if another thread re-creates the track during obtainBuffer() 658 sp<AudioRecordClientProxy> proxy; 659 sp<IMemory> iMem; 660 sp<IMemory> bufferMem; 661 { 662 // start of lock scope 663 AutoMutex lock(mLock); 664 665 newSequence = mSequence; 666 // did previous obtainBuffer() fail due to media server death or voluntary invalidation? 667 if (status == DEAD_OBJECT) { 668 // re-create track, unless someone else has already done so 669 if (newSequence == oldSequence) { 670 status = restoreRecord_l("obtainBuffer"); 671 if (status != NO_ERROR) { 672 buffer.mFrameCount = 0; 673 buffer.mRaw = NULL; 674 buffer.mNonContig = 0; 675 break; 676 } 677 } 678 } 679 oldSequence = newSequence; 680 681 // Keep the extra references 682 proxy = mProxy; 683 iMem = mCblkMemory; 684 bufferMem = mBufferMemory; 685 686 // Non-blocking if track is stopped 687 if (!mActive) { 688 requested = &ClientProxy::kNonBlocking; 689 } 690 691 } // end of lock scope 692 693 buffer.mFrameCount = audioBuffer->frameCount; 694 // FIXME starts the requested timeout and elapsed over from scratch 695 status = proxy->obtainBuffer(&buffer, requested, elapsed); 696 697 } while ((status == DEAD_OBJECT) && (tryCounter-- > 0)); 698 699 audioBuffer->frameCount = buffer.mFrameCount; 700 audioBuffer->size = buffer.mFrameCount * mFrameSize; 701 audioBuffer->raw = buffer.mRaw; 702 if (nonContig != NULL) { 703 *nonContig = buffer.mNonContig; 704 } 705 return status; 706} 707 708void AudioRecord::releaseBuffer(Buffer* audioBuffer) 709{ 710 // all TRANSFER_* are valid 711 712 size_t stepCount = audioBuffer->size / mFrameSize; 713 if (stepCount == 0) { 714 return; 715 } 716 717 Proxy::Buffer buffer; 718 buffer.mFrameCount = stepCount; 719 buffer.mRaw = audioBuffer->raw; 720 721 AutoMutex lock(mLock); 722 mInOverrun = false; 723 mProxy->releaseBuffer(&buffer); 724 725 // the server does not automatically disable recorder on overrun, so no need to restart 726} 727 728audio_io_handle_t AudioRecord::getInput() const 729{ 730 AutoMutex lock(mLock); 731 return mInput; 732} 733 734// ------------------------------------------------------------------------- 735 736ssize_t AudioRecord::read(void* buffer, size_t userSize) 737{ 738 if (mTransfer != TRANSFER_SYNC) { 739 return INVALID_OPERATION; 740 } 741 742 if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) { 743 // sanity-check. user is most-likely passing an error code, and it would 744 // make the return value ambiguous (actualSize vs error). 745 ALOGE("AudioRecord::read(buffer=%p, size=%zu (%zu)", buffer, userSize, userSize); 746 return BAD_VALUE; 747 } 748 749 ssize_t read = 0; 750 Buffer audioBuffer; 751 752 while (userSize >= mFrameSize) { 753 audioBuffer.frameCount = userSize / mFrameSize; 754 755 status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever); 756 if (err < 0) { 757 if (read > 0) { 758 break; 759 } 760 return ssize_t(err); 761 } 762 763 size_t bytesRead = audioBuffer.size; 764 memcpy(buffer, audioBuffer.i8, bytesRead); 765 buffer = ((char *) buffer) + bytesRead; 766 userSize -= bytesRead; 767 read += bytesRead; 768 769 releaseBuffer(&audioBuffer); 770 } 771 772 return read; 773} 774 775// ------------------------------------------------------------------------- 776 777nsecs_t AudioRecord::processAudioBuffer() 778{ 779 mLock.lock(); 780 if (mAwaitBoost) { 781 mAwaitBoost = false; 782 mLock.unlock(); 783 static const int32_t kMaxTries = 5; 784 int32_t tryCounter = kMaxTries; 785 uint32_t pollUs = 10000; 786 do { 787 int policy = sched_getscheduler(0); 788 if (policy == SCHED_FIFO || policy == SCHED_RR) { 789 break; 790 } 791 usleep(pollUs); 792 pollUs <<= 1; 793 } while (tryCounter-- > 0); 794 if (tryCounter < 0) { 795 ALOGE("did not receive expected priority boost on time"); 796 } 797 // Run again immediately 798 return 0; 799 } 800 801 // Can only reference mCblk while locked 802 int32_t flags = android_atomic_and(~CBLK_OVERRUN, &mCblk->mFlags); 803 804 // Check for track invalidation 805 if (flags & CBLK_INVALID) { 806 (void) restoreRecord_l("processAudioBuffer"); 807 mLock.unlock(); 808 // Run again immediately, but with a new IAudioRecord 809 return 0; 810 } 811 812 bool active = mActive; 813 814 // Manage overrun callback, must be done under lock to avoid race with releaseBuffer() 815 bool newOverrun = false; 816 if (flags & CBLK_OVERRUN) { 817 if (!mInOverrun) { 818 mInOverrun = true; 819 newOverrun = true; 820 } 821 } 822 823 // Get current position of server 824 size_t position = mProxy->getPosition(); 825 826 // Manage marker callback 827 bool markerReached = false; 828 size_t markerPosition = mMarkerPosition; 829 // FIXME fails for wraparound, need 64 bits 830 if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) { 831 mMarkerReached = markerReached = true; 832 } 833 834 // Determine the number of new position callback(s) that will be needed, while locked 835 size_t newPosCount = 0; 836 size_t newPosition = mNewPosition; 837 uint32_t updatePeriod = mUpdatePeriod; 838 // FIXME fails for wraparound, need 64 bits 839 if (updatePeriod > 0 && position >= newPosition) { 840 newPosCount = ((position - newPosition) / updatePeriod) + 1; 841 mNewPosition += updatePeriod * newPosCount; 842 } 843 844 // Cache other fields that will be needed soon 845 uint32_t notificationFrames = mNotificationFramesAct; 846 if (mRefreshRemaining) { 847 mRefreshRemaining = false; 848 mRemainingFrames = notificationFrames; 849 mRetryOnPartialBuffer = false; 850 } 851 size_t misalignment = mProxy->getMisalignment(); 852 uint32_t sequence = mSequence; 853 854 // These fields don't need to be cached, because they are assigned only by set(): 855 // mTransfer, mCbf, mUserData, mSampleRate, mFrameSize 856 857 mLock.unlock(); 858 859 // perform callbacks while unlocked 860 if (newOverrun) { 861 mCbf(EVENT_OVERRUN, mUserData, NULL); 862 } 863 if (markerReached) { 864 mCbf(EVENT_MARKER, mUserData, &markerPosition); 865 } 866 while (newPosCount > 0) { 867 size_t temp = newPosition; 868 mCbf(EVENT_NEW_POS, mUserData, &temp); 869 newPosition += updatePeriod; 870 newPosCount--; 871 } 872 if (mObservedSequence != sequence) { 873 mObservedSequence = sequence; 874 mCbf(EVENT_NEW_IAUDIORECORD, mUserData, NULL); 875 } 876 877 // if inactive, then don't run me again until re-started 878 if (!active) { 879 return NS_INACTIVE; 880 } 881 882 // Compute the estimated time until the next timed event (position, markers) 883 uint32_t minFrames = ~0; 884 if (!markerReached && position < markerPosition) { 885 minFrames = markerPosition - position; 886 } 887 if (updatePeriod > 0 && updatePeriod < minFrames) { 888 minFrames = updatePeriod; 889 } 890 891 // If > 0, poll periodically to recover from a stuck server. A good value is 2. 892 static const uint32_t kPoll = 0; 893 if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) { 894 minFrames = kPoll * notificationFrames; 895 } 896 897 // Convert frame units to time units 898 nsecs_t ns = NS_WHENEVER; 899 if (minFrames != (uint32_t) ~0) { 900 // This "fudge factor" avoids soaking CPU, and compensates for late progress by server 901 static const nsecs_t kFudgeNs = 10000000LL; // 10 ms 902 ns = ((minFrames * 1000000000LL) / mSampleRate) + kFudgeNs; 903 } 904 905 // If not supplying data by EVENT_MORE_DATA, then we're done 906 if (mTransfer != TRANSFER_CALLBACK) { 907 return ns; 908 } 909 910 struct timespec timeout; 911 const struct timespec *requested = &ClientProxy::kForever; 912 if (ns != NS_WHENEVER) { 913 timeout.tv_sec = ns / 1000000000LL; 914 timeout.tv_nsec = ns % 1000000000LL; 915 ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000); 916 requested = &timeout; 917 } 918 919 while (mRemainingFrames > 0) { 920 921 Buffer audioBuffer; 922 audioBuffer.frameCount = mRemainingFrames; 923 size_t nonContig; 924 status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig); 925 LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0), 926 "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount); 927 requested = &ClientProxy::kNonBlocking; 928 size_t avail = audioBuffer.frameCount + nonContig; 929 ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d", 930 mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err); 931 if (err != NO_ERROR) { 932 if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) { 933 break; 934 } 935 ALOGE("Error %d obtaining an audio buffer, giving up.", err); 936 return NS_NEVER; 937 } 938 939 if (mRetryOnPartialBuffer) { 940 mRetryOnPartialBuffer = false; 941 if (avail < mRemainingFrames) { 942 int64_t myns = ((mRemainingFrames - avail) * 943 1100000000LL) / mSampleRate; 944 if (ns < 0 || myns < ns) { 945 ns = myns; 946 } 947 return ns; 948 } 949 } 950 951 size_t reqSize = audioBuffer.size; 952 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer); 953 size_t readSize = audioBuffer.size; 954 955 // Sanity check on returned size 956 if (ssize_t(readSize) < 0 || readSize > reqSize) { 957 ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes", 958 reqSize, ssize_t(readSize)); 959 return NS_NEVER; 960 } 961 962 if (readSize == 0) { 963 // The callback is done consuming buffers 964 // Keep this thread going to handle timed events and 965 // still try to provide more data in intervals of WAIT_PERIOD_MS 966 // but don't just loop and block the CPU, so wait 967 return WAIT_PERIOD_MS * 1000000LL; 968 } 969 970 size_t releasedFrames = readSize / mFrameSize; 971 audioBuffer.frameCount = releasedFrames; 972 mRemainingFrames -= releasedFrames; 973 if (misalignment >= releasedFrames) { 974 misalignment -= releasedFrames; 975 } else { 976 misalignment = 0; 977 } 978 979 releaseBuffer(&audioBuffer); 980 981 // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer 982 // if callback doesn't like to accept the full chunk 983 if (readSize < reqSize) { 984 continue; 985 } 986 987 // There could be enough non-contiguous frames available to satisfy the remaining request 988 if (mRemainingFrames <= nonContig) { 989 continue; 990 } 991 992#if 0 993 // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a 994 // sum <= notificationFrames. It replaces that series by at most two EVENT_MORE_DATA 995 // that total to a sum == notificationFrames. 996 if (0 < misalignment && misalignment <= mRemainingFrames) { 997 mRemainingFrames = misalignment; 998 return (mRemainingFrames * 1100000000LL) / mSampleRate; 999 } 1000#endif 1001 1002 } 1003 mRemainingFrames = notificationFrames; 1004 mRetryOnPartialBuffer = true; 1005 1006 // A lot has transpired since ns was calculated, so run again immediately and re-calculate 1007 return 0; 1008} 1009 1010status_t AudioRecord::restoreRecord_l(const char *from) 1011{ 1012 ALOGW("dead IAudioRecord, creating a new one from %s()", from); 1013 ++mSequence; 1014 status_t result; 1015 1016 // if the new IAudioRecord is created, openRecord_l() will modify the 1017 // following member variables: mAudioRecord, mCblkMemory, mCblk, mBufferMemory. 1018 // It will also delete the strong references on previous IAudioRecord and IMemory 1019 size_t position = mProxy->getPosition(); 1020 mNewPosition = position + mUpdatePeriod; 1021 result = openRecord_l(position); 1022 if (result == NO_ERROR) { 1023 if (mActive) { 1024 // callback thread or sync event hasn't changed 1025 // FIXME this fails if we have a new AudioFlinger instance 1026 result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, 0); 1027 } 1028 } 1029 if (result != NO_ERROR) { 1030 ALOGW("restoreRecord_l() failed status %d", result); 1031 mActive = false; 1032 } 1033 1034 return result; 1035} 1036 1037// ========================================================================= 1038 1039void AudioRecord::DeathNotifier::binderDied(const wp<IBinder>& who __unused) 1040{ 1041 sp<AudioRecord> audioRecord = mAudioRecord.promote(); 1042 if (audioRecord != 0) { 1043 AutoMutex lock(audioRecord->mLock); 1044 audioRecord->mProxy->binderDied(); 1045 } 1046} 1047 1048// ========================================================================= 1049 1050AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver, bool bCanCallJava) 1051 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL), 1052 mIgnoreNextPausedInt(false) 1053{ 1054} 1055 1056AudioRecord::AudioRecordThread::~AudioRecordThread() 1057{ 1058} 1059 1060bool AudioRecord::AudioRecordThread::threadLoop() 1061{ 1062 { 1063 AutoMutex _l(mMyLock); 1064 if (mPaused) { 1065 mMyCond.wait(mMyLock); 1066 // caller will check for exitPending() 1067 return true; 1068 } 1069 if (mIgnoreNextPausedInt) { 1070 mIgnoreNextPausedInt = false; 1071 mPausedInt = false; 1072 } 1073 if (mPausedInt) { 1074 if (mPausedNs > 0) { 1075 (void) mMyCond.waitRelative(mMyLock, mPausedNs); 1076 } else { 1077 mMyCond.wait(mMyLock); 1078 } 1079 mPausedInt = false; 1080 return true; 1081 } 1082 } 1083 nsecs_t ns = mReceiver.processAudioBuffer(); 1084 switch (ns) { 1085 case 0: 1086 return true; 1087 case NS_INACTIVE: 1088 pauseInternal(); 1089 return true; 1090 case NS_NEVER: 1091 return false; 1092 case NS_WHENEVER: 1093 // FIXME increase poll interval, or make event-driven 1094 ns = 1000000000LL; 1095 // fall through 1096 default: 1097 LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns); 1098 pauseInternal(ns); 1099 return true; 1100 } 1101} 1102 1103void AudioRecord::AudioRecordThread::requestExit() 1104{ 1105 // must be in this order to avoid a race condition 1106 Thread::requestExit(); 1107 resume(); 1108} 1109 1110void AudioRecord::AudioRecordThread::pause() 1111{ 1112 AutoMutex _l(mMyLock); 1113 mPaused = true; 1114} 1115 1116void AudioRecord::AudioRecordThread::resume() 1117{ 1118 AutoMutex _l(mMyLock); 1119 mIgnoreNextPausedInt = true; 1120 if (mPaused || mPausedInt) { 1121 mPaused = false; 1122 mPausedInt = false; 1123 mMyCond.signal(); 1124 } 1125} 1126 1127void AudioRecord::AudioRecordThread::pauseInternal(nsecs_t ns) 1128{ 1129 AutoMutex _l(mMyLock); 1130 mPausedInt = true; 1131 mPausedNs = ns; 1132} 1133 1134// ------------------------------------------------------------------------- 1135 1136}; // namespace android 1137