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