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