AudioRecord.cpp revision 864585df53eb97c31e77b3ad7c0d89e4f9b42588
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    mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
470    mCblk->waitTimeMs = 0;
471    return NO_ERROR;
472}
473
474status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
475{
476    AutoMutex lock(mLock);
477    bool active;
478    status_t result = NO_ERROR;
479    audio_track_cblk_t* cblk = mCblk;
480    uint32_t framesReq = audioBuffer->frameCount;
481    uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
482
483    audioBuffer->frameCount  = 0;
484    audioBuffer->size        = 0;
485
486    uint32_t framesReady = cblk->framesReadyIn();
487
488    if (framesReady == 0) {
489        cblk->lock.lock();
490        goto start_loop_here;
491        while (framesReady == 0) {
492            active = mActive;
493            if (CC_UNLIKELY(!active)) {
494                cblk->lock.unlock();
495                return NO_MORE_BUFFERS;
496            }
497            if (CC_UNLIKELY(!waitCount)) {
498                cblk->lock.unlock();
499                return WOULD_BLOCK;
500            }
501            if (!(cblk->flags & CBLK_INVALID)) {
502                mLock.unlock();
503                result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
504                cblk->lock.unlock();
505                mLock.lock();
506                if (!mActive) {
507                    return status_t(STOPPED);
508                }
509                cblk->lock.lock();
510            }
511            if (cblk->flags & CBLK_INVALID) {
512                goto create_new_record;
513            }
514            if (CC_UNLIKELY(result != NO_ERROR)) {
515                cblk->waitTimeMs += waitTimeMs;
516                if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
517                    ALOGW(   "obtainBuffer timed out (is the CPU pegged?) "
518                            "user=%08x, server=%08x", cblk->user, cblk->server);
519                    cblk->lock.unlock();
520                    // callback thread or sync event hasn't changed
521                    result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, 0);
522                    cblk->lock.lock();
523                    if (result == DEAD_OBJECT) {
524                        android_atomic_or(CBLK_INVALID, &cblk->flags);
525create_new_record:
526                        result = AudioRecord::restoreRecord_l(cblk);
527                    }
528                    if (result != NO_ERROR) {
529                        ALOGW("obtainBuffer create Track error %d", result);
530                        cblk->lock.unlock();
531                        return result;
532                    }
533                    cblk->waitTimeMs = 0;
534                }
535                if (--waitCount == 0) {
536                    cblk->lock.unlock();
537                    return TIMED_OUT;
538                }
539            }
540            // read the server count again
541        start_loop_here:
542            framesReady = cblk->framesReadyIn();
543        }
544        cblk->lock.unlock();
545    }
546
547    cblk->waitTimeMs = 0;
548    // reset time out to running value after obtaining a buffer
549    cblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
550
551    if (framesReq > framesReady) {
552        framesReq = framesReady;
553    }
554
555    uint32_t u = cblk->user;
556    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
557
558    if (framesReq > bufferEnd - u) {
559        framesReq = bufferEnd - u;
560    }
561
562    audioBuffer->frameCount  = framesReq;
563    audioBuffer->size        = framesReq*cblk->frameSize;
564    audioBuffer->raw         = (int8_t*)cblk->buffer(u);
565    active = mActive;
566    return active ? status_t(NO_ERROR) : status_t(STOPPED);
567}
568
569void AudioRecord::releaseBuffer(Buffer* audioBuffer)
570{
571    AutoMutex lock(mLock);
572    mCblk->stepUserIn(audioBuffer->frameCount);
573}
574
575audio_io_handle_t AudioRecord::getInput() const
576{
577    AutoMutex lock(mLock);
578    return mInput;
579}
580
581// must be called with mLock held
582audio_io_handle_t AudioRecord::getInput_l()
583{
584    mInput = AudioSystem::getInput(mInputSource,
585                                mCblk->sampleRate,
586                                mFormat,
587                                mChannelMask,
588                                mSessionId);
589    return mInput;
590}
591
592int AudioRecord::getSessionId() const
593{
594    // no lock needed because session ID doesn't change after first set()
595    return mSessionId;
596}
597
598// -------------------------------------------------------------------------
599
600ssize_t AudioRecord::read(void* buffer, size_t userSize)
601{
602    ssize_t read = 0;
603    Buffer audioBuffer;
604    int8_t *dst = static_cast<int8_t*>(buffer);
605
606    if (ssize_t(userSize) < 0) {
607        // sanity-check. user is most-likely passing an error code.
608        ALOGE("AudioRecord::read(buffer=%p, size=%u (%d)",
609                buffer, userSize, userSize);
610        return BAD_VALUE;
611    }
612
613    mLock.lock();
614    // acquire a strong reference on the IAudioRecord and IMemory so that they cannot be destroyed
615    // while we are accessing the cblk
616    sp<IAudioRecord> audioRecord = mAudioRecord;
617    sp<IMemory> iMem = mCblkMemory;
618    mLock.unlock();
619
620    do {
621
622        audioBuffer.frameCount = userSize/frameSize();
623
624        // By using a wait count corresponding to twice the timeout period in
625        // obtainBuffer() we give a chance to recover once for a read timeout
626        // (if media_server crashed for instance) before returning a length of
627        // 0 bytes read to the client
628        status_t err = obtainBuffer(&audioBuffer, ((2 * MAX_RUN_TIMEOUT_MS) / WAIT_PERIOD_MS));
629        if (err < 0) {
630            // out of buffers, return #bytes written
631            if (err == status_t(NO_MORE_BUFFERS))
632                break;
633            if (err == status_t(TIMED_OUT))
634                err = 0;
635            return ssize_t(err);
636        }
637
638        size_t bytesRead = audioBuffer.size;
639        memcpy(dst, audioBuffer.i8, bytesRead);
640
641        dst += bytesRead;
642        userSize -= bytesRead;
643        read += bytesRead;
644
645        releaseBuffer(&audioBuffer);
646    } while (userSize);
647
648    return read;
649}
650
651// -------------------------------------------------------------------------
652
653bool AudioRecord::processAudioBuffer(const sp<AudioRecordThread>& thread)
654{
655    Buffer audioBuffer;
656    uint32_t frames = mRemainingFrames;
657    size_t readSize;
658
659    mLock.lock();
660    // acquire a strong reference on the IAudioRecord and IMemory so that they cannot be destroyed
661    // while we are accessing the cblk
662    sp<IAudioRecord> audioRecord = mAudioRecord;
663    sp<IMemory> iMem = mCblkMemory;
664    audio_track_cblk_t* cblk = mCblk;
665    bool active = mActive;
666    uint32_t markerPosition = mMarkerPosition;
667    uint32_t newPosition = mNewPosition;
668    uint32_t user = cblk->user;
669    // determine whether a marker callback will be needed, while locked
670    bool needMarker = !mMarkerReached && (mMarkerPosition > 0) && (user >= mMarkerPosition);
671    if (needMarker) {
672        mMarkerReached = true;
673    }
674    // determine the number of new position callback(s) that will be needed, while locked
675    uint32_t updatePeriod = mUpdatePeriod;
676    uint32_t needNewPos = updatePeriod > 0 && user >= newPosition ?
677            ((user - newPosition) / updatePeriod) + 1 : 0;
678    mNewPosition = newPosition + updatePeriod * needNewPos;
679    mLock.unlock();
680
681    // perform marker callback, while unlocked
682    if (needMarker) {
683        mCbf(EVENT_MARKER, mUserData, &markerPosition);
684    }
685
686    // perform new position callback(s), while unlocked
687    for (; needNewPos > 0; --needNewPos) {
688        uint32_t temp = newPosition;
689        mCbf(EVENT_NEW_POS, mUserData, &temp);
690        newPosition += updatePeriod;
691    }
692
693    do {
694        audioBuffer.frameCount = frames;
695        // Calling obtainBuffer() with a wait count of 1
696        // limits wait time to WAIT_PERIOD_MS. This prevents from being
697        // stuck here not being able to handle timed events (position, markers).
698        status_t err = obtainBuffer(&audioBuffer, 1);
699        if (err < NO_ERROR) {
700            if (err != TIMED_OUT) {
701                ALOGE_IF(err != status_t(NO_MORE_BUFFERS),
702                        "Error obtaining an audio buffer, giving up.");
703                return false;
704            }
705            break;
706        }
707        if (err == status_t(STOPPED)) return false;
708
709        size_t reqSize = audioBuffer.size;
710        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
711        readSize = audioBuffer.size;
712
713        // Sanity check on returned size
714        if (ssize_t(readSize) <= 0) {
715            // The callback is done filling buffers
716            // Keep this thread going to handle timed events and
717            // still try to get more data in intervals of WAIT_PERIOD_MS
718            // but don't just loop and block the CPU, so wait
719            usleep(WAIT_PERIOD_MS*1000);
720            break;
721        }
722        if (readSize > reqSize) readSize = reqSize;
723
724        audioBuffer.size = readSize;
725        audioBuffer.frameCount = readSize/frameSize();
726        frames -= audioBuffer.frameCount;
727
728        releaseBuffer(&audioBuffer);
729
730    } while (frames);
731
732
733    // Manage overrun callback
734    if (active && (cblk->framesAvailableIn() == 0)) {
735        // The value of active is stale, but we are almost sure to be active here because
736        // otherwise we would have exited when obtainBuffer returned STOPPED earlier.
737        ALOGV("Overrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
738        if (!(android_atomic_or(CBLK_UNDERRUN, &cblk->flags) & CBLK_UNDERRUN)) {
739            mCbf(EVENT_OVERRUN, mUserData, NULL);
740        }
741    }
742
743    if (frames == 0) {
744        mRemainingFrames = mNotificationFrames;
745    } else {
746        mRemainingFrames = frames;
747    }
748    return true;
749}
750
751// must be called with mLock and cblk.lock held. Callers must also hold strong references on
752// the IAudioRecord and IMemory in case they are recreated here.
753// If the IAudioRecord is successfully restored, the cblk pointer is updated
754status_t AudioRecord::restoreRecord_l(audio_track_cblk_t*& cblk)
755{
756    status_t result;
757
758    if (!(android_atomic_or(CBLK_RESTORING, &cblk->flags) & CBLK_RESTORING)) {
759        ALOGW("dead IAudioRecord, creating a new one");
760        // signal old cblk condition so that other threads waiting for available buffers stop
761        // waiting now
762        cblk->cv.broadcast();
763        cblk->lock.unlock();
764
765        // if the new IAudioRecord is created, openRecord_l() will modify the
766        // following member variables: mAudioRecord, mCblkMemory and mCblk.
767        // It will also delete the strong references on previous IAudioRecord and IMemory
768        result = openRecord_l(cblk->sampleRate, mFormat, mChannelMask,
769                mFrameCount, getInput_l());
770        if (result == NO_ERROR) {
771            // callback thread or sync event hasn't changed
772            result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, 0);
773        }
774        if (result != NO_ERROR) {
775            mActive = false;
776        }
777
778        // signal old cblk condition for other threads waiting for restore completion
779        android_atomic_or(CBLK_RESTORED, &cblk->flags);
780        cblk->cv.broadcast();
781    } else {
782        if (!(cblk->flags & CBLK_RESTORED)) {
783            ALOGW("dead IAudioRecord, waiting for a new one to be created");
784            mLock.unlock();
785            result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
786            cblk->lock.unlock();
787            mLock.lock();
788        } else {
789            ALOGW("dead IAudioRecord, already restored");
790            result = NO_ERROR;
791            cblk->lock.unlock();
792        }
793        if (result != NO_ERROR || !mActive) {
794            result = status_t(STOPPED);
795        }
796    }
797    ALOGV("restoreRecord_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
798        result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
799
800    if (result == NO_ERROR) {
801        // from now on we switch to the newly created cblk
802        cblk = mCblk;
803    }
804    cblk->lock.lock();
805
806    ALOGW_IF(result != NO_ERROR, "restoreRecord_l() error %d", result);
807
808    return result;
809}
810
811// =========================================================================
812
813AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver, bool bCanCallJava)
814    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true)
815{
816}
817
818AudioRecord::AudioRecordThread::~AudioRecordThread()
819{
820}
821
822bool AudioRecord::AudioRecordThread::threadLoop()
823{
824    {
825        AutoMutex _l(mMyLock);
826        if (mPaused) {
827            mMyCond.wait(mMyLock);
828            // caller will check for exitPending()
829            return true;
830        }
831    }
832    if (!mReceiver.processAudioBuffer(this)) {
833        pause();
834    }
835    return true;
836}
837
838void AudioRecord::AudioRecordThread::requestExit()
839{
840    // must be in this order to avoid a race condition
841    Thread::requestExit();
842    resume();
843}
844
845void AudioRecord::AudioRecordThread::pause()
846{
847    AutoMutex _l(mMyLock);
848    mPaused = true;
849}
850
851void AudioRecord::AudioRecordThread::resume()
852{
853    AutoMutex _l(mMyLock);
854    if (mPaused) {
855        mPaused = false;
856        mMyCond.signal();
857    }
858}
859
860// -------------------------------------------------------------------------
861
862}; // namespace android
863