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