AudioRecord.cpp revision 382d11ac489a917d3d009c3d05bc960f4af58176
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        // stop capture so that audio policy manager does not reject the new instance start request
485        // as only one capture can be active at a time.
486        if (mAudioRecord != 0 && mActive) {
487            mAudioRecord->stop();
488        }
489        android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
490    }
491    return NO_ERROR;
492}
493
494audio_port_handle_t AudioRecord::getInputDevice() {
495    AutoMutex lock(mLock);
496    return mSelectedDeviceId;
497}
498
499audio_port_handle_t AudioRecord::getRoutedDeviceId() {
500    AutoMutex lock(mLock);
501    if (mInput == AUDIO_IO_HANDLE_NONE) {
502        return AUDIO_PORT_HANDLE_NONE;
503    }
504    return AudioSystem::getDeviceIdForIo(mInput);
505}
506
507// -------------------------------------------------------------------------
508
509// must be called with mLock held
510status_t AudioRecord::openRecord_l(const Modulo<uint32_t> &epoch, const String16& opPackageName)
511{
512    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
513    if (audioFlinger == 0) {
514        ALOGE("Could not get audioflinger");
515        return NO_INIT;
516    }
517
518    if (mDeviceCallback != 0 && mInput != AUDIO_IO_HANDLE_NONE) {
519        AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mInput);
520    }
521    audio_io_handle_t input;
522
523    // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
524    // After fast request is denied, we will request again if IAudioRecord is re-created.
525
526    status_t status;
527
528    // Not a conventional loop, but a retry loop for at most two iterations total.
529    // Try first maybe with FAST flag then try again without FAST flag if that fails.
530    // Exits loop normally via a return at the bottom, or with error via a break.
531    // The sp<> references will be dropped when re-entering scope.
532    // The lack of indentation is deliberate, to reduce code churn and ease merges.
533    for (;;) {
534    audio_config_base_t config  = {
535            .sample_rate = mSampleRate,
536            .channel_mask = mChannelMask,
537            .format = mFormat
538        };
539    status = AudioSystem::getInputForAttr(&mAttributes, &input,
540                                        mSessionId,
541                                        // FIXME compare to AudioTrack
542                                        mClientPid,
543                                        mClientUid,
544                                        &config,
545                                        mFlags, mSelectedDeviceId, &mPortId);
546
547    if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE) {
548        ALOGE("Could not get audio input for session %d, record source %d, sample rate %u, "
549              "format %#x, channel mask %#x, flags %#x",
550              mSessionId, mAttributes.source, mSampleRate, mFormat, mChannelMask, mFlags);
551        return BAD_VALUE;
552    }
553
554    // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
555    // we must release it ourselves if anything goes wrong.
556
557#if 0
558    size_t afFrameCount;
559    status = AudioSystem::getFrameCount(input, &afFrameCount);
560    if (status != NO_ERROR) {
561        ALOGE("getFrameCount(input=%d) status %d", input, status);
562        break;
563    }
564#endif
565
566    uint32_t afSampleRate;
567    status = AudioSystem::getSamplingRate(input, &afSampleRate);
568    if (status != NO_ERROR) {
569        ALOGE("getSamplingRate(input=%d) status %d", input, status);
570        break;
571    }
572    if (mSampleRate == 0) {
573        mSampleRate = afSampleRate;
574    }
575
576    // Client can only express a preference for FAST.  Server will perform additional tests.
577    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
578        bool useCaseAllowed =
579            // any of these use cases:
580            // use case 1: callback transfer mode
581            (mTransfer == TRANSFER_CALLBACK) ||
582            // use case 2: blocking read mode
583            // The default buffer capacity at 48 kHz is 2048 frames, or ~42.6 ms.
584            // That's enough for double-buffering with our standard 20 ms rule of thumb for
585            // the minimum period of a non-SCHED_FIFO thread.
586            // This is needed so that AAudio apps can do a low latency non-blocking read from a
587            // callback running with SCHED_FIFO.
588            (mTransfer == TRANSFER_SYNC) ||
589            // use case 3: obtain/release mode
590            (mTransfer == TRANSFER_OBTAIN);
591        // sample rates must also match
592        bool fastAllowed = useCaseAllowed && (mSampleRate == afSampleRate);
593        if (!fastAllowed) {
594            ALOGW("AUDIO_INPUT_FLAG_FAST denied by client; transfer %d, "
595                "track %u Hz, input %u Hz",
596                mTransfer, mSampleRate, afSampleRate);
597            mFlags = (audio_input_flags_t) (mFlags & ~(AUDIO_INPUT_FLAG_FAST |
598                    AUDIO_INPUT_FLAG_RAW));
599            AudioSystem::releaseInput(input, mSessionId);
600            continue;   // retry
601        }
602    }
603
604    // The notification frame count is the period between callbacks, as suggested by the client
605    // but moderated by the server.  For record, the calculations are done entirely on server side.
606    size_t notificationFrames = mNotificationFramesReq;
607    size_t frameCount = mReqFrameCount;
608
609    audio_input_flags_t flags = mFlags;
610
611    pid_t tid = -1;
612    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
613        if (mAudioRecordThread != 0) {
614            tid = mAudioRecordThread->getTid();
615        }
616    }
617
618    size_t temp = frameCount;   // temp may be replaced by a revised value of frameCount,
619                                // but we will still need the original value also
620    audio_session_t originalSessionId = mSessionId;
621
622    sp<IMemory> iMem;           // for cblk
623    sp<IMemory> bufferMem;
624    sp<IAudioRecord> record = audioFlinger->openRecord(input,
625                                                       mSampleRate,
626                                                       mFormat,
627                                                       mChannelMask,
628                                                       opPackageName,
629                                                       &temp,
630                                                       &flags,
631                                                       mClientPid,
632                                                       tid,
633                                                       mClientUid,
634                                                       &mSessionId,
635                                                       &notificationFrames,
636                                                       iMem,
637                                                       bufferMem,
638                                                       &status,
639                                                       mPortId);
640    ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
641            "session ID changed from %d to %d", originalSessionId, mSessionId);
642
643    if (status != NO_ERROR) {
644        ALOGE("AudioFlinger could not create record track, status: %d", status);
645        break;
646    }
647    ALOG_ASSERT(record != 0);
648
649    // AudioFlinger now owns the reference to the I/O handle,
650    // so we are no longer responsible for releasing it.
651
652    mAwaitBoost = false;
653    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
654        if (flags & AUDIO_INPUT_FLAG_FAST) {
655            ALOGI("AUDIO_INPUT_FLAG_FAST successful; frameCount %zu -> %zu", frameCount, temp);
656            mAwaitBoost = true;
657        } else {
658            ALOGW("AUDIO_INPUT_FLAG_FAST denied by server; frameCount %zu -> %zu", frameCount, temp);
659            mFlags = (audio_input_flags_t) (mFlags & ~(AUDIO_INPUT_FLAG_FAST |
660                    AUDIO_INPUT_FLAG_RAW));
661            continue;   // retry
662        }
663    }
664    mFlags = flags;
665
666    if (iMem == 0) {
667        ALOGE("Could not get control block");
668        return NO_INIT;
669    }
670    void *iMemPointer = iMem->pointer();
671    if (iMemPointer == NULL) {
672        ALOGE("Could not get control block pointer");
673        return NO_INIT;
674    }
675    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
676
677    // Starting address of buffers in shared memory.
678    // The buffers are either immediately after the control block,
679    // or in a separate area at discretion of server.
680    void *buffers;
681    if (bufferMem == 0) {
682        buffers = cblk + 1;
683    } else {
684        buffers = bufferMem->pointer();
685        if (buffers == NULL) {
686            ALOGE("Could not get buffer pointer");
687            return NO_INIT;
688        }
689    }
690
691    // invariant that mAudioRecord != 0 is true only after set() returns successfully
692    if (mAudioRecord != 0) {
693        IInterface::asBinder(mAudioRecord)->unlinkToDeath(mDeathNotifier, this);
694        mDeathNotifier.clear();
695    }
696    mAudioRecord = record;
697    mCblkMemory = iMem;
698    mBufferMemory = bufferMem;
699    IPCThreadState::self()->flushCommands();
700
701    mCblk = cblk;
702    // note that temp is the (possibly revised) value of frameCount
703    if (temp < frameCount || (frameCount == 0 && temp == 0)) {
704        ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
705    }
706    frameCount = temp;
707
708    // Make sure that application is notified with sufficient margin before overrun.
709    // The computation is done on server side.
710    if (mNotificationFramesReq > 0 && notificationFrames != mNotificationFramesReq) {
711        ALOGW("Server adjusted notificationFrames from %u to %zu for frameCount %zu",
712                mNotificationFramesReq, notificationFrames, frameCount);
713    }
714    mNotificationFramesAct = (uint32_t) notificationFrames;
715
716    // We retain a copy of the I/O handle, but don't own the reference
717    mInput = input;
718    mRefreshRemaining = true;
719
720    mFrameCount = frameCount;
721    // If IAudioRecord is re-created, don't let the requested frameCount
722    // decrease.  This can confuse clients that cache frameCount().
723    if (frameCount > mReqFrameCount) {
724        mReqFrameCount = frameCount;
725    }
726
727    // update proxy
728    mProxy = new AudioRecordClientProxy(cblk, buffers, mFrameCount, mFrameSize);
729    mProxy->setEpoch(epoch);
730    mProxy->setMinimum(mNotificationFramesAct);
731
732    mDeathNotifier = new DeathNotifier(this);
733    IInterface::asBinder(mAudioRecord)->linkToDeath(mDeathNotifier, this);
734
735    if (mDeviceCallback != 0) {
736        AudioSystem::addAudioDeviceCallback(mDeviceCallback, mInput);
737    }
738
739    return NO_ERROR;
740
741    // End of retry loop.
742    // The lack of indentation is deliberate, to reduce code churn and ease merges.
743    }
744
745// Arrive here on error, via a break
746    AudioSystem::releaseInput(input, mSessionId);
747    if (status == NO_ERROR) {
748        status = NO_INIT;
749    }
750    return status;
751}
752
753status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
754{
755    if (audioBuffer == NULL) {
756        if (nonContig != NULL) {
757            *nonContig = 0;
758        }
759        return BAD_VALUE;
760    }
761    if (mTransfer != TRANSFER_OBTAIN) {
762        audioBuffer->frameCount = 0;
763        audioBuffer->size = 0;
764        audioBuffer->raw = NULL;
765        if (nonContig != NULL) {
766            *nonContig = 0;
767        }
768        return INVALID_OPERATION;
769    }
770
771    const struct timespec *requested;
772    struct timespec timeout;
773    if (waitCount == -1) {
774        requested = &ClientProxy::kForever;
775    } else if (waitCount == 0) {
776        requested = &ClientProxy::kNonBlocking;
777    } else if (waitCount > 0) {
778        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
779        timeout.tv_sec = ms / 1000;
780        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
781        requested = &timeout;
782    } else {
783        ALOGE("%s invalid waitCount %d", __func__, waitCount);
784        requested = NULL;
785    }
786    return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
787}
788
789status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
790        struct timespec *elapsed, size_t *nonContig)
791{
792    // previous and new IAudioRecord sequence numbers are used to detect track re-creation
793    uint32_t oldSequence = 0;
794    uint32_t newSequence;
795
796    Proxy::Buffer buffer;
797    status_t status = NO_ERROR;
798
799    static const int32_t kMaxTries = 5;
800    int32_t tryCounter = kMaxTries;
801
802    do {
803        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
804        // keep them from going away if another thread re-creates the track during obtainBuffer()
805        sp<AudioRecordClientProxy> proxy;
806        sp<IMemory> iMem;
807        sp<IMemory> bufferMem;
808        {
809            // start of lock scope
810            AutoMutex lock(mLock);
811
812            newSequence = mSequence;
813            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
814            if (status == DEAD_OBJECT) {
815                // re-create track, unless someone else has already done so
816                if (newSequence == oldSequence) {
817                    status = restoreRecord_l("obtainBuffer");
818                    if (status != NO_ERROR) {
819                        buffer.mFrameCount = 0;
820                        buffer.mRaw = NULL;
821                        buffer.mNonContig = 0;
822                        break;
823                    }
824                }
825            }
826            oldSequence = newSequence;
827
828            // Keep the extra references
829            proxy = mProxy;
830            iMem = mCblkMemory;
831            bufferMem = mBufferMemory;
832
833            // Non-blocking if track is stopped
834            if (!mActive) {
835                requested = &ClientProxy::kNonBlocking;
836            }
837
838        }   // end of lock scope
839
840        buffer.mFrameCount = audioBuffer->frameCount;
841        // FIXME starts the requested timeout and elapsed over from scratch
842        status = proxy->obtainBuffer(&buffer, requested, elapsed);
843
844    } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
845
846    audioBuffer->frameCount = buffer.mFrameCount;
847    audioBuffer->size = buffer.mFrameCount * mFrameSize;
848    audioBuffer->raw = buffer.mRaw;
849    if (nonContig != NULL) {
850        *nonContig = buffer.mNonContig;
851    }
852    return status;
853}
854
855void AudioRecord::releaseBuffer(const Buffer* audioBuffer)
856{
857    // FIXME add error checking on mode, by adding an internal version
858
859    size_t stepCount = audioBuffer->size / mFrameSize;
860    if (stepCount == 0) {
861        return;
862    }
863
864    Proxy::Buffer buffer;
865    buffer.mFrameCount = stepCount;
866    buffer.mRaw = audioBuffer->raw;
867
868    AutoMutex lock(mLock);
869    mInOverrun = false;
870    mProxy->releaseBuffer(&buffer);
871
872    // the server does not automatically disable recorder on overrun, so no need to restart
873}
874
875audio_io_handle_t AudioRecord::getInputPrivate() const
876{
877    AutoMutex lock(mLock);
878    return mInput;
879}
880
881// -------------------------------------------------------------------------
882
883ssize_t AudioRecord::read(void* buffer, size_t userSize, bool blocking)
884{
885    if (mTransfer != TRANSFER_SYNC) {
886        return INVALID_OPERATION;
887    }
888
889    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
890        // sanity-check. user is most-likely passing an error code, and it would
891        // make the return value ambiguous (actualSize vs error).
892        ALOGE("AudioRecord::read(buffer=%p, size=%zu (%zu)", buffer, userSize, userSize);
893        return BAD_VALUE;
894    }
895
896    ssize_t read = 0;
897    Buffer audioBuffer;
898
899    while (userSize >= mFrameSize) {
900        audioBuffer.frameCount = userSize / mFrameSize;
901
902        status_t err = obtainBuffer(&audioBuffer,
903                blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
904        if (err < 0) {
905            if (read > 0) {
906                break;
907            }
908            if (err == TIMED_OUT || err == -EINTR) {
909                err = WOULD_BLOCK;
910            }
911            return ssize_t(err);
912        }
913
914        size_t bytesRead = audioBuffer.size;
915        memcpy(buffer, audioBuffer.i8, bytesRead);
916        buffer = ((char *) buffer) + bytesRead;
917        userSize -= bytesRead;
918        read += bytesRead;
919
920        releaseBuffer(&audioBuffer);
921    }
922    if (read > 0) {
923        mFramesRead += read / mFrameSize;
924        // mFramesReadTime = systemTime(SYSTEM_TIME_MONOTONIC); // not provided at this time.
925    }
926    return read;
927}
928
929// -------------------------------------------------------------------------
930
931nsecs_t AudioRecord::processAudioBuffer()
932{
933    mLock.lock();
934    if (mAwaitBoost) {
935        mAwaitBoost = false;
936        mLock.unlock();
937        static const int32_t kMaxTries = 5;
938        int32_t tryCounter = kMaxTries;
939        uint32_t pollUs = 10000;
940        do {
941            int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
942            if (policy == SCHED_FIFO || policy == SCHED_RR) {
943                break;
944            }
945            usleep(pollUs);
946            pollUs <<= 1;
947        } while (tryCounter-- > 0);
948        if (tryCounter < 0) {
949            ALOGE("did not receive expected priority boost on time");
950        }
951        // Run again immediately
952        return 0;
953    }
954
955    // Can only reference mCblk while locked
956    int32_t flags = android_atomic_and(~CBLK_OVERRUN, &mCblk->mFlags);
957
958    // Check for track invalidation
959    if (flags & CBLK_INVALID) {
960        (void) restoreRecord_l("processAudioBuffer");
961        mLock.unlock();
962        // Run again immediately, but with a new IAudioRecord
963        return 0;
964    }
965
966    bool active = mActive;
967
968    // Manage overrun callback, must be done under lock to avoid race with releaseBuffer()
969    bool newOverrun = false;
970    if (flags & CBLK_OVERRUN) {
971        if (!mInOverrun) {
972            mInOverrun = true;
973            newOverrun = true;
974        }
975    }
976
977    // Get current position of server
978    Modulo<uint32_t> position(mProxy->getPosition());
979
980    // Manage marker callback
981    bool markerReached = false;
982    Modulo<uint32_t> markerPosition(mMarkerPosition);
983    // FIXME fails for wraparound, need 64 bits
984    if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
985        mMarkerReached = markerReached = true;
986    }
987
988    // Determine the number of new position callback(s) that will be needed, while locked
989    size_t newPosCount = 0;
990    Modulo<uint32_t> newPosition(mNewPosition);
991    uint32_t updatePeriod = mUpdatePeriod;
992    // FIXME fails for wraparound, need 64 bits
993    if (updatePeriod > 0 && position >= newPosition) {
994        newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
995        mNewPosition += updatePeriod * newPosCount;
996    }
997
998    // Cache other fields that will be needed soon
999    uint32_t notificationFrames = mNotificationFramesAct;
1000    if (mRefreshRemaining) {
1001        mRefreshRemaining = false;
1002        mRemainingFrames = notificationFrames;
1003        mRetryOnPartialBuffer = false;
1004    }
1005    size_t misalignment = mProxy->getMisalignment();
1006    uint32_t sequence = mSequence;
1007
1008    // These fields don't need to be cached, because they are assigned only by set():
1009    //      mTransfer, mCbf, mUserData, mSampleRate, mFrameSize
1010
1011    mLock.unlock();
1012
1013    // perform callbacks while unlocked
1014    if (newOverrun) {
1015        mCbf(EVENT_OVERRUN, mUserData, NULL);
1016    }
1017    if (markerReached) {
1018        mCbf(EVENT_MARKER, mUserData, &markerPosition);
1019    }
1020    while (newPosCount > 0) {
1021        size_t temp = newPosition.value(); // FIXME size_t != uint32_t
1022        mCbf(EVENT_NEW_POS, mUserData, &temp);
1023        newPosition += updatePeriod;
1024        newPosCount--;
1025    }
1026    if (mObservedSequence != sequence) {
1027        mObservedSequence = sequence;
1028        mCbf(EVENT_NEW_IAUDIORECORD, mUserData, NULL);
1029    }
1030
1031    // if inactive, then don't run me again until re-started
1032    if (!active) {
1033        return NS_INACTIVE;
1034    }
1035
1036    // Compute the estimated time until the next timed event (position, markers)
1037    uint32_t minFrames = ~0;
1038    if (!markerReached && position < markerPosition) {
1039        minFrames = (markerPosition - position).value();
1040    }
1041    if (updatePeriod > 0) {
1042        uint32_t remaining = (newPosition - position).value();
1043        if (remaining < minFrames) {
1044            minFrames = remaining;
1045        }
1046    }
1047
1048    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
1049    static const uint32_t kPoll = 0;
1050    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1051        minFrames = kPoll * notificationFrames;
1052    }
1053
1054    // Convert frame units to time units
1055    nsecs_t ns = NS_WHENEVER;
1056    if (minFrames != (uint32_t) ~0) {
1057        // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1058        static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1059        ns = ((minFrames * 1000000000LL) / mSampleRate) + kFudgeNs;
1060    }
1061
1062    // If not supplying data by EVENT_MORE_DATA, then we're done
1063    if (mTransfer != TRANSFER_CALLBACK) {
1064        return ns;
1065    }
1066
1067    struct timespec timeout;
1068    const struct timespec *requested = &ClientProxy::kForever;
1069    if (ns != NS_WHENEVER) {
1070        timeout.tv_sec = ns / 1000000000LL;
1071        timeout.tv_nsec = ns % 1000000000LL;
1072        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1073        requested = &timeout;
1074    }
1075
1076    size_t readFrames = 0;
1077    while (mRemainingFrames > 0) {
1078
1079        Buffer audioBuffer;
1080        audioBuffer.frameCount = mRemainingFrames;
1081        size_t nonContig;
1082        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1083        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1084                "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
1085        requested = &ClientProxy::kNonBlocking;
1086        size_t avail = audioBuffer.frameCount + nonContig;
1087        ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
1088                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
1089        if (err != NO_ERROR) {
1090            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
1091                break;
1092            }
1093            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1094            return NS_NEVER;
1095        }
1096
1097        if (mRetryOnPartialBuffer) {
1098            mRetryOnPartialBuffer = false;
1099            if (avail < mRemainingFrames) {
1100                int64_t myns = ((mRemainingFrames - avail) *
1101                        1100000000LL) / mSampleRate;
1102                if (ns < 0 || myns < ns) {
1103                    ns = myns;
1104                }
1105                return ns;
1106            }
1107        }
1108
1109        size_t reqSize = audioBuffer.size;
1110        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1111        size_t readSize = audioBuffer.size;
1112
1113        // Sanity check on returned size
1114        if (ssize_t(readSize) < 0 || readSize > reqSize) {
1115            ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1116                    reqSize, ssize_t(readSize));
1117            return NS_NEVER;
1118        }
1119
1120        if (readSize == 0) {
1121            // The callback is done consuming buffers
1122            // Keep this thread going to handle timed events and
1123            // still try to provide more data in intervals of WAIT_PERIOD_MS
1124            // but don't just loop and block the CPU, so wait
1125            return WAIT_PERIOD_MS * 1000000LL;
1126        }
1127
1128        size_t releasedFrames = readSize / mFrameSize;
1129        audioBuffer.frameCount = releasedFrames;
1130        mRemainingFrames -= releasedFrames;
1131        if (misalignment >= releasedFrames) {
1132            misalignment -= releasedFrames;
1133        } else {
1134            misalignment = 0;
1135        }
1136
1137        releaseBuffer(&audioBuffer);
1138        readFrames += releasedFrames;
1139
1140        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1141        // if callback doesn't like to accept the full chunk
1142        if (readSize < reqSize) {
1143            continue;
1144        }
1145
1146        // There could be enough non-contiguous frames available to satisfy the remaining request
1147        if (mRemainingFrames <= nonContig) {
1148            continue;
1149        }
1150
1151#if 0
1152        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1153        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
1154        // that total to a sum == notificationFrames.
1155        if (0 < misalignment && misalignment <= mRemainingFrames) {
1156            mRemainingFrames = misalignment;
1157            return (mRemainingFrames * 1100000000LL) / mSampleRate;
1158        }
1159#endif
1160
1161    }
1162    if (readFrames > 0) {
1163        AutoMutex lock(mLock);
1164        mFramesRead += readFrames;
1165        // mFramesReadTime = systemTime(SYSTEM_TIME_MONOTONIC); // not provided at this time.
1166    }
1167    mRemainingFrames = notificationFrames;
1168    mRetryOnPartialBuffer = true;
1169
1170    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1171    return 0;
1172}
1173
1174status_t AudioRecord::restoreRecord_l(const char *from)
1175{
1176    ALOGW("dead IAudioRecord, creating a new one from %s()", from);
1177    ++mSequence;
1178
1179    mFlags = mOrigFlags;
1180
1181    // if the new IAudioRecord is created, openRecord_l() will modify the
1182    // following member variables: mAudioRecord, mCblkMemory, mCblk, mBufferMemory.
1183    // It will also delete the strong references on previous IAudioRecord and IMemory
1184    Modulo<uint32_t> position(mProxy->getPosition());
1185    mNewPosition = position + mUpdatePeriod;
1186    status_t result = openRecord_l(position, mOpPackageName);
1187    if (result == NO_ERROR) {
1188        if (mActive) {
1189            // callback thread or sync event hasn't changed
1190            // FIXME this fails if we have a new AudioFlinger instance
1191            result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, AUDIO_SESSION_NONE);
1192        }
1193        mFramesReadServerOffset = mFramesRead; // server resets to zero so we need an offset.
1194    }
1195    if (result != NO_ERROR) {
1196        ALOGW("restoreRecord_l() failed status %d", result);
1197        mActive = false;
1198    }
1199
1200    return result;
1201}
1202
1203status_t AudioRecord::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
1204{
1205    if (callback == 0) {
1206        ALOGW("%s adding NULL callback!", __FUNCTION__);
1207        return BAD_VALUE;
1208    }
1209    AutoMutex lock(mLock);
1210    if (mDeviceCallback == callback) {
1211        ALOGW("%s adding same callback!", __FUNCTION__);
1212        return INVALID_OPERATION;
1213    }
1214    status_t status = NO_ERROR;
1215    if (mInput != AUDIO_IO_HANDLE_NONE) {
1216        if (mDeviceCallback != 0) {
1217            ALOGW("%s callback already present!", __FUNCTION__);
1218            AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mInput);
1219        }
1220        status = AudioSystem::addAudioDeviceCallback(callback, mInput);
1221    }
1222    mDeviceCallback = callback;
1223    return status;
1224}
1225
1226status_t AudioRecord::removeAudioDeviceCallback(
1227        const sp<AudioSystem::AudioDeviceCallback>& callback)
1228{
1229    if (callback == 0) {
1230        ALOGW("%s removing NULL callback!", __FUNCTION__);
1231        return BAD_VALUE;
1232    }
1233    AutoMutex lock(mLock);
1234    if (mDeviceCallback != callback) {
1235        ALOGW("%s removing different callback!", __FUNCTION__);
1236        return INVALID_OPERATION;
1237    }
1238    if (mInput != AUDIO_IO_HANDLE_NONE) {
1239        AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mInput);
1240    }
1241    mDeviceCallback = 0;
1242    return NO_ERROR;
1243}
1244
1245// =========================================================================
1246
1247void AudioRecord::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
1248{
1249    sp<AudioRecord> audioRecord = mAudioRecord.promote();
1250    if (audioRecord != 0) {
1251        AutoMutex lock(audioRecord->mLock);
1252        audioRecord->mProxy->binderDied();
1253    }
1254}
1255
1256// =========================================================================
1257
1258AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver, bool bCanCallJava)
1259    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
1260      mIgnoreNextPausedInt(false)
1261{
1262}
1263
1264AudioRecord::AudioRecordThread::~AudioRecordThread()
1265{
1266}
1267
1268bool AudioRecord::AudioRecordThread::threadLoop()
1269{
1270    {
1271        AutoMutex _l(mMyLock);
1272        if (mPaused) {
1273            mMyCond.wait(mMyLock);
1274            // caller will check for exitPending()
1275            return true;
1276        }
1277        if (mIgnoreNextPausedInt) {
1278            mIgnoreNextPausedInt = false;
1279            mPausedInt = false;
1280        }
1281        if (mPausedInt) {
1282            if (mPausedNs > 0) {
1283                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1284            } else {
1285                mMyCond.wait(mMyLock);
1286            }
1287            mPausedInt = false;
1288            return true;
1289        }
1290    }
1291    if (exitPending()) {
1292        return false;
1293    }
1294    nsecs_t ns =  mReceiver.processAudioBuffer();
1295    switch (ns) {
1296    case 0:
1297        return true;
1298    case NS_INACTIVE:
1299        pauseInternal();
1300        return true;
1301    case NS_NEVER:
1302        return false;
1303    case NS_WHENEVER:
1304        // Event driven: call wake() when callback notifications conditions change.
1305        ns = INT64_MAX;
1306        // fall through
1307    default:
1308        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
1309        pauseInternal(ns);
1310        return true;
1311    }
1312}
1313
1314void AudioRecord::AudioRecordThread::requestExit()
1315{
1316    // must be in this order to avoid a race condition
1317    Thread::requestExit();
1318    resume();
1319}
1320
1321void AudioRecord::AudioRecordThread::pause()
1322{
1323    AutoMutex _l(mMyLock);
1324    mPaused = true;
1325}
1326
1327void AudioRecord::AudioRecordThread::resume()
1328{
1329    AutoMutex _l(mMyLock);
1330    mIgnoreNextPausedInt = true;
1331    if (mPaused || mPausedInt) {
1332        mPaused = false;
1333        mPausedInt = false;
1334        mMyCond.signal();
1335    }
1336}
1337
1338void AudioRecord::AudioRecordThread::wake()
1339{
1340    AutoMutex _l(mMyLock);
1341    if (!mPaused) {
1342        // wake() might be called while servicing a callback - ignore the next
1343        // pause time and call processAudioBuffer.
1344        mIgnoreNextPausedInt = true;
1345        if (mPausedInt && mPausedNs > 0) {
1346            // audio record is active and internally paused with timeout.
1347            mPausedInt = false;
1348            mMyCond.signal();
1349        }
1350    }
1351}
1352
1353void AudioRecord::AudioRecordThread::pauseInternal(nsecs_t ns)
1354{
1355    AutoMutex _l(mMyLock);
1356    mPausedInt = true;
1357    mPausedNs = ns;
1358}
1359
1360// -------------------------------------------------------------------------
1361
1362} // namespace android
1363