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