AudioRecord.cpp revision 882469cfe767188a4c67d2d83f3d72ab553a4818
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        if (mAudioRecord != 0) {
106            mAudioRecord->asBinder()->unlinkToDeath(mDeathNotifier, this);
107            mAudioRecord.clear();
108        }
109        IPCThreadState::self()->flushCommands();
110        AudioSystem::releaseAudioSessionId(mSessionId, -1);
111    }
112}
113
114status_t AudioRecord::set(
115        audio_source_t inputSource,
116        uint32_t sampleRate,
117        audio_format_t format,
118        audio_channel_mask_t channelMask,
119        int frameCountInt,
120        callback_t cbf,
121        void* user,
122        int notificationFrames,
123        bool threadCanCallJava,
124        int sessionId,
125        transfer_type transferType,
126        audio_input_flags_t flags)
127{
128    ALOGV("set(): inputSource %d, sampleRate %u, format %#x, channelMask %#x, frameCount %d, "
129          "notificationFrames %d, sessionId %d, transferType %d, flags %#x",
130          inputSource, sampleRate, format, channelMask, frameCountInt, notificationFrames,
131          sessionId, transferType, flags);
132
133    switch (transferType) {
134    case TRANSFER_DEFAULT:
135        if (cbf == NULL || threadCanCallJava) {
136            transferType = TRANSFER_SYNC;
137        } else {
138            transferType = TRANSFER_CALLBACK;
139        }
140        break;
141    case TRANSFER_CALLBACK:
142        if (cbf == NULL) {
143            ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL");
144            return BAD_VALUE;
145        }
146        break;
147    case TRANSFER_OBTAIN:
148    case TRANSFER_SYNC:
149        break;
150    default:
151        ALOGE("Invalid transfer type %d", transferType);
152        return BAD_VALUE;
153    }
154    mTransfer = transferType;
155
156    // FIXME "int" here is legacy and will be replaced by size_t later
157    if (frameCountInt < 0) {
158        ALOGE("Invalid frame count %d", frameCountInt);
159        return BAD_VALUE;
160    }
161    size_t frameCount = frameCountInt;
162
163    AutoMutex lock(mLock);
164
165    if (mAudioRecord != 0) {
166        ALOGE("Track already in use");
167        return INVALID_OPERATION;
168    }
169
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    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 mFrameCount
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    // starting address of buffers in shared memory
541    void *buffers = (char*)cblk + sizeof(audio_track_cblk_t);
542
543    mFrameCount = frameCount;
544    // If IAudioRecord is re-created, don't let the requested frameCount
545    // decrease.  This can confuse clients that cache frameCount().
546    if (frameCount > mReqFrameCount) {
547        mReqFrameCount = frameCount;
548    }
549
550    // update proxy
551    mProxy = new AudioRecordClientProxy(cblk, buffers, mFrameCount, mFrameSize);
552    mProxy->setEpoch(epoch);
553    mProxy->setMinimum(mNotificationFramesAct);
554
555    mDeathNotifier = new DeathNotifier(this);
556    mAudioRecord->asBinder()->linkToDeath(mDeathNotifier, this);
557
558    return NO_ERROR;
559    }
560
561release:
562    AudioSystem::releaseInput(input);
563    if (status == NO_ERROR) {
564        status = NO_INIT;
565    }
566    return status;
567}
568
569status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
570{
571    if (audioBuffer == NULL) {
572        return BAD_VALUE;
573    }
574    if (mTransfer != TRANSFER_OBTAIN) {
575        audioBuffer->frameCount = 0;
576        audioBuffer->size = 0;
577        audioBuffer->raw = NULL;
578        return INVALID_OPERATION;
579    }
580
581    const struct timespec *requested;
582    struct timespec timeout;
583    if (waitCount == -1) {
584        requested = &ClientProxy::kForever;
585    } else if (waitCount == 0) {
586        requested = &ClientProxy::kNonBlocking;
587    } else if (waitCount > 0) {
588        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
589        timeout.tv_sec = ms / 1000;
590        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
591        requested = &timeout;
592    } else {
593        ALOGE("%s invalid waitCount %d", __func__, waitCount);
594        requested = NULL;
595    }
596    return obtainBuffer(audioBuffer, requested);
597}
598
599status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
600        struct timespec *elapsed, size_t *nonContig)
601{
602    // previous and new IAudioRecord sequence numbers are used to detect track re-creation
603    uint32_t oldSequence = 0;
604    uint32_t newSequence;
605
606    Proxy::Buffer buffer;
607    status_t status = NO_ERROR;
608
609    static const int32_t kMaxTries = 5;
610    int32_t tryCounter = kMaxTries;
611
612    do {
613        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
614        // keep them from going away if another thread re-creates the track during obtainBuffer()
615        sp<AudioRecordClientProxy> proxy;
616        sp<IMemory> iMem;
617        {
618            // start of lock scope
619            AutoMutex lock(mLock);
620
621            newSequence = mSequence;
622            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
623            if (status == DEAD_OBJECT) {
624                // re-create track, unless someone else has already done so
625                if (newSequence == oldSequence) {
626                    status = restoreRecord_l("obtainBuffer");
627                    if (status != NO_ERROR) {
628                        buffer.mFrameCount = 0;
629                        buffer.mRaw = NULL;
630                        buffer.mNonContig = 0;
631                        break;
632                    }
633                }
634            }
635            oldSequence = newSequence;
636
637            // Keep the extra references
638            proxy = mProxy;
639            iMem = mCblkMemory;
640
641            // Non-blocking if track is stopped
642            if (!mActive) {
643                requested = &ClientProxy::kNonBlocking;
644            }
645
646        }   // end of lock scope
647
648        buffer.mFrameCount = audioBuffer->frameCount;
649        // FIXME starts the requested timeout and elapsed over from scratch
650        status = proxy->obtainBuffer(&buffer, requested, elapsed);
651
652    } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
653
654    audioBuffer->frameCount = buffer.mFrameCount;
655    audioBuffer->size = buffer.mFrameCount * mFrameSize;
656    audioBuffer->raw = buffer.mRaw;
657    if (nonContig != NULL) {
658        *nonContig = buffer.mNonContig;
659    }
660    return status;
661}
662
663void AudioRecord::releaseBuffer(Buffer* audioBuffer)
664{
665    // all TRANSFER_* are valid
666
667    size_t stepCount = audioBuffer->size / mFrameSize;
668    if (stepCount == 0) {
669        return;
670    }
671
672    Proxy::Buffer buffer;
673    buffer.mFrameCount = stepCount;
674    buffer.mRaw = audioBuffer->raw;
675
676    AutoMutex lock(mLock);
677    mInOverrun = false;
678    mProxy->releaseBuffer(&buffer);
679
680    // the server does not automatically disable recorder on overrun, so no need to restart
681}
682
683audio_io_handle_t AudioRecord::getInput() const
684{
685    AutoMutex lock(mLock);
686    return mInput;
687}
688
689// -------------------------------------------------------------------------
690
691ssize_t AudioRecord::read(void* buffer, size_t userSize)
692{
693    if (mTransfer != TRANSFER_SYNC) {
694        return INVALID_OPERATION;
695    }
696
697    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
698        // sanity-check. user is most-likely passing an error code, and it would
699        // make the return value ambiguous (actualSize vs error).
700        ALOGE("AudioRecord::read(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
701        return BAD_VALUE;
702    }
703
704    ssize_t read = 0;
705    Buffer audioBuffer;
706
707    while (userSize >= mFrameSize) {
708        audioBuffer.frameCount = userSize / mFrameSize;
709
710        status_t err = obtainBuffer(&audioBuffer, &ClientProxy::kForever);
711        if (err < 0) {
712            if (read > 0) {
713                break;
714            }
715            return ssize_t(err);
716        }
717
718        size_t bytesRead = audioBuffer.size;
719        memcpy(buffer, audioBuffer.i8, bytesRead);
720        buffer = ((char *) buffer) + bytesRead;
721        userSize -= bytesRead;
722        read += bytesRead;
723
724        releaseBuffer(&audioBuffer);
725    }
726
727    return read;
728}
729
730// -------------------------------------------------------------------------
731
732nsecs_t AudioRecord::processAudioBuffer()
733{
734    mLock.lock();
735    if (mAwaitBoost) {
736        mAwaitBoost = false;
737        mLock.unlock();
738        static const int32_t kMaxTries = 5;
739        int32_t tryCounter = kMaxTries;
740        uint32_t pollUs = 10000;
741        do {
742            int policy = sched_getscheduler(0);
743            if (policy == SCHED_FIFO || policy == SCHED_RR) {
744                break;
745            }
746            usleep(pollUs);
747            pollUs <<= 1;
748        } while (tryCounter-- > 0);
749        if (tryCounter < 0) {
750            ALOGE("did not receive expected priority boost on time");
751        }
752        // Run again immediately
753        return 0;
754    }
755
756    // Can only reference mCblk while locked
757    int32_t flags = android_atomic_and(~CBLK_OVERRUN, &mCblk->mFlags);
758
759    // Check for track invalidation
760    if (flags & CBLK_INVALID) {
761        (void) restoreRecord_l("processAudioBuffer");
762        mLock.unlock();
763        // Run again immediately, but with a new IAudioRecord
764        return 0;
765    }
766
767    bool active = mActive;
768
769    // Manage overrun callback, must be done under lock to avoid race with releaseBuffer()
770    bool newOverrun = false;
771    if (flags & CBLK_OVERRUN) {
772        if (!mInOverrun) {
773            mInOverrun = true;
774            newOverrun = true;
775        }
776    }
777
778    // Get current position of server
779    size_t position = mProxy->getPosition();
780
781    // Manage marker callback
782    bool markerReached = false;
783    size_t markerPosition = mMarkerPosition;
784    // FIXME fails for wraparound, need 64 bits
785    if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
786        mMarkerReached = markerReached = true;
787    }
788
789    // Determine the number of new position callback(s) that will be needed, while locked
790    size_t newPosCount = 0;
791    size_t newPosition = mNewPosition;
792    uint32_t updatePeriod = mUpdatePeriod;
793    // FIXME fails for wraparound, need 64 bits
794    if (updatePeriod > 0 && position >= newPosition) {
795        newPosCount = ((position - newPosition) / updatePeriod) + 1;
796        mNewPosition += updatePeriod * newPosCount;
797    }
798
799    // Cache other fields that will be needed soon
800    size_t notificationFrames = mNotificationFramesAct;
801    if (mRefreshRemaining) {
802        mRefreshRemaining = false;
803        mRemainingFrames = notificationFrames;
804        mRetryOnPartialBuffer = false;
805    }
806    size_t misalignment = mProxy->getMisalignment();
807    uint32_t sequence = mSequence;
808
809    // These fields don't need to be cached, because they are assigned only by set():
810    //      mTransfer, mCbf, mUserData, mSampleRate, mFrameSize
811
812    mLock.unlock();
813
814    // perform callbacks while unlocked
815    if (newOverrun) {
816        mCbf(EVENT_OVERRUN, mUserData, NULL);
817    }
818    if (markerReached) {
819        mCbf(EVENT_MARKER, mUserData, &markerPosition);
820    }
821    while (newPosCount > 0) {
822        size_t temp = newPosition;
823        mCbf(EVENT_NEW_POS, mUserData, &temp);
824        newPosition += updatePeriod;
825        newPosCount--;
826    }
827    if (mObservedSequence != sequence) {
828        mObservedSequence = sequence;
829        mCbf(EVENT_NEW_IAUDIORECORD, mUserData, NULL);
830    }
831
832    // if inactive, then don't run me again until re-started
833    if (!active) {
834        return NS_INACTIVE;
835    }
836
837    // Compute the estimated time until the next timed event (position, markers)
838    uint32_t minFrames = ~0;
839    if (!markerReached && position < markerPosition) {
840        minFrames = markerPosition - position;
841    }
842    if (updatePeriod > 0 && updatePeriod < minFrames) {
843        minFrames = updatePeriod;
844    }
845
846    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
847    static const uint32_t kPoll = 0;
848    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
849        minFrames = kPoll * notificationFrames;
850    }
851
852    // Convert frame units to time units
853    nsecs_t ns = NS_WHENEVER;
854    if (minFrames != (uint32_t) ~0) {
855        // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
856        static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
857        ns = ((minFrames * 1000000000LL) / mSampleRate) + kFudgeNs;
858    }
859
860    // If not supplying data by EVENT_MORE_DATA, then we're done
861    if (mTransfer != TRANSFER_CALLBACK) {
862        return ns;
863    }
864
865    struct timespec timeout;
866    const struct timespec *requested = &ClientProxy::kForever;
867    if (ns != NS_WHENEVER) {
868        timeout.tv_sec = ns / 1000000000LL;
869        timeout.tv_nsec = ns % 1000000000LL;
870        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
871        requested = &timeout;
872    }
873
874    while (mRemainingFrames > 0) {
875
876        Buffer audioBuffer;
877        audioBuffer.frameCount = mRemainingFrames;
878        size_t nonContig;
879        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
880        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
881                "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
882        requested = &ClientProxy::kNonBlocking;
883        size_t avail = audioBuffer.frameCount + nonContig;
884        ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
885                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
886        if (err != NO_ERROR) {
887            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
888                break;
889            }
890            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
891            return NS_NEVER;
892        }
893
894        if (mRetryOnPartialBuffer) {
895            mRetryOnPartialBuffer = false;
896            if (avail < mRemainingFrames) {
897                int64_t myns = ((mRemainingFrames - avail) *
898                        1100000000LL) / mSampleRate;
899                if (ns < 0 || myns < ns) {
900                    ns = myns;
901                }
902                return ns;
903            }
904        }
905
906        size_t reqSize = audioBuffer.size;
907        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
908        size_t readSize = audioBuffer.size;
909
910        // Sanity check on returned size
911        if (ssize_t(readSize) < 0 || readSize > reqSize) {
912            ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
913                    reqSize, (int) readSize);
914            return NS_NEVER;
915        }
916
917        if (readSize == 0) {
918            // The callback is done consuming buffers
919            // Keep this thread going to handle timed events and
920            // still try to provide more data in intervals of WAIT_PERIOD_MS
921            // but don't just loop and block the CPU, so wait
922            return WAIT_PERIOD_MS * 1000000LL;
923        }
924
925        size_t releasedFrames = readSize / mFrameSize;
926        audioBuffer.frameCount = releasedFrames;
927        mRemainingFrames -= releasedFrames;
928        if (misalignment >= releasedFrames) {
929            misalignment -= releasedFrames;
930        } else {
931            misalignment = 0;
932        }
933
934        releaseBuffer(&audioBuffer);
935
936        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
937        // if callback doesn't like to accept the full chunk
938        if (readSize < reqSize) {
939            continue;
940        }
941
942        // There could be enough non-contiguous frames available to satisfy the remaining request
943        if (mRemainingFrames <= nonContig) {
944            continue;
945        }
946
947#if 0
948        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
949        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
950        // that total to a sum == notificationFrames.
951        if (0 < misalignment && misalignment <= mRemainingFrames) {
952            mRemainingFrames = misalignment;
953            return (mRemainingFrames * 1100000000LL) / mSampleRate;
954        }
955#endif
956
957    }
958    mRemainingFrames = notificationFrames;
959    mRetryOnPartialBuffer = true;
960
961    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
962    return 0;
963}
964
965status_t AudioRecord::restoreRecord_l(const char *from)
966{
967    ALOGW("dead IAudioRecord, creating a new one from %s()", from);
968    ++mSequence;
969    status_t result;
970
971    // if the new IAudioRecord is created, openRecord_l() will modify the
972    // following member variables: mAudioRecord, mCblkMemory and mCblk.
973    // It will also delete the strong references on previous IAudioRecord and IMemory
974    size_t position = mProxy->getPosition();
975    mNewPosition = position + mUpdatePeriod;
976    result = openRecord_l(position);
977    if (result == NO_ERROR) {
978        if (mActive) {
979            // callback thread or sync event hasn't changed
980            // FIXME this fails if we have a new AudioFlinger instance
981            result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, 0);
982        }
983    }
984    if (result != NO_ERROR) {
985        ALOGW("restoreRecord_l() failed status %d", result);
986        mActive = false;
987    }
988
989    return result;
990}
991
992// =========================================================================
993
994void AudioRecord::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
995{
996    sp<AudioRecord> audioRecord = mAudioRecord.promote();
997    if (audioRecord != 0) {
998        AutoMutex lock(audioRecord->mLock);
999        audioRecord->mProxy->binderDied();
1000    }
1001}
1002
1003// =========================================================================
1004
1005AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver, bool bCanCallJava)
1006    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
1007      mIgnoreNextPausedInt(false)
1008{
1009}
1010
1011AudioRecord::AudioRecordThread::~AudioRecordThread()
1012{
1013}
1014
1015bool AudioRecord::AudioRecordThread::threadLoop()
1016{
1017    {
1018        AutoMutex _l(mMyLock);
1019        if (mPaused) {
1020            mMyCond.wait(mMyLock);
1021            // caller will check for exitPending()
1022            return true;
1023        }
1024        if (mIgnoreNextPausedInt) {
1025            mIgnoreNextPausedInt = false;
1026            mPausedInt = false;
1027        }
1028        if (mPausedInt) {
1029            if (mPausedNs > 0) {
1030                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1031            } else {
1032                mMyCond.wait(mMyLock);
1033            }
1034            mPausedInt = false;
1035            return true;
1036        }
1037    }
1038    nsecs_t ns =  mReceiver.processAudioBuffer();
1039    switch (ns) {
1040    case 0:
1041        return true;
1042    case NS_INACTIVE:
1043        pauseInternal();
1044        return true;
1045    case NS_NEVER:
1046        return false;
1047    case NS_WHENEVER:
1048        // FIXME increase poll interval, or make event-driven
1049        ns = 1000000000LL;
1050        // fall through
1051    default:
1052        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
1053        pauseInternal(ns);
1054        return true;
1055    }
1056}
1057
1058void AudioRecord::AudioRecordThread::requestExit()
1059{
1060    // must be in this order to avoid a race condition
1061    Thread::requestExit();
1062    resume();
1063}
1064
1065void AudioRecord::AudioRecordThread::pause()
1066{
1067    AutoMutex _l(mMyLock);
1068    mPaused = true;
1069}
1070
1071void AudioRecord::AudioRecordThread::resume()
1072{
1073    AutoMutex _l(mMyLock);
1074    mIgnoreNextPausedInt = true;
1075    if (mPaused || mPausedInt) {
1076        mPaused = false;
1077        mPausedInt = false;
1078        mMyCond.signal();
1079    }
1080}
1081
1082void AudioRecord::AudioRecordThread::pauseInternal(nsecs_t ns)
1083{
1084    AutoMutex _l(mMyLock);
1085    mPausedInt = true;
1086    mPausedNs = ns;
1087}
1088
1089// -------------------------------------------------------------------------
1090
1091}; // namespace android
1092