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