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