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