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