AudioRecord.cpp revision 3a0b6bd22aa32daa729b05c33896400807027eee
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    // force refresh of remaining frames by processAudioBuffer() as last
293    // read before stop could be partial.
294    mRefreshRemaining = true;
295
296    mNewPosition = mProxy->getPosition() + mUpdatePeriod;
297    int32_t flags = android_atomic_acquire_load(&mCblk->mFlags);
298
299    status_t status = NO_ERROR;
300    if (!(flags & CBLK_INVALID)) {
301        ALOGV("mAudioRecord->start()");
302        status = mAudioRecord->start(event, triggerSession);
303        if (status == DEAD_OBJECT) {
304            flags |= CBLK_INVALID;
305        }
306    }
307    if (flags & CBLK_INVALID) {
308        status = restoreRecord_l("start");
309    }
310
311    if (status != NO_ERROR) {
312        ALOGE("start() status %d", status);
313    } else {
314        mActive = true;
315        sp<AudioRecordThread> t = mAudioRecordThread;
316        if (t != 0) {
317            t->resume();
318        } else {
319            mPreviousPriority = getpriority(PRIO_PROCESS, 0);
320            get_sched_policy(0, &mPreviousSchedulingGroup);
321            androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
322        }
323    }
324
325    return status;
326}
327
328void AudioRecord::stop()
329{
330    AutoMutex lock(mLock);
331    if (!mActive) {
332        return;
333    }
334
335    mActive = false;
336    mProxy->interrupt();
337    mAudioRecord->stop();
338    // the record head position will reset to 0, so if a marker is set, we need
339    // to activate it again
340    mMarkerReached = false;
341    sp<AudioRecordThread> t = mAudioRecordThread;
342    if (t != 0) {
343        t->pause();
344    } else {
345        setpriority(PRIO_PROCESS, 0, mPreviousPriority);
346        set_sched_policy(0, mPreviousSchedulingGroup);
347    }
348}
349
350bool AudioRecord::stopped() const
351{
352    AutoMutex lock(mLock);
353    return !mActive;
354}
355
356status_t AudioRecord::setMarkerPosition(uint32_t marker)
357{
358    // The only purpose of setting marker position is to get a callback
359    if (mCbf == NULL) {
360        return INVALID_OPERATION;
361    }
362
363    AutoMutex lock(mLock);
364    mMarkerPosition = marker;
365    mMarkerReached = false;
366
367    return NO_ERROR;
368}
369
370status_t AudioRecord::getMarkerPosition(uint32_t *marker) const
371{
372    if (marker == NULL) {
373        return BAD_VALUE;
374    }
375
376    AutoMutex lock(mLock);
377    *marker = mMarkerPosition;
378
379    return NO_ERROR;
380}
381
382status_t AudioRecord::setPositionUpdatePeriod(uint32_t updatePeriod)
383{
384    // The only purpose of setting position update period is to get a callback
385    if (mCbf == NULL) {
386        return INVALID_OPERATION;
387    }
388
389    AutoMutex lock(mLock);
390    mNewPosition = mProxy->getPosition() + updatePeriod;
391    mUpdatePeriod = updatePeriod;
392
393    return NO_ERROR;
394}
395
396status_t AudioRecord::getPositionUpdatePeriod(uint32_t *updatePeriod) const
397{
398    if (updatePeriod == NULL) {
399        return BAD_VALUE;
400    }
401
402    AutoMutex lock(mLock);
403    *updatePeriod = mUpdatePeriod;
404
405    return NO_ERROR;
406}
407
408status_t AudioRecord::getPosition(uint32_t *position) const
409{
410    if (position == NULL) {
411        return BAD_VALUE;
412    }
413
414    AutoMutex lock(mLock);
415    *position = mProxy->getPosition();
416
417    return NO_ERROR;
418}
419
420uint32_t AudioRecord::getInputFramesLost() const
421{
422    // no need to check mActive, because if inactive this will return 0, which is what we want
423    return AudioSystem::getInputFramesLost(getInput());
424}
425
426// -------------------------------------------------------------------------
427
428// must be called with mLock held
429status_t AudioRecord::openRecord_l(size_t epoch)
430{
431    status_t status;
432    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
433    if (audioFlinger == 0) {
434        ALOGE("Could not get audioflinger");
435        return NO_INIT;
436    }
437
438    IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
439    pid_t tid = -1;
440
441    // Client can only express a preference for FAST.  Server will perform additional tests.
442    // The only supported use case for FAST is callback transfer mode.
443    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
444        if ((mTransfer != TRANSFER_CALLBACK) || (mAudioRecordThread == 0)) {
445            ALOGW("AUDIO_INPUT_FLAG_FAST denied by client");
446            // once denied, do not request again if IAudioRecord is re-created
447            mFlags = (audio_input_flags_t) (mFlags & ~AUDIO_INPUT_FLAG_FAST);
448        } else {
449            trackFlags |= IAudioFlinger::TRACK_FAST;
450            tid = mAudioRecordThread->getTid();
451        }
452    }
453
454    mNotificationFramesAct = mNotificationFramesReq;
455
456    if (!(mFlags & AUDIO_INPUT_FLAG_FAST)) {
457        // Make sure that application is notified with sufficient margin before overrun
458        if (mNotificationFramesAct == 0 || mNotificationFramesAct > mFrameCount/2) {
459            mNotificationFramesAct = mFrameCount/2;
460        }
461    }
462
463    audio_io_handle_t input = AudioSystem::getInput(mInputSource, mSampleRate, mFormat,
464            mChannelMask, mSessionId);
465    if (input == 0) {
466        ALOGE("Could not get audio input for record source %d", mInputSource);
467        return BAD_VALUE;
468    }
469
470    int originalSessionId = mSessionId;
471    sp<IAudioRecord> record = audioFlinger->openRecord(input,
472                                                       mSampleRate, mFormat,
473                                                       mChannelMask,
474                                                       mFrameCount,
475                                                       &trackFlags,
476                                                       tid,
477                                                       &mSessionId,
478                                                       &status);
479    ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
480            "session ID changed from %d to %d", originalSessionId, mSessionId);
481
482    if (record == 0 || status != NO_ERROR) {
483        ALOGE("AudioFlinger could not create record track, status: %d", status);
484        AudioSystem::releaseInput(input);
485        return status;
486    }
487    sp<IMemory> iMem = record->getCblk();
488    if (iMem == 0) {
489        ALOGE("Could not get control block");
490        return NO_INIT;
491    }
492    void *iMemPointer = iMem->pointer();
493    if (iMemPointer == NULL) {
494        ALOGE("Could not get control block pointer");
495        return NO_INIT;
496    }
497    if (mAudioRecord != 0) {
498        mAudioRecord->asBinder()->unlinkToDeath(mDeathNotifier, this);
499        mDeathNotifier.clear();
500    }
501    mInput = input;
502    mAudioRecord = record;
503    mCblkMemory = iMem;
504    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
505    mCblk = cblk;
506    // FIXME missing fast track frameCount logic
507    mAwaitBoost = false;
508    if (mFlags & AUDIO_INPUT_FLAG_FAST) {
509        if (trackFlags & IAudioFlinger::TRACK_FAST) {
510            ALOGV("AUDIO_INPUT_FLAG_FAST successful; frameCount %u", mFrameCount);
511            mAwaitBoost = true;
512            // double-buffering is not required for fast tracks, due to tighter scheduling
513            if (mNotificationFramesAct == 0 || mNotificationFramesAct > mFrameCount) {
514                mNotificationFramesAct = mFrameCount;
515            }
516        } else {
517            ALOGV("AUDIO_INPUT_FLAG_FAST denied by server; frameCount %u", mFrameCount);
518            // once denied, do not request again if IAudioRecord is re-created
519            mFlags = (audio_input_flags_t) (mFlags & ~AUDIO_INPUT_FLAG_FAST);
520            if (mNotificationFramesAct == 0 || mNotificationFramesAct > mFrameCount/2) {
521                mNotificationFramesAct = mFrameCount/2;
522            }
523        }
524    }
525
526    // starting address of buffers in shared memory
527    void *buffers = (char*)cblk + sizeof(audio_track_cblk_t);
528
529    // update proxy
530    mProxy = new AudioRecordClientProxy(cblk, buffers, mFrameCount, mFrameSize);
531    mProxy->setEpoch(epoch);
532    mProxy->setMinimum(mNotificationFramesAct);
533
534    mDeathNotifier = new DeathNotifier(this);
535    mAudioRecord->asBinder()->linkToDeath(mDeathNotifier, this);
536
537    return NO_ERROR;
538}
539
540status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
541{
542    if (audioBuffer == NULL) {
543        return BAD_VALUE;
544    }
545    if (mTransfer != TRANSFER_OBTAIN) {
546        audioBuffer->frameCount = 0;
547        audioBuffer->size = 0;
548        audioBuffer->raw = NULL;
549        return INVALID_OPERATION;
550    }
551
552    const struct timespec *requested;
553    if (waitCount == -1) {
554        requested = &ClientProxy::kForever;
555    } else if (waitCount == 0) {
556        requested = &ClientProxy::kNonBlocking;
557    } else if (waitCount > 0) {
558        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
559        struct timespec timeout;
560        timeout.tv_sec = ms / 1000;
561        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
562        requested = &timeout;
563    } else {
564        ALOGE("%s invalid waitCount %d", __func__, waitCount);
565        requested = NULL;
566    }
567    return obtainBuffer(audioBuffer, requested);
568}
569
570status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
571        struct timespec *elapsed, size_t *nonContig)
572{
573    // previous and new IAudioRecord sequence numbers are used to detect track re-creation
574    uint32_t oldSequence = 0;
575    uint32_t newSequence;
576
577    Proxy::Buffer buffer;
578    status_t status = NO_ERROR;
579
580    static const int32_t kMaxTries = 5;
581    int32_t tryCounter = kMaxTries;
582
583    do {
584        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
585        // keep them from going away if another thread re-creates the track during obtainBuffer()
586        sp<AudioRecordClientProxy> proxy;
587        sp<IMemory> iMem;
588        {
589            // start of lock scope
590            AutoMutex lock(mLock);
591
592            newSequence = mSequence;
593            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
594            if (status == DEAD_OBJECT) {
595                // re-create track, unless someone else has already done so
596                if (newSequence == oldSequence) {
597                    status = restoreRecord_l("obtainBuffer");
598                    if (status != NO_ERROR) {
599                        buffer.mFrameCount = 0;
600                        buffer.mRaw = NULL;
601                        buffer.mNonContig = 0;
602                        break;
603                    }
604                }
605            }
606            oldSequence = newSequence;
607
608            // Keep the extra references
609            proxy = mProxy;
610            iMem = mCblkMemory;
611
612            // Non-blocking if track is stopped
613            if (!mActive) {
614                requested = &ClientProxy::kNonBlocking;
615            }
616
617        }   // end of lock scope
618
619        buffer.mFrameCount = audioBuffer->frameCount;
620        // FIXME starts the requested timeout and elapsed over from scratch
621        status = proxy->obtainBuffer(&buffer, requested, elapsed);
622
623    } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
624
625    audioBuffer->frameCount = buffer.mFrameCount;
626    audioBuffer->size = buffer.mFrameCount * mFrameSize;
627    audioBuffer->raw = buffer.mRaw;
628    if (nonContig != NULL) {
629        *nonContig = buffer.mNonContig;
630    }
631    return status;
632}
633
634void AudioRecord::releaseBuffer(Buffer* audioBuffer)
635{
636    // all TRANSFER_* are valid
637
638    size_t stepCount = audioBuffer->size / mFrameSize;
639    if (stepCount == 0) {
640        return;
641    }
642
643    Proxy::Buffer buffer;
644    buffer.mFrameCount = stepCount;
645    buffer.mRaw = audioBuffer->raw;
646
647    AutoMutex lock(mLock);
648    mInOverrun = false;
649    mProxy->releaseBuffer(&buffer);
650
651    // the server does not automatically disable recorder on overrun, so no need to restart
652}
653
654audio_io_handle_t AudioRecord::getInput() const
655{
656    AutoMutex lock(mLock);
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()
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    uint32_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, mFrameSize
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 err %d",
856                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
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(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 __unused)
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), mPausedInt(false), mPausedNs(0LL),
978      mIgnoreNextPausedInt(false)
979{
980}
981
982AudioRecord::AudioRecordThread::~AudioRecordThread()
983{
984}
985
986bool AudioRecord::AudioRecordThread::threadLoop()
987{
988    {
989        AutoMutex _l(mMyLock);
990        if (mPaused) {
991            mMyCond.wait(mMyLock);
992            // caller will check for exitPending()
993            return true;
994        }
995        if (mIgnoreNextPausedInt) {
996            mIgnoreNextPausedInt = false;
997            mPausedInt = false;
998        }
999        if (mPausedInt) {
1000            if (mPausedNs > 0) {
1001                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1002            } else {
1003                mMyCond.wait(mMyLock);
1004            }
1005            mPausedInt = false;
1006            return true;
1007        }
1008    }
1009    nsecs_t ns =  mReceiver.processAudioBuffer();
1010    switch (ns) {
1011    case 0:
1012        return true;
1013    case NS_INACTIVE:
1014        pauseInternal();
1015        return true;
1016    case NS_NEVER:
1017        return false;
1018    case NS_WHENEVER:
1019        // FIXME increase poll interval, or make event-driven
1020        ns = 1000000000LL;
1021        // fall through
1022    default:
1023        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
1024        pauseInternal(ns);
1025        return true;
1026    }
1027}
1028
1029void AudioRecord::AudioRecordThread::requestExit()
1030{
1031    // must be in this order to avoid a race condition
1032    Thread::requestExit();
1033    resume();
1034}
1035
1036void AudioRecord::AudioRecordThread::pause()
1037{
1038    AutoMutex _l(mMyLock);
1039    mPaused = true;
1040}
1041
1042void AudioRecord::AudioRecordThread::resume()
1043{
1044    AutoMutex _l(mMyLock);
1045    mIgnoreNextPausedInt = true;
1046    if (mPaused || mPausedInt) {
1047        mPaused = false;
1048        mPausedInt = false;
1049        mMyCond.signal();
1050    }
1051}
1052
1053void AudioRecord::AudioRecordThread::pauseInternal(nsecs_t ns)
1054{
1055    AutoMutex _l(mMyLock);
1056    mPausedInt = true;
1057    mPausedNs = ns;
1058}
1059
1060// -------------------------------------------------------------------------
1061
1062}; // namespace android
1063