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