AudioRecord.cpp revision f0f33c4acd231fa95deb9eeef2c46b0129e64463
1/*
2**
3** Copyright 2008, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioRecord"
20
21#include <sys/resource.h>
22#include <binder/IPCThreadState.h>
23#include <media/AudioRecord.h>
24#include <utils/Log.h>
25#include <private/media/AudioTrackShared.h>
26#include <media/IAudioFlinger.h>
27
28#define WAIT_PERIOD_MS          10
29
30namespace android {
31// ---------------------------------------------------------------------------
32
33// static
34status_t AudioRecord::getMinFrameCount(
35        size_t* frameCount,
36        uint32_t sampleRate,
37        audio_format_t format,
38        audio_channel_mask_t channelMask)
39{
40    if (frameCount == NULL) {
41        return BAD_VALUE;
42    }
43
44    // default to 0 in case of error
45    *frameCount = 0;
46
47    size_t size = 0;
48    status_t status = AudioSystem::getInputBufferSize(sampleRate, format, channelMask, &size);
49    if (status != NO_ERROR) {
50        ALOGE("AudioSystem could not query the input buffer size; status %d", status);
51        return NO_INIT;
52    }
53
54    if (size == 0) {
55        ALOGE("Unsupported configuration: sampleRate %u, format %d, channelMask %#x",
56            sampleRate, format, channelMask);
57        return BAD_VALUE;
58    }
59
60    // We double the size of input buffer for ping pong use of record buffer.
61    size <<= 1;
62
63    if (audio_is_linear_pcm(format)) {
64        uint32_t channelCount = popcount(channelMask);
65        size /= channelCount * audio_bytes_per_sample(format);
66    }
67
68    *frameCount = size;
69    return NO_ERROR;
70}
71
72// ---------------------------------------------------------------------------
73
74AudioRecord::AudioRecord()
75    : mStatus(NO_INIT), mSessionId(0),
76      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT)
77{
78}
79
80AudioRecord::AudioRecord(
81        audio_source_t inputSource,
82        uint32_t sampleRate,
83        audio_format_t format,
84        audio_channel_mask_t channelMask,
85        int frameCount,
86        callback_t cbf,
87        void* user,
88        int notificationFrames,
89        int sessionId,
90        transfer_type transferType)
91    : 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{
134    switch (transferType) {
135    case TRANSFER_DEFAULT:
136        if (cbf == NULL || threadCanCallJava) {
137            transferType = TRANSFER_SYNC;
138        } else {
139            transferType = TRANSFER_CALLBACK;
140        }
141        break;
142    case TRANSFER_CALLBACK:
143        if (cbf == NULL) {
144            ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL");
145            return BAD_VALUE;
146        }
147        break;
148    case TRANSFER_OBTAIN:
149    case TRANSFER_SYNC:
150        break;
151    default:
152        ALOGE("Invalid transfer type %d", transferType);
153        return BAD_VALUE;
154    }
155    mTransfer = transferType;
156
157    // FIXME "int" here is legacy and will be replaced by size_t later
158    if (frameCountInt < 0) {
159        ALOGE("Invalid frame count %d", frameCountInt);
160        return BAD_VALUE;
161    }
162    size_t frameCount = frameCountInt;
163
164    ALOGV("set(): sampleRate %u, channelMask %#x, frameCount %u", sampleRate, channelMask,
165            frameCount);
166
167    AutoMutex lock(mLock);
168
169    if (mAudioRecord != 0) {
170        ALOGE("Track already in use");
171        return INVALID_OPERATION;
172    }
173
174    if (inputSource == AUDIO_SOURCE_DEFAULT) {
175        inputSource = AUDIO_SOURCE_MIC;
176    }
177
178    if (sampleRate == 0) {
179        ALOGE("Invalid sample rate %u", sampleRate);
180        return BAD_VALUE;
181    }
182    mSampleRate = sampleRate;
183
184    // these below should probably come from the audioFlinger too...
185    if (format == AUDIO_FORMAT_DEFAULT) {
186        format = AUDIO_FORMAT_PCM_16_BIT;
187    }
188
189    // validate parameters
190    if (!audio_is_valid_format(format)) {
191        ALOGE("Invalid format %d", format);
192        return BAD_VALUE;
193    }
194    // Temporary restriction: AudioFlinger currently supports 16-bit PCM only
195    if (format != AUDIO_FORMAT_PCM_16_BIT) {
196        ALOGE("Format %d is not supported", format);
197        return BAD_VALUE;
198    }
199    mFormat = format;
200
201    if (!audio_is_input_channel(channelMask)) {
202        ALOGE("Invalid channel mask %#x", channelMask);
203        return BAD_VALUE;
204    }
205    mChannelMask = channelMask;
206    uint32_t channelCount = popcount(channelMask);
207    mChannelCount = channelCount;
208
209    if (audio_is_linear_pcm(format)) {
210        mFrameSize = channelCount * audio_bytes_per_sample(format);
211    } else {
212        mFrameSize = sizeof(uint8_t);
213    }
214
215    if (sessionId == 0 ) {
216        mSessionId = AudioSystem::newAudioSessionId();
217    } else {
218        mSessionId = sessionId;
219    }
220    ALOGV("set(): mSessionId %d", mSessionId);
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    int originalSessionId = mSessionId;
452    sp<IAudioRecord> record = audioFlinger->openRecord(input,
453                                                       sampleRate, format,
454                                                       mChannelMask,
455                                                       frameCount,
456                                                       IAudioFlinger::TRACK_DEFAULT,
457                                                       tid,
458                                                       &mSessionId,
459                                                       &status);
460    ALOGE_IF(originalSessionId != 0 && mSessionId != originalSessionId,
461            "session ID changed from %d to %d", originalSessionId, mSessionId);
462
463    if (record == 0) {
464        ALOGE("AudioFlinger could not create record track, status: %d", status);
465        return status;
466    }
467    sp<IMemory> iMem = record->getCblk();
468    if (iMem == 0) {
469        ALOGE("Could not get control block");
470        return NO_INIT;
471    }
472    if (mAudioRecord != 0) {
473        mAudioRecord->asBinder()->unlinkToDeath(mDeathNotifier, this);
474        mDeathNotifier.clear();
475    }
476    mAudioRecord = record;
477    mCblkMemory = iMem;
478    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMem->pointer());
479    mCblk = cblk;
480
481    // starting address of buffers in shared memory
482    void *buffers = (char*)cblk + sizeof(audio_track_cblk_t);
483
484    // update proxy
485    mProxy = new AudioRecordClientProxy(cblk, buffers, frameCount, mFrameSize);
486    mProxy->setEpoch(epoch);
487    mProxy->setMinimum(mNotificationFrames);
488
489    mDeathNotifier = new DeathNotifier(this);
490    mAudioRecord->asBinder()->linkToDeath(mDeathNotifier, this);
491
492    return NO_ERROR;
493}
494
495status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
496{
497    if (audioBuffer == NULL) {
498        return BAD_VALUE;
499    }
500    if (mTransfer != TRANSFER_OBTAIN) {
501        audioBuffer->frameCount = 0;
502        audioBuffer->size = 0;
503        audioBuffer->raw = NULL;
504        return INVALID_OPERATION;
505    }
506
507    const struct timespec *requested;
508    if (waitCount == -1) {
509        requested = &ClientProxy::kForever;
510    } else if (waitCount == 0) {
511        requested = &ClientProxy::kNonBlocking;
512    } else if (waitCount > 0) {
513        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
514        struct timespec timeout;
515        timeout.tv_sec = ms / 1000;
516        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
517        requested = &timeout;
518    } else {
519        ALOGE("%s invalid waitCount %d", __func__, waitCount);
520        requested = NULL;
521    }
522    return obtainBuffer(audioBuffer, requested);
523}
524
525status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
526        struct timespec *elapsed, size_t *nonContig)
527{
528    // previous and new IAudioRecord sequence numbers are used to detect track re-creation
529    uint32_t oldSequence = 0;
530    uint32_t newSequence;
531
532    Proxy::Buffer buffer;
533    status_t status = NO_ERROR;
534
535    static const int32_t kMaxTries = 5;
536    int32_t tryCounter = kMaxTries;
537
538    do {
539        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
540        // keep them from going away if another thread re-creates the track during obtainBuffer()
541        sp<AudioRecordClientProxy> proxy;
542        sp<IMemory> iMem;
543        {
544            // start of lock scope
545            AutoMutex lock(mLock);
546
547            newSequence = mSequence;
548            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
549            if (status == DEAD_OBJECT) {
550                // re-create track, unless someone else has already done so
551                if (newSequence == oldSequence) {
552                    status = restoreRecord_l("obtainBuffer");
553                    if (status != NO_ERROR) {
554                        break;
555                    }
556                }
557            }
558            oldSequence = newSequence;
559
560            // Keep the extra references
561            proxy = mProxy;
562            iMem = mCblkMemory;
563
564            // Non-blocking if track is stopped
565            if (!mActive) {
566                requested = &ClientProxy::kNonBlocking;
567            }
568
569        }   // end of lock scope
570
571        buffer.mFrameCount = audioBuffer->frameCount;
572        // FIXME starts the requested timeout and elapsed over from scratch
573        status = proxy->obtainBuffer(&buffer, requested, elapsed);
574
575    } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
576
577    audioBuffer->frameCount = buffer.mFrameCount;
578    audioBuffer->size = buffer.mFrameCount * mFrameSize;
579    audioBuffer->raw = buffer.mRaw;
580    if (nonContig != NULL) {
581        *nonContig = buffer.mNonContig;
582    }
583    return status;
584}
585
586void AudioRecord::releaseBuffer(Buffer* audioBuffer)
587{
588    // all TRANSFER_* are valid
589
590    size_t stepCount = audioBuffer->size / mFrameSize;
591    if (stepCount == 0) {
592        return;
593    }
594
595    Proxy::Buffer buffer;
596    buffer.mFrameCount = stepCount;
597    buffer.mRaw = audioBuffer->raw;
598
599    AutoMutex lock(mLock);
600    mInOverrun = false;
601    mProxy->releaseBuffer(&buffer);
602
603    // the server does not automatically disable recorder on overrun, so no need to restart
604}
605
606audio_io_handle_t AudioRecord::getInput() const
607{
608    AutoMutex lock(mLock);
609    return mInput;
610}
611
612// must be called with mLock held
613audio_io_handle_t AudioRecord::getInput_l()
614{
615    mInput = AudioSystem::getInput(mInputSource,
616                                mSampleRate,
617                                mFormat,
618                                mChannelMask,
619                                mSessionId);
620    return mInput;
621}
622
623// -------------------------------------------------------------------------
624
625ssize_t AudioRecord::read(void* buffer, size_t userSize)
626{
627    if (mTransfer != TRANSFER_SYNC) {
628        return INVALID_OPERATION;
629    }
630
631    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
632        // sanity-check. user is most-likely passing an error code, and it would
633        // make the return value ambiguous (actualSize vs error).
634        ALOGE("AudioRecord::read(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
635        return BAD_VALUE;
636    }
637
638    ssize_t read = 0;
639    Buffer audioBuffer;
640
641    while (userSize >= mFrameSize) {
642        audioBuffer.frameCount = userSize / mFrameSize;
643
644        status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
645        if (err < 0) {
646            if (read > 0) {
647                break;
648            }
649            return ssize_t(err);
650        }
651
652        size_t bytesRead = audioBuffer.size;
653        memcpy(buffer, audioBuffer.i8, bytesRead);
654        buffer = ((char *) buffer) + bytesRead;
655        userSize -= bytesRead;
656        read += bytesRead;
657
658        releaseBuffer(&audioBuffer);
659    }
660
661    return read;
662}
663
664// -------------------------------------------------------------------------
665
666nsecs_t AudioRecord::processAudioBuffer(const sp<AudioRecordThread>& thread)
667{
668    mLock.lock();
669
670    // Can only reference mCblk while locked
671    int32_t flags = android_atomic_and(~CBLK_OVERRUN, &mCblk->mFlags);
672
673    // Check for track invalidation
674    if (flags & CBLK_INVALID) {
675        (void) restoreRecord_l("processAudioBuffer");
676        mLock.unlock();
677        // Run again immediately, but with a new IAudioRecord
678        return 0;
679    }
680
681    bool active = mActive;
682
683    // Manage overrun callback, must be done under lock to avoid race with releaseBuffer()
684    bool newOverrun = false;
685    if (flags & CBLK_OVERRUN) {
686        if (!mInOverrun) {
687            mInOverrun = true;
688            newOverrun = true;
689        }
690    }
691
692    // Get current position of server
693    size_t position = mProxy->getPosition();
694
695    // Manage marker callback
696    bool markerReached = false;
697    size_t markerPosition = mMarkerPosition;
698    // FIXME fails for wraparound, need 64 bits
699    if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
700        mMarkerReached = markerReached = true;
701    }
702
703    // Determine the number of new position callback(s) that will be needed, while locked
704    size_t newPosCount = 0;
705    size_t newPosition = mNewPosition;
706    uint32_t updatePeriod = mUpdatePeriod;
707    // FIXME fails for wraparound, need 64 bits
708    if (updatePeriod > 0 && position >= newPosition) {
709        newPosCount = ((position - newPosition) / updatePeriod) + 1;
710        mNewPosition += updatePeriod * newPosCount;
711    }
712
713    // Cache other fields that will be needed soon
714    size_t notificationFrames = mNotificationFrames;
715    if (mRefreshRemaining) {
716        mRefreshRemaining = false;
717        mRemainingFrames = notificationFrames;
718        mRetryOnPartialBuffer = false;
719    }
720    size_t misalignment = mProxy->getMisalignment();
721    int32_t sequence = mSequence;
722
723    // These fields don't need to be cached, because they are assigned only by set():
724    //      mTransfer, mCbf, mUserData, mSampleRate
725
726    mLock.unlock();
727
728    // perform callbacks while unlocked
729    if (newOverrun) {
730        mCbf(EVENT_OVERRUN, mUserData, NULL);
731    }
732    if (markerReached) {
733        mCbf(EVENT_MARKER, mUserData, &markerPosition);
734    }
735    while (newPosCount > 0) {
736        size_t temp = newPosition;
737        mCbf(EVENT_NEW_POS, mUserData, &temp);
738        newPosition += updatePeriod;
739        newPosCount--;
740    }
741    if (mObservedSequence != sequence) {
742        mObservedSequence = sequence;
743        mCbf(EVENT_NEW_IAUDIORECORD, mUserData, NULL);
744    }
745
746    // if inactive, then don't run me again until re-started
747    if (!active) {
748        return NS_INACTIVE;
749    }
750
751    // Compute the estimated time until the next timed event (position, markers)
752    uint32_t minFrames = ~0;
753    if (!markerReached && position < markerPosition) {
754        minFrames = markerPosition - position;
755    }
756    if (updatePeriod > 0 && updatePeriod < minFrames) {
757        minFrames = updatePeriod;
758    }
759
760    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
761    static const uint32_t kPoll = 0;
762    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
763        minFrames = kPoll * notificationFrames;
764    }
765
766    // Convert frame units to time units
767    nsecs_t ns = NS_WHENEVER;
768    if (minFrames != (uint32_t) ~0) {
769        // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
770        static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
771        ns = ((minFrames * 1000000000LL) / mSampleRate) + kFudgeNs;
772    }
773
774    // If not supplying data by EVENT_MORE_DATA, then we're done
775    if (mTransfer != TRANSFER_CALLBACK) {
776        return ns;
777    }
778
779    struct timespec timeout;
780    const struct timespec *requested = &ClientProxy::kForever;
781    if (ns != NS_WHENEVER) {
782        timeout.tv_sec = ns / 1000000000LL;
783        timeout.tv_nsec = ns % 1000000000LL;
784        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
785        requested = &timeout;
786    }
787
788    while (mRemainingFrames > 0) {
789
790        Buffer audioBuffer;
791        audioBuffer.frameCount = mRemainingFrames;
792        size_t nonContig;
793        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
794        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
795                "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
796        requested = &ClientProxy::kNonBlocking;
797        size_t avail = audioBuffer.frameCount + nonContig;
798        ALOGV("obtainBuffer(%u) returned %u = %u + %u",
799                mRemainingFrames, avail, audioBuffer.frameCount, nonContig);
800        if (err != NO_ERROR) {
801            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
802                break;
803            }
804            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
805            return NS_NEVER;
806        }
807
808        if (mRetryOnPartialBuffer) {
809            mRetryOnPartialBuffer = false;
810            if (avail < mRemainingFrames) {
811                int64_t myns = ((mRemainingFrames - avail) *
812                        1100000000LL) / mSampleRate;
813                if (ns < 0 || myns < ns) {
814                    ns = myns;
815                }
816                return ns;
817            }
818        }
819
820        size_t reqSize = audioBuffer.size;
821        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
822        size_t readSize = audioBuffer.size;
823
824        // Sanity check on returned size
825        if (ssize_t(readSize) < 0 || readSize > reqSize) {
826            ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
827                    reqSize, (int) readSize);
828            return NS_NEVER;
829        }
830
831        if (readSize == 0) {
832            // The callback is done consuming buffers
833            // Keep this thread going to handle timed events and
834            // still try to provide more data in intervals of WAIT_PERIOD_MS
835            // but don't just loop and block the CPU, so wait
836            return WAIT_PERIOD_MS * 1000000LL;
837        }
838
839        size_t releasedFrames = readSize / mFrameSize;
840        audioBuffer.frameCount = releasedFrames;
841        mRemainingFrames -= releasedFrames;
842        if (misalignment >= releasedFrames) {
843            misalignment -= releasedFrames;
844        } else {
845            misalignment = 0;
846        }
847
848        releaseBuffer(&audioBuffer);
849
850        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
851        // if callback doesn't like to accept the full chunk
852        if (readSize < reqSize) {
853            continue;
854        }
855
856        // There could be enough non-contiguous frames available to satisfy the remaining request
857        if (mRemainingFrames <= nonContig) {
858            continue;
859        }
860
861#if 0
862        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
863        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
864        // that total to a sum == notificationFrames.
865        if (0 < misalignment && misalignment <= mRemainingFrames) {
866            mRemainingFrames = misalignment;
867            return (mRemainingFrames * 1100000000LL) / mSampleRate;
868        }
869#endif
870
871    }
872    mRemainingFrames = notificationFrames;
873    mRetryOnPartialBuffer = true;
874
875    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
876    return 0;
877}
878
879status_t AudioRecord::restoreRecord_l(const char *from)
880{
881    ALOGW("dead IAudioRecord, creating a new one from %s()", from);
882    ++mSequence;
883    status_t result;
884
885    // if the new IAudioRecord is created, openRecord_l() will modify the
886    // following member variables: mAudioRecord, mCblkMemory and mCblk.
887    // It will also delete the strong references on previous IAudioRecord and IMemory
888    size_t position = mProxy->getPosition();
889    mNewPosition = position + mUpdatePeriod;
890    result = openRecord_l(mSampleRate, mFormat, mFrameCount, getInput_l(), position);
891    if (result == NO_ERROR) {
892        if (mActive) {
893            // callback thread or sync event hasn't changed
894            // FIXME this fails if we have a new AudioFlinger instance
895            result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, 0);
896        }
897    }
898    if (result != NO_ERROR) {
899        ALOGW("restoreRecord_l() failed status %d", result);
900        mActive = false;
901    }
902
903    return result;
904}
905
906// =========================================================================
907
908void AudioRecord::DeathNotifier::binderDied(const wp<IBinder>& who)
909{
910    sp<AudioRecord> audioRecord = mAudioRecord.promote();
911    if (audioRecord != 0) {
912        AutoMutex lock(audioRecord->mLock);
913        audioRecord->mProxy->binderDied();
914    }
915}
916
917// =========================================================================
918
919AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver, bool bCanCallJava)
920    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mResumeLatch(false)
921{
922}
923
924AudioRecord::AudioRecordThread::~AudioRecordThread()
925{
926}
927
928bool AudioRecord::AudioRecordThread::threadLoop()
929{
930    {
931        AutoMutex _l(mMyLock);
932        if (mPaused) {
933            mMyCond.wait(mMyLock);
934            // caller will check for exitPending()
935            return true;
936        }
937    }
938    nsecs_t ns =  mReceiver.processAudioBuffer(this);
939    switch (ns) {
940    case 0:
941        return true;
942    case NS_WHENEVER:
943        sleep(1);
944        return true;
945    case NS_INACTIVE:
946        pauseConditional();
947        return true;
948    case NS_NEVER:
949        return false;
950    default:
951        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
952        struct timespec req;
953        req.tv_sec = ns / 1000000000LL;
954        req.tv_nsec = ns % 1000000000LL;
955        nanosleep(&req, NULL /*rem*/);
956        return true;
957    }
958}
959
960void AudioRecord::AudioRecordThread::requestExit()
961{
962    // must be in this order to avoid a race condition
963    Thread::requestExit();
964    resume();
965}
966
967void AudioRecord::AudioRecordThread::pause()
968{
969    AutoMutex _l(mMyLock);
970    mPaused = true;
971    mResumeLatch = false;
972}
973
974void AudioRecord::AudioRecordThread::pauseConditional()
975{
976    AutoMutex _l(mMyLock);
977    if (mResumeLatch) {
978        mResumeLatch = false;
979    } else {
980        mPaused = true;
981    }
982}
983
984void AudioRecord::AudioRecordThread::resume()
985{
986    AutoMutex _l(mMyLock);
987    if (mPaused) {
988        mPaused = false;
989        mResumeLatch = false;
990        mMyCond.signal();
991    } else {
992        mResumeLatch = true;
993    }
994}
995
996// -------------------------------------------------------------------------
997
998}; // namespace android
999