AudioRecord.cpp revision 33f3177c08d238285b296d137e527ec99e34228f
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, mFlags, 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_input_flags_t flags,
439        audio_io_handle_t input,
440        size_t epoch)
441{
442    status_t status;
443    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
444    if (audioFlinger == 0) {
445        ALOGE("Could not get audioflinger");
446        return NO_INIT;
447    }
448
449    IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
450    pid_t tid = -1;
451
452    // Client can only express a preference for FAST.  Server will perform additional tests.
453    // The only supported use case for FAST is callback transfer mode.
454    if (flags & AUDIO_INPUT_FLAG_FAST) {
455        if ((mTransfer != TRANSFER_CALLBACK) || (mAudioRecordThread == 0)) {
456            ALOGW("AUDIO_INPUT_FLAG_FAST denied by client");
457            // once denied, do not request again if IAudioRecord is re-created
458            mFlags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_FAST);
459        } else {
460            trackFlags |= IAudioFlinger::TRACK_FAST;
461            tid = mAudioRecordThread->getTid();
462        }
463    }
464
465    int originalSessionId = mSessionId;
466    sp<IAudioRecord> record = audioFlinger->openRecord(input,
467                                                       sampleRate, format,
468                                                       mChannelMask,
469                                                       frameCount,
470                                                       &trackFlags,
471                                                       tid,
472                                                       &mSessionId,
473                                                       &status);
474    ALOGE_IF(originalSessionId != 0 && mSessionId != originalSessionId,
475            "session ID changed from %d to %d", originalSessionId, mSessionId);
476
477    if (record == 0) {
478        ALOGE("AudioFlinger could not create record track, status: %d", status);
479        return status;
480    }
481    sp<IMemory> iMem = record->getCblk();
482    if (iMem == 0) {
483        ALOGE("Could not get control block");
484        return NO_INIT;
485    }
486    if (mAudioRecord != 0) {
487        mAudioRecord->asBinder()->unlinkToDeath(mDeathNotifier, this);
488        mDeathNotifier.clear();
489    }
490    mAudioRecord = record;
491    mCblkMemory = iMem;
492    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMem->pointer());
493    mCblk = cblk;
494
495    // starting address of buffers in shared memory
496    void *buffers = (char*)cblk + sizeof(audio_track_cblk_t);
497
498    // update proxy
499    mProxy = new AudioRecordClientProxy(cblk, buffers, frameCount, mFrameSize);
500    mProxy->setEpoch(epoch);
501    mProxy->setMinimum(mNotificationFrames);
502
503    mDeathNotifier = new DeathNotifier(this);
504    mAudioRecord->asBinder()->linkToDeath(mDeathNotifier, this);
505
506    return NO_ERROR;
507}
508
509status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
510{
511    if (audioBuffer == NULL) {
512        return BAD_VALUE;
513    }
514    if (mTransfer != TRANSFER_OBTAIN) {
515        audioBuffer->frameCount = 0;
516        audioBuffer->size = 0;
517        audioBuffer->raw = NULL;
518        return INVALID_OPERATION;
519    }
520
521    const struct timespec *requested;
522    if (waitCount == -1) {
523        requested = &ClientProxy::kForever;
524    } else if (waitCount == 0) {
525        requested = &ClientProxy::kNonBlocking;
526    } else if (waitCount > 0) {
527        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
528        struct timespec timeout;
529        timeout.tv_sec = ms / 1000;
530        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
531        requested = &timeout;
532    } else {
533        ALOGE("%s invalid waitCount %d", __func__, waitCount);
534        requested = NULL;
535    }
536    return obtainBuffer(audioBuffer, requested);
537}
538
539status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
540        struct timespec *elapsed, size_t *nonContig)
541{
542    // previous and new IAudioRecord sequence numbers are used to detect track re-creation
543    uint32_t oldSequence = 0;
544    uint32_t newSequence;
545
546    Proxy::Buffer buffer;
547    status_t status = NO_ERROR;
548
549    static const int32_t kMaxTries = 5;
550    int32_t tryCounter = kMaxTries;
551
552    do {
553        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
554        // keep them from going away if another thread re-creates the track during obtainBuffer()
555        sp<AudioRecordClientProxy> proxy;
556        sp<IMemory> iMem;
557        {
558            // start of lock scope
559            AutoMutex lock(mLock);
560
561            newSequence = mSequence;
562            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
563            if (status == DEAD_OBJECT) {
564                // re-create track, unless someone else has already done so
565                if (newSequence == oldSequence) {
566                    status = restoreRecord_l("obtainBuffer");
567                    if (status != NO_ERROR) {
568                        break;
569                    }
570                }
571            }
572            oldSequence = newSequence;
573
574            // Keep the extra references
575            proxy = mProxy;
576            iMem = mCblkMemory;
577
578            // Non-blocking if track is stopped
579            if (!mActive) {
580                requested = &ClientProxy::kNonBlocking;
581            }
582
583        }   // end of lock scope
584
585        buffer.mFrameCount = audioBuffer->frameCount;
586        // FIXME starts the requested timeout and elapsed over from scratch
587        status = proxy->obtainBuffer(&buffer, requested, elapsed);
588
589    } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
590
591    audioBuffer->frameCount = buffer.mFrameCount;
592    audioBuffer->size = buffer.mFrameCount * mFrameSize;
593    audioBuffer->raw = buffer.mRaw;
594    if (nonContig != NULL) {
595        *nonContig = buffer.mNonContig;
596    }
597    return status;
598}
599
600void AudioRecord::releaseBuffer(Buffer* audioBuffer)
601{
602    // all TRANSFER_* are valid
603
604    size_t stepCount = audioBuffer->size / mFrameSize;
605    if (stepCount == 0) {
606        return;
607    }
608
609    Proxy::Buffer buffer;
610    buffer.mFrameCount = stepCount;
611    buffer.mRaw = audioBuffer->raw;
612
613    AutoMutex lock(mLock);
614    mInOverrun = false;
615    mProxy->releaseBuffer(&buffer);
616
617    // the server does not automatically disable recorder on overrun, so no need to restart
618}
619
620audio_io_handle_t AudioRecord::getInput() const
621{
622    AutoMutex lock(mLock);
623    return mInput;
624}
625
626// must be called with mLock held
627audio_io_handle_t AudioRecord::getInput_l()
628{
629    mInput = AudioSystem::getInput(mInputSource,
630                                mSampleRate,
631                                mFormat,
632                                mChannelMask,
633                                mSessionId);
634    return mInput;
635}
636
637// -------------------------------------------------------------------------
638
639ssize_t AudioRecord::read(void* buffer, size_t userSize)
640{
641    if (mTransfer != TRANSFER_SYNC) {
642        return INVALID_OPERATION;
643    }
644
645    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
646        // sanity-check. user is most-likely passing an error code, and it would
647        // make the return value ambiguous (actualSize vs error).
648        ALOGE("AudioRecord::read(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
649        return BAD_VALUE;
650    }
651
652    ssize_t read = 0;
653    Buffer audioBuffer;
654
655    while (userSize >= mFrameSize) {
656        audioBuffer.frameCount = userSize / mFrameSize;
657
658        status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
659        if (err < 0) {
660            if (read > 0) {
661                break;
662            }
663            return ssize_t(err);
664        }
665
666        size_t bytesRead = audioBuffer.size;
667        memcpy(buffer, audioBuffer.i8, bytesRead);
668        buffer = ((char *) buffer) + bytesRead;
669        userSize -= bytesRead;
670        read += bytesRead;
671
672        releaseBuffer(&audioBuffer);
673    }
674
675    return read;
676}
677
678// -------------------------------------------------------------------------
679
680nsecs_t AudioRecord::processAudioBuffer(const sp<AudioRecordThread>& thread)
681{
682    mLock.lock();
683    if (mAwaitBoost) {
684        mAwaitBoost = false;
685        mLock.unlock();
686        static const int32_t kMaxTries = 5;
687        int32_t tryCounter = kMaxTries;
688        uint32_t pollUs = 10000;
689        do {
690            int policy = sched_getscheduler(0);
691            if (policy == SCHED_FIFO || policy == SCHED_RR) {
692                break;
693            }
694            usleep(pollUs);
695            pollUs <<= 1;
696        } while (tryCounter-- > 0);
697        if (tryCounter < 0) {
698            ALOGE("did not receive expected priority boost on time");
699        }
700        // Run again immediately
701        return 0;
702    }
703
704    // Can only reference mCblk while locked
705    int32_t flags = android_atomic_and(~CBLK_OVERRUN, &mCblk->mFlags);
706
707    // Check for track invalidation
708    if (flags & CBLK_INVALID) {
709        (void) restoreRecord_l("processAudioBuffer");
710        mLock.unlock();
711        // Run again immediately, but with a new IAudioRecord
712        return 0;
713    }
714
715    bool active = mActive;
716
717    // Manage overrun callback, must be done under lock to avoid race with releaseBuffer()
718    bool newOverrun = false;
719    if (flags & CBLK_OVERRUN) {
720        if (!mInOverrun) {
721            mInOverrun = true;
722            newOverrun = true;
723        }
724    }
725
726    // Get current position of server
727    size_t position = mProxy->getPosition();
728
729    // Manage marker callback
730    bool markerReached = false;
731    size_t markerPosition = mMarkerPosition;
732    // FIXME fails for wraparound, need 64 bits
733    if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
734        mMarkerReached = markerReached = true;
735    }
736
737    // Determine the number of new position callback(s) that will be needed, while locked
738    size_t newPosCount = 0;
739    size_t newPosition = mNewPosition;
740    uint32_t updatePeriod = mUpdatePeriod;
741    // FIXME fails for wraparound, need 64 bits
742    if (updatePeriod > 0 && position >= newPosition) {
743        newPosCount = ((position - newPosition) / updatePeriod) + 1;
744        mNewPosition += updatePeriod * newPosCount;
745    }
746
747    // Cache other fields that will be needed soon
748    size_t notificationFrames = mNotificationFrames;
749    if (mRefreshRemaining) {
750        mRefreshRemaining = false;
751        mRemainingFrames = notificationFrames;
752        mRetryOnPartialBuffer = false;
753    }
754    size_t misalignment = mProxy->getMisalignment();
755    int32_t sequence = mSequence;
756
757    // These fields don't need to be cached, because they are assigned only by set():
758    //      mTransfer, mCbf, mUserData, mSampleRate
759
760    mLock.unlock();
761
762    // perform callbacks while unlocked
763    if (newOverrun) {
764        mCbf(EVENT_OVERRUN, mUserData, NULL);
765    }
766    if (markerReached) {
767        mCbf(EVENT_MARKER, mUserData, &markerPosition);
768    }
769    while (newPosCount > 0) {
770        size_t temp = newPosition;
771        mCbf(EVENT_NEW_POS, mUserData, &temp);
772        newPosition += updatePeriod;
773        newPosCount--;
774    }
775    if (mObservedSequence != sequence) {
776        mObservedSequence = sequence;
777        mCbf(EVENT_NEW_IAUDIORECORD, mUserData, NULL);
778    }
779
780    // if inactive, then don't run me again until re-started
781    if (!active) {
782        return NS_INACTIVE;
783    }
784
785    // Compute the estimated time until the next timed event (position, markers)
786    uint32_t minFrames = ~0;
787    if (!markerReached && position < markerPosition) {
788        minFrames = markerPosition - position;
789    }
790    if (updatePeriod > 0 && updatePeriod < minFrames) {
791        minFrames = updatePeriod;
792    }
793
794    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
795    static const uint32_t kPoll = 0;
796    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
797        minFrames = kPoll * notificationFrames;
798    }
799
800    // Convert frame units to time units
801    nsecs_t ns = NS_WHENEVER;
802    if (minFrames != (uint32_t) ~0) {
803        // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
804        static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
805        ns = ((minFrames * 1000000000LL) / mSampleRate) + kFudgeNs;
806    }
807
808    // If not supplying data by EVENT_MORE_DATA, then we're done
809    if (mTransfer != TRANSFER_CALLBACK) {
810        return ns;
811    }
812
813    struct timespec timeout;
814    const struct timespec *requested = &ClientProxy::kForever;
815    if (ns != NS_WHENEVER) {
816        timeout.tv_sec = ns / 1000000000LL;
817        timeout.tv_nsec = ns % 1000000000LL;
818        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
819        requested = &timeout;
820    }
821
822    while (mRemainingFrames > 0) {
823
824        Buffer audioBuffer;
825        audioBuffer.frameCount = mRemainingFrames;
826        size_t nonContig;
827        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
828        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
829                "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
830        requested = &ClientProxy::kNonBlocking;
831        size_t avail = audioBuffer.frameCount + nonContig;
832        ALOGV("obtainBuffer(%u) returned %u = %u + %u",
833                mRemainingFrames, avail, audioBuffer.frameCount, nonContig);
834        if (err != NO_ERROR) {
835            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
836                break;
837            }
838            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
839            return NS_NEVER;
840        }
841
842        if (mRetryOnPartialBuffer) {
843            mRetryOnPartialBuffer = false;
844            if (avail < mRemainingFrames) {
845                int64_t myns = ((mRemainingFrames - avail) *
846                        1100000000LL) / mSampleRate;
847                if (ns < 0 || myns < ns) {
848                    ns = myns;
849                }
850                return ns;
851            }
852        }
853
854        size_t reqSize = audioBuffer.size;
855        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
856        size_t readSize = audioBuffer.size;
857
858        // Sanity check on returned size
859        if (ssize_t(readSize) < 0 || readSize > reqSize) {
860            ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
861                    reqSize, (int) readSize);
862            return NS_NEVER;
863        }
864
865        if (readSize == 0) {
866            // The callback is done consuming buffers
867            // Keep this thread going to handle timed events and
868            // still try to provide more data in intervals of WAIT_PERIOD_MS
869            // but don't just loop and block the CPU, so wait
870            return WAIT_PERIOD_MS * 1000000LL;
871        }
872
873        size_t releasedFrames = readSize / mFrameSize;
874        audioBuffer.frameCount = releasedFrames;
875        mRemainingFrames -= releasedFrames;
876        if (misalignment >= releasedFrames) {
877            misalignment -= releasedFrames;
878        } else {
879            misalignment = 0;
880        }
881
882        releaseBuffer(&audioBuffer);
883
884        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
885        // if callback doesn't like to accept the full chunk
886        if (readSize < reqSize) {
887            continue;
888        }
889
890        // There could be enough non-contiguous frames available to satisfy the remaining request
891        if (mRemainingFrames <= nonContig) {
892            continue;
893        }
894
895#if 0
896        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
897        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
898        // that total to a sum == notificationFrames.
899        if (0 < misalignment && misalignment <= mRemainingFrames) {
900            mRemainingFrames = misalignment;
901            return (mRemainingFrames * 1100000000LL) / mSampleRate;
902        }
903#endif
904
905    }
906    mRemainingFrames = notificationFrames;
907    mRetryOnPartialBuffer = true;
908
909    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
910    return 0;
911}
912
913status_t AudioRecord::restoreRecord_l(const char *from)
914{
915    ALOGW("dead IAudioRecord, creating a new one from %s()", from);
916    ++mSequence;
917    status_t result;
918
919    // if the new IAudioRecord is created, openRecord_l() will modify the
920    // following member variables: mAudioRecord, mCblkMemory and mCblk.
921    // It will also delete the strong references on previous IAudioRecord and IMemory
922    size_t position = mProxy->getPosition();
923    mNewPosition = position + mUpdatePeriod;
924    result = openRecord_l(mSampleRate, mFormat, mFrameCount, mFlags, getInput_l(), position);
925    if (result == NO_ERROR) {
926        if (mActive) {
927            // callback thread or sync event hasn't changed
928            // FIXME this fails if we have a new AudioFlinger instance
929            result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, 0);
930        }
931    }
932    if (result != NO_ERROR) {
933        ALOGW("restoreRecord_l() failed status %d", result);
934        mActive = false;
935    }
936
937    return result;
938}
939
940// =========================================================================
941
942void AudioRecord::DeathNotifier::binderDied(const wp<IBinder>& who)
943{
944    sp<AudioRecord> audioRecord = mAudioRecord.promote();
945    if (audioRecord != 0) {
946        AutoMutex lock(audioRecord->mLock);
947        audioRecord->mProxy->binderDied();
948    }
949}
950
951// =========================================================================
952
953AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver, bool bCanCallJava)
954    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mResumeLatch(false)
955{
956}
957
958AudioRecord::AudioRecordThread::~AudioRecordThread()
959{
960}
961
962bool AudioRecord::AudioRecordThread::threadLoop()
963{
964    {
965        AutoMutex _l(mMyLock);
966        if (mPaused) {
967            mMyCond.wait(mMyLock);
968            // caller will check for exitPending()
969            return true;
970        }
971    }
972    nsecs_t ns =  mReceiver.processAudioBuffer(this);
973    switch (ns) {
974    case 0:
975        return true;
976    case NS_WHENEVER:
977        sleep(1);
978        return true;
979    case NS_INACTIVE:
980        pauseConditional();
981        return true;
982    case NS_NEVER:
983        return false;
984    default:
985        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
986        struct timespec req;
987        req.tv_sec = ns / 1000000000LL;
988        req.tv_nsec = ns % 1000000000LL;
989        nanosleep(&req, NULL /*rem*/);
990        return true;
991    }
992}
993
994void AudioRecord::AudioRecordThread::requestExit()
995{
996    // must be in this order to avoid a race condition
997    Thread::requestExit();
998    resume();
999}
1000
1001void AudioRecord::AudioRecordThread::pause()
1002{
1003    AutoMutex _l(mMyLock);
1004    mPaused = true;
1005    mResumeLatch = false;
1006}
1007
1008void AudioRecord::AudioRecordThread::pauseConditional()
1009{
1010    AutoMutex _l(mMyLock);
1011    if (mResumeLatch) {
1012        mResumeLatch = false;
1013    } else {
1014        mPaused = true;
1015    }
1016}
1017
1018void AudioRecord::AudioRecordThread::resume()
1019{
1020    AutoMutex _l(mMyLock);
1021    if (mPaused) {
1022        mPaused = false;
1023        mResumeLatch = false;
1024        mMyCond.signal();
1025    } else {
1026        mResumeLatch = true;
1027    }
1028}
1029
1030// -------------------------------------------------------------------------
1031
1032}; // namespace android
1033