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 <inttypes.h>
22 #include <android-base/macros.h>
23 #include <sys/resource.h>
24 
25 #include <audiomanager/AudioManager.h>
26 #include <audiomanager/IAudioManager.h>
27 #include <binder/Binder.h>
28 #include <binder/IPCThreadState.h>
29 #include <binder/IServiceManager.h>
30 #include <media/AudioRecord.h>
31 #include <utils/Log.h>
32 #include <private/media/AudioTrackShared.h>
33 #include <processgroup/sched_policy.h>
34 #include <media/IAudioFlinger.h>
35 #include <media/MediaAnalyticsItem.h>
36 #include <media/TypeConverter.h>
37 
38 #define WAIT_PERIOD_MS          10
39 
40 namespace android {
41 // ---------------------------------------------------------------------------
42 
43 // static
getMinFrameCount(size_t * frameCount,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask)44 status_t AudioRecord::getMinFrameCount(
45         size_t* frameCount,
46         uint32_t sampleRate,
47         audio_format_t format,
48         audio_channel_mask_t channelMask)
49 {
50     if (frameCount == NULL) {
51         return BAD_VALUE;
52     }
53 
54     size_t size;
55     status_t status = AudioSystem::getInputBufferSize(sampleRate, format, channelMask, &size);
56     if (status != NO_ERROR) {
57         ALOGE("%s(): AudioSystem could not query the input buffer size for"
58               " sampleRate %u, format %#x, channelMask %#x; status %d",
59                __func__, sampleRate, format, channelMask, status);
60         return status;
61     }
62 
63     // We double the size of input buffer for ping pong use of record buffer.
64     // Assumes audio_is_linear_pcm(format)
65     if ((*frameCount = (size * 2) / (audio_channel_count_from_in_mask(channelMask) *
66             audio_bytes_per_sample(format))) == 0) {
67         ALOGE("%s(): Unsupported configuration: sampleRate %u, format %#x, channelMask %#x",
68                 __func__, sampleRate, format, channelMask);
69         return BAD_VALUE;
70     }
71 
72     return NO_ERROR;
73 }
74 
75 // ---------------------------------------------------------------------------
76 
gather(const AudioRecord * record)77 void AudioRecord::MediaMetrics::gather(const AudioRecord *record)
78 {
79 #define MM_PREFIX "android.media.audiorecord." // avoid cut-n-paste errors.
80 
81     // Java API 28 entries, do not change.
82     mAnalyticsItem->setCString(MM_PREFIX "encoding", toString(record->mFormat).c_str());
83     mAnalyticsItem->setCString(MM_PREFIX "source", toString(record->mAttributes.source).c_str());
84     mAnalyticsItem->setInt32(MM_PREFIX "latency", (int32_t)record->mLatency); // bad estimate.
85     mAnalyticsItem->setInt32(MM_PREFIX "samplerate", (int32_t)record->mSampleRate);
86     mAnalyticsItem->setInt32(MM_PREFIX "channels", (int32_t)record->mChannelCount);
87 
88     // Non-API entries, these can change.
89     mAnalyticsItem->setInt32(MM_PREFIX "portId", (int32_t)record->mPortId);
90     mAnalyticsItem->setInt32(MM_PREFIX "frameCount", (int32_t)record->mFrameCount);
91     mAnalyticsItem->setCString(MM_PREFIX "attributes", toString(record->mAttributes).c_str());
92     mAnalyticsItem->setInt64(MM_PREFIX "channelMask", (int64_t)record->mChannelMask);
93 
94     // log total duration recording, including anything currently running.
95     int64_t activeNs = 0;
96     if (mStartedNs != 0) {
97         activeNs = systemTime() - mStartedNs;
98     }
99     mAnalyticsItem->setDouble(MM_PREFIX "durationMs", (mDurationNs + activeNs) * 1e-6);
100     mAnalyticsItem->setInt64(MM_PREFIX "startCount", (int64_t)mCount);
101 
102     if (mLastError != NO_ERROR) {
103         mAnalyticsItem->setInt32(MM_PREFIX "lastError.code", (int32_t)mLastError);
104         mAnalyticsItem->setCString(MM_PREFIX "lastError.at", mLastErrorFunc.c_str());
105     }
106 }
107 
108 // hand the user a snapshot of the metrics.
getMetrics(MediaAnalyticsItem * & item)109 status_t AudioRecord::getMetrics(MediaAnalyticsItem * &item)
110 {
111     mMediaMetrics.gather(this);
112     MediaAnalyticsItem *tmp = mMediaMetrics.dup();
113     if (tmp == nullptr) {
114         return BAD_VALUE;
115     }
116     item = tmp;
117     return NO_ERROR;
118 }
119 
AudioRecord(const String16 & opPackageName)120 AudioRecord::AudioRecord(const String16 &opPackageName)
121     : mActive(false), mStatus(NO_INIT), mOpPackageName(opPackageName),
122       mSessionId(AUDIO_SESSION_ALLOCATE),
123       mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT),
124       mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE), mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
125       mSelectedMicDirection(MIC_DIRECTION_UNSPECIFIED),
126       mSelectedMicFieldDimension(MIC_FIELD_DIMENSION_DEFAULT)
127 {
128 }
129 
AudioRecord(audio_source_t inputSource,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,const String16 & opPackageName,size_t frameCount,callback_t cbf,void * user,uint32_t notificationFrames,audio_session_t sessionId,transfer_type transferType,audio_input_flags_t flags,uid_t uid,pid_t pid,const audio_attributes_t * pAttributes,audio_port_handle_t selectedDeviceId,audio_microphone_direction_t selectedMicDirection,float microphoneFieldDimension)130 AudioRecord::AudioRecord(
131         audio_source_t inputSource,
132         uint32_t sampleRate,
133         audio_format_t format,
134         audio_channel_mask_t channelMask,
135         const String16& opPackageName,
136         size_t frameCount,
137         callback_t cbf,
138         void* user,
139         uint32_t notificationFrames,
140         audio_session_t sessionId,
141         transfer_type transferType,
142         audio_input_flags_t flags,
143         uid_t uid,
144         pid_t pid,
145         const audio_attributes_t* pAttributes,
146         audio_port_handle_t selectedDeviceId,
147         audio_microphone_direction_t selectedMicDirection,
148         float microphoneFieldDimension)
149     : mActive(false),
150       mStatus(NO_INIT),
151       mOpPackageName(opPackageName),
152       mSessionId(AUDIO_SESSION_ALLOCATE),
153       mPreviousPriority(ANDROID_PRIORITY_NORMAL),
154       mPreviousSchedulingGroup(SP_DEFAULT),
155       mProxy(NULL)
156 {
157     (void)set(inputSource, sampleRate, format, channelMask, frameCount, cbf, user,
158             notificationFrames, false /*threadCanCallJava*/, sessionId, transferType, flags,
159             uid, pid, pAttributes, selectedDeviceId,
160             selectedMicDirection, microphoneFieldDimension);
161 }
162 
~AudioRecord()163 AudioRecord::~AudioRecord()
164 {
165     mMediaMetrics.gather(this);
166 
167     if (mStatus == NO_ERROR) {
168         // Make sure that callback function exits in the case where
169         // it is looping on buffer empty condition in obtainBuffer().
170         // Otherwise the callback thread will never exit.
171         stop();
172         if (mAudioRecordThread != 0) {
173             mProxy->interrupt();
174             mAudioRecordThread->requestExit();  // see comment in AudioRecord.h
175             mAudioRecordThread->requestExitAndWait();
176             mAudioRecordThread.clear();
177         }
178         // No lock here: worst case we remove a NULL callback which will be a nop
179         if (mDeviceCallback != 0 && mInput != AUDIO_IO_HANDLE_NONE) {
180             AudioSystem::removeAudioDeviceCallback(this, mInput, mPortId);
181         }
182         IInterface::asBinder(mAudioRecord)->unlinkToDeath(mDeathNotifier, this);
183         mAudioRecord.clear();
184         mCblkMemory.clear();
185         mBufferMemory.clear();
186         IPCThreadState::self()->flushCommands();
187         ALOGV("%s(%d): releasing session id %d",
188                 __func__, mPortId, mSessionId);
189         AudioSystem::releaseAudioSessionId(mSessionId, -1 /*pid*/);
190     }
191 }
192 
set(audio_source_t inputSource,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,callback_t cbf,void * user,uint32_t notificationFrames,bool threadCanCallJava,audio_session_t sessionId,transfer_type transferType,audio_input_flags_t flags,uid_t uid,pid_t pid,const audio_attributes_t * pAttributes,audio_port_handle_t selectedDeviceId,audio_microphone_direction_t selectedMicDirection,float microphoneFieldDimension)193 status_t AudioRecord::set(
194         audio_source_t inputSource,
195         uint32_t sampleRate,
196         audio_format_t format,
197         audio_channel_mask_t channelMask,
198         size_t frameCount,
199         callback_t cbf,
200         void* user,
201         uint32_t notificationFrames,
202         bool threadCanCallJava,
203         audio_session_t sessionId,
204         transfer_type transferType,
205         audio_input_flags_t flags,
206         uid_t uid,
207         pid_t pid,
208         const audio_attributes_t* pAttributes,
209         audio_port_handle_t selectedDeviceId,
210         audio_microphone_direction_t selectedMicDirection,
211         float microphoneFieldDimension)
212 {
213     status_t status = NO_ERROR;
214     uint32_t channelCount;
215     pid_t callingPid;
216     pid_t myPid;
217 
218     // Note mPortId is not valid until the track is created, so omit mPortId in ALOG for set.
219     ALOGV("%s(): inputSource %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
220           "notificationFrames %u, sessionId %d, transferType %d, flags %#x, opPackageName %s "
221           "uid %d, pid %d",
222           __func__,
223           inputSource, sampleRate, format, channelMask, frameCount, notificationFrames,
224           sessionId, transferType, flags, String8(mOpPackageName).string(), uid, pid);
225 
226     mTracker.reset(new RecordingActivityTracker());
227 
228     mSelectedDeviceId = selectedDeviceId;
229     mSelectedMicDirection = selectedMicDirection;
230     mSelectedMicFieldDimension = microphoneFieldDimension;
231 
232     switch (transferType) {
233     case TRANSFER_DEFAULT:
234         if (cbf == NULL || threadCanCallJava) {
235             transferType = TRANSFER_SYNC;
236         } else {
237             transferType = TRANSFER_CALLBACK;
238         }
239         break;
240     case TRANSFER_CALLBACK:
241         if (cbf == NULL) {
242             ALOGE("%s(): Transfer type TRANSFER_CALLBACK but cbf == NULL", __func__);
243             status = BAD_VALUE;
244             goto exit;
245         }
246         break;
247     case TRANSFER_OBTAIN:
248     case TRANSFER_SYNC:
249         break;
250     default:
251         ALOGE("%s(): Invalid transfer type %d", __func__, transferType);
252         status = BAD_VALUE;
253         goto exit;
254     }
255     mTransfer = transferType;
256 
257     // invariant that mAudioRecord != 0 is true only after set() returns successfully
258     if (mAudioRecord != 0) {
259         ALOGE("%s(): Track already in use", __func__);
260         status = INVALID_OPERATION;
261         goto exit;
262     }
263 
264     if (pAttributes == NULL) {
265         memset(&mAttributes, 0, sizeof(audio_attributes_t));
266         mAttributes.source = inputSource;
267     } else {
268         // stream type shouldn't be looked at, this track has audio attributes
269         memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
270         ALOGV("%s(): Building AudioRecord with attributes: source=%d flags=0x%x tags=[%s]",
271                 __func__, mAttributes.source, mAttributes.flags, mAttributes.tags);
272     }
273 
274     mSampleRate = sampleRate;
275 
276     // these below should probably come from the audioFlinger too...
277     if (format == AUDIO_FORMAT_DEFAULT) {
278         format = AUDIO_FORMAT_PCM_16_BIT;
279     }
280 
281     // validate parameters
282     // AudioFlinger capture only supports linear PCM
283     if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
284         ALOGE("%s(): Format %#x is not linear pcm", __func__, format);
285         status = BAD_VALUE;
286         goto exit;
287     }
288     mFormat = format;
289 
290     if (!audio_is_input_channel(channelMask)) {
291         ALOGE("%s(): Invalid channel mask %#x", __func__, channelMask);
292         status = BAD_VALUE;
293         goto exit;
294     }
295     mChannelMask = channelMask;
296     channelCount = audio_channel_count_from_in_mask(channelMask);
297     mChannelCount = channelCount;
298 
299     if (audio_is_linear_pcm(format)) {
300         mFrameSize = channelCount * audio_bytes_per_sample(format);
301     } else {
302         mFrameSize = sizeof(uint8_t);
303     }
304 
305     // mFrameCount is initialized in createRecord_l
306     mReqFrameCount = frameCount;
307 
308     mNotificationFramesReq = notificationFrames;
309     // mNotificationFramesAct is initialized in createRecord_l
310 
311     mSessionId = sessionId;
312     ALOGV("%s(): mSessionId %d", __func__, mSessionId);
313 
314     callingPid = IPCThreadState::self()->getCallingPid();
315     myPid = getpid();
316     if (uid == AUDIO_UID_INVALID || (callingPid != myPid)) {
317         mClientUid = IPCThreadState::self()->getCallingUid();
318     } else {
319         mClientUid = uid;
320     }
321     if (pid == -1 || (callingPid != myPid)) {
322         mClientPid = callingPid;
323     } else {
324         mClientPid = pid;
325     }
326 
327     mOrigFlags = mFlags = flags;
328     mCbf = cbf;
329 
330     if (cbf != NULL) {
331         mAudioRecordThread = new AudioRecordThread(*this);
332         mAudioRecordThread->run("AudioRecord", ANDROID_PRIORITY_AUDIO);
333         // thread begins in paused state, and will not reference us until start()
334     }
335 
336     // create the IAudioRecord
337     {
338         AutoMutex lock(mLock);
339         status = createRecord_l(0 /*epoch*/, mOpPackageName);
340     }
341 
342     ALOGV("%s(%d): status %d", __func__, mPortId, status);
343 
344     if (status != NO_ERROR) {
345         if (mAudioRecordThread != 0) {
346             mAudioRecordThread->requestExit();   // see comment in AudioRecord.h
347             mAudioRecordThread->requestExitAndWait();
348             mAudioRecordThread.clear();
349         }
350         goto exit;
351     }
352 
353     mUserData = user;
354     // TODO: add audio hardware input latency here
355     mLatency = (1000LL * mFrameCount) / mSampleRate;
356     mMarkerPosition = 0;
357     mMarkerReached = false;
358     mNewPosition = 0;
359     mUpdatePeriod = 0;
360     AudioSystem::acquireAudioSessionId(mSessionId, -1);
361     mSequence = 1;
362     mObservedSequence = mSequence;
363     mInOverrun = false;
364     mFramesRead = 0;
365     mFramesReadServerOffset = 0;
366 
367 exit:
368     mStatus = status;
369     if (status != NO_ERROR) {
370         mMediaMetrics.markError(status, __FUNCTION__);
371     }
372     return status;
373 }
374 
375 // -------------------------------------------------------------------------
376 
start(AudioSystem::sync_event_t event,audio_session_t triggerSession)377 status_t AudioRecord::start(AudioSystem::sync_event_t event, audio_session_t triggerSession)
378 {
379     ALOGV("%s(%d): sync event %d trigger session %d", __func__, mPortId, event, triggerSession);
380 
381     AutoMutex lock(mLock);
382     if (mActive) {
383         return NO_ERROR;
384     }
385 
386     // discard data in buffer
387     const uint32_t framesFlushed = mProxy->flush();
388     mFramesReadServerOffset -= mFramesRead + framesFlushed;
389     mFramesRead = 0;
390     mProxy->clearTimestamp();  // timestamp is invalid until next server push
391     mPreviousTimestamp.clear();
392     mTimestampRetrogradePositionReported = false;
393     mTimestampRetrogradeTimeReported = false;
394 
395     // reset current position as seen by client to 0
396     mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
397     // force refresh of remaining frames by processAudioBuffer() as last
398     // read before stop could be partial.
399     mRefreshRemaining = true;
400 
401     mNewPosition = mProxy->getPosition() + mUpdatePeriod;
402     int32_t flags = android_atomic_acquire_load(&mCblk->mFlags);
403 
404     // we reactivate markers (mMarkerPosition != 0) as the position is reset to 0.
405     // This is legacy behavior.  This is not done in stop() to avoid a race condition
406     // where the last marker event is issued twice.
407     mMarkerReached = false;
408     // mActive is checked by restoreRecord_l
409     mActive = true;
410 
411     status_t status = NO_ERROR;
412     if (!(flags & CBLK_INVALID)) {
413         status = mAudioRecord->start(event, triggerSession).transactionError();
414         if (status == DEAD_OBJECT) {
415             flags |= CBLK_INVALID;
416         }
417     }
418     if (flags & CBLK_INVALID) {
419         status = restoreRecord_l("start");
420     }
421 
422     // Call these directly because we are already holding the lock.
423     mAudioRecord->setPreferredMicrophoneDirection(mSelectedMicDirection);
424     mAudioRecord->setPreferredMicrophoneFieldDimension(mSelectedMicFieldDimension);
425 
426     if (status != NO_ERROR) {
427         mActive = false;
428         ALOGE("%s(%d): status %d", __func__, mPortId, status);
429         mMediaMetrics.markError(status, __FUNCTION__);
430     } else {
431         mTracker->recordingStarted();
432         sp<AudioRecordThread> t = mAudioRecordThread;
433         if (t != 0) {
434             t->resume();
435         } else {
436             mPreviousPriority = getpriority(PRIO_PROCESS, 0);
437             get_sched_policy(0, &mPreviousSchedulingGroup);
438             androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
439         }
440 
441         // we've successfully started, log that time
442         mMediaMetrics.logStart(systemTime());
443     }
444     return status;
445 }
446 
stop()447 void AudioRecord::stop()
448 {
449     AutoMutex lock(mLock);
450     ALOGV("%s(%d): mActive:%d\n", __func__, mPortId, mActive);
451     if (!mActive) {
452         return;
453     }
454 
455     mActive = false;
456     mProxy->interrupt();
457     mAudioRecord->stop();
458     mTracker->recordingStopped();
459 
460     // Note: legacy handling - stop does not clear record marker and
461     // periodic update position; we update those on start().
462 
463     sp<AudioRecordThread> t = mAudioRecordThread;
464     if (t != 0) {
465         t->pause();
466     } else {
467         setpriority(PRIO_PROCESS, 0, mPreviousPriority);
468         set_sched_policy(0, mPreviousSchedulingGroup);
469     }
470 
471     // we've successfully started, log that time
472     mMediaMetrics.logStop(systemTime());
473 }
474 
stopped() const475 bool AudioRecord::stopped() const
476 {
477     AutoMutex lock(mLock);
478     return !mActive;
479 }
480 
setMarkerPosition(uint32_t marker)481 status_t AudioRecord::setMarkerPosition(uint32_t marker)
482 {
483     // The only purpose of setting marker position is to get a callback
484     if (mCbf == NULL) {
485         return INVALID_OPERATION;
486     }
487 
488     AutoMutex lock(mLock);
489     mMarkerPosition = marker;
490     mMarkerReached = false;
491 
492     sp<AudioRecordThread> t = mAudioRecordThread;
493     if (t != 0) {
494         t->wake();
495     }
496     return NO_ERROR;
497 }
498 
getMarkerPosition(uint32_t * marker) const499 status_t AudioRecord::getMarkerPosition(uint32_t *marker) const
500 {
501     if (marker == NULL) {
502         return BAD_VALUE;
503     }
504 
505     AutoMutex lock(mLock);
506     mMarkerPosition.getValue(marker);
507 
508     return NO_ERROR;
509 }
510 
setPositionUpdatePeriod(uint32_t updatePeriod)511 status_t AudioRecord::setPositionUpdatePeriod(uint32_t updatePeriod)
512 {
513     // The only purpose of setting position update period is to get a callback
514     if (mCbf == NULL) {
515         return INVALID_OPERATION;
516     }
517 
518     AutoMutex lock(mLock);
519     mNewPosition = mProxy->getPosition() + updatePeriod;
520     mUpdatePeriod = updatePeriod;
521 
522     sp<AudioRecordThread> t = mAudioRecordThread;
523     if (t != 0) {
524         t->wake();
525     }
526     return NO_ERROR;
527 }
528 
getPositionUpdatePeriod(uint32_t * updatePeriod) const529 status_t AudioRecord::getPositionUpdatePeriod(uint32_t *updatePeriod) const
530 {
531     if (updatePeriod == NULL) {
532         return BAD_VALUE;
533     }
534 
535     AutoMutex lock(mLock);
536     *updatePeriod = mUpdatePeriod;
537 
538     return NO_ERROR;
539 }
540 
getPosition(uint32_t * position) const541 status_t AudioRecord::getPosition(uint32_t *position) const
542 {
543     if (position == NULL) {
544         return BAD_VALUE;
545     }
546 
547     AutoMutex lock(mLock);
548     mProxy->getPosition().getValue(position);
549 
550     return NO_ERROR;
551 }
552 
getInputFramesLost() const553 uint32_t AudioRecord::getInputFramesLost() const
554 {
555     // no need to check mActive, because if inactive this will return 0, which is what we want
556     return AudioSystem::getInputFramesLost(getInputPrivate());
557 }
558 
getTimestamp(ExtendedTimestamp * timestamp)559 status_t AudioRecord::getTimestamp(ExtendedTimestamp *timestamp)
560 {
561     if (timestamp == nullptr) {
562         return BAD_VALUE;
563     }
564     AutoMutex lock(mLock);
565     status_t status = mProxy->getTimestamp(timestamp);
566     if (status == OK) {
567         timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesRead;
568         timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
569         // server side frame offset in case AudioRecord has been restored.
570         for (int i = ExtendedTimestamp::LOCATION_SERVER;
571                 i < ExtendedTimestamp::LOCATION_MAX; ++i) {
572             if (timestamp->mTimeNs[i] >= 0) {
573                 timestamp->mPosition[i] += mFramesReadServerOffset;
574             }
575         }
576 
577         bool timestampRetrogradeTimeReported = false;
578         bool timestampRetrogradePositionReported = false;
579         for (int i = 0; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
580             if (timestamp->mTimeNs[i] >= 0 && mPreviousTimestamp.mTimeNs[i] >= 0) {
581                 if (timestamp->mTimeNs[i] < mPreviousTimestamp.mTimeNs[i]) {
582                     if (!mTimestampRetrogradeTimeReported) {
583                         ALOGD("%s: retrograde time adjusting [%d] current:%lld to previous:%lld",
584                                 __func__, i, (long long)timestamp->mTimeNs[i],
585                                 (long long)mPreviousTimestamp.mTimeNs[i]);
586                         timestampRetrogradeTimeReported = true;
587                     }
588                     timestamp->mTimeNs[i] = mPreviousTimestamp.mTimeNs[i];
589                 }
590                 if (timestamp->mPosition[i] < mPreviousTimestamp.mPosition[i]) {
591                     if (!mTimestampRetrogradePositionReported) {
592                         ALOGD("%s: retrograde position"
593                                 " adjusting [%d] current:%lld to previous:%lld",
594                                 __func__, i, (long long)timestamp->mPosition[i],
595                                 (long long)mPreviousTimestamp.mPosition[i]);
596                         timestampRetrogradePositionReported = true;
597                     }
598                     timestamp->mPosition[i] = mPreviousTimestamp.mPosition[i];
599                 }
600             }
601         }
602         mPreviousTimestamp = *timestamp;
603         if (timestampRetrogradeTimeReported) {
604             mTimestampRetrogradeTimeReported = true;
605         }
606         if (timestampRetrogradePositionReported) {
607             mTimestampRetrogradePositionReported = true;
608         }
609     }
610     return status;
611 }
612 
613 // ---- Explicit Routing ---------------------------------------------------
setInputDevice(audio_port_handle_t deviceId)614 status_t AudioRecord::setInputDevice(audio_port_handle_t deviceId) {
615     AutoMutex lock(mLock);
616     if (mSelectedDeviceId != deviceId) {
617         mSelectedDeviceId = deviceId;
618         if (mStatus == NO_ERROR) {
619             // stop capture so that audio policy manager does not reject the new instance start request
620             // as only one capture can be active at a time.
621             if (mAudioRecord != 0 && mActive) {
622                 mAudioRecord->stop();
623             }
624             android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
625             mProxy->interrupt();
626         }
627     }
628     return NO_ERROR;
629 }
630 
getInputDevice()631 audio_port_handle_t AudioRecord::getInputDevice() {
632     AutoMutex lock(mLock);
633     return mSelectedDeviceId;
634 }
635 
636 // must be called with mLock held
updateRoutedDeviceId_l()637 void AudioRecord::updateRoutedDeviceId_l()
638 {
639     // if the record is inactive, do not update actual device as the input stream maybe routed
640     // from a device not relevant to this client because of other active use cases.
641     if (!mActive) {
642         return;
643     }
644     if (mInput != AUDIO_IO_HANDLE_NONE) {
645         audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mInput);
646         if (deviceId != AUDIO_PORT_HANDLE_NONE) {
647             mRoutedDeviceId = deviceId;
648         }
649      }
650 }
651 
getRoutedDeviceId()652 audio_port_handle_t AudioRecord::getRoutedDeviceId() {
653     AutoMutex lock(mLock);
654     updateRoutedDeviceId_l();
655     return mRoutedDeviceId;
656 }
657 
dump(int fd,const Vector<String16> & args __unused) const658 status_t AudioRecord::dump(int fd, const Vector<String16>& args __unused) const
659 {
660     String8 result;
661 
662     result.append(" AudioRecord::dump\n");
663     result.appendFormat("  id(%d) status(%d), active(%d), session Id(%d)\n",
664                         mPortId, mStatus, mActive, mSessionId);
665     result.appendFormat("  flags(%#x), req. flags(%#x), audio source(%d)\n",
666                         mFlags, mOrigFlags, mAttributes.source);
667     result.appendFormat("  format(%#x), channel mask(%#x), channel count(%u), sample rate(%u)\n",
668                   mFormat, mChannelMask, mChannelCount, mSampleRate);
669     result.appendFormat("  frame count(%zu), req. frame count(%zu)\n",
670                   mFrameCount, mReqFrameCount);
671     result.appendFormat("  notif. frame count(%u), req. notif. frame count(%u)\n",
672              mNotificationFramesAct, mNotificationFramesReq);
673     result.appendFormat("  input(%d), latency(%u), selected device Id(%d), routed device Id(%d)\n",
674                         mInput, mLatency, mSelectedDeviceId, mRoutedDeviceId);
675     result.appendFormat("  mic direction(%d) mic field dimension(%f)",
676                         mSelectedMicDirection, mSelectedMicFieldDimension);
677     ::write(fd, result.string(), result.size());
678     return NO_ERROR;
679 }
680 
681 // -------------------------------------------------------------------------
682 // TODO Move this macro to a common header file for enum to string conversion in audio framework.
683 #define MEDIA_CASE_ENUM(name) case name: return #name
convertTransferToText(transfer_type transferType)684 const char * AudioRecord::convertTransferToText(transfer_type transferType) {
685     switch (transferType) {
686         MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
687         MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
688         MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
689         MEDIA_CASE_ENUM(TRANSFER_SYNC);
690         default:
691             return "UNRECOGNIZED";
692     }
693 }
694 
695 // must be called with mLock held
createRecord_l(const Modulo<uint32_t> & epoch,const String16 & opPackageName)696 status_t AudioRecord::createRecord_l(const Modulo<uint32_t> &epoch, const String16& opPackageName)
697 {
698     const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
699     IAudioFlinger::CreateRecordInput input;
700     IAudioFlinger::CreateRecordOutput output;
701     audio_session_t originalSessionId;
702     sp<media::IAudioRecord> record;
703     void *iMemPointer;
704     audio_track_cblk_t* cblk;
705     status_t status;
706 
707     if (audioFlinger == 0) {
708         ALOGE("%s(%d): Could not get audioflinger", __func__, mPortId);
709         status = NO_INIT;
710         goto exit;
711     }
712 
713     // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
714     // After fast request is denied, we will request again if IAudioRecord is re-created.
715 
716     // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
717     // we must release it ourselves if anything goes wrong.
718 
719     // Client can only express a preference for FAST.  Server will perform additional tests.
720     if (mFlags & AUDIO_INPUT_FLAG_FAST) {
721         bool useCaseAllowed =
722             // any of these use cases:
723             // use case 1: callback transfer mode
724             (mTransfer == TRANSFER_CALLBACK) ||
725             // use case 2: blocking read mode
726             // The default buffer capacity at 48 kHz is 2048 frames, or ~42.6 ms.
727             // That's enough for double-buffering with our standard 20 ms rule of thumb for
728             // the minimum period of a non-SCHED_FIFO thread.
729             // This is needed so that AAudio apps can do a low latency non-blocking read from a
730             // callback running with SCHED_FIFO.
731             (mTransfer == TRANSFER_SYNC) ||
732             // use case 3: obtain/release mode
733             (mTransfer == TRANSFER_OBTAIN);
734         if (!useCaseAllowed) {
735             ALOGW("%s(%d): AUDIO_INPUT_FLAG_FAST denied, incompatible transfer = %s",
736                   __func__, mPortId,
737                   convertTransferToText(mTransfer));
738             mFlags = (audio_input_flags_t) (mFlags & ~(AUDIO_INPUT_FLAG_FAST |
739                     AUDIO_INPUT_FLAG_RAW));
740         }
741     }
742 
743     input.attr = mAttributes;
744     input.config.sample_rate = mSampleRate;
745     input.config.channel_mask = mChannelMask;
746     input.config.format = mFormat;
747     input.clientInfo.clientUid = mClientUid;
748     input.clientInfo.clientPid = mClientPid;
749     input.clientInfo.clientTid = -1;
750     if (mFlags & AUDIO_INPUT_FLAG_FAST) {
751         if (mAudioRecordThread != 0) {
752             input.clientInfo.clientTid = mAudioRecordThread->getTid();
753         }
754     }
755     input.opPackageName = opPackageName;
756     input.riid = mTracker->getRiid();
757 
758     input.flags = mFlags;
759     // The notification frame count is the period between callbacks, as suggested by the client
760     // but moderated by the server.  For record, the calculations are done entirely on server side.
761     input.frameCount = mReqFrameCount;
762     input.notificationFrameCount = mNotificationFramesReq;
763     input.selectedDeviceId = mSelectedDeviceId;
764     input.sessionId = mSessionId;
765     originalSessionId = mSessionId;
766 
767     record = audioFlinger->createRecord(input,
768                                                               output,
769                                                               &status);
770 
771     if (status != NO_ERROR) {
772         ALOGE("%s(%d): AudioFlinger could not create record track, status: %d",
773               __func__, mPortId, status);
774         goto exit;
775     }
776     ALOG_ASSERT(record != 0);
777 
778     // AudioFlinger now owns the reference to the I/O handle,
779     // so we are no longer responsible for releasing it.
780 
781     mAwaitBoost = false;
782     if (output.flags & AUDIO_INPUT_FLAG_FAST) {
783         ALOGI("%s(%d): AUDIO_INPUT_FLAG_FAST successful; frameCount %zu -> %zu",
784               __func__, mPortId,
785               mReqFrameCount, output.frameCount);
786         mAwaitBoost = true;
787     }
788     mFlags = output.flags;
789     mRoutedDeviceId = output.selectedDeviceId;
790     mSessionId = output.sessionId;
791     mSampleRate = output.sampleRate;
792 
793     if (output.cblk == 0) {
794         ALOGE("%s(%d): Could not get control block", __func__, mPortId);
795         status = NO_INIT;
796         goto exit;
797     }
798     iMemPointer = output.cblk ->pointer();
799     if (iMemPointer == NULL) {
800         ALOGE("%s(%d): Could not get control block pointer", __func__, mPortId);
801         status = NO_INIT;
802         goto exit;
803     }
804     cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
805 
806     // Starting address of buffers in shared memory.
807     // The buffers are either immediately after the control block,
808     // or in a separate area at discretion of server.
809     void *buffers;
810     if (output.buffers == 0) {
811         buffers = cblk + 1;
812     } else {
813         buffers = output.buffers->pointer();
814         if (buffers == NULL) {
815             ALOGE("%s(%d): Could not get buffer pointer", __func__, mPortId);
816             status = NO_INIT;
817             goto exit;
818         }
819     }
820 
821     // invariant that mAudioRecord != 0 is true only after set() returns successfully
822     if (mAudioRecord != 0) {
823         IInterface::asBinder(mAudioRecord)->unlinkToDeath(mDeathNotifier, this);
824         mDeathNotifier.clear();
825     }
826     mAudioRecord = record;
827     mCblkMemory = output.cblk;
828     mBufferMemory = output.buffers;
829     IPCThreadState::self()->flushCommands();
830 
831     mCblk = cblk;
832     // note that output.frameCount is the (possibly revised) value of mReqFrameCount
833     if (output.frameCount < mReqFrameCount || (mReqFrameCount == 0 && output.frameCount == 0)) {
834         ALOGW("%s(%d): Requested frameCount %zu but received frameCount %zu",
835               __func__, output.portId,
836               mReqFrameCount,  output.frameCount);
837     }
838 
839     // Make sure that application is notified with sufficient margin before overrun.
840     // The computation is done on server side.
841     if (mNotificationFramesReq > 0 && output.notificationFrameCount != mNotificationFramesReq) {
842         ALOGW("%s(%d): Server adjusted notificationFrames from %u to %zu for frameCount %zu",
843                 __func__, output.portId,
844                 mNotificationFramesReq, output.notificationFrameCount, output.frameCount);
845     }
846     mNotificationFramesAct = (uint32_t)output.notificationFrameCount;
847 
848     //mInput != input includes the case where mInput == AUDIO_IO_HANDLE_NONE for first creation
849     if (mDeviceCallback != 0) {
850         if (mInput != AUDIO_IO_HANDLE_NONE) {
851             AudioSystem::removeAudioDeviceCallback(this, mInput, mPortId);
852         }
853         AudioSystem::addAudioDeviceCallback(this, output.inputId, output.portId);
854     }
855 
856     mPortId = output.portId;
857     // We retain a copy of the I/O handle, but don't own the reference
858     mInput = output.inputId;
859     mRefreshRemaining = true;
860 
861     mFrameCount = output.frameCount;
862     // If IAudioRecord is re-created, don't let the requested frameCount
863     // decrease.  This can confuse clients that cache frameCount().
864     if (mFrameCount > mReqFrameCount) {
865         mReqFrameCount = mFrameCount;
866     }
867 
868     // update proxy
869     mProxy = new AudioRecordClientProxy(cblk, buffers, mFrameCount, mFrameSize);
870     mProxy->setEpoch(epoch);
871     mProxy->setMinimum(mNotificationFramesAct);
872 
873     mDeathNotifier = new DeathNotifier(this);
874     IInterface::asBinder(mAudioRecord)->linkToDeath(mDeathNotifier, this);
875 
876 exit:
877     mStatus = status;
878     // sp<IAudioTrack> track destructor will cause releaseOutput() to be called by AudioFlinger
879     return status;
880 }
881 
obtainBuffer(Buffer * audioBuffer,int32_t waitCount,size_t * nonContig)882 status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
883 {
884     if (audioBuffer == NULL) {
885         if (nonContig != NULL) {
886             *nonContig = 0;
887         }
888         return BAD_VALUE;
889     }
890     if (mTransfer != TRANSFER_OBTAIN) {
891         audioBuffer->frameCount = 0;
892         audioBuffer->size = 0;
893         audioBuffer->raw = NULL;
894         if (nonContig != NULL) {
895             *nonContig = 0;
896         }
897         return INVALID_OPERATION;
898     }
899 
900     const struct timespec *requested;
901     struct timespec timeout;
902     if (waitCount == -1) {
903         requested = &ClientProxy::kForever;
904     } else if (waitCount == 0) {
905         requested = &ClientProxy::kNonBlocking;
906     } else if (waitCount > 0) {
907         time_t ms = WAIT_PERIOD_MS * (time_t) waitCount;
908         timeout.tv_sec = ms / 1000;
909         timeout.tv_nsec = (long) (ms % 1000) * 1000000;
910         requested = &timeout;
911     } else {
912         ALOGE("%s(%d): invalid waitCount %d", __func__, mPortId, waitCount);
913         requested = NULL;
914     }
915     return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
916 }
917 
obtainBuffer(Buffer * audioBuffer,const struct timespec * requested,struct timespec * elapsed,size_t * nonContig)918 status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
919         struct timespec *elapsed, size_t *nonContig)
920 {
921     // previous and new IAudioRecord sequence numbers are used to detect track re-creation
922     uint32_t oldSequence = 0;
923 
924     Proxy::Buffer buffer;
925     status_t status = NO_ERROR;
926 
927     static const int32_t kMaxTries = 5;
928     int32_t tryCounter = kMaxTries;
929 
930     do {
931         // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
932         // keep them from going away if another thread re-creates the track during obtainBuffer()
933         sp<AudioRecordClientProxy> proxy;
934         sp<IMemory> iMem;
935         sp<IMemory> bufferMem;
936         {
937             // start of lock scope
938             AutoMutex lock(mLock);
939 
940             uint32_t newSequence = mSequence;
941             // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
942             if (status == DEAD_OBJECT) {
943                 // re-create track, unless someone else has already done so
944                 if (newSequence == oldSequence) {
945                     status = restoreRecord_l("obtainBuffer");
946                     if (status != NO_ERROR) {
947                         buffer.mFrameCount = 0;
948                         buffer.mRaw = NULL;
949                         buffer.mNonContig = 0;
950                         break;
951                     }
952                 }
953             }
954             oldSequence = newSequence;
955 
956             // Keep the extra references
957             proxy = mProxy;
958             iMem = mCblkMemory;
959             bufferMem = mBufferMemory;
960 
961             // Non-blocking if track is stopped
962             if (!mActive) {
963                 requested = &ClientProxy::kNonBlocking;
964             }
965 
966         }   // end of lock scope
967 
968         buffer.mFrameCount = audioBuffer->frameCount;
969         // FIXME starts the requested timeout and elapsed over from scratch
970         status = proxy->obtainBuffer(&buffer, requested, elapsed);
971 
972     } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
973 
974     audioBuffer->frameCount = buffer.mFrameCount;
975     audioBuffer->size = buffer.mFrameCount * mFrameSize;
976     audioBuffer->raw = buffer.mRaw;
977     audioBuffer->sequence = oldSequence;
978     if (nonContig != NULL) {
979         *nonContig = buffer.mNonContig;
980     }
981     return status;
982 }
983 
releaseBuffer(const Buffer * audioBuffer)984 void AudioRecord::releaseBuffer(const Buffer* audioBuffer)
985 {
986     // FIXME add error checking on mode, by adding an internal version
987 
988     size_t stepCount = audioBuffer->size / mFrameSize;
989     if (stepCount == 0) {
990         return;
991     }
992 
993     Proxy::Buffer buffer;
994     buffer.mFrameCount = stepCount;
995     buffer.mRaw = audioBuffer->raw;
996 
997     AutoMutex lock(mLock);
998     if (audioBuffer->sequence != mSequence) {
999         // This Buffer came from a different IAudioRecord instance, so ignore the releaseBuffer
1000         ALOGD("%s is no-op due to IAudioRecord sequence mismatch %u != %u",
1001                 __func__, audioBuffer->sequence, mSequence);
1002         return;
1003     }
1004     mInOverrun = false;
1005     mProxy->releaseBuffer(&buffer);
1006 
1007     // the server does not automatically disable recorder on overrun, so no need to restart
1008 }
1009 
getInputPrivate() const1010 audio_io_handle_t AudioRecord::getInputPrivate() const
1011 {
1012     AutoMutex lock(mLock);
1013     return mInput;
1014 }
1015 
1016 // -------------------------------------------------------------------------
1017 
read(void * buffer,size_t userSize,bool blocking)1018 ssize_t AudioRecord::read(void* buffer, size_t userSize, bool blocking)
1019 {
1020     if (mTransfer != TRANSFER_SYNC) {
1021         return INVALID_OPERATION;
1022     }
1023 
1024     if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
1025         // Validation. user is most-likely passing an error code, and it would
1026         // make the return value ambiguous (actualSize vs error).
1027         ALOGE("%s(%d) (buffer=%p, size=%zu (%zu)",
1028                 __func__, mPortId, buffer, userSize, userSize);
1029         return BAD_VALUE;
1030     }
1031 
1032     ssize_t read = 0;
1033     Buffer audioBuffer;
1034 
1035     while (userSize >= mFrameSize) {
1036         audioBuffer.frameCount = userSize / mFrameSize;
1037 
1038         status_t err = obtainBuffer(&audioBuffer,
1039                 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
1040         if (err < 0) {
1041             if (read > 0) {
1042                 break;
1043             }
1044             if (err == TIMED_OUT || err == -EINTR) {
1045                 err = WOULD_BLOCK;
1046             }
1047             return ssize_t(err);
1048         }
1049 
1050         size_t bytesRead = audioBuffer.size;
1051         memcpy(buffer, audioBuffer.i8, bytesRead);
1052         buffer = ((char *) buffer) + bytesRead;
1053         userSize -= bytesRead;
1054         read += bytesRead;
1055 
1056         releaseBuffer(&audioBuffer);
1057     }
1058     if (read > 0) {
1059         mFramesRead += read / mFrameSize;
1060         // mFramesReadTime = systemTime(SYSTEM_TIME_MONOTONIC); // not provided at this time.
1061     }
1062     return read;
1063 }
1064 
1065 // -------------------------------------------------------------------------
1066 
processAudioBuffer()1067 nsecs_t AudioRecord::processAudioBuffer()
1068 {
1069     mLock.lock();
1070     if (mAwaitBoost) {
1071         mAwaitBoost = false;
1072         mLock.unlock();
1073         static const int32_t kMaxTries = 5;
1074         int32_t tryCounter = kMaxTries;
1075         uint32_t pollUs = 10000;
1076         do {
1077             int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
1078             if (policy == SCHED_FIFO || policy == SCHED_RR) {
1079                 break;
1080             }
1081             usleep(pollUs);
1082             pollUs <<= 1;
1083         } while (tryCounter-- > 0);
1084         if (tryCounter < 0) {
1085             ALOGE("%s(%d): did not receive expected priority boost on time", __func__, mPortId);
1086         }
1087         // Run again immediately
1088         return 0;
1089     }
1090 
1091     // Can only reference mCblk while locked
1092     int32_t flags = android_atomic_and(~CBLK_OVERRUN, &mCblk->mFlags);
1093 
1094     // Check for track invalidation
1095     if (flags & CBLK_INVALID) {
1096         (void) restoreRecord_l("processAudioBuffer");
1097         mLock.unlock();
1098         // Run again immediately, but with a new IAudioRecord
1099         return 0;
1100     }
1101 
1102     bool active = mActive;
1103 
1104     // Manage overrun callback, must be done under lock to avoid race with releaseBuffer()
1105     bool newOverrun = false;
1106     if (flags & CBLK_OVERRUN) {
1107         if (!mInOverrun) {
1108             mInOverrun = true;
1109             newOverrun = true;
1110         }
1111     }
1112 
1113     // Get current position of server
1114     Modulo<uint32_t> position(mProxy->getPosition());
1115 
1116     // Manage marker callback
1117     bool markerReached = false;
1118     Modulo<uint32_t> markerPosition(mMarkerPosition);
1119     // FIXME fails for wraparound, need 64 bits
1120     if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
1121         mMarkerReached = markerReached = true;
1122     }
1123 
1124     // Determine the number of new position callback(s) that will be needed, while locked
1125     size_t newPosCount = 0;
1126     Modulo<uint32_t> newPosition(mNewPosition);
1127     uint32_t updatePeriod = mUpdatePeriod;
1128     // FIXME fails for wraparound, need 64 bits
1129     if (updatePeriod > 0 && position >= newPosition) {
1130         newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
1131         mNewPosition += updatePeriod * newPosCount;
1132     }
1133 
1134     // Cache other fields that will be needed soon
1135     uint32_t notificationFrames = mNotificationFramesAct;
1136     if (mRefreshRemaining) {
1137         mRefreshRemaining = false;
1138         mRemainingFrames = notificationFrames;
1139         mRetryOnPartialBuffer = false;
1140     }
1141     size_t misalignment = mProxy->getMisalignment();
1142     uint32_t sequence = mSequence;
1143 
1144     // These fields don't need to be cached, because they are assigned only by set():
1145     //      mTransfer, mCbf, mUserData, mSampleRate, mFrameSize
1146 
1147     mLock.unlock();
1148 
1149     // perform callbacks while unlocked
1150     if (newOverrun) {
1151         mCbf(EVENT_OVERRUN, mUserData, NULL);
1152     }
1153     if (markerReached) {
1154         mCbf(EVENT_MARKER, mUserData, &markerPosition);
1155     }
1156     while (newPosCount > 0) {
1157         size_t temp = newPosition.value(); // FIXME size_t != uint32_t
1158         mCbf(EVENT_NEW_POS, mUserData, &temp);
1159         newPosition += updatePeriod;
1160         newPosCount--;
1161     }
1162     if (mObservedSequence != sequence) {
1163         mObservedSequence = sequence;
1164         mCbf(EVENT_NEW_IAUDIORECORD, mUserData, NULL);
1165     }
1166 
1167     // if inactive, then don't run me again until re-started
1168     if (!active) {
1169         return NS_INACTIVE;
1170     }
1171 
1172     // Compute the estimated time until the next timed event (position, markers)
1173     uint32_t minFrames = ~0;
1174     if (!markerReached && position < markerPosition) {
1175         minFrames = (markerPosition - position).value();
1176     }
1177     if (updatePeriod > 0) {
1178         uint32_t remaining = (newPosition - position).value();
1179         if (remaining < minFrames) {
1180             minFrames = remaining;
1181         }
1182     }
1183 
1184     // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
1185     static const uint32_t kPoll = 0;
1186     if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1187         minFrames = kPoll * notificationFrames;
1188     }
1189 
1190     // Convert frame units to time units
1191     nsecs_t ns = NS_WHENEVER;
1192     if (minFrames != (uint32_t) ~0) {
1193         // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1194         static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1195         ns = ((minFrames * 1000000000LL) / mSampleRate) + kFudgeNs;
1196     }
1197 
1198     // If not supplying data by EVENT_MORE_DATA, then we're done
1199     if (mTransfer != TRANSFER_CALLBACK) {
1200         return ns;
1201     }
1202 
1203     struct timespec timeout;
1204     const struct timespec *requested = &ClientProxy::kForever;
1205     if (ns != NS_WHENEVER) {
1206         timeout.tv_sec = ns / 1000000000LL;
1207         timeout.tv_nsec = ns % 1000000000LL;
1208         ALOGV("%s(%d): timeout %ld.%03d",
1209                 __func__, mPortId, timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1210         requested = &timeout;
1211     }
1212 
1213     size_t readFrames = 0;
1214     while (mRemainingFrames > 0) {
1215 
1216         Buffer audioBuffer;
1217         audioBuffer.frameCount = mRemainingFrames;
1218         size_t nonContig;
1219         status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1220         LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1221                 "%s(%d): obtainBuffer() err=%d frameCount=%zu",
1222                 __func__, mPortId, err, audioBuffer.frameCount);
1223         requested = &ClientProxy::kNonBlocking;
1224         size_t avail = audioBuffer.frameCount + nonContig;
1225         ALOGV("%s(%d): obtainBuffer(%u) returned %zu = %zu + %zu err %d",
1226                 __func__, mPortId, mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
1227         if (err != NO_ERROR) {
1228             if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
1229                 break;
1230             }
1231             ALOGE("%s(%d): Error %d obtaining an audio buffer, giving up.",
1232                     __func__, mPortId, err);
1233             return NS_NEVER;
1234         }
1235 
1236         if (mRetryOnPartialBuffer) {
1237             mRetryOnPartialBuffer = false;
1238             if (avail < mRemainingFrames) {
1239                 int64_t myns = ((mRemainingFrames - avail) *
1240                         1100000000LL) / mSampleRate;
1241                 if (ns < 0 || myns < ns) {
1242                     ns = myns;
1243                 }
1244                 return ns;
1245             }
1246         }
1247 
1248         size_t reqSize = audioBuffer.size;
1249         mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1250         size_t readSize = audioBuffer.size;
1251 
1252         // Validate on returned size
1253         if (ssize_t(readSize) < 0 || readSize > reqSize) {
1254             ALOGE("%s(%d):  EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1255                     __func__, mPortId, reqSize, ssize_t(readSize));
1256             return NS_NEVER;
1257         }
1258 
1259         if (readSize == 0) {
1260             // The callback is done consuming buffers
1261             // Keep this thread going to handle timed events and
1262             // still try to provide more data in intervals of WAIT_PERIOD_MS
1263             // but don't just loop and block the CPU, so wait
1264             return WAIT_PERIOD_MS * 1000000LL;
1265         }
1266 
1267         size_t releasedFrames = readSize / mFrameSize;
1268         audioBuffer.frameCount = releasedFrames;
1269         mRemainingFrames -= releasedFrames;
1270         if (misalignment >= releasedFrames) {
1271             misalignment -= releasedFrames;
1272         } else {
1273             misalignment = 0;
1274         }
1275 
1276         releaseBuffer(&audioBuffer);
1277         readFrames += releasedFrames;
1278 
1279         // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1280         // if callback doesn't like to accept the full chunk
1281         if (readSize < reqSize) {
1282             continue;
1283         }
1284 
1285         // There could be enough non-contiguous frames available to satisfy the remaining request
1286         if (mRemainingFrames <= nonContig) {
1287             continue;
1288         }
1289 
1290 #if 0
1291         // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1292         // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
1293         // that total to a sum == notificationFrames.
1294         if (0 < misalignment && misalignment <= mRemainingFrames) {
1295             mRemainingFrames = misalignment;
1296             return (mRemainingFrames * 1100000000LL) / mSampleRate;
1297         }
1298 #endif
1299 
1300     }
1301     if (readFrames > 0) {
1302         AutoMutex lock(mLock);
1303         mFramesRead += readFrames;
1304         // mFramesReadTime = systemTime(SYSTEM_TIME_MONOTONIC); // not provided at this time.
1305     }
1306     mRemainingFrames = notificationFrames;
1307     mRetryOnPartialBuffer = true;
1308 
1309     // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1310     return 0;
1311 }
1312 
restoreRecord_l(const char * from)1313 status_t AudioRecord::restoreRecord_l(const char *from)
1314 {
1315     ALOGW("%s(%d): dead IAudioRecord, creating a new one from %s()", __func__, mPortId, from);
1316     ++mSequence;
1317 
1318     const int INITIAL_RETRIES = 3;
1319     int retries = INITIAL_RETRIES;
1320 retry:
1321     if (retries < INITIAL_RETRIES) {
1322         // refresh the audio configuration cache in this process to make sure we get new
1323         // input parameters and new IAudioRecord in createRecord_l()
1324         AudioSystem::clearAudioConfigCache();
1325     }
1326     mFlags = mOrigFlags;
1327 
1328     // if the new IAudioRecord is created, createRecord_l() will modify the
1329     // following member variables: mAudioRecord, mCblkMemory, mCblk, mBufferMemory.
1330     // It will also delete the strong references on previous IAudioRecord and IMemory
1331     Modulo<uint32_t> position(mProxy->getPosition());
1332     mNewPosition = position + mUpdatePeriod;
1333     status_t result = createRecord_l(position, mOpPackageName);
1334 
1335     if (result == NO_ERROR) {
1336         if (mActive) {
1337             // callback thread or sync event hasn't changed
1338             // FIXME this fails if we have a new AudioFlinger instance
1339             result = mAudioRecord->start(
1340                 AudioSystem::SYNC_EVENT_SAME, AUDIO_SESSION_NONE).transactionError();
1341         }
1342         mFramesReadServerOffset = mFramesRead; // server resets to zero so we need an offset.
1343     }
1344 
1345     if (result != NO_ERROR) {
1346         ALOGW("%s(%d): failed status %d, retries %d", __func__, mPortId, result, retries);
1347         if (--retries > 0) {
1348             // leave time for an eventual race condition to clear before retrying
1349             usleep(500000);
1350             goto retry;
1351         }
1352         // if no retries left, set invalid bit to force restoring at next occasion
1353         // and avoid inconsistent active state on client and server sides
1354         if (mCblk != nullptr) {
1355             android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
1356         }
1357     }
1358 
1359     return result;
1360 }
1361 
addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)1362 status_t AudioRecord::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
1363 {
1364     if (callback == 0) {
1365         ALOGW("%s(%d): adding NULL callback!", __func__, mPortId);
1366         return BAD_VALUE;
1367     }
1368     AutoMutex lock(mLock);
1369     if (mDeviceCallback.unsafe_get() == callback.get()) {
1370         ALOGW("%s(%d): adding same callback!", __func__, mPortId);
1371         return INVALID_OPERATION;
1372     }
1373     status_t status = NO_ERROR;
1374     if (mInput != AUDIO_IO_HANDLE_NONE) {
1375         if (mDeviceCallback != 0) {
1376             ALOGW("%s(%d): callback already present!", __func__, mPortId);
1377             AudioSystem::removeAudioDeviceCallback(this, mInput, mPortId);
1378         }
1379         status = AudioSystem::addAudioDeviceCallback(this, mInput, mPortId);
1380     }
1381     mDeviceCallback = callback;
1382     return status;
1383 }
1384 
removeAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)1385 status_t AudioRecord::removeAudioDeviceCallback(
1386         const sp<AudioSystem::AudioDeviceCallback>& callback)
1387 {
1388     if (callback == 0) {
1389         ALOGW("%s(%d): removing NULL callback!", __func__, mPortId);
1390         return BAD_VALUE;
1391     }
1392     AutoMutex lock(mLock);
1393     if (mDeviceCallback.unsafe_get() != callback.get()) {
1394         ALOGW("%s(%d): removing different callback!", __func__, mPortId);
1395         return INVALID_OPERATION;
1396     }
1397     mDeviceCallback.clear();
1398     if (mInput != AUDIO_IO_HANDLE_NONE) {
1399         AudioSystem::removeAudioDeviceCallback(this, mInput, mPortId);
1400     }
1401     return NO_ERROR;
1402 }
1403 
onAudioDeviceUpdate(audio_io_handle_t audioIo,audio_port_handle_t deviceId)1404 void AudioRecord::onAudioDeviceUpdate(audio_io_handle_t audioIo,
1405                                  audio_port_handle_t deviceId)
1406 {
1407     sp<AudioSystem::AudioDeviceCallback> callback;
1408     {
1409         AutoMutex lock(mLock);
1410         if (audioIo != mInput) {
1411             return;
1412         }
1413         callback = mDeviceCallback.promote();
1414         // only update device if the record is active as route changes due to other use cases are
1415         // irrelevant for this client
1416         if (mActive) {
1417             mRoutedDeviceId = deviceId;
1418         }
1419     }
1420     if (callback.get() != nullptr) {
1421         callback->onAudioDeviceUpdate(mInput, mRoutedDeviceId);
1422     }
1423 }
1424 
1425 // -------------------------------------------------------------------------
1426 
getActiveMicrophones(std::vector<media::MicrophoneInfo> * activeMicrophones)1427 status_t AudioRecord::getActiveMicrophones(std::vector<media::MicrophoneInfo>* activeMicrophones)
1428 {
1429     AutoMutex lock(mLock);
1430     return mAudioRecord->getActiveMicrophones(activeMicrophones).transactionError();
1431 }
1432 
setPreferredMicrophoneDirection(audio_microphone_direction_t direction)1433 status_t AudioRecord::setPreferredMicrophoneDirection(audio_microphone_direction_t direction)
1434 {
1435     AutoMutex lock(mLock);
1436     if (mSelectedMicDirection == direction) {
1437         // NOP
1438         return OK;
1439     }
1440 
1441     mSelectedMicDirection = direction;
1442     if (mAudioRecord == 0) {
1443         // the internal AudioRecord hasn't be created yet, so just stash the attribute.
1444         return OK;
1445     } else {
1446         return mAudioRecord->setPreferredMicrophoneDirection(direction).transactionError();
1447     }
1448 }
1449 
setPreferredMicrophoneFieldDimension(float zoom)1450 status_t AudioRecord::setPreferredMicrophoneFieldDimension(float zoom) {
1451     AutoMutex lock(mLock);
1452     if (mSelectedMicFieldDimension == zoom) {
1453         // NOP
1454         return OK;
1455     }
1456 
1457     mSelectedMicFieldDimension = zoom;
1458     if (mAudioRecord == 0) {
1459         // the internal AudioRecord hasn't be created yet, so just stash the attribute.
1460         return OK;
1461     } else {
1462         return mAudioRecord->setPreferredMicrophoneFieldDimension(zoom).transactionError();
1463     }
1464 }
1465 
1466 // =========================================================================
1467 
binderDied(const wp<IBinder> & who __unused)1468 void AudioRecord::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
1469 {
1470     sp<AudioRecord> audioRecord = mAudioRecord.promote();
1471     if (audioRecord != 0) {
1472         AutoMutex lock(audioRecord->mLock);
1473         audioRecord->mProxy->binderDied();
1474     }
1475 }
1476 
1477 // =========================================================================
1478 
AudioRecordThread(AudioRecord & receiver)1479 AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver)
1480     : Thread(true /* bCanCallJava */)  // binder recursion on restoreRecord_l() may call Java.
1481     , mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
1482       mIgnoreNextPausedInt(false)
1483 {
1484 }
1485 
~AudioRecordThread()1486 AudioRecord::AudioRecordThread::~AudioRecordThread()
1487 {
1488 }
1489 
threadLoop()1490 bool AudioRecord::AudioRecordThread::threadLoop()
1491 {
1492     {
1493         AutoMutex _l(mMyLock);
1494         if (mPaused) {
1495             // TODO check return value and handle or log
1496             mMyCond.wait(mMyLock);
1497             // caller will check for exitPending()
1498             return true;
1499         }
1500         if (mIgnoreNextPausedInt) {
1501             mIgnoreNextPausedInt = false;
1502             mPausedInt = false;
1503         }
1504         if (mPausedInt) {
1505             if (mPausedNs > 0) {
1506                 // TODO check return value and handle or log
1507                 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1508             } else {
1509                 // TODO check return value and handle or log
1510                 mMyCond.wait(mMyLock);
1511             }
1512             mPausedInt = false;
1513             return true;
1514         }
1515     }
1516     if (exitPending()) {
1517         return false;
1518     }
1519     nsecs_t ns =  mReceiver.processAudioBuffer();
1520     switch (ns) {
1521     case 0:
1522         return true;
1523     case NS_INACTIVE:
1524         pauseInternal();
1525         return true;
1526     case NS_NEVER:
1527         return false;
1528     case NS_WHENEVER:
1529         // Event driven: call wake() when callback notifications conditions change.
1530         ns = INT64_MAX;
1531         FALLTHROUGH_INTENDED;
1532     default:
1533         LOG_ALWAYS_FATAL_IF(ns < 0, "%s() returned %lld", __func__, (long long)ns);
1534         pauseInternal(ns);
1535         return true;
1536     }
1537 }
1538 
requestExit()1539 void AudioRecord::AudioRecordThread::requestExit()
1540 {
1541     // must be in this order to avoid a race condition
1542     Thread::requestExit();
1543     resume();
1544 }
1545 
pause()1546 void AudioRecord::AudioRecordThread::pause()
1547 {
1548     AutoMutex _l(mMyLock);
1549     mPaused = true;
1550 }
1551 
resume()1552 void AudioRecord::AudioRecordThread::resume()
1553 {
1554     AutoMutex _l(mMyLock);
1555     mIgnoreNextPausedInt = true;
1556     if (mPaused || mPausedInt) {
1557         mPaused = false;
1558         mPausedInt = false;
1559         mMyCond.signal();
1560     }
1561 }
1562 
wake()1563 void AudioRecord::AudioRecordThread::wake()
1564 {
1565     AutoMutex _l(mMyLock);
1566     if (!mPaused) {
1567         // wake() might be called while servicing a callback - ignore the next
1568         // pause time and call processAudioBuffer.
1569         mIgnoreNextPausedInt = true;
1570         if (mPausedInt && mPausedNs > 0) {
1571             // audio record is active and internally paused with timeout.
1572             mPausedInt = false;
1573             mMyCond.signal();
1574         }
1575     }
1576 }
1577 
pauseInternal(nsecs_t ns)1578 void AudioRecord::AudioRecordThread::pauseInternal(nsecs_t ns)
1579 {
1580     AutoMutex _l(mMyLock);
1581     mPausedInt = true;
1582     mPausedNs = ns;
1583 }
1584 
1585 // -------------------------------------------------------------------------
1586 
1587 } // namespace android
1588