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