AudioRecord.cpp revision 6d88aaf9cd810d96a4888dff8bd33d44cd01ccaa
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                        break;
600                    }
601                }
602            }
603            oldSequence = newSequence;
604
605            // Keep the extra references
606            proxy = mProxy;
607            iMem = mCblkMemory;
608
609            // Non-blocking if track is stopped
610            if (!mActive) {
611                requested = &ClientProxy::kNonBlocking;
612            }
613
614        }   // end of lock scope
615
616        buffer.mFrameCount = audioBuffer->frameCount;
617        // FIXME starts the requested timeout and elapsed over from scratch
618        status = proxy->obtainBuffer(&buffer, requested, elapsed);
619
620    } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
621
622    audioBuffer->frameCount = buffer.mFrameCount;
623    audioBuffer->size = buffer.mFrameCount * mFrameSize;
624    audioBuffer->raw = buffer.mRaw;
625    if (nonContig != NULL) {
626        *nonContig = buffer.mNonContig;
627    }
628    return status;
629}
630
631void AudioRecord::releaseBuffer(Buffer* audioBuffer)
632{
633    // all TRANSFER_* are valid
634
635    size_t stepCount = audioBuffer->size / mFrameSize;
636    if (stepCount == 0) {
637        return;
638    }
639
640    Proxy::Buffer buffer;
641    buffer.mFrameCount = stepCount;
642    buffer.mRaw = audioBuffer->raw;
643
644    AutoMutex lock(mLock);
645    mInOverrun = false;
646    mProxy->releaseBuffer(&buffer);
647
648    // the server does not automatically disable recorder on overrun, so no need to restart
649}
650
651audio_io_handle_t AudioRecord::getInput() const
652{
653    AutoMutex lock(mLock);
654    return mInput;
655}
656
657// -------------------------------------------------------------------------
658
659ssize_t AudioRecord::read(void* buffer, size_t userSize)
660{
661    if (mTransfer != TRANSFER_SYNC) {
662        return INVALID_OPERATION;
663    }
664
665    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
666        // sanity-check. user is most-likely passing an error code, and it would
667        // make the return value ambiguous (actualSize vs error).
668        ALOGE("AudioRecord::read(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
669        return BAD_VALUE;
670    }
671
672    ssize_t read = 0;
673    Buffer audioBuffer;
674
675    while (userSize >= mFrameSize) {
676        audioBuffer.frameCount = userSize / mFrameSize;
677
678        status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
679        if (err < 0) {
680            if (read > 0) {
681                break;
682            }
683            return ssize_t(err);
684        }
685
686        size_t bytesRead = audioBuffer.size;
687        memcpy(buffer, audioBuffer.i8, bytesRead);
688        buffer = ((char *) buffer) + bytesRead;
689        userSize -= bytesRead;
690        read += bytesRead;
691
692        releaseBuffer(&audioBuffer);
693    }
694
695    return read;
696}
697
698// -------------------------------------------------------------------------
699
700nsecs_t AudioRecord::processAudioBuffer()
701{
702    mLock.lock();
703    if (mAwaitBoost) {
704        mAwaitBoost = false;
705        mLock.unlock();
706        static const int32_t kMaxTries = 5;
707        int32_t tryCounter = kMaxTries;
708        uint32_t pollUs = 10000;
709        do {
710            int policy = sched_getscheduler(0);
711            if (policy == SCHED_FIFO || policy == SCHED_RR) {
712                break;
713            }
714            usleep(pollUs);
715            pollUs <<= 1;
716        } while (tryCounter-- > 0);
717        if (tryCounter < 0) {
718            ALOGE("did not receive expected priority boost on time");
719        }
720        // Run again immediately
721        return 0;
722    }
723
724    // Can only reference mCblk while locked
725    int32_t flags = android_atomic_and(~CBLK_OVERRUN, &mCblk->mFlags);
726
727    // Check for track invalidation
728    if (flags & CBLK_INVALID) {
729        (void) restoreRecord_l("processAudioBuffer");
730        mLock.unlock();
731        // Run again immediately, but with a new IAudioRecord
732        return 0;
733    }
734
735    bool active = mActive;
736
737    // Manage overrun callback, must be done under lock to avoid race with releaseBuffer()
738    bool newOverrun = false;
739    if (flags & CBLK_OVERRUN) {
740        if (!mInOverrun) {
741            mInOverrun = true;
742            newOverrun = true;
743        }
744    }
745
746    // Get current position of server
747    size_t position = mProxy->getPosition();
748
749    // Manage marker callback
750    bool markerReached = false;
751    size_t markerPosition = mMarkerPosition;
752    // FIXME fails for wraparound, need 64 bits
753    if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
754        mMarkerReached = markerReached = true;
755    }
756
757    // Determine the number of new position callback(s) that will be needed, while locked
758    size_t newPosCount = 0;
759    size_t newPosition = mNewPosition;
760    uint32_t updatePeriod = mUpdatePeriod;
761    // FIXME fails for wraparound, need 64 bits
762    if (updatePeriod > 0 && position >= newPosition) {
763        newPosCount = ((position - newPosition) / updatePeriod) + 1;
764        mNewPosition += updatePeriod * newPosCount;
765    }
766
767    // Cache other fields that will be needed soon
768    size_t notificationFrames = mNotificationFramesAct;
769    if (mRefreshRemaining) {
770        mRefreshRemaining = false;
771        mRemainingFrames = notificationFrames;
772        mRetryOnPartialBuffer = false;
773    }
774    size_t misalignment = mProxy->getMisalignment();
775    int32_t sequence = mSequence;
776
777    // These fields don't need to be cached, because they are assigned only by set():
778    //      mTransfer, mCbf, mUserData, mSampleRate, mFrameSize
779
780    mLock.unlock();
781
782    // perform callbacks while unlocked
783    if (newOverrun) {
784        mCbf(EVENT_OVERRUN, mUserData, NULL);
785    }
786    if (markerReached) {
787        mCbf(EVENT_MARKER, mUserData, &markerPosition);
788    }
789    while (newPosCount > 0) {
790        size_t temp = newPosition;
791        mCbf(EVENT_NEW_POS, mUserData, &temp);
792        newPosition += updatePeriod;
793        newPosCount--;
794    }
795    if (mObservedSequence != sequence) {
796        mObservedSequence = sequence;
797        mCbf(EVENT_NEW_IAUDIORECORD, mUserData, NULL);
798    }
799
800    // if inactive, then don't run me again until re-started
801    if (!active) {
802        return NS_INACTIVE;
803    }
804
805    // Compute the estimated time until the next timed event (position, markers)
806    uint32_t minFrames = ~0;
807    if (!markerReached && position < markerPosition) {
808        minFrames = markerPosition - position;
809    }
810    if (updatePeriod > 0 && updatePeriod < minFrames) {
811        minFrames = updatePeriod;
812    }
813
814    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
815    static const uint32_t kPoll = 0;
816    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
817        minFrames = kPoll * notificationFrames;
818    }
819
820    // Convert frame units to time units
821    nsecs_t ns = NS_WHENEVER;
822    if (minFrames != (uint32_t) ~0) {
823        // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
824        static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
825        ns = ((minFrames * 1000000000LL) / mSampleRate) + kFudgeNs;
826    }
827
828    // If not supplying data by EVENT_MORE_DATA, then we're done
829    if (mTransfer != TRANSFER_CALLBACK) {
830        return ns;
831    }
832
833    struct timespec timeout;
834    const struct timespec *requested = &ClientProxy::kForever;
835    if (ns != NS_WHENEVER) {
836        timeout.tv_sec = ns / 1000000000LL;
837        timeout.tv_nsec = ns % 1000000000LL;
838        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
839        requested = &timeout;
840    }
841
842    while (mRemainingFrames > 0) {
843
844        Buffer audioBuffer;
845        audioBuffer.frameCount = mRemainingFrames;
846        size_t nonContig;
847        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
848        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
849                "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
850        requested = &ClientProxy::kNonBlocking;
851        size_t avail = audioBuffer.frameCount + nonContig;
852        ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
853                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
854        if (err != NO_ERROR) {
855            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
856                break;
857            }
858            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
859            return NS_NEVER;
860        }
861
862        if (mRetryOnPartialBuffer) {
863            mRetryOnPartialBuffer = false;
864            if (avail < mRemainingFrames) {
865                int64_t myns = ((mRemainingFrames - avail) *
866                        1100000000LL) / mSampleRate;
867                if (ns < 0 || myns < ns) {
868                    ns = myns;
869                }
870                return ns;
871            }
872        }
873
874        size_t reqSize = audioBuffer.size;
875        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
876        size_t readSize = audioBuffer.size;
877
878        // Sanity check on returned size
879        if (ssize_t(readSize) < 0 || readSize > reqSize) {
880            ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
881                    reqSize, (int) readSize);
882            return NS_NEVER;
883        }
884
885        if (readSize == 0) {
886            // The callback is done consuming buffers
887            // Keep this thread going to handle timed events and
888            // still try to provide more data in intervals of WAIT_PERIOD_MS
889            // but don't just loop and block the CPU, so wait
890            return WAIT_PERIOD_MS * 1000000LL;
891        }
892
893        size_t releasedFrames = readSize / mFrameSize;
894        audioBuffer.frameCount = releasedFrames;
895        mRemainingFrames -= releasedFrames;
896        if (misalignment >= releasedFrames) {
897            misalignment -= releasedFrames;
898        } else {
899            misalignment = 0;
900        }
901
902        releaseBuffer(&audioBuffer);
903
904        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
905        // if callback doesn't like to accept the full chunk
906        if (readSize < reqSize) {
907            continue;
908        }
909
910        // There could be enough non-contiguous frames available to satisfy the remaining request
911        if (mRemainingFrames <= nonContig) {
912            continue;
913        }
914
915#if 0
916        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
917        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
918        // that total to a sum == notificationFrames.
919        if (0 < misalignment && misalignment <= mRemainingFrames) {
920            mRemainingFrames = misalignment;
921            return (mRemainingFrames * 1100000000LL) / mSampleRate;
922        }
923#endif
924
925    }
926    mRemainingFrames = notificationFrames;
927    mRetryOnPartialBuffer = true;
928
929    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
930    return 0;
931}
932
933status_t AudioRecord::restoreRecord_l(const char *from)
934{
935    ALOGW("dead IAudioRecord, creating a new one from %s()", from);
936    ++mSequence;
937    status_t result;
938
939    // if the new IAudioRecord is created, openRecord_l() will modify the
940    // following member variables: mAudioRecord, mCblkMemory and mCblk.
941    // It will also delete the strong references on previous IAudioRecord and IMemory
942    size_t position = mProxy->getPosition();
943    mNewPosition = position + mUpdatePeriod;
944    result = openRecord_l(position);
945    if (result == NO_ERROR) {
946        if (mActive) {
947            // callback thread or sync event hasn't changed
948            // FIXME this fails if we have a new AudioFlinger instance
949            result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, 0);
950        }
951    }
952    if (result != NO_ERROR) {
953        ALOGW("restoreRecord_l() failed status %d", result);
954        mActive = false;
955    }
956
957    return result;
958}
959
960// =========================================================================
961
962void AudioRecord::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
963{
964    sp<AudioRecord> audioRecord = mAudioRecord.promote();
965    if (audioRecord != 0) {
966        AutoMutex lock(audioRecord->mLock);
967        audioRecord->mProxy->binderDied();
968    }
969}
970
971// =========================================================================
972
973AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver, bool bCanCallJava)
974    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
975      mIgnoreNextPausedInt(false)
976{
977}
978
979AudioRecord::AudioRecordThread::~AudioRecordThread()
980{
981}
982
983bool AudioRecord::AudioRecordThread::threadLoop()
984{
985    {
986        AutoMutex _l(mMyLock);
987        if (mPaused) {
988            mMyCond.wait(mMyLock);
989            // caller will check for exitPending()
990            return true;
991        }
992        if (mIgnoreNextPausedInt) {
993            mIgnoreNextPausedInt = false;
994            mPausedInt = false;
995        }
996        if (mPausedInt) {
997            if (mPausedNs > 0) {
998                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
999            } else {
1000                mMyCond.wait(mMyLock);
1001            }
1002            mPausedInt = false;
1003            return true;
1004        }
1005    }
1006    nsecs_t ns =  mReceiver.processAudioBuffer();
1007    switch (ns) {
1008    case 0:
1009        return true;
1010    case NS_INACTIVE:
1011        pauseInternal();
1012        return true;
1013    case NS_NEVER:
1014        return false;
1015    case NS_WHENEVER:
1016        // FIXME increase poll interval, or make event-driven
1017        ns = 1000000000LL;
1018        // fall through
1019    default:
1020        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
1021        pauseInternal(ns);
1022        return true;
1023    }
1024}
1025
1026void AudioRecord::AudioRecordThread::requestExit()
1027{
1028    // must be in this order to avoid a race condition
1029    Thread::requestExit();
1030    resume();
1031}
1032
1033void AudioRecord::AudioRecordThread::pause()
1034{
1035    AutoMutex _l(mMyLock);
1036    mPaused = true;
1037}
1038
1039void AudioRecord::AudioRecordThread::resume()
1040{
1041    AutoMutex _l(mMyLock);
1042    mIgnoreNextPausedInt = true;
1043    if (mPaused || mPausedInt) {
1044        mPaused = false;
1045        mPausedInt = false;
1046        mMyCond.signal();
1047    }
1048}
1049
1050void AudioRecord::AudioRecordThread::pauseInternal(nsecs_t ns)
1051{
1052    AutoMutex _l(mMyLock);
1053    mPausedInt = true;
1054    mPausedNs = ns;
1055}
1056
1057// -------------------------------------------------------------------------
1058
1059}; // namespace android
1060