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