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