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