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