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