AudioRecord.cpp revision 0aa3c6eba07f987fe84b5fa450274a8e730971e3
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(const String16 &opPackageName)
69    : mActive(false), mStatus(NO_INIT), mOpPackageName(opPackageName),
70      mSessionId(AUDIO_SESSION_ALLOCATE),
71      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT),
72      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE), mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
73      mPortId(AUDIO_PORT_HANDLE_NONE)
74{
75}
76
77AudioRecord::AudioRecord(
78        audio_source_t inputSource,
79        uint32_t sampleRate,
80        audio_format_t format,
81        audio_channel_mask_t channelMask,
82        const String16& opPackageName,
83        size_t frameCount,
84        callback_t cbf,
85        void* user,
86        uint32_t notificationFrames,
87        audio_session_t sessionId,
88        transfer_type transferType,
89        audio_input_flags_t flags,
90        uid_t uid,
91        pid_t pid,
92        const audio_attributes_t* pAttributes,
93        audio_port_handle_t selectedDeviceId)
94    : mActive(false),
95      mStatus(NO_INIT),
96      mOpPackageName(opPackageName),
97      mSessionId(AUDIO_SESSION_ALLOCATE),
98      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
99      mPreviousSchedulingGroup(SP_DEFAULT),
100      mProxy(NULL),
101      mPortId(AUDIO_PORT_HANDLE_NONE)
102{
103    mStatus = set(inputSource, sampleRate, format, channelMask, frameCount, cbf, user,
104            notificationFrames, false /*threadCanCallJava*/, sessionId, transferType, flags,
105            uid, pid, pAttributes, selectedDeviceId);
106}
107
108AudioRecord::~AudioRecord()
109{
110    if (mStatus == NO_ERROR) {
111        // Make sure that callback function exits in the case where
112        // it is looping on buffer empty condition in obtainBuffer().
113        // Otherwise the callback thread will never exit.
114        stop();
115        if (mAudioRecordThread != 0) {
116            mProxy->interrupt();
117            mAudioRecordThread->requestExit();  // see comment in AudioRecord.h
118            mAudioRecordThread->requestExitAndWait();
119            mAudioRecordThread.clear();
120        }
121        // No lock here: worst case we remove a NULL callback which will be a nop
122        if (mDeviceCallback != 0 && mInput != AUDIO_IO_HANDLE_NONE) {
123            AudioSystem::removeAudioDeviceCallback(this, mInput);
124        }
125        IInterface::asBinder(mAudioRecord)->unlinkToDeath(mDeathNotifier, this);
126        mAudioRecord.clear();
127        mCblkMemory.clear();
128        mBufferMemory.clear();
129        IPCThreadState::self()->flushCommands();
130        ALOGV("~AudioRecord, releasing session id %d",
131                mSessionId);
132        AudioSystem::releaseAudioSessionId(mSessionId, -1 /*pid*/);
133    }
134}
135
136status_t AudioRecord::set(
137        audio_source_t inputSource,
138        uint32_t sampleRate,
139        audio_format_t format,
140        audio_channel_mask_t channelMask,
141        size_t frameCount,
142        callback_t cbf,
143        void* user,
144        uint32_t notificationFrames,
145        bool threadCanCallJava,
146        audio_session_t sessionId,
147        transfer_type transferType,
148        audio_input_flags_t flags,
149        uid_t uid,
150        pid_t pid,
151        const audio_attributes_t* pAttributes,
152        audio_port_handle_t selectedDeviceId)
153{
154    ALOGV("set(): inputSource %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
155          "notificationFrames %u, sessionId %d, transferType %d, flags %#x, opPackageName %s "
156          "uid %d, pid %d",
157          inputSource, sampleRate, format, channelMask, frameCount, notificationFrames,
158          sessionId, transferType, flags, String8(mOpPackageName).string(), uid, pid);
159
160    mSelectedDeviceId = selectedDeviceId;
161
162    switch (transferType) {
163    case TRANSFER_DEFAULT:
164        if (cbf == NULL || threadCanCallJava) {
165            transferType = TRANSFER_SYNC;
166        } else {
167            transferType = TRANSFER_CALLBACK;
168        }
169        break;
170    case TRANSFER_CALLBACK:
171        if (cbf == NULL) {
172            ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL");
173            return BAD_VALUE;
174        }
175        break;
176    case TRANSFER_OBTAIN:
177    case TRANSFER_SYNC:
178        break;
179    default:
180        ALOGE("Invalid transfer type %d", transferType);
181        return BAD_VALUE;
182    }
183    mTransfer = transferType;
184
185    // invariant that mAudioRecord != 0 is true only after set() returns successfully
186    if (mAudioRecord != 0) {
187        ALOGE("Track already in use");
188        return INVALID_OPERATION;
189    }
190
191    if (pAttributes == NULL) {
192        memset(&mAttributes, 0, sizeof(audio_attributes_t));
193        mAttributes.source = inputSource;
194    } else {
195        // stream type shouldn't be looked at, this track has audio attributes
196        memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
197        ALOGV("Building AudioRecord with attributes: source=%d flags=0x%x tags=[%s]",
198              mAttributes.source, mAttributes.flags, mAttributes.tags);
199    }
200
201    mSampleRate = sampleRate;
202
203    // these below should probably come from the audioFlinger too...
204    if (format == AUDIO_FORMAT_DEFAULT) {
205        format = AUDIO_FORMAT_PCM_16_BIT;
206    }
207
208    // validate parameters
209    // AudioFlinger capture only supports linear PCM
210    if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
211        ALOGE("Format %#x is not linear pcm", format);
212        return BAD_VALUE;
213    }
214    mFormat = format;
215
216    if (!audio_is_input_channel(channelMask)) {
217        ALOGE("Invalid channel mask %#x", channelMask);
218        return BAD_VALUE;
219    }
220    mChannelMask = channelMask;
221    uint32_t channelCount = audio_channel_count_from_in_mask(channelMask);
222    mChannelCount = channelCount;
223
224    if (audio_is_linear_pcm(format)) {
225        mFrameSize = channelCount * audio_bytes_per_sample(format);
226    } else {
227        mFrameSize = sizeof(uint8_t);
228    }
229
230    // mFrameCount is initialized in openRecord_l
231    mReqFrameCount = frameCount;
232
233    mNotificationFramesReq = notificationFrames;
234    // mNotificationFramesAct is initialized in openRecord_l
235
236    if (sessionId == AUDIO_SESSION_ALLOCATE) {
237        mSessionId = (audio_session_t) AudioSystem::newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
238    } else {
239        mSessionId = sessionId;
240    }
241    ALOGV("set(): mSessionId %d", mSessionId);
242
243    int callingpid = IPCThreadState::self()->getCallingPid();
244    int mypid = getpid();
245    if (uid == AUDIO_UID_INVALID || (callingpid != mypid)) {
246        mClientUid = IPCThreadState::self()->getCallingUid();
247    } else {
248        mClientUid = uid;
249    }
250    if (pid == -1 || (callingpid != mypid)) {
251        mClientPid = callingpid;
252    } else {
253        mClientPid = pid;
254    }
255
256    mOrigFlags = mFlags = flags;
257    mCbf = cbf;
258
259    if (cbf != NULL) {
260        mAudioRecordThread = new AudioRecordThread(*this, threadCanCallJava);
261        mAudioRecordThread->run("AudioRecord", ANDROID_PRIORITY_AUDIO);
262        // thread begins in paused state, and will not reference us until start()
263    }
264
265    // create the IAudioRecord
266    status_t status = openRecord_l(0 /*epoch*/, mOpPackageName);
267
268    if (status != NO_ERROR) {
269        if (mAudioRecordThread != 0) {
270            mAudioRecordThread->requestExit();   // see comment in AudioRecord.h
271            mAudioRecordThread->requestExitAndWait();
272            mAudioRecordThread.clear();
273        }
274        return status;
275    }
276
277    mStatus = NO_ERROR;
278    mUserData = user;
279    // TODO: add audio hardware input latency here
280    mLatency = (1000LL * mFrameCount) / mSampleRate;
281    mMarkerPosition = 0;
282    mMarkerReached = false;
283    mNewPosition = 0;
284    mUpdatePeriod = 0;
285    AudioSystem::acquireAudioSessionId(mSessionId, -1);
286    mSequence = 1;
287    mObservedSequence = mSequence;
288    mInOverrun = false;
289    mFramesRead = 0;
290    mFramesReadServerOffset = 0;
291
292    return NO_ERROR;
293}
294
295// -------------------------------------------------------------------------
296
297status_t AudioRecord::start(AudioSystem::sync_event_t event, audio_session_t triggerSession)
298{
299    ALOGV("start, sync event %d trigger session %d", event, triggerSession);
300
301    AutoMutex lock(mLock);
302    if (mActive) {
303        return NO_ERROR;
304    }
305
306    // discard data in buffer
307    const uint32_t framesFlushed = mProxy->flush();
308    mFramesReadServerOffset -= mFramesRead + framesFlushed;
309    mFramesRead = 0;
310    mProxy->clearTimestamp();  // timestamp is invalid until next server push
311
312    // reset current position as seen by client to 0
313    mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
314    // force refresh of remaining frames by processAudioBuffer() as last
315    // read before stop could be partial.
316    mRefreshRemaining = true;
317
318    mNewPosition = mProxy->getPosition() + mUpdatePeriod;
319    int32_t flags = android_atomic_acquire_load(&mCblk->mFlags);
320
321    // we reactivate markers (mMarkerPosition != 0) as the position is reset to 0.
322    // This is legacy behavior.  This is not done in stop() to avoid a race condition
323    // where the last marker event is issued twice.
324    mMarkerReached = false;
325    mActive = true;
326
327    status_t status = NO_ERROR;
328    if (!(flags & CBLK_INVALID)) {
329        status = mAudioRecord->start(event, triggerSession).transactionError();
330        if (status == DEAD_OBJECT) {
331            flags |= CBLK_INVALID;
332        }
333    }
334    if (flags & CBLK_INVALID) {
335        status = restoreRecord_l("start");
336    }
337
338    if (status != NO_ERROR) {
339        mActive = false;
340        ALOGE("start() status %d", status);
341    } else {
342        sp<AudioRecordThread> t = mAudioRecordThread;
343        if (t != 0) {
344            t->resume();
345        } else {
346            mPreviousPriority = getpriority(PRIO_PROCESS, 0);
347            get_sched_policy(0, &mPreviousSchedulingGroup);
348            androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
349        }
350    }
351
352    return status;
353}
354
355void AudioRecord::stop()
356{
357    AutoMutex lock(mLock);
358    if (!mActive) {
359        return;
360    }
361
362    mActive = false;
363    mProxy->interrupt();
364    mAudioRecord->stop();
365
366    // Note: legacy handling - stop does not clear record marker and
367    // periodic update position; we update those on start().
368
369    sp<AudioRecordThread> t = mAudioRecordThread;
370    if (t != 0) {
371        t->pause();
372    } else {
373        setpriority(PRIO_PROCESS, 0, mPreviousPriority);
374        set_sched_policy(0, mPreviousSchedulingGroup);
375    }
376}
377
378bool AudioRecord::stopped() const
379{
380    AutoMutex lock(mLock);
381    return !mActive;
382}
383
384status_t AudioRecord::setMarkerPosition(uint32_t marker)
385{
386    // The only purpose of setting marker position is to get a callback
387    if (mCbf == NULL) {
388        return INVALID_OPERATION;
389    }
390
391    AutoMutex lock(mLock);
392    mMarkerPosition = marker;
393    mMarkerReached = false;
394
395    sp<AudioRecordThread> t = mAudioRecordThread;
396    if (t != 0) {
397        t->wake();
398    }
399    return NO_ERROR;
400}
401
402status_t AudioRecord::getMarkerPosition(uint32_t *marker) const
403{
404    if (marker == NULL) {
405        return BAD_VALUE;
406    }
407
408    AutoMutex lock(mLock);
409    mMarkerPosition.getValue(marker);
410
411    return NO_ERROR;
412}
413
414status_t AudioRecord::setPositionUpdatePeriod(uint32_t updatePeriod)
415{
416    // The only purpose of setting position update period is to get a callback
417    if (mCbf == NULL) {
418        return INVALID_OPERATION;
419    }
420
421    AutoMutex lock(mLock);
422    mNewPosition = mProxy->getPosition() + updatePeriod;
423    mUpdatePeriod = updatePeriod;
424
425    sp<AudioRecordThread> t = mAudioRecordThread;
426    if (t != 0) {
427        t->wake();
428    }
429    return NO_ERROR;
430}
431
432status_t AudioRecord::getPositionUpdatePeriod(uint32_t *updatePeriod) const
433{
434    if (updatePeriod == NULL) {
435        return BAD_VALUE;
436    }
437
438    AutoMutex lock(mLock);
439    *updatePeriod = mUpdatePeriod;
440
441    return NO_ERROR;
442}
443
444status_t AudioRecord::getPosition(uint32_t *position) const
445{
446    if (position == NULL) {
447        return BAD_VALUE;
448    }
449
450    AutoMutex lock(mLock);
451    mProxy->getPosition().getValue(position);
452
453    return NO_ERROR;
454}
455
456uint32_t AudioRecord::getInputFramesLost() const
457{
458    // no need to check mActive, because if inactive this will return 0, which is what we want
459    return AudioSystem::getInputFramesLost(getInputPrivate());
460}
461
462status_t AudioRecord::getTimestamp(ExtendedTimestamp *timestamp)
463{
464    if (timestamp == nullptr) {
465        return BAD_VALUE;
466    }
467    AutoMutex lock(mLock);
468    status_t status = mProxy->getTimestamp(timestamp);
469    if (status == OK) {
470        timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesRead;
471        timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
472        // server side frame offset in case AudioRecord has been restored.
473        for (int i = ExtendedTimestamp::LOCATION_SERVER;
474                i < ExtendedTimestamp::LOCATION_MAX; ++i) {
475            if (timestamp->mTimeNs[i] >= 0) {
476                timestamp->mPosition[i] += mFramesReadServerOffset;
477            }
478        }
479    }
480    return status;
481}
482
483// ---- Explicit Routing ---------------------------------------------------
484status_t AudioRecord::setInputDevice(audio_port_handle_t deviceId) {
485    AutoMutex lock(mLock);
486    if (mSelectedDeviceId != deviceId) {
487        mSelectedDeviceId = deviceId;
488        if (mStatus == NO_ERROR) {
489            // stop capture so that audio policy manager does not reject the new instance start request
490            // as only one capture can be active at a time.
491            if (mAudioRecord != 0 && mActive) {
492                mAudioRecord->stop();
493            }
494            android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
495            mProxy->interrupt();
496        }
497    }
498    return NO_ERROR;
499}
500
501audio_port_handle_t AudioRecord::getInputDevice() {
502    AutoMutex lock(mLock);
503    return mSelectedDeviceId;
504}
505
506// must be called with mLock held
507void AudioRecord::updateRoutedDeviceId_l()
508{
509    // if the record is inactive, do not update actual device as the input stream maybe routed
510    // from a device not relevant to this client because of other active use cases.
511    if (!mActive) {
512        return;
513    }
514    if (mInput != AUDIO_IO_HANDLE_NONE) {
515        audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mInput);
516        if (deviceId != AUDIO_PORT_HANDLE_NONE) {
517            mRoutedDeviceId = deviceId;
518        }
519     }
520}
521
522audio_port_handle_t AudioRecord::getRoutedDeviceId() {
523    AutoMutex lock(mLock);
524    updateRoutedDeviceId_l();
525    return mRoutedDeviceId;
526}
527
528// -------------------------------------------------------------------------
529// TODO Move this macro to a common header file for enum to string conversion in audio framework.
530#define MEDIA_CASE_ENUM(name) case name: return #name
531const char * AudioRecord::convertTransferToText(transfer_type transferType) {
532    switch (transferType) {
533        MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
534        MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
535        MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
536        MEDIA_CASE_ENUM(TRANSFER_SYNC);
537        default:
538            return "UNRECOGNIZED";
539    }
540}
541
542// must be called with mLock held
543status_t AudioRecord::openRecord_l(const Modulo<uint32_t> &epoch, const String16& opPackageName)
544{
545    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
546    if (audioFlinger == 0) {
547        ALOGE("Could not get audioflinger");
548        return NO_INIT;
549    }
550
551    audio_io_handle_t input;
552
553    // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
554    // After fast request is denied, we will request again if IAudioRecord is re-created.
555
556    status_t status;
557
558    // Not a conventional loop, but a retry loop for at most two iterations total.
559    // Try first maybe with FAST flag then try again without FAST flag if that fails.
560    // Exits loop normally via a return at the bottom, or with error via a break.
561    // The sp<> references will be dropped when re-entering scope.
562    // The lack of indentation is deliberate, to reduce code churn and ease merges.
563    for (;;) {
564    audio_config_base_t config  = {
565            .sample_rate = mSampleRate,
566            .channel_mask = mChannelMask,
567            .format = mFormat
568        };
569    mRoutedDeviceId = mSelectedDeviceId;
570    status = AudioSystem::getInputForAttr(&mAttributes, &input,
571                                        mSessionId,
572                                        // FIXME compare to AudioTrack
573                                        mClientPid,
574                                        mClientUid,
575                                        &config,
576                                        mFlags, &mRoutedDeviceId, &mPortId);
577
578    if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE) {
579        ALOGE("Could not get audio input for session %d, record source %d, sample rate %u, "
580              "format %#x, channel mask %#x, flags %#x",
581              mSessionId, mAttributes.source, mSampleRate, mFormat, mChannelMask, mFlags);
582        return BAD_VALUE;
583    }
584
585    // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
586    // we must release it ourselves if anything goes wrong.
587
588#if 0
589    size_t afFrameCount;
590    status = AudioSystem::getFrameCount(input, &afFrameCount);
591    if (status != NO_ERROR) {
592        ALOGE("getFrameCount(input=%d) status %d", input, status);
593        break;
594    }
595#endif
596
597    uint32_t afSampleRate;
598    status = AudioSystem::getSamplingRate(input, &afSampleRate);
599    if (status != NO_ERROR) {
600        ALOGE("getSamplingRate(input=%d) status %d", input, status);
601        break;
602    }
603    if (mSampleRate == 0) {
604        mSampleRate = afSampleRate;
605    }
606
607    // Client can only express a preference for FAST.  Server will perform additional tests.
608    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
609        bool useCaseAllowed =
610            // any of these use cases:
611            // use case 1: callback transfer mode
612            (mTransfer == TRANSFER_CALLBACK) ||
613            // use case 2: blocking read mode
614            // The default buffer capacity at 48 kHz is 2048 frames, or ~42.6 ms.
615            // That's enough for double-buffering with our standard 20 ms rule of thumb for
616            // the minimum period of a non-SCHED_FIFO thread.
617            // This is needed so that AAudio apps can do a low latency non-blocking read from a
618            // callback running with SCHED_FIFO.
619            (mTransfer == TRANSFER_SYNC) ||
620            // use case 3: obtain/release mode
621            (mTransfer == TRANSFER_OBTAIN);
622        if (!useCaseAllowed) {
623            ALOGW("AUDIO_INPUT_FLAG_FAST denied, incompatible transfer = %s",
624                  convertTransferToText(mTransfer));
625        }
626
627        // sample rates must also match
628        bool sampleRateAllowed = mSampleRate == afSampleRate;
629        if (!sampleRateAllowed) {
630            ALOGW("AUDIO_INPUT_FLAG_FAST denied, rates do not match %u Hz, require %u Hz",
631                  mSampleRate, afSampleRate);
632        }
633
634        bool fastAllowed = useCaseAllowed && sampleRateAllowed;
635        if (!fastAllowed) {
636            mFlags = (audio_input_flags_t) (mFlags & ~(AUDIO_INPUT_FLAG_FAST |
637                    AUDIO_INPUT_FLAG_RAW));
638            AudioSystem::releaseInput(input, mSessionId);
639            continue;   // retry
640        }
641    }
642
643    // The notification frame count is the period between callbacks, as suggested by the client
644    // but moderated by the server.  For record, the calculations are done entirely on server side.
645    size_t notificationFrames = mNotificationFramesReq;
646    size_t frameCount = mReqFrameCount;
647
648    audio_input_flags_t flags = mFlags;
649
650    pid_t tid = -1;
651    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
652        if (mAudioRecordThread != 0) {
653            tid = mAudioRecordThread->getTid();
654        }
655    }
656
657    size_t temp = frameCount;   // temp may be replaced by a revised value of frameCount,
658                                // but we will still need the original value also
659    audio_session_t originalSessionId = mSessionId;
660
661    sp<IMemory> iMem;           // for cblk
662    sp<IMemory> bufferMem;
663    sp<media::IAudioRecord> record = audioFlinger->openRecord(input,
664                                                              mSampleRate,
665                                                              mFormat,
666                                                              mChannelMask,
667                                                              opPackageName,
668                                                              &temp,
669                                                              &flags,
670                                                              mClientPid,
671                                                              tid,
672                                                              mClientUid,
673                                                              &mSessionId,
674                                                              &notificationFrames,
675                                                              iMem,
676                                                              bufferMem,
677                                                              &status,
678                                                              mPortId);
679    ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
680            "session ID changed from %d to %d", originalSessionId, mSessionId);
681
682    if (status != NO_ERROR) {
683        ALOGE("AudioFlinger could not create record track, status: %d", status);
684        break;
685    }
686    ALOG_ASSERT(record != 0);
687
688    // AudioFlinger now owns the reference to the I/O handle,
689    // so we are no longer responsible for releasing it.
690
691    mAwaitBoost = false;
692    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
693        if (flags & AUDIO_INPUT_FLAG_FAST) {
694            ALOGI("AUDIO_INPUT_FLAG_FAST successful; frameCount %zu -> %zu", frameCount, temp);
695            mAwaitBoost = true;
696        } else {
697            ALOGW("AUDIO_INPUT_FLAG_FAST denied by server; frameCount %zu -> %zu", frameCount, temp);
698            mFlags = (audio_input_flags_t) (mFlags & ~(AUDIO_INPUT_FLAG_FAST |
699                    AUDIO_INPUT_FLAG_RAW));
700            continue;   // retry
701        }
702    }
703    mFlags = flags;
704
705    if (iMem == 0) {
706        ALOGE("Could not get control block");
707        return NO_INIT;
708    }
709    void *iMemPointer = iMem->pointer();
710    if (iMemPointer == NULL) {
711        ALOGE("Could not get control block pointer");
712        return NO_INIT;
713    }
714    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
715
716    // Starting address of buffers in shared memory.
717    // The buffers are either immediately after the control block,
718    // or in a separate area at discretion of server.
719    void *buffers;
720    if (bufferMem == 0) {
721        buffers = cblk + 1;
722    } else {
723        buffers = bufferMem->pointer();
724        if (buffers == NULL) {
725            ALOGE("Could not get buffer pointer");
726            return NO_INIT;
727        }
728    }
729
730    // invariant that mAudioRecord != 0 is true only after set() returns successfully
731    if (mAudioRecord != 0) {
732        IInterface::asBinder(mAudioRecord)->unlinkToDeath(mDeathNotifier, this);
733        mDeathNotifier.clear();
734    }
735    mAudioRecord = record;
736    mCblkMemory = iMem;
737    mBufferMemory = bufferMem;
738    IPCThreadState::self()->flushCommands();
739
740    mCblk = cblk;
741    // note that temp is the (possibly revised) value of frameCount
742    if (temp < frameCount || (frameCount == 0 && temp == 0)) {
743        ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
744    }
745    frameCount = temp;
746
747    // Make sure that application is notified with sufficient margin before overrun.
748    // The computation is done on server side.
749    if (mNotificationFramesReq > 0 && notificationFrames != mNotificationFramesReq) {
750        ALOGW("Server adjusted notificationFrames from %u to %zu for frameCount %zu",
751                mNotificationFramesReq, notificationFrames, frameCount);
752    }
753    mNotificationFramesAct = (uint32_t) notificationFrames;
754
755
756    //mInput != input includes the case where mInput == AUDIO_IO_HANDLE_NONE for first creation
757    if (mDeviceCallback != 0 && mInput != input) {
758        if (mInput != AUDIO_IO_HANDLE_NONE) {
759            AudioSystem::removeAudioDeviceCallback(this, mInput);
760        }
761        AudioSystem::addAudioDeviceCallback(this, input);
762    }
763
764    // We retain a copy of the I/O handle, but don't own the reference
765    mInput = input;
766    mRefreshRemaining = true;
767
768    mFrameCount = frameCount;
769    // If IAudioRecord is re-created, don't let the requested frameCount
770    // decrease.  This can confuse clients that cache frameCount().
771    if (frameCount > mReqFrameCount) {
772        mReqFrameCount = frameCount;
773    }
774
775    // update proxy
776    mProxy = new AudioRecordClientProxy(cblk, buffers, mFrameCount, mFrameSize);
777    mProxy->setEpoch(epoch);
778    mProxy->setMinimum(mNotificationFramesAct);
779
780    mDeathNotifier = new DeathNotifier(this);
781    IInterface::asBinder(mAudioRecord)->linkToDeath(mDeathNotifier, this);
782
783    return NO_ERROR;
784
785    // End of retry loop.
786    // The lack of indentation is deliberate, to reduce code churn and ease merges.
787    }
788
789// Arrive here on error, via a break
790    AudioSystem::releaseInput(input, mSessionId);
791    if (status == NO_ERROR) {
792        status = NO_INIT;
793    }
794    return status;
795}
796
797status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
798{
799    if (audioBuffer == NULL) {
800        if (nonContig != NULL) {
801            *nonContig = 0;
802        }
803        return BAD_VALUE;
804    }
805    if (mTransfer != TRANSFER_OBTAIN) {
806        audioBuffer->frameCount = 0;
807        audioBuffer->size = 0;
808        audioBuffer->raw = NULL;
809        if (nonContig != NULL) {
810            *nonContig = 0;
811        }
812        return INVALID_OPERATION;
813    }
814
815    const struct timespec *requested;
816    struct timespec timeout;
817    if (waitCount == -1) {
818        requested = &ClientProxy::kForever;
819    } else if (waitCount == 0) {
820        requested = &ClientProxy::kNonBlocking;
821    } else if (waitCount > 0) {
822        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
823        timeout.tv_sec = ms / 1000;
824        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
825        requested = &timeout;
826    } else {
827        ALOGE("%s invalid waitCount %d", __func__, waitCount);
828        requested = NULL;
829    }
830    return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
831}
832
833status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
834        struct timespec *elapsed, size_t *nonContig)
835{
836    // previous and new IAudioRecord sequence numbers are used to detect track re-creation
837    uint32_t oldSequence = 0;
838    uint32_t newSequence;
839
840    Proxy::Buffer buffer;
841    status_t status = NO_ERROR;
842
843    static const int32_t kMaxTries = 5;
844    int32_t tryCounter = kMaxTries;
845
846    do {
847        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
848        // keep them from going away if another thread re-creates the track during obtainBuffer()
849        sp<AudioRecordClientProxy> proxy;
850        sp<IMemory> iMem;
851        sp<IMemory> bufferMem;
852        {
853            // start of lock scope
854            AutoMutex lock(mLock);
855
856            newSequence = mSequence;
857            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
858            if (status == DEAD_OBJECT) {
859                // re-create track, unless someone else has already done so
860                if (newSequence == oldSequence) {
861                    status = restoreRecord_l("obtainBuffer");
862                    if (status != NO_ERROR) {
863                        buffer.mFrameCount = 0;
864                        buffer.mRaw = NULL;
865                        buffer.mNonContig = 0;
866                        break;
867                    }
868                }
869            }
870            oldSequence = newSequence;
871
872            // Keep the extra references
873            proxy = mProxy;
874            iMem = mCblkMemory;
875            bufferMem = mBufferMemory;
876
877            // Non-blocking if track is stopped
878            if (!mActive) {
879                requested = &ClientProxy::kNonBlocking;
880            }
881
882        }   // end of lock scope
883
884        buffer.mFrameCount = audioBuffer->frameCount;
885        // FIXME starts the requested timeout and elapsed over from scratch
886        status = proxy->obtainBuffer(&buffer, requested, elapsed);
887
888    } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
889
890    audioBuffer->frameCount = buffer.mFrameCount;
891    audioBuffer->size = buffer.mFrameCount * mFrameSize;
892    audioBuffer->raw = buffer.mRaw;
893    if (nonContig != NULL) {
894        *nonContig = buffer.mNonContig;
895    }
896    return status;
897}
898
899void AudioRecord::releaseBuffer(const Buffer* audioBuffer)
900{
901    // FIXME add error checking on mode, by adding an internal version
902
903    size_t stepCount = audioBuffer->size / mFrameSize;
904    if (stepCount == 0) {
905        return;
906    }
907
908    Proxy::Buffer buffer;
909    buffer.mFrameCount = stepCount;
910    buffer.mRaw = audioBuffer->raw;
911
912    AutoMutex lock(mLock);
913    mInOverrun = false;
914    mProxy->releaseBuffer(&buffer);
915
916    // the server does not automatically disable recorder on overrun, so no need to restart
917}
918
919audio_io_handle_t AudioRecord::getInputPrivate() const
920{
921    AutoMutex lock(mLock);
922    return mInput;
923}
924
925// -------------------------------------------------------------------------
926
927ssize_t AudioRecord::read(void* buffer, size_t userSize, bool blocking)
928{
929    if (mTransfer != TRANSFER_SYNC) {
930        return INVALID_OPERATION;
931    }
932
933    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
934        // sanity-check. user is most-likely passing an error code, and it would
935        // make the return value ambiguous (actualSize vs error).
936        ALOGE("AudioRecord::read(buffer=%p, size=%zu (%zu)", buffer, userSize, userSize);
937        return BAD_VALUE;
938    }
939
940    ssize_t read = 0;
941    Buffer audioBuffer;
942
943    while (userSize >= mFrameSize) {
944        audioBuffer.frameCount = userSize / mFrameSize;
945
946        status_t err = obtainBuffer(&audioBuffer,
947                blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
948        if (err < 0) {
949            if (read > 0) {
950                break;
951            }
952            if (err == TIMED_OUT || err == -EINTR) {
953                err = WOULD_BLOCK;
954            }
955            return ssize_t(err);
956        }
957
958        size_t bytesRead = audioBuffer.size;
959        memcpy(buffer, audioBuffer.i8, bytesRead);
960        buffer = ((char *) buffer) + bytesRead;
961        userSize -= bytesRead;
962        read += bytesRead;
963
964        releaseBuffer(&audioBuffer);
965    }
966    if (read > 0) {
967        mFramesRead += read / mFrameSize;
968        // mFramesReadTime = systemTime(SYSTEM_TIME_MONOTONIC); // not provided at this time.
969    }
970    return read;
971}
972
973// -------------------------------------------------------------------------
974
975nsecs_t AudioRecord::processAudioBuffer()
976{
977    mLock.lock();
978    if (mAwaitBoost) {
979        mAwaitBoost = false;
980        mLock.unlock();
981        static const int32_t kMaxTries = 5;
982        int32_t tryCounter = kMaxTries;
983        uint32_t pollUs = 10000;
984        do {
985            int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
986            if (policy == SCHED_FIFO || policy == SCHED_RR) {
987                break;
988            }
989            usleep(pollUs);
990            pollUs <<= 1;
991        } while (tryCounter-- > 0);
992        if (tryCounter < 0) {
993            ALOGE("did not receive expected priority boost on time");
994        }
995        // Run again immediately
996        return 0;
997    }
998
999    // Can only reference mCblk while locked
1000    int32_t flags = android_atomic_and(~CBLK_OVERRUN, &mCblk->mFlags);
1001
1002    // Check for track invalidation
1003    if (flags & CBLK_INVALID) {
1004        (void) restoreRecord_l("processAudioBuffer");
1005        mLock.unlock();
1006        // Run again immediately, but with a new IAudioRecord
1007        return 0;
1008    }
1009
1010    bool active = mActive;
1011
1012    // Manage overrun callback, must be done under lock to avoid race with releaseBuffer()
1013    bool newOverrun = false;
1014    if (flags & CBLK_OVERRUN) {
1015        if (!mInOverrun) {
1016            mInOverrun = true;
1017            newOverrun = true;
1018        }
1019    }
1020
1021    // Get current position of server
1022    Modulo<uint32_t> position(mProxy->getPosition());
1023
1024    // Manage marker callback
1025    bool markerReached = false;
1026    Modulo<uint32_t> markerPosition(mMarkerPosition);
1027    // FIXME fails for wraparound, need 64 bits
1028    if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
1029        mMarkerReached = markerReached = true;
1030    }
1031
1032    // Determine the number of new position callback(s) that will be needed, while locked
1033    size_t newPosCount = 0;
1034    Modulo<uint32_t> newPosition(mNewPosition);
1035    uint32_t updatePeriod = mUpdatePeriod;
1036    // FIXME fails for wraparound, need 64 bits
1037    if (updatePeriod > 0 && position >= newPosition) {
1038        newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
1039        mNewPosition += updatePeriod * newPosCount;
1040    }
1041
1042    // Cache other fields that will be needed soon
1043    uint32_t notificationFrames = mNotificationFramesAct;
1044    if (mRefreshRemaining) {
1045        mRefreshRemaining = false;
1046        mRemainingFrames = notificationFrames;
1047        mRetryOnPartialBuffer = false;
1048    }
1049    size_t misalignment = mProxy->getMisalignment();
1050    uint32_t sequence = mSequence;
1051
1052    // These fields don't need to be cached, because they are assigned only by set():
1053    //      mTransfer, mCbf, mUserData, mSampleRate, mFrameSize
1054
1055    mLock.unlock();
1056
1057    // perform callbacks while unlocked
1058    if (newOverrun) {
1059        mCbf(EVENT_OVERRUN, mUserData, NULL);
1060    }
1061    if (markerReached) {
1062        mCbf(EVENT_MARKER, mUserData, &markerPosition);
1063    }
1064    while (newPosCount > 0) {
1065        size_t temp = newPosition.value(); // FIXME size_t != uint32_t
1066        mCbf(EVENT_NEW_POS, mUserData, &temp);
1067        newPosition += updatePeriod;
1068        newPosCount--;
1069    }
1070    if (mObservedSequence != sequence) {
1071        mObservedSequence = sequence;
1072        mCbf(EVENT_NEW_IAUDIORECORD, mUserData, NULL);
1073    }
1074
1075    // if inactive, then don't run me again until re-started
1076    if (!active) {
1077        return NS_INACTIVE;
1078    }
1079
1080    // Compute the estimated time until the next timed event (position, markers)
1081    uint32_t minFrames = ~0;
1082    if (!markerReached && position < markerPosition) {
1083        minFrames = (markerPosition - position).value();
1084    }
1085    if (updatePeriod > 0) {
1086        uint32_t remaining = (newPosition - position).value();
1087        if (remaining < minFrames) {
1088            minFrames = remaining;
1089        }
1090    }
1091
1092    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
1093    static const uint32_t kPoll = 0;
1094    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1095        minFrames = kPoll * notificationFrames;
1096    }
1097
1098    // Convert frame units to time units
1099    nsecs_t ns = NS_WHENEVER;
1100    if (minFrames != (uint32_t) ~0) {
1101        // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1102        static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1103        ns = ((minFrames * 1000000000LL) / mSampleRate) + kFudgeNs;
1104    }
1105
1106    // If not supplying data by EVENT_MORE_DATA, then we're done
1107    if (mTransfer != TRANSFER_CALLBACK) {
1108        return ns;
1109    }
1110
1111    struct timespec timeout;
1112    const struct timespec *requested = &ClientProxy::kForever;
1113    if (ns != NS_WHENEVER) {
1114        timeout.tv_sec = ns / 1000000000LL;
1115        timeout.tv_nsec = ns % 1000000000LL;
1116        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1117        requested = &timeout;
1118    }
1119
1120    size_t readFrames = 0;
1121    while (mRemainingFrames > 0) {
1122
1123        Buffer audioBuffer;
1124        audioBuffer.frameCount = mRemainingFrames;
1125        size_t nonContig;
1126        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1127        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1128                "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
1129        requested = &ClientProxy::kNonBlocking;
1130        size_t avail = audioBuffer.frameCount + nonContig;
1131        ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
1132                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
1133        if (err != NO_ERROR) {
1134            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
1135                break;
1136            }
1137            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1138            return NS_NEVER;
1139        }
1140
1141        if (mRetryOnPartialBuffer) {
1142            mRetryOnPartialBuffer = false;
1143            if (avail < mRemainingFrames) {
1144                int64_t myns = ((mRemainingFrames - avail) *
1145                        1100000000LL) / mSampleRate;
1146                if (ns < 0 || myns < ns) {
1147                    ns = myns;
1148                }
1149                return ns;
1150            }
1151        }
1152
1153        size_t reqSize = audioBuffer.size;
1154        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1155        size_t readSize = audioBuffer.size;
1156
1157        // Sanity check on returned size
1158        if (ssize_t(readSize) < 0 || readSize > reqSize) {
1159            ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1160                    reqSize, ssize_t(readSize));
1161            return NS_NEVER;
1162        }
1163
1164        if (readSize == 0) {
1165            // The callback is done consuming buffers
1166            // Keep this thread going to handle timed events and
1167            // still try to provide more data in intervals of WAIT_PERIOD_MS
1168            // but don't just loop and block the CPU, so wait
1169            return WAIT_PERIOD_MS * 1000000LL;
1170        }
1171
1172        size_t releasedFrames = readSize / mFrameSize;
1173        audioBuffer.frameCount = releasedFrames;
1174        mRemainingFrames -= releasedFrames;
1175        if (misalignment >= releasedFrames) {
1176            misalignment -= releasedFrames;
1177        } else {
1178            misalignment = 0;
1179        }
1180
1181        releaseBuffer(&audioBuffer);
1182        readFrames += releasedFrames;
1183
1184        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1185        // if callback doesn't like to accept the full chunk
1186        if (readSize < reqSize) {
1187            continue;
1188        }
1189
1190        // There could be enough non-contiguous frames available to satisfy the remaining request
1191        if (mRemainingFrames <= nonContig) {
1192            continue;
1193        }
1194
1195#if 0
1196        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1197        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
1198        // that total to a sum == notificationFrames.
1199        if (0 < misalignment && misalignment <= mRemainingFrames) {
1200            mRemainingFrames = misalignment;
1201            return (mRemainingFrames * 1100000000LL) / mSampleRate;
1202        }
1203#endif
1204
1205    }
1206    if (readFrames > 0) {
1207        AutoMutex lock(mLock);
1208        mFramesRead += readFrames;
1209        // mFramesReadTime = systemTime(SYSTEM_TIME_MONOTONIC); // not provided at this time.
1210    }
1211    mRemainingFrames = notificationFrames;
1212    mRetryOnPartialBuffer = true;
1213
1214    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1215    return 0;
1216}
1217
1218status_t AudioRecord::restoreRecord_l(const char *from)
1219{
1220    ALOGW("dead IAudioRecord, creating a new one from %s()", from);
1221    ++mSequence;
1222
1223    mFlags = mOrigFlags;
1224
1225    // if the new IAudioRecord is created, openRecord_l() will modify the
1226    // following member variables: mAudioRecord, mCblkMemory, mCblk, mBufferMemory.
1227    // It will also delete the strong references on previous IAudioRecord and IMemory
1228    Modulo<uint32_t> position(mProxy->getPosition());
1229    mNewPosition = position + mUpdatePeriod;
1230    status_t result = openRecord_l(position, mOpPackageName);
1231    if (result == NO_ERROR) {
1232        if (mActive) {
1233            // callback thread or sync event hasn't changed
1234            // FIXME this fails if we have a new AudioFlinger instance
1235            result = mAudioRecord->start(
1236                AudioSystem::SYNC_EVENT_SAME, AUDIO_SESSION_NONE).transactionError();
1237        }
1238        mFramesReadServerOffset = mFramesRead; // server resets to zero so we need an offset.
1239    }
1240    if (result != NO_ERROR) {
1241        ALOGW("restoreRecord_l() failed status %d", result);
1242        mActive = false;
1243    }
1244
1245    return result;
1246}
1247
1248status_t AudioRecord::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
1249{
1250    if (callback == 0) {
1251        ALOGW("%s adding NULL callback!", __FUNCTION__);
1252        return BAD_VALUE;
1253    }
1254    AutoMutex lock(mLock);
1255    if (mDeviceCallback.unsafe_get() == callback.get()) {
1256        ALOGW("%s adding same callback!", __FUNCTION__);
1257        return INVALID_OPERATION;
1258    }
1259    status_t status = NO_ERROR;
1260    if (mInput != AUDIO_IO_HANDLE_NONE) {
1261        if (mDeviceCallback != 0) {
1262            ALOGW("%s callback already present!", __FUNCTION__);
1263            AudioSystem::removeAudioDeviceCallback(this, mInput);
1264        }
1265        status = AudioSystem::addAudioDeviceCallback(this, mInput);
1266    }
1267    mDeviceCallback = callback;
1268    return status;
1269}
1270
1271status_t AudioRecord::removeAudioDeviceCallback(
1272        const sp<AudioSystem::AudioDeviceCallback>& callback)
1273{
1274    if (callback == 0) {
1275        ALOGW("%s removing NULL callback!", __FUNCTION__);
1276        return BAD_VALUE;
1277    }
1278    AutoMutex lock(mLock);
1279    if (mDeviceCallback.unsafe_get() != callback.get()) {
1280        ALOGW("%s removing different callback!", __FUNCTION__);
1281        return INVALID_OPERATION;
1282    }
1283    mDeviceCallback.clear();
1284    if (mInput != AUDIO_IO_HANDLE_NONE) {
1285        AudioSystem::removeAudioDeviceCallback(this, mInput);
1286    }
1287    return NO_ERROR;
1288}
1289
1290void AudioRecord::onAudioDeviceUpdate(audio_io_handle_t audioIo,
1291                                 audio_port_handle_t deviceId)
1292{
1293    sp<AudioSystem::AudioDeviceCallback> callback;
1294    {
1295        AutoMutex lock(mLock);
1296        if (audioIo != mInput) {
1297            return;
1298        }
1299        callback = mDeviceCallback.promote();
1300        // only update device if the record is active as route changes due to other use cases are
1301        // irrelevant for this client
1302        if (mActive) {
1303            mRoutedDeviceId = deviceId;
1304        }
1305    }
1306    if (callback.get() != nullptr) {
1307        callback->onAudioDeviceUpdate(mInput, mRoutedDeviceId);
1308    }
1309}
1310
1311// =========================================================================
1312
1313void AudioRecord::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
1314{
1315    sp<AudioRecord> audioRecord = mAudioRecord.promote();
1316    if (audioRecord != 0) {
1317        AutoMutex lock(audioRecord->mLock);
1318        audioRecord->mProxy->binderDied();
1319    }
1320}
1321
1322// =========================================================================
1323
1324AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver, bool bCanCallJava)
1325    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
1326      mIgnoreNextPausedInt(false)
1327{
1328}
1329
1330AudioRecord::AudioRecordThread::~AudioRecordThread()
1331{
1332}
1333
1334bool AudioRecord::AudioRecordThread::threadLoop()
1335{
1336    {
1337        AutoMutex _l(mMyLock);
1338        if (mPaused) {
1339            // TODO check return value and handle or log
1340            mMyCond.wait(mMyLock);
1341            // caller will check for exitPending()
1342            return true;
1343        }
1344        if (mIgnoreNextPausedInt) {
1345            mIgnoreNextPausedInt = false;
1346            mPausedInt = false;
1347        }
1348        if (mPausedInt) {
1349            if (mPausedNs > 0) {
1350                // TODO check return value and handle or log
1351                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1352            } else {
1353                // TODO check return value and handle or log
1354                mMyCond.wait(mMyLock);
1355            }
1356            mPausedInt = false;
1357            return true;
1358        }
1359    }
1360    if (exitPending()) {
1361        return false;
1362    }
1363    nsecs_t ns =  mReceiver.processAudioBuffer();
1364    switch (ns) {
1365    case 0:
1366        return true;
1367    case NS_INACTIVE:
1368        pauseInternal();
1369        return true;
1370    case NS_NEVER:
1371        return false;
1372    case NS_WHENEVER:
1373        // Event driven: call wake() when callback notifications conditions change.
1374        ns = INT64_MAX;
1375        // fall through
1376    default:
1377        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
1378        pauseInternal(ns);
1379        return true;
1380    }
1381}
1382
1383void AudioRecord::AudioRecordThread::requestExit()
1384{
1385    // must be in this order to avoid a race condition
1386    Thread::requestExit();
1387    resume();
1388}
1389
1390void AudioRecord::AudioRecordThread::pause()
1391{
1392    AutoMutex _l(mMyLock);
1393    mPaused = true;
1394}
1395
1396void AudioRecord::AudioRecordThread::resume()
1397{
1398    AutoMutex _l(mMyLock);
1399    mIgnoreNextPausedInt = true;
1400    if (mPaused || mPausedInt) {
1401        mPaused = false;
1402        mPausedInt = false;
1403        mMyCond.signal();
1404    }
1405}
1406
1407void AudioRecord::AudioRecordThread::wake()
1408{
1409    AutoMutex _l(mMyLock);
1410    if (!mPaused) {
1411        // wake() might be called while servicing a callback - ignore the next
1412        // pause time and call processAudioBuffer.
1413        mIgnoreNextPausedInt = true;
1414        if (mPausedInt && mPausedNs > 0) {
1415            // audio record is active and internally paused with timeout.
1416            mPausedInt = false;
1417            mMyCond.signal();
1418        }
1419    }
1420}
1421
1422void AudioRecord::AudioRecordThread::pauseInternal(nsecs_t ns)
1423{
1424    AutoMutex _l(mMyLock);
1425    mPausedInt = true;
1426    mPausedNs = ns;
1427}
1428
1429// -------------------------------------------------------------------------
1430
1431} // namespace android
1432