AudioRecord.cpp revision 26ba972eafde73a26271ecf027a1d5988ce50eb8
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 <sys/resource.h> 22#include <sys/types.h> 23 24#include <binder/IPCThreadState.h> 25#include <cutils/atomic.h> 26#include <cutils/compiler.h> 27#include <media/AudioRecord.h> 28#include <media/AudioSystem.h> 29#include <system/audio.h> 30#include <utils/Log.h> 31 32#include <private/media/AudioTrackShared.h> 33 34namespace android { 35// --------------------------------------------------------------------------- 36 37// static 38status_t AudioRecord::getMinFrameCount( 39 int* frameCount, 40 uint32_t sampleRate, 41 audio_format_t format, 42 audio_channel_mask_t channelMask) 43{ 44 if (frameCount == NULL) return BAD_VALUE; 45 46 // default to 0 in case of error 47 *frameCount = 0; 48 49 size_t size = 0; 50 if (AudioSystem::getInputBufferSize(sampleRate, format, channelMask, &size) 51 != NO_ERROR) { 52 ALOGE("AudioSystem could not query the input buffer size."); 53 return NO_INIT; 54 } 55 56 if (size == 0) { 57 ALOGE("Unsupported configuration: sampleRate %d, format %d, channelMask %#x", 58 sampleRate, format, channelMask); 59 return BAD_VALUE; 60 } 61 62 // We double the size of input buffer for ping pong use of record buffer. 63 size <<= 1; 64 65 if (audio_is_linear_pcm(format)) { 66 int channelCount = popcount(channelMask); 67 size /= channelCount * audio_bytes_per_sample(format); 68 } 69 70 *frameCount = size; 71 return NO_ERROR; 72} 73 74// --------------------------------------------------------------------------- 75 76AudioRecord::AudioRecord() 77 : mStatus(NO_INIT), mSessionId(0), 78 mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT) 79{ 80} 81 82AudioRecord::AudioRecord( 83 audio_source_t inputSource, 84 uint32_t sampleRate, 85 audio_format_t format, 86 audio_channel_mask_t channelMask, 87 int frameCount, 88 callback_t cbf, 89 void* user, 90 int notificationFrames, 91 int sessionId) 92 : mStatus(NO_INIT), mSessionId(0), 93 mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT) 94{ 95 mStatus = set(inputSource, sampleRate, format, channelMask, 96 frameCount, cbf, user, notificationFrames, sessionId); 97} 98 99AudioRecord::~AudioRecord() 100{ 101 if (mStatus == NO_ERROR) { 102 // Make sure that callback function exits in the case where 103 // it is looping on buffer empty condition in obtainBuffer(). 104 // Otherwise the callback thread will never exit. 105 stop(); 106 if (mAudioRecordThread != 0) { 107 mAudioRecordThread->requestExit(); // see comment in AudioRecord.h 108 mAudioRecordThread->requestExitAndWait(); 109 mAudioRecordThread.clear(); 110 } 111 mAudioRecord.clear(); 112 IPCThreadState::self()->flushCommands(); 113 AudioSystem::releaseAudioSessionId(mSessionId); 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 int frameCount, 123 callback_t cbf, 124 void* user, 125 int notificationFrames, 126 bool threadCanCallJava, 127 int sessionId) 128{ 129 130 ALOGV("set(): sampleRate %d, channelMask %#x, frameCount %d",sampleRate, channelMask, 131 frameCount); 132 133 AutoMutex lock(mLock); 134 135 if (mAudioRecord != 0) { 136 return INVALID_OPERATION; 137 } 138 139 if (inputSource == AUDIO_SOURCE_DEFAULT) { 140 inputSource = AUDIO_SOURCE_MIC; 141 } 142 143 if (sampleRate == 0) { 144 sampleRate = DEFAULT_SAMPLE_RATE; 145 } 146 // these below should probably come from the audioFlinger too... 147 if (format == AUDIO_FORMAT_DEFAULT) { 148 format = AUDIO_FORMAT_PCM_16_BIT; 149 } 150 // validate parameters 151 if (!audio_is_valid_format(format)) { 152 ALOGE("Invalid format"); 153 return BAD_VALUE; 154 } 155 156 if (!audio_is_input_channel(channelMask)) { 157 return BAD_VALUE; 158 } 159 160 int channelCount = popcount(channelMask); 161 162 if (sessionId == 0 ) { 163 mSessionId = AudioSystem::newAudioSessionId(); 164 } else { 165 mSessionId = sessionId; 166 } 167 ALOGV("set(): mSessionId %d", mSessionId); 168 169 audio_io_handle_t input = AudioSystem::getInput(inputSource, 170 sampleRate, 171 format, 172 channelMask, 173 mSessionId); 174 if (input == 0) { 175 ALOGE("Could not get audio input for record source %d", inputSource); 176 return BAD_VALUE; 177 } 178 179 // validate framecount 180 int minFrameCount = 0; 181 status_t status = getMinFrameCount(&minFrameCount, sampleRate, format, channelMask); 182 if (status != NO_ERROR) { 183 return status; 184 } 185 ALOGV("AudioRecord::set() minFrameCount = %d", minFrameCount); 186 187 if (frameCount == 0) { 188 frameCount = minFrameCount; 189 } else if (frameCount < minFrameCount) { 190 return BAD_VALUE; 191 } 192 193 if (notificationFrames == 0) { 194 notificationFrames = frameCount/2; 195 } 196 197 // create the IAudioRecord 198 status = openRecord_l(sampleRate, format, channelMask, 199 frameCount, input); 200 if (status != NO_ERROR) { 201 return status; 202 } 203 204 if (cbf != NULL) { 205 mAudioRecordThread = new AudioRecordThread(*this, threadCanCallJava); 206 mAudioRecordThread->run("AudioRecord", ANDROID_PRIORITY_AUDIO); 207 } 208 209 mStatus = NO_ERROR; 210 211 mFormat = format; 212 // Update buffer size in case it has been limited by AudioFlinger during track creation 213 mFrameCount = mCblk->frameCount; 214 mChannelCount = (uint8_t)channelCount; 215 mChannelMask = channelMask; 216 mActive = false; 217 mCbf = cbf; 218 mNotificationFrames = notificationFrames; 219 mRemainingFrames = notificationFrames; 220 mUserData = user; 221 // TODO: add audio hardware input latency here 222 mLatency = (1000*mFrameCount) / sampleRate; 223 mMarkerPosition = 0; 224 mMarkerReached = false; 225 mNewPosition = 0; 226 mUpdatePeriod = 0; 227 mInputSource = inputSource; 228 mInput = input; 229 AudioSystem::acquireAudioSessionId(mSessionId); 230 231 return NO_ERROR; 232} 233 234status_t AudioRecord::initCheck() const 235{ 236 return mStatus; 237} 238 239// ------------------------------------------------------------------------- 240 241uint32_t AudioRecord::latency() const 242{ 243 return mLatency; 244} 245 246audio_format_t AudioRecord::format() const 247{ 248 return mFormat; 249} 250 251int AudioRecord::channelCount() const 252{ 253 return mChannelCount; 254} 255 256uint32_t AudioRecord::frameCount() const 257{ 258 return mFrameCount; 259} 260 261size_t AudioRecord::frameSize() const 262{ 263 if (audio_is_linear_pcm(mFormat)) { 264 return channelCount()*audio_bytes_per_sample(mFormat); 265 } else { 266 return sizeof(uint8_t); 267 } 268} 269 270audio_source_t AudioRecord::inputSource() const 271{ 272 return mInputSource; 273} 274 275// ------------------------------------------------------------------------- 276 277status_t AudioRecord::start(AudioSystem::sync_event_t event, int triggerSession) 278{ 279 status_t ret = NO_ERROR; 280 sp<AudioRecordThread> t = mAudioRecordThread; 281 282 ALOGV("start, sync event %d trigger session %d", event, triggerSession); 283 284 AutoMutex lock(mLock); 285 // acquire a strong reference on the IAudioRecord and IMemory so that they cannot be destroyed 286 // while we are accessing the cblk 287 sp<IAudioRecord> audioRecord = mAudioRecord; 288 sp<IMemory> iMem = mCblkMemory; 289 audio_track_cblk_t* cblk = mCblk; 290 291 if (!mActive) { 292 mActive = true; 293 294 cblk->lock.lock(); 295 if (!(cblk->flags & CBLK_INVALID)) { 296 cblk->lock.unlock(); 297 ALOGV("mAudioRecord->start()"); 298 ret = mAudioRecord->start(event, triggerSession); 299 cblk->lock.lock(); 300 if (ret == DEAD_OBJECT) { 301 android_atomic_or(CBLK_INVALID, &cblk->flags); 302 } 303 } 304 if (cblk->flags & CBLK_INVALID) { 305 ret = restoreRecord_l(cblk); 306 } 307 cblk->lock.unlock(); 308 if (ret == NO_ERROR) { 309 mNewPosition = cblk->user + mUpdatePeriod; 310 cblk->bufferTimeoutMs = (event == AudioSystem::SYNC_EVENT_NONE) ? MAX_RUN_TIMEOUT_MS : 311 AudioSystem::kSyncRecordStartTimeOutMs; 312 cblk->waitTimeMs = 0; 313 if (t != 0) { 314 t->resume(); 315 } else { 316 mPreviousPriority = getpriority(PRIO_PROCESS, 0); 317 get_sched_policy(0, &mPreviousSchedulingGroup); 318 androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO); 319 } 320 } else { 321 mActive = false; 322 } 323 } 324 325 return ret; 326} 327 328void AudioRecord::stop() 329{ 330 sp<AudioRecordThread> t = mAudioRecordThread; 331 332 ALOGV("stop"); 333 334 AutoMutex lock(mLock); 335 if (mActive) { 336 mActive = false; 337 mCblk->cv.signal(); 338 mAudioRecord->stop(); 339 // the record head position will reset to 0, so if a marker is set, we need 340 // to activate it again 341 mMarkerReached = false; 342 if (t != 0) { 343 t->pause(); 344 } else { 345 setpriority(PRIO_PROCESS, 0, mPreviousPriority); 346 set_sched_policy(0, mPreviousSchedulingGroup); 347 } 348 } 349} 350 351bool AudioRecord::stopped() const 352{ 353 AutoMutex lock(mLock); 354 return !mActive; 355} 356 357uint32_t AudioRecord::getSampleRate() const 358{ 359 return mCblk->sampleRate; 360} 361 362status_t AudioRecord::setMarkerPosition(uint32_t marker) 363{ 364 if (mCbf == NULL) return INVALID_OPERATION; 365 366 AutoMutex lock(mLock); 367 mMarkerPosition = marker; 368 mMarkerReached = false; 369 370 return NO_ERROR; 371} 372 373status_t AudioRecord::getMarkerPosition(uint32_t *marker) const 374{ 375 if (marker == NULL) return BAD_VALUE; 376 377 AutoMutex lock(mLock); 378 *marker = mMarkerPosition; 379 380 return NO_ERROR; 381} 382 383status_t AudioRecord::setPositionUpdatePeriod(uint32_t updatePeriod) 384{ 385 if (mCbf == NULL) return INVALID_OPERATION; 386 387 uint32_t curPosition; 388 getPosition(&curPosition); 389 390 AutoMutex lock(mLock); 391 mNewPosition = curPosition + updatePeriod; 392 mUpdatePeriod = updatePeriod; 393 394 return NO_ERROR; 395} 396 397status_t AudioRecord::getPositionUpdatePeriod(uint32_t *updatePeriod) const 398{ 399 if (updatePeriod == NULL) return BAD_VALUE; 400 401 AutoMutex lock(mLock); 402 *updatePeriod = mUpdatePeriod; 403 404 return NO_ERROR; 405} 406 407status_t AudioRecord::getPosition(uint32_t *position) const 408{ 409 if (position == NULL) return BAD_VALUE; 410 411 AutoMutex lock(mLock); 412 *position = mCblk->user; 413 414 return NO_ERROR; 415} 416 417unsigned int AudioRecord::getInputFramesLost() const 418{ 419 // no need to check mActive, because if inactive this will return 0, which is what we want 420 return AudioSystem::getInputFramesLost(mInput); 421} 422 423// ------------------------------------------------------------------------- 424 425// must be called with mLock held 426status_t AudioRecord::openRecord_l( 427 uint32_t sampleRate, 428 audio_format_t format, 429 audio_channel_mask_t channelMask, 430 int frameCount, 431 audio_io_handle_t input) 432{ 433 status_t status; 434 const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger(); 435 if (audioFlinger == 0) { 436 return NO_INIT; 437 } 438 439 pid_t tid = -1; 440 // FIXME see similar logic at AudioTrack 441 442 int originalSessionId = mSessionId; 443 sp<IAudioRecord> record = audioFlinger->openRecord(getpid(), input, 444 sampleRate, format, 445 channelMask, 446 frameCount, 447 IAudioFlinger::TRACK_DEFAULT, 448 tid, 449 &mSessionId, 450 &status); 451 ALOGE_IF(originalSessionId != 0 && mSessionId != originalSessionId, 452 "session ID changed from %d to %d", originalSessionId, mSessionId); 453 454 if (record == 0) { 455 ALOGE("AudioFlinger could not create record track, status: %d", status); 456 return status; 457 } 458 sp<IMemory> cblk = record->getCblk(); 459 if (cblk == 0) { 460 ALOGE("Could not get control block"); 461 return NO_INIT; 462 } 463 mAudioRecord.clear(); 464 mAudioRecord = record; 465 mCblkMemory.clear(); 466 mCblkMemory = cblk; 467 mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer()); 468 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t); 469 android_atomic_and(~CBLK_DIRECTION, &mCblk->flags); 470 mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS; 471 mCblk->waitTimeMs = 0; 472 return NO_ERROR; 473} 474 475status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount) 476{ 477 AutoMutex lock(mLock); 478 bool active; 479 status_t result = NO_ERROR; 480 audio_track_cblk_t* cblk = mCblk; 481 uint32_t framesReq = audioBuffer->frameCount; 482 uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS; 483 484 audioBuffer->frameCount = 0; 485 audioBuffer->size = 0; 486 487 uint32_t framesReady = cblk->framesReady(); 488 489 if (framesReady == 0) { 490 cblk->lock.lock(); 491 goto start_loop_here; 492 while (framesReady == 0) { 493 active = mActive; 494 if (CC_UNLIKELY(!active)) { 495 cblk->lock.unlock(); 496 return NO_MORE_BUFFERS; 497 } 498 if (CC_UNLIKELY(!waitCount)) { 499 cblk->lock.unlock(); 500 return WOULD_BLOCK; 501 } 502 if (!(cblk->flags & CBLK_INVALID)) { 503 mLock.unlock(); 504 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs)); 505 cblk->lock.unlock(); 506 mLock.lock(); 507 if (!mActive) { 508 return status_t(STOPPED); 509 } 510 cblk->lock.lock(); 511 } 512 if (cblk->flags & CBLK_INVALID) { 513 goto create_new_record; 514 } 515 if (CC_UNLIKELY(result != NO_ERROR)) { 516 cblk->waitTimeMs += waitTimeMs; 517 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) { 518 ALOGW( "obtainBuffer timed out (is the CPU pegged?) " 519 "user=%08x, server=%08x", cblk->user, cblk->server); 520 cblk->lock.unlock(); 521 // callback thread or sync event hasn't changed 522 result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, 0); 523 cblk->lock.lock(); 524 if (result == DEAD_OBJECT) { 525 android_atomic_or(CBLK_INVALID, &cblk->flags); 526create_new_record: 527 result = AudioRecord::restoreRecord_l(cblk); 528 } 529 if (result != NO_ERROR) { 530 ALOGW("obtainBuffer create Track error %d", result); 531 cblk->lock.unlock(); 532 return result; 533 } 534 cblk->waitTimeMs = 0; 535 } 536 if (--waitCount == 0) { 537 cblk->lock.unlock(); 538 return TIMED_OUT; 539 } 540 } 541 // read the server count again 542 start_loop_here: 543 framesReady = cblk->framesReady(); 544 } 545 cblk->lock.unlock(); 546 } 547 548 cblk->waitTimeMs = 0; 549 // reset time out to running value after obtaining a buffer 550 cblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS; 551 552 if (framesReq > framesReady) { 553 framesReq = framesReady; 554 } 555 556 uint32_t u = cblk->user; 557 uint32_t bufferEnd = cblk->userBase + cblk->frameCount; 558 559 if (framesReq > bufferEnd - u) { 560 framesReq = bufferEnd - u; 561 } 562 563 audioBuffer->frameCount = framesReq; 564 audioBuffer->size = framesReq*cblk->frameSize; 565 audioBuffer->raw = (int8_t*)cblk->buffer(u); 566 active = mActive; 567 return active ? status_t(NO_ERROR) : status_t(STOPPED); 568} 569 570void AudioRecord::releaseBuffer(Buffer* audioBuffer) 571{ 572 AutoMutex lock(mLock); 573 mCblk->stepUser(audioBuffer->frameCount); 574} 575 576audio_io_handle_t AudioRecord::getInput() const 577{ 578 AutoMutex lock(mLock); 579 return mInput; 580} 581 582// must be called with mLock held 583audio_io_handle_t AudioRecord::getInput_l() 584{ 585 mInput = AudioSystem::getInput(mInputSource, 586 mCblk->sampleRate, 587 mFormat, 588 mChannelMask, 589 mSessionId); 590 return mInput; 591} 592 593int AudioRecord::getSessionId() const 594{ 595 // no lock needed because session ID doesn't change after first set() 596 return mSessionId; 597} 598 599// ------------------------------------------------------------------------- 600 601ssize_t AudioRecord::read(void* buffer, size_t userSize) 602{ 603 ssize_t read = 0; 604 Buffer audioBuffer; 605 int8_t *dst = static_cast<int8_t*>(buffer); 606 607 if (ssize_t(userSize) < 0) { 608 // sanity-check. user is most-likely passing an error code. 609 ALOGE("AudioRecord::read(buffer=%p, size=%u (%d)", 610 buffer, userSize, userSize); 611 return BAD_VALUE; 612 } 613 614 mLock.lock(); 615 // acquire a strong reference on the IAudioRecord and IMemory so that they cannot be destroyed 616 // while we are accessing the cblk 617 sp<IAudioRecord> audioRecord = mAudioRecord; 618 sp<IMemory> iMem = mCblkMemory; 619 mLock.unlock(); 620 621 do { 622 623 audioBuffer.frameCount = userSize/frameSize(); 624 625 // By using a wait count corresponding to twice the timeout period in 626 // obtainBuffer() we give a chance to recover once for a read timeout 627 // (if media_server crashed for instance) before returning a length of 628 // 0 bytes read to the client 629 status_t err = obtainBuffer(&audioBuffer, ((2 * MAX_RUN_TIMEOUT_MS) / WAIT_PERIOD_MS)); 630 if (err < 0) { 631 // out of buffers, return #bytes written 632 if (err == status_t(NO_MORE_BUFFERS)) 633 break; 634 if (err == status_t(TIMED_OUT)) 635 err = 0; 636 return ssize_t(err); 637 } 638 639 size_t bytesRead = audioBuffer.size; 640 memcpy(dst, audioBuffer.i8, bytesRead); 641 642 dst += bytesRead; 643 userSize -= bytesRead; 644 read += bytesRead; 645 646 releaseBuffer(&audioBuffer); 647 } while (userSize); 648 649 return read; 650} 651 652// ------------------------------------------------------------------------- 653 654bool AudioRecord::processAudioBuffer(const sp<AudioRecordThread>& thread) 655{ 656 Buffer audioBuffer; 657 uint32_t frames = mRemainingFrames; 658 size_t readSize; 659 660 mLock.lock(); 661 // acquire a strong reference on the IAudioRecord and IMemory so that they cannot be destroyed 662 // while we are accessing the cblk 663 sp<IAudioRecord> audioRecord = mAudioRecord; 664 sp<IMemory> iMem = mCblkMemory; 665 audio_track_cblk_t* cblk = mCblk; 666 bool active = mActive; 667 uint32_t markerPosition = mMarkerPosition; 668 uint32_t newPosition = mNewPosition; 669 uint32_t user = cblk->user; 670 // determine whether a marker callback will be needed, while locked 671 bool needMarker = !mMarkerReached && (mMarkerPosition > 0) && (user >= mMarkerPosition); 672 if (needMarker) { 673 mMarkerReached = true; 674 } 675 // determine the number of new position callback(s) that will be needed, while locked 676 uint32_t updatePeriod = mUpdatePeriod; 677 uint32_t needNewPos = updatePeriod > 0 && user >= newPosition ? 678 ((user - newPosition) / updatePeriod) + 1 : 0; 679 mNewPosition = newPosition + updatePeriod * needNewPos; 680 mLock.unlock(); 681 682 // perform marker callback, while unlocked 683 if (needMarker) { 684 mCbf(EVENT_MARKER, mUserData, &markerPosition); 685 } 686 687 // perform new position callback(s), while unlocked 688 for (; needNewPos > 0; --needNewPos) { 689 uint32_t temp = newPosition; 690 mCbf(EVENT_NEW_POS, mUserData, &temp); 691 newPosition += updatePeriod; 692 } 693 694 do { 695 audioBuffer.frameCount = frames; 696 // Calling obtainBuffer() with a wait count of 1 697 // limits wait time to WAIT_PERIOD_MS. This prevents from being 698 // stuck here not being able to handle timed events (position, markers). 699 status_t err = obtainBuffer(&audioBuffer, 1); 700 if (err < NO_ERROR) { 701 if (err != TIMED_OUT) { 702 ALOGE_IF(err != status_t(NO_MORE_BUFFERS), 703 "Error obtaining an audio buffer, giving up."); 704 return false; 705 } 706 break; 707 } 708 if (err == status_t(STOPPED)) return false; 709 710 size_t reqSize = audioBuffer.size; 711 mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer); 712 readSize = audioBuffer.size; 713 714 // Sanity check on returned size 715 if (ssize_t(readSize) <= 0) { 716 // The callback is done filling buffers 717 // Keep this thread going to handle timed events and 718 // still try to get more data in intervals of WAIT_PERIOD_MS 719 // but don't just loop and block the CPU, so wait 720 usleep(WAIT_PERIOD_MS*1000); 721 break; 722 } 723 if (readSize > reqSize) readSize = reqSize; 724 725 audioBuffer.size = readSize; 726 audioBuffer.frameCount = readSize/frameSize(); 727 frames -= audioBuffer.frameCount; 728 729 releaseBuffer(&audioBuffer); 730 731 } while (frames); 732 733 734 // Manage overrun callback 735 if (active && (cblk->framesAvailable() == 0)) { 736 // The value of active is stale, but we are almost sure to be active here because 737 // otherwise we would have exited when obtainBuffer returned STOPPED earlier. 738 ALOGV("Overrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags); 739 if (!(android_atomic_or(CBLK_UNDERRUN, &cblk->flags) & CBLK_UNDERRUN)) { 740 mCbf(EVENT_OVERRUN, mUserData, NULL); 741 } 742 } 743 744 if (frames == 0) { 745 mRemainingFrames = mNotificationFrames; 746 } else { 747 mRemainingFrames = frames; 748 } 749 return true; 750} 751 752// must be called with mLock and cblk.lock held. Callers must also hold strong references on 753// the IAudioRecord and IMemory in case they are recreated here. 754// If the IAudioRecord is successfully restored, the cblk pointer is updated 755status_t AudioRecord::restoreRecord_l(audio_track_cblk_t*& cblk) 756{ 757 status_t result; 758 759 if (!(android_atomic_or(CBLK_RESTORING, &cblk->flags) & CBLK_RESTORING)) { 760 ALOGW("dead IAudioRecord, creating a new one"); 761 // signal old cblk condition so that other threads waiting for available buffers stop 762 // waiting now 763 cblk->cv.broadcast(); 764 cblk->lock.unlock(); 765 766 // if the new IAudioRecord is created, openRecord_l() will modify the 767 // following member variables: mAudioRecord, mCblkMemory and mCblk. 768 // It will also delete the strong references on previous IAudioRecord and IMemory 769 result = openRecord_l(cblk->sampleRate, mFormat, mChannelMask, 770 mFrameCount, getInput_l()); 771 if (result == NO_ERROR) { 772 // callback thread or sync event hasn't changed 773 result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, 0); 774 } 775 if (result != NO_ERROR) { 776 mActive = false; 777 } 778 779 // signal old cblk condition for other threads waiting for restore completion 780 android_atomic_or(CBLK_RESTORED, &cblk->flags); 781 cblk->cv.broadcast(); 782 } else { 783 if (!(cblk->flags & CBLK_RESTORED)) { 784 ALOGW("dead IAudioRecord, waiting for a new one to be created"); 785 mLock.unlock(); 786 result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS)); 787 cblk->lock.unlock(); 788 mLock.lock(); 789 } else { 790 ALOGW("dead IAudioRecord, already restored"); 791 result = NO_ERROR; 792 cblk->lock.unlock(); 793 } 794 if (result != NO_ERROR || !mActive) { 795 result = status_t(STOPPED); 796 } 797 } 798 ALOGV("restoreRecord_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x", 799 result, mActive, mCblk, cblk, mCblk->flags, cblk->flags); 800 801 if (result == NO_ERROR) { 802 // from now on we switch to the newly created cblk 803 cblk = mCblk; 804 } 805 cblk->lock.lock(); 806 807 ALOGW_IF(result != NO_ERROR, "restoreRecord_l() error %d", result); 808 809 return result; 810} 811 812// ========================================================================= 813 814AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver, bool bCanCallJava) 815 : Thread(bCanCallJava), mReceiver(receiver), mPaused(true) 816{ 817} 818 819AudioRecord::AudioRecordThread::~AudioRecordThread() 820{ 821} 822 823bool AudioRecord::AudioRecordThread::threadLoop() 824{ 825 { 826 AutoMutex _l(mMyLock); 827 if (mPaused) { 828 mMyCond.wait(mMyLock); 829 // caller will check for exitPending() 830 return true; 831 } 832 } 833 if (!mReceiver.processAudioBuffer(this)) { 834 pause(); 835 } 836 return true; 837} 838 839void AudioRecord::AudioRecordThread::requestExit() 840{ 841 // must be in this order to avoid a race condition 842 Thread::requestExit(); 843 resume(); 844} 845 846void AudioRecord::AudioRecordThread::pause() 847{ 848 AutoMutex _l(mMyLock); 849 mPaused = true; 850} 851 852void AudioRecord::AudioRecordThread::resume() 853{ 854 AutoMutex _l(mMyLock); 855 if (mPaused) { 856 mPaused = false; 857 mMyCond.signal(); 858 } 859} 860 861// ------------------------------------------------------------------------- 862 863}; // namespace android 864