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