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