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