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