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