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