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