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