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 
392     // reset current position as seen by client to 0
393     mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
394     // force refresh of remaining frames by processAudioBuffer() as last
395     // read before stop could be partial.
396     mRefreshRemaining = true;
397 
398     mNewPosition = mProxy->getPosition() + mUpdatePeriod;
399     int32_t flags = android_atomic_acquire_load(&mCblk->mFlags);
400 
401     // we reactivate markers (mMarkerPosition != 0) as the position is reset to 0.
402     // This is legacy behavior.  This is not done in stop() to avoid a race condition
403     // where the last marker event is issued twice.
404     mMarkerReached = false;
405     // mActive is checked by restoreRecord_l
406     mActive = true;
407 
408     status_t status = NO_ERROR;
409     if (!(flags & CBLK_INVALID)) {
410         status = mAudioRecord->start(event, triggerSession).transactionError();
411         if (status == DEAD_OBJECT) {
412             flags |= CBLK_INVALID;
413         }
414     }
415     if (flags & CBLK_INVALID) {
416         status = restoreRecord_l("start");
417     }
418 
419     // Call these directly because we are already holding the lock.
420     mAudioRecord->setPreferredMicrophoneDirection(mSelectedMicDirection);
421     mAudioRecord->setPreferredMicrophoneFieldDimension(mSelectedMicFieldDimension);
422 
423     if (status != NO_ERROR) {
424         mActive = false;
425         ALOGE("%s(%d): status %d", __func__, mPortId, status);
426         mMediaMetrics.markError(status, __FUNCTION__);
427     } else {
428         mTracker->recordingStarted();
429         sp<AudioRecordThread> t = mAudioRecordThread;
430         if (t != 0) {
431             t->resume();
432         } else {
433             mPreviousPriority = getpriority(PRIO_PROCESS, 0);
434             get_sched_policy(0, &mPreviousSchedulingGroup);
435             androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
436         }
437 
438         // we've successfully started, log that time
439         mMediaMetrics.logStart(systemTime());
440     }
441     return status;
442 }
443 
stop()444 void AudioRecord::stop()
445 {
446     AutoMutex lock(mLock);
447     ALOGV("%s(%d): mActive:%d\n", __func__, mPortId, mActive);
448     if (!mActive) {
449         return;
450     }
451 
452     mActive = false;
453     mProxy->interrupt();
454     mAudioRecord->stop();
455     mTracker->recordingStopped();
456 
457     // Note: legacy handling - stop does not clear record marker and
458     // periodic update position; we update those on start().
459 
460     sp<AudioRecordThread> t = mAudioRecordThread;
461     if (t != 0) {
462         t->pause();
463     } else {
464         setpriority(PRIO_PROCESS, 0, mPreviousPriority);
465         set_sched_policy(0, mPreviousSchedulingGroup);
466     }
467 
468     // we've successfully started, log that time
469     mMediaMetrics.logStop(systemTime());
470 }
471 
stopped() const472 bool AudioRecord::stopped() const
473 {
474     AutoMutex lock(mLock);
475     return !mActive;
476 }
477 
setMarkerPosition(uint32_t marker)478 status_t AudioRecord::setMarkerPosition(uint32_t marker)
479 {
480     // The only purpose of setting marker position is to get a callback
481     if (mCbf == NULL) {
482         return INVALID_OPERATION;
483     }
484 
485     AutoMutex lock(mLock);
486     mMarkerPosition = marker;
487     mMarkerReached = false;
488 
489     sp<AudioRecordThread> t = mAudioRecordThread;
490     if (t != 0) {
491         t->wake();
492     }
493     return NO_ERROR;
494 }
495 
getMarkerPosition(uint32_t * marker) const496 status_t AudioRecord::getMarkerPosition(uint32_t *marker) const
497 {
498     if (marker == NULL) {
499         return BAD_VALUE;
500     }
501 
502     AutoMutex lock(mLock);
503     mMarkerPosition.getValue(marker);
504 
505     return NO_ERROR;
506 }
507 
setPositionUpdatePeriod(uint32_t updatePeriod)508 status_t AudioRecord::setPositionUpdatePeriod(uint32_t updatePeriod)
509 {
510     // The only purpose of setting position update period is to get a callback
511     if (mCbf == NULL) {
512         return INVALID_OPERATION;
513     }
514 
515     AutoMutex lock(mLock);
516     mNewPosition = mProxy->getPosition() + updatePeriod;
517     mUpdatePeriod = updatePeriod;
518 
519     sp<AudioRecordThread> t = mAudioRecordThread;
520     if (t != 0) {
521         t->wake();
522     }
523     return NO_ERROR;
524 }
525 
getPositionUpdatePeriod(uint32_t * updatePeriod) const526 status_t AudioRecord::getPositionUpdatePeriod(uint32_t *updatePeriod) const
527 {
528     if (updatePeriod == NULL) {
529         return BAD_VALUE;
530     }
531 
532     AutoMutex lock(mLock);
533     *updatePeriod = mUpdatePeriod;
534 
535     return NO_ERROR;
536 }
537 
getPosition(uint32_t * position) const538 status_t AudioRecord::getPosition(uint32_t *position) const
539 {
540     if (position == NULL) {
541         return BAD_VALUE;
542     }
543 
544     AutoMutex lock(mLock);
545     mProxy->getPosition().getValue(position);
546 
547     return NO_ERROR;
548 }
549 
getInputFramesLost() const550 uint32_t AudioRecord::getInputFramesLost() const
551 {
552     // no need to check mActive, because if inactive this will return 0, which is what we want
553     return AudioSystem::getInputFramesLost(getInputPrivate());
554 }
555 
getTimestamp(ExtendedTimestamp * timestamp)556 status_t AudioRecord::getTimestamp(ExtendedTimestamp *timestamp)
557 {
558     if (timestamp == nullptr) {
559         return BAD_VALUE;
560     }
561     AutoMutex lock(mLock);
562     status_t status = mProxy->getTimestamp(timestamp);
563     if (status == OK) {
564         timestamp->mPosition[ExtendedTimestamp::LOCATION_CLIENT] = mFramesRead;
565         timestamp->mTimeNs[ExtendedTimestamp::LOCATION_CLIENT] = 0;
566         // server side frame offset in case AudioRecord has been restored.
567         for (int i = ExtendedTimestamp::LOCATION_SERVER;
568                 i < ExtendedTimestamp::LOCATION_MAX; ++i) {
569             if (timestamp->mTimeNs[i] >= 0) {
570                 timestamp->mPosition[i] += mFramesReadServerOffset;
571             }
572         }
573     }
574     return status;
575 }
576 
577 // ---- Explicit Routing ---------------------------------------------------
setInputDevice(audio_port_handle_t deviceId)578 status_t AudioRecord::setInputDevice(audio_port_handle_t deviceId) {
579     AutoMutex lock(mLock);
580     if (mSelectedDeviceId != deviceId) {
581         mSelectedDeviceId = deviceId;
582         if (mStatus == NO_ERROR) {
583             // stop capture so that audio policy manager does not reject the new instance start request
584             // as only one capture can be active at a time.
585             if (mAudioRecord != 0 && mActive) {
586                 mAudioRecord->stop();
587             }
588             android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
589             mProxy->interrupt();
590         }
591     }
592     return NO_ERROR;
593 }
594 
getInputDevice()595 audio_port_handle_t AudioRecord::getInputDevice() {
596     AutoMutex lock(mLock);
597     return mSelectedDeviceId;
598 }
599 
600 // must be called with mLock held
updateRoutedDeviceId_l()601 void AudioRecord::updateRoutedDeviceId_l()
602 {
603     // if the record is inactive, do not update actual device as the input stream maybe routed
604     // from a device not relevant to this client because of other active use cases.
605     if (!mActive) {
606         return;
607     }
608     if (mInput != AUDIO_IO_HANDLE_NONE) {
609         audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mInput);
610         if (deviceId != AUDIO_PORT_HANDLE_NONE) {
611             mRoutedDeviceId = deviceId;
612         }
613      }
614 }
615 
getRoutedDeviceId()616 audio_port_handle_t AudioRecord::getRoutedDeviceId() {
617     AutoMutex lock(mLock);
618     updateRoutedDeviceId_l();
619     return mRoutedDeviceId;
620 }
621 
dump(int fd,const Vector<String16> & args __unused) const622 status_t AudioRecord::dump(int fd, const Vector<String16>& args __unused) const
623 {
624     String8 result;
625 
626     result.append(" AudioRecord::dump\n");
627     result.appendFormat("  id(%d) status(%d), active(%d), session Id(%d)\n",
628                         mPortId, mStatus, mActive, mSessionId);
629     result.appendFormat("  flags(%#x), req. flags(%#x), audio source(%d)\n",
630                         mFlags, mOrigFlags, mAttributes.source);
631     result.appendFormat("  format(%#x), channel mask(%#x), channel count(%u), sample rate(%u)\n",
632                   mFormat, mChannelMask, mChannelCount, mSampleRate);
633     result.appendFormat("  frame count(%zu), req. frame count(%zu)\n",
634                   mFrameCount, mReqFrameCount);
635     result.appendFormat("  notif. frame count(%u), req. notif. frame count(%u)\n",
636              mNotificationFramesAct, mNotificationFramesReq);
637     result.appendFormat("  input(%d), latency(%u), selected device Id(%d), routed device Id(%d)\n",
638                         mInput, mLatency, mSelectedDeviceId, mRoutedDeviceId);
639     result.appendFormat("  mic direction(%d) mic field dimension(%f)",
640                         mSelectedMicDirection, mSelectedMicFieldDimension);
641     ::write(fd, result.string(), result.size());
642     return NO_ERROR;
643 }
644 
645 // -------------------------------------------------------------------------
646 // TODO Move this macro to a common header file for enum to string conversion in audio framework.
647 #define MEDIA_CASE_ENUM(name) case name: return #name
convertTransferToText(transfer_type transferType)648 const char * AudioRecord::convertTransferToText(transfer_type transferType) {
649     switch (transferType) {
650         MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
651         MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
652         MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
653         MEDIA_CASE_ENUM(TRANSFER_SYNC);
654         default:
655             return "UNRECOGNIZED";
656     }
657 }
658 
659 // must be called with mLock held
createRecord_l(const Modulo<uint32_t> & epoch,const String16 & opPackageName)660 status_t AudioRecord::createRecord_l(const Modulo<uint32_t> &epoch, const String16& opPackageName)
661 {
662     const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
663     IAudioFlinger::CreateRecordInput input;
664     IAudioFlinger::CreateRecordOutput output;
665     audio_session_t originalSessionId;
666     sp<media::IAudioRecord> record;
667     void *iMemPointer;
668     audio_track_cblk_t* cblk;
669     status_t status;
670 
671     if (audioFlinger == 0) {
672         ALOGE("%s(%d): Could not get audioflinger", __func__, mPortId);
673         status = NO_INIT;
674         goto exit;
675     }
676 
677     // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
678     // After fast request is denied, we will request again if IAudioRecord is re-created.
679 
680     // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
681     // we must release it ourselves if anything goes wrong.
682 
683     // Client can only express a preference for FAST.  Server will perform additional tests.
684     if (mFlags & AUDIO_INPUT_FLAG_FAST) {
685         bool useCaseAllowed =
686             // any of these use cases:
687             // use case 1: callback transfer mode
688             (mTransfer == TRANSFER_CALLBACK) ||
689             // use case 2: blocking read mode
690             // The default buffer capacity at 48 kHz is 2048 frames, or ~42.6 ms.
691             // That's enough for double-buffering with our standard 20 ms rule of thumb for
692             // the minimum period of a non-SCHED_FIFO thread.
693             // This is needed so that AAudio apps can do a low latency non-blocking read from a
694             // callback running with SCHED_FIFO.
695             (mTransfer == TRANSFER_SYNC) ||
696             // use case 3: obtain/release mode
697             (mTransfer == TRANSFER_OBTAIN);
698         if (!useCaseAllowed) {
699             ALOGW("%s(%d): AUDIO_INPUT_FLAG_FAST denied, incompatible transfer = %s",
700                   __func__, mPortId,
701                   convertTransferToText(mTransfer));
702             mFlags = (audio_input_flags_t) (mFlags & ~(AUDIO_INPUT_FLAG_FAST |
703                     AUDIO_INPUT_FLAG_RAW));
704         }
705     }
706 
707     input.attr = mAttributes;
708     input.config.sample_rate = mSampleRate;
709     input.config.channel_mask = mChannelMask;
710     input.config.format = mFormat;
711     input.clientInfo.clientUid = mClientUid;
712     input.clientInfo.clientPid = mClientPid;
713     input.clientInfo.clientTid = -1;
714     if (mFlags & AUDIO_INPUT_FLAG_FAST) {
715         if (mAudioRecordThread != 0) {
716             input.clientInfo.clientTid = mAudioRecordThread->getTid();
717         }
718     }
719     input.opPackageName = opPackageName;
720     input.riid = mTracker->getRiid();
721 
722     input.flags = mFlags;
723     // The notification frame count is the period between callbacks, as suggested by the client
724     // but moderated by the server.  For record, the calculations are done entirely on server side.
725     input.frameCount = mReqFrameCount;
726     input.notificationFrameCount = mNotificationFramesReq;
727     input.selectedDeviceId = mSelectedDeviceId;
728     input.sessionId = mSessionId;
729     originalSessionId = mSessionId;
730 
731     record = audioFlinger->createRecord(input,
732                                                               output,
733                                                               &status);
734 
735     if (status != NO_ERROR) {
736         ALOGE("%s(%d): AudioFlinger could not create record track, status: %d",
737               __func__, mPortId, status);
738         goto exit;
739     }
740     ALOG_ASSERT(record != 0);
741 
742     // AudioFlinger now owns the reference to the I/O handle,
743     // so we are no longer responsible for releasing it.
744 
745     mAwaitBoost = false;
746     if (output.flags & AUDIO_INPUT_FLAG_FAST) {
747         ALOGI("%s(%d): AUDIO_INPUT_FLAG_FAST successful; frameCount %zu -> %zu",
748               __func__, mPortId,
749               mReqFrameCount, output.frameCount);
750         mAwaitBoost = true;
751     }
752     mFlags = output.flags;
753     mRoutedDeviceId = output.selectedDeviceId;
754     mSessionId = output.sessionId;
755     mSampleRate = output.sampleRate;
756 
757     if (output.cblk == 0) {
758         ALOGE("%s(%d): Could not get control block", __func__, mPortId);
759         status = NO_INIT;
760         goto exit;
761     }
762     iMemPointer = output.cblk ->pointer();
763     if (iMemPointer == NULL) {
764         ALOGE("%s(%d): Could not get control block pointer", __func__, mPortId);
765         status = NO_INIT;
766         goto exit;
767     }
768     cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
769 
770     // Starting address of buffers in shared memory.
771     // The buffers are either immediately after the control block,
772     // or in a separate area at discretion of server.
773     void *buffers;
774     if (output.buffers == 0) {
775         buffers = cblk + 1;
776     } else {
777         buffers = output.buffers->pointer();
778         if (buffers == NULL) {
779             ALOGE("%s(%d): Could not get buffer pointer", __func__, mPortId);
780             status = NO_INIT;
781             goto exit;
782         }
783     }
784 
785     // invariant that mAudioRecord != 0 is true only after set() returns successfully
786     if (mAudioRecord != 0) {
787         IInterface::asBinder(mAudioRecord)->unlinkToDeath(mDeathNotifier, this);
788         mDeathNotifier.clear();
789     }
790     mAudioRecord = record;
791     mCblkMemory = output.cblk;
792     mBufferMemory = output.buffers;
793     IPCThreadState::self()->flushCommands();
794 
795     mCblk = cblk;
796     // note that output.frameCount is the (possibly revised) value of mReqFrameCount
797     if (output.frameCount < mReqFrameCount || (mReqFrameCount == 0 && output.frameCount == 0)) {
798         ALOGW("%s(%d): Requested frameCount %zu but received frameCount %zu",
799               __func__, output.portId,
800               mReqFrameCount,  output.frameCount);
801     }
802 
803     // Make sure that application is notified with sufficient margin before overrun.
804     // The computation is done on server side.
805     if (mNotificationFramesReq > 0 && output.notificationFrameCount != mNotificationFramesReq) {
806         ALOGW("%s(%d): Server adjusted notificationFrames from %u to %zu for frameCount %zu",
807                 __func__, output.portId,
808                 mNotificationFramesReq, output.notificationFrameCount, output.frameCount);
809     }
810     mNotificationFramesAct = (uint32_t)output.notificationFrameCount;
811 
812     //mInput != input includes the case where mInput == AUDIO_IO_HANDLE_NONE for first creation
813     if (mDeviceCallback != 0) {
814         if (mInput != AUDIO_IO_HANDLE_NONE) {
815             AudioSystem::removeAudioDeviceCallback(this, mInput, mPortId);
816         }
817         AudioSystem::addAudioDeviceCallback(this, output.inputId, output.portId);
818     }
819 
820     mPortId = output.portId;
821     // We retain a copy of the I/O handle, but don't own the reference
822     mInput = output.inputId;
823     mRefreshRemaining = true;
824 
825     mFrameCount = output.frameCount;
826     // If IAudioRecord is re-created, don't let the requested frameCount
827     // decrease.  This can confuse clients that cache frameCount().
828     if (mFrameCount > mReqFrameCount) {
829         mReqFrameCount = mFrameCount;
830     }
831 
832     // update proxy
833     mProxy = new AudioRecordClientProxy(cblk, buffers, mFrameCount, mFrameSize);
834     mProxy->setEpoch(epoch);
835     mProxy->setMinimum(mNotificationFramesAct);
836 
837     mDeathNotifier = new DeathNotifier(this);
838     IInterface::asBinder(mAudioRecord)->linkToDeath(mDeathNotifier, this);
839 
840 exit:
841     mStatus = status;
842     // sp<IAudioTrack> track destructor will cause releaseOutput() to be called by AudioFlinger
843     return status;
844 }
845 
obtainBuffer(Buffer * audioBuffer,int32_t waitCount,size_t * nonContig)846 status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
847 {
848     if (audioBuffer == NULL) {
849         if (nonContig != NULL) {
850             *nonContig = 0;
851         }
852         return BAD_VALUE;
853     }
854     if (mTransfer != TRANSFER_OBTAIN) {
855         audioBuffer->frameCount = 0;
856         audioBuffer->size = 0;
857         audioBuffer->raw = NULL;
858         if (nonContig != NULL) {
859             *nonContig = 0;
860         }
861         return INVALID_OPERATION;
862     }
863 
864     const struct timespec *requested;
865     struct timespec timeout;
866     if (waitCount == -1) {
867         requested = &ClientProxy::kForever;
868     } else if (waitCount == 0) {
869         requested = &ClientProxy::kNonBlocking;
870     } else if (waitCount > 0) {
871         time_t ms = WAIT_PERIOD_MS * (time_t) waitCount;
872         timeout.tv_sec = ms / 1000;
873         timeout.tv_nsec = (long) (ms % 1000) * 1000000;
874         requested = &timeout;
875     } else {
876         ALOGE("%s(%d): invalid waitCount %d", __func__, mPortId, waitCount);
877         requested = NULL;
878     }
879     return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
880 }
881 
obtainBuffer(Buffer * audioBuffer,const struct timespec * requested,struct timespec * elapsed,size_t * nonContig)882 status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
883         struct timespec *elapsed, size_t *nonContig)
884 {
885     // previous and new IAudioRecord sequence numbers are used to detect track re-creation
886     uint32_t oldSequence = 0;
887     uint32_t newSequence;
888 
889     Proxy::Buffer buffer;
890     status_t status = NO_ERROR;
891 
892     static const int32_t kMaxTries = 5;
893     int32_t tryCounter = kMaxTries;
894 
895     do {
896         // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
897         // keep them from going away if another thread re-creates the track during obtainBuffer()
898         sp<AudioRecordClientProxy> proxy;
899         sp<IMemory> iMem;
900         sp<IMemory> bufferMem;
901         {
902             // start of lock scope
903             AutoMutex lock(mLock);
904 
905             newSequence = mSequence;
906             // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
907             if (status == DEAD_OBJECT) {
908                 // re-create track, unless someone else has already done so
909                 if (newSequence == oldSequence) {
910                     status = restoreRecord_l("obtainBuffer");
911                     if (status != NO_ERROR) {
912                         buffer.mFrameCount = 0;
913                         buffer.mRaw = NULL;
914                         buffer.mNonContig = 0;
915                         break;
916                     }
917                 }
918             }
919             oldSequence = newSequence;
920 
921             // Keep the extra references
922             proxy = mProxy;
923             iMem = mCblkMemory;
924             bufferMem = mBufferMemory;
925 
926             // Non-blocking if track is stopped
927             if (!mActive) {
928                 requested = &ClientProxy::kNonBlocking;
929             }
930 
931         }   // end of lock scope
932 
933         buffer.mFrameCount = audioBuffer->frameCount;
934         // FIXME starts the requested timeout and elapsed over from scratch
935         status = proxy->obtainBuffer(&buffer, requested, elapsed);
936 
937     } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
938 
939     audioBuffer->frameCount = buffer.mFrameCount;
940     audioBuffer->size = buffer.mFrameCount * mFrameSize;
941     audioBuffer->raw = buffer.mRaw;
942     if (nonContig != NULL) {
943         *nonContig = buffer.mNonContig;
944     }
945     return status;
946 }
947 
releaseBuffer(const Buffer * audioBuffer)948 void AudioRecord::releaseBuffer(const Buffer* audioBuffer)
949 {
950     // FIXME add error checking on mode, by adding an internal version
951 
952     size_t stepCount = audioBuffer->size / mFrameSize;
953     if (stepCount == 0) {
954         return;
955     }
956 
957     Proxy::Buffer buffer;
958     buffer.mFrameCount = stepCount;
959     buffer.mRaw = audioBuffer->raw;
960 
961     AutoMutex lock(mLock);
962     mInOverrun = false;
963     mProxy->releaseBuffer(&buffer);
964 
965     // the server does not automatically disable recorder on overrun, so no need to restart
966 }
967 
getInputPrivate() const968 audio_io_handle_t AudioRecord::getInputPrivate() const
969 {
970     AutoMutex lock(mLock);
971     return mInput;
972 }
973 
974 // -------------------------------------------------------------------------
975 
read(void * buffer,size_t userSize,bool blocking)976 ssize_t AudioRecord::read(void* buffer, size_t userSize, bool blocking)
977 {
978     if (mTransfer != TRANSFER_SYNC) {
979         return INVALID_OPERATION;
980     }
981 
982     if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
983         // sanity-check. user is most-likely passing an error code, and it would
984         // make the return value ambiguous (actualSize vs error).
985         ALOGE("%s(%d) (buffer=%p, size=%zu (%zu)",
986                 __func__, mPortId, buffer, userSize, userSize);
987         return BAD_VALUE;
988     }
989 
990     ssize_t read = 0;
991     Buffer audioBuffer;
992 
993     while (userSize >= mFrameSize) {
994         audioBuffer.frameCount = userSize / mFrameSize;
995 
996         status_t err = obtainBuffer(&audioBuffer,
997                 blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
998         if (err < 0) {
999             if (read > 0) {
1000                 break;
1001             }
1002             if (err == TIMED_OUT || err == -EINTR) {
1003                 err = WOULD_BLOCK;
1004             }
1005             return ssize_t(err);
1006         }
1007 
1008         size_t bytesRead = audioBuffer.size;
1009         memcpy(buffer, audioBuffer.i8, bytesRead);
1010         buffer = ((char *) buffer) + bytesRead;
1011         userSize -= bytesRead;
1012         read += bytesRead;
1013 
1014         releaseBuffer(&audioBuffer);
1015     }
1016     if (read > 0) {
1017         mFramesRead += read / mFrameSize;
1018         // mFramesReadTime = systemTime(SYSTEM_TIME_MONOTONIC); // not provided at this time.
1019     }
1020     return read;
1021 }
1022 
1023 // -------------------------------------------------------------------------
1024 
processAudioBuffer()1025 nsecs_t AudioRecord::processAudioBuffer()
1026 {
1027     mLock.lock();
1028     if (mAwaitBoost) {
1029         mAwaitBoost = false;
1030         mLock.unlock();
1031         static const int32_t kMaxTries = 5;
1032         int32_t tryCounter = kMaxTries;
1033         uint32_t pollUs = 10000;
1034         do {
1035             int policy = sched_getscheduler(0) & ~SCHED_RESET_ON_FORK;
1036             if (policy == SCHED_FIFO || policy == SCHED_RR) {
1037                 break;
1038             }
1039             usleep(pollUs);
1040             pollUs <<= 1;
1041         } while (tryCounter-- > 0);
1042         if (tryCounter < 0) {
1043             ALOGE("%s(%d): did not receive expected priority boost on time", __func__, mPortId);
1044         }
1045         // Run again immediately
1046         return 0;
1047     }
1048 
1049     // Can only reference mCblk while locked
1050     int32_t flags = android_atomic_and(~CBLK_OVERRUN, &mCblk->mFlags);
1051 
1052     // Check for track invalidation
1053     if (flags & CBLK_INVALID) {
1054         (void) restoreRecord_l("processAudioBuffer");
1055         mLock.unlock();
1056         // Run again immediately, but with a new IAudioRecord
1057         return 0;
1058     }
1059 
1060     bool active = mActive;
1061 
1062     // Manage overrun callback, must be done under lock to avoid race with releaseBuffer()
1063     bool newOverrun = false;
1064     if (flags & CBLK_OVERRUN) {
1065         if (!mInOverrun) {
1066             mInOverrun = true;
1067             newOverrun = true;
1068         }
1069     }
1070 
1071     // Get current position of server
1072     Modulo<uint32_t> position(mProxy->getPosition());
1073 
1074     // Manage marker callback
1075     bool markerReached = false;
1076     Modulo<uint32_t> markerPosition(mMarkerPosition);
1077     // FIXME fails for wraparound, need 64 bits
1078     if (!mMarkerReached && markerPosition.value() > 0 && position >= markerPosition) {
1079         mMarkerReached = markerReached = true;
1080     }
1081 
1082     // Determine the number of new position callback(s) that will be needed, while locked
1083     size_t newPosCount = 0;
1084     Modulo<uint32_t> newPosition(mNewPosition);
1085     uint32_t updatePeriod = mUpdatePeriod;
1086     // FIXME fails for wraparound, need 64 bits
1087     if (updatePeriod > 0 && position >= newPosition) {
1088         newPosCount = ((position - newPosition).value() / updatePeriod) + 1;
1089         mNewPosition += updatePeriod * newPosCount;
1090     }
1091 
1092     // Cache other fields that will be needed soon
1093     uint32_t notificationFrames = mNotificationFramesAct;
1094     if (mRefreshRemaining) {
1095         mRefreshRemaining = false;
1096         mRemainingFrames = notificationFrames;
1097         mRetryOnPartialBuffer = false;
1098     }
1099     size_t misalignment = mProxy->getMisalignment();
1100     uint32_t sequence = mSequence;
1101 
1102     // These fields don't need to be cached, because they are assigned only by set():
1103     //      mTransfer, mCbf, mUserData, mSampleRate, mFrameSize
1104 
1105     mLock.unlock();
1106 
1107     // perform callbacks while unlocked
1108     if (newOverrun) {
1109         mCbf(EVENT_OVERRUN, mUserData, NULL);
1110     }
1111     if (markerReached) {
1112         mCbf(EVENT_MARKER, mUserData, &markerPosition);
1113     }
1114     while (newPosCount > 0) {
1115         size_t temp = newPosition.value(); // FIXME size_t != uint32_t
1116         mCbf(EVENT_NEW_POS, mUserData, &temp);
1117         newPosition += updatePeriod;
1118         newPosCount--;
1119     }
1120     if (mObservedSequence != sequence) {
1121         mObservedSequence = sequence;
1122         mCbf(EVENT_NEW_IAUDIORECORD, mUserData, NULL);
1123     }
1124 
1125     // if inactive, then don't run me again until re-started
1126     if (!active) {
1127         return NS_INACTIVE;
1128     }
1129 
1130     // Compute the estimated time until the next timed event (position, markers)
1131     uint32_t minFrames = ~0;
1132     if (!markerReached && position < markerPosition) {
1133         minFrames = (markerPosition - position).value();
1134     }
1135     if (updatePeriod > 0) {
1136         uint32_t remaining = (newPosition - position).value();
1137         if (remaining < minFrames) {
1138             minFrames = remaining;
1139         }
1140     }
1141 
1142     // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
1143     static const uint32_t kPoll = 0;
1144     if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1145         minFrames = kPoll * notificationFrames;
1146     }
1147 
1148     // Convert frame units to time units
1149     nsecs_t ns = NS_WHENEVER;
1150     if (minFrames != (uint32_t) ~0) {
1151         // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1152         static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1153         ns = ((minFrames * 1000000000LL) / mSampleRate) + kFudgeNs;
1154     }
1155 
1156     // If not supplying data by EVENT_MORE_DATA, then we're done
1157     if (mTransfer != TRANSFER_CALLBACK) {
1158         return ns;
1159     }
1160 
1161     struct timespec timeout;
1162     const struct timespec *requested = &ClientProxy::kForever;
1163     if (ns != NS_WHENEVER) {
1164         timeout.tv_sec = ns / 1000000000LL;
1165         timeout.tv_nsec = ns % 1000000000LL;
1166         ALOGV("%s(%d): timeout %ld.%03d",
1167                 __func__, mPortId, timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1168         requested = &timeout;
1169     }
1170 
1171     size_t readFrames = 0;
1172     while (mRemainingFrames > 0) {
1173 
1174         Buffer audioBuffer;
1175         audioBuffer.frameCount = mRemainingFrames;
1176         size_t nonContig;
1177         status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1178         LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1179                 "%s(%d): obtainBuffer() err=%d frameCount=%zu",
1180                 __func__, mPortId, err, audioBuffer.frameCount);
1181         requested = &ClientProxy::kNonBlocking;
1182         size_t avail = audioBuffer.frameCount + nonContig;
1183         ALOGV("%s(%d): obtainBuffer(%u) returned %zu = %zu + %zu err %d",
1184                 __func__, mPortId, mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
1185         if (err != NO_ERROR) {
1186             if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR) {
1187                 break;
1188             }
1189             ALOGE("%s(%d): Error %d obtaining an audio buffer, giving up.",
1190                     __func__, mPortId, err);
1191             return NS_NEVER;
1192         }
1193 
1194         if (mRetryOnPartialBuffer) {
1195             mRetryOnPartialBuffer = false;
1196             if (avail < mRemainingFrames) {
1197                 int64_t myns = ((mRemainingFrames - avail) *
1198                         1100000000LL) / mSampleRate;
1199                 if (ns < 0 || myns < ns) {
1200                     ns = myns;
1201                 }
1202                 return ns;
1203             }
1204         }
1205 
1206         size_t reqSize = audioBuffer.size;
1207         mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1208         size_t readSize = audioBuffer.size;
1209 
1210         // Sanity check on returned size
1211         if (ssize_t(readSize) < 0 || readSize > reqSize) {
1212             ALOGE("%s(%d):  EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1213                     __func__, mPortId, reqSize, ssize_t(readSize));
1214             return NS_NEVER;
1215         }
1216 
1217         if (readSize == 0) {
1218             // The callback is done consuming buffers
1219             // Keep this thread going to handle timed events and
1220             // still try to provide more data in intervals of WAIT_PERIOD_MS
1221             // but don't just loop and block the CPU, so wait
1222             return WAIT_PERIOD_MS * 1000000LL;
1223         }
1224 
1225         size_t releasedFrames = readSize / mFrameSize;
1226         audioBuffer.frameCount = releasedFrames;
1227         mRemainingFrames -= releasedFrames;
1228         if (misalignment >= releasedFrames) {
1229             misalignment -= releasedFrames;
1230         } else {
1231             misalignment = 0;
1232         }
1233 
1234         releaseBuffer(&audioBuffer);
1235         readFrames += releasedFrames;
1236 
1237         // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1238         // if callback doesn't like to accept the full chunk
1239         if (readSize < reqSize) {
1240             continue;
1241         }
1242 
1243         // There could be enough non-contiguous frames available to satisfy the remaining request
1244         if (mRemainingFrames <= nonContig) {
1245             continue;
1246         }
1247 
1248 #if 0
1249         // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1250         // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
1251         // that total to a sum == notificationFrames.
1252         if (0 < misalignment && misalignment <= mRemainingFrames) {
1253             mRemainingFrames = misalignment;
1254             return (mRemainingFrames * 1100000000LL) / mSampleRate;
1255         }
1256 #endif
1257 
1258     }
1259     if (readFrames > 0) {
1260         AutoMutex lock(mLock);
1261         mFramesRead += readFrames;
1262         // mFramesReadTime = systemTime(SYSTEM_TIME_MONOTONIC); // not provided at this time.
1263     }
1264     mRemainingFrames = notificationFrames;
1265     mRetryOnPartialBuffer = true;
1266 
1267     // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1268     return 0;
1269 }
1270 
restoreRecord_l(const char * from)1271 status_t AudioRecord::restoreRecord_l(const char *from)
1272 {
1273     ALOGW("%s(%d): dead IAudioRecord, creating a new one from %s()", __func__, mPortId, from);
1274     ++mSequence;
1275 
1276     const int INITIAL_RETRIES = 3;
1277     int retries = INITIAL_RETRIES;
1278 retry:
1279     if (retries < INITIAL_RETRIES) {
1280         // refresh the audio configuration cache in this process to make sure we get new
1281         // input parameters and new IAudioRecord in createRecord_l()
1282         AudioSystem::clearAudioConfigCache();
1283     }
1284     mFlags = mOrigFlags;
1285 
1286     // if the new IAudioRecord is created, createRecord_l() will modify the
1287     // following member variables: mAudioRecord, mCblkMemory, mCblk, mBufferMemory.
1288     // It will also delete the strong references on previous IAudioRecord and IMemory
1289     Modulo<uint32_t> position(mProxy->getPosition());
1290     mNewPosition = position + mUpdatePeriod;
1291     status_t result = createRecord_l(position, mOpPackageName);
1292 
1293     if (result == NO_ERROR) {
1294         if (mActive) {
1295             // callback thread or sync event hasn't changed
1296             // FIXME this fails if we have a new AudioFlinger instance
1297             result = mAudioRecord->start(
1298                 AudioSystem::SYNC_EVENT_SAME, AUDIO_SESSION_NONE).transactionError();
1299         }
1300         mFramesReadServerOffset = mFramesRead; // server resets to zero so we need an offset.
1301     }
1302 
1303     if (result != NO_ERROR) {
1304         ALOGW("%s(%d): failed status %d, retries %d", __func__, mPortId, result, retries);
1305         if (--retries > 0) {
1306             // leave time for an eventual race condition to clear before retrying
1307             usleep(500000);
1308             goto retry;
1309         }
1310         // if no retries left, set invalid bit to force restoring at next occasion
1311         // and avoid inconsistent active state on client and server sides
1312         if (mCblk != nullptr) {
1313             android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
1314         }
1315     }
1316 
1317     return result;
1318 }
1319 
addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)1320 status_t AudioRecord::addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback)
1321 {
1322     if (callback == 0) {
1323         ALOGW("%s(%d): adding NULL callback!", __func__, mPortId);
1324         return BAD_VALUE;
1325     }
1326     AutoMutex lock(mLock);
1327     if (mDeviceCallback.unsafe_get() == callback.get()) {
1328         ALOGW("%s(%d): adding same callback!", __func__, mPortId);
1329         return INVALID_OPERATION;
1330     }
1331     status_t status = NO_ERROR;
1332     if (mInput != AUDIO_IO_HANDLE_NONE) {
1333         if (mDeviceCallback != 0) {
1334             ALOGW("%s(%d): callback already present!", __func__, mPortId);
1335             AudioSystem::removeAudioDeviceCallback(this, mInput, mPortId);
1336         }
1337         status = AudioSystem::addAudioDeviceCallback(this, mInput, mPortId);
1338     }
1339     mDeviceCallback = callback;
1340     return status;
1341 }
1342 
removeAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback> & callback)1343 status_t AudioRecord::removeAudioDeviceCallback(
1344         const sp<AudioSystem::AudioDeviceCallback>& callback)
1345 {
1346     if (callback == 0) {
1347         ALOGW("%s(%d): removing NULL callback!", __func__, mPortId);
1348         return BAD_VALUE;
1349     }
1350     AutoMutex lock(mLock);
1351     if (mDeviceCallback.unsafe_get() != callback.get()) {
1352         ALOGW("%s(%d): removing different callback!", __func__, mPortId);
1353         return INVALID_OPERATION;
1354     }
1355     mDeviceCallback.clear();
1356     if (mInput != AUDIO_IO_HANDLE_NONE) {
1357         AudioSystem::removeAudioDeviceCallback(this, mInput, mPortId);
1358     }
1359     return NO_ERROR;
1360 }
1361 
onAudioDeviceUpdate(audio_io_handle_t audioIo,audio_port_handle_t deviceId)1362 void AudioRecord::onAudioDeviceUpdate(audio_io_handle_t audioIo,
1363                                  audio_port_handle_t deviceId)
1364 {
1365     sp<AudioSystem::AudioDeviceCallback> callback;
1366     {
1367         AutoMutex lock(mLock);
1368         if (audioIo != mInput) {
1369             return;
1370         }
1371         callback = mDeviceCallback.promote();
1372         // only update device if the record is active as route changes due to other use cases are
1373         // irrelevant for this client
1374         if (mActive) {
1375             mRoutedDeviceId = deviceId;
1376         }
1377     }
1378     if (callback.get() != nullptr) {
1379         callback->onAudioDeviceUpdate(mInput, mRoutedDeviceId);
1380     }
1381 }
1382 
1383 // -------------------------------------------------------------------------
1384 
getActiveMicrophones(std::vector<media::MicrophoneInfo> * activeMicrophones)1385 status_t AudioRecord::getActiveMicrophones(std::vector<media::MicrophoneInfo>* activeMicrophones)
1386 {
1387     AutoMutex lock(mLock);
1388     return mAudioRecord->getActiveMicrophones(activeMicrophones).transactionError();
1389 }
1390 
setPreferredMicrophoneDirection(audio_microphone_direction_t direction)1391 status_t AudioRecord::setPreferredMicrophoneDirection(audio_microphone_direction_t direction)
1392 {
1393     AutoMutex lock(mLock);
1394     if (mSelectedMicDirection == direction) {
1395         // NOP
1396         return OK;
1397     }
1398 
1399     mSelectedMicDirection = direction;
1400     if (mAudioRecord == 0) {
1401         // the internal AudioRecord hasn't be created yet, so just stash the attribute.
1402         return OK;
1403     } else {
1404         return mAudioRecord->setPreferredMicrophoneDirection(direction).transactionError();
1405     }
1406 }
1407 
setPreferredMicrophoneFieldDimension(float zoom)1408 status_t AudioRecord::setPreferredMicrophoneFieldDimension(float zoom) {
1409     AutoMutex lock(mLock);
1410     if (mSelectedMicFieldDimension == zoom) {
1411         // NOP
1412         return OK;
1413     }
1414 
1415     mSelectedMicFieldDimension = zoom;
1416     if (mAudioRecord == 0) {
1417         // the internal AudioRecord hasn't be created yet, so just stash the attribute.
1418         return OK;
1419     } else {
1420         return mAudioRecord->setPreferredMicrophoneFieldDimension(zoom).transactionError();
1421     }
1422 }
1423 
1424 // =========================================================================
1425 
binderDied(const wp<IBinder> & who __unused)1426 void AudioRecord::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
1427 {
1428     sp<AudioRecord> audioRecord = mAudioRecord.promote();
1429     if (audioRecord != 0) {
1430         AutoMutex lock(audioRecord->mLock);
1431         audioRecord->mProxy->binderDied();
1432     }
1433 }
1434 
1435 // =========================================================================
1436 
AudioRecordThread(AudioRecord & receiver)1437 AudioRecord::AudioRecordThread::AudioRecordThread(AudioRecord& receiver)
1438     : Thread(true /* bCanCallJava */)  // binder recursion on restoreRecord_l() may call Java.
1439     , mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
1440       mIgnoreNextPausedInt(false)
1441 {
1442 }
1443 
~AudioRecordThread()1444 AudioRecord::AudioRecordThread::~AudioRecordThread()
1445 {
1446 }
1447 
threadLoop()1448 bool AudioRecord::AudioRecordThread::threadLoop()
1449 {
1450     {
1451         AutoMutex _l(mMyLock);
1452         if (mPaused) {
1453             // TODO check return value and handle or log
1454             mMyCond.wait(mMyLock);
1455             // caller will check for exitPending()
1456             return true;
1457         }
1458         if (mIgnoreNextPausedInt) {
1459             mIgnoreNextPausedInt = false;
1460             mPausedInt = false;
1461         }
1462         if (mPausedInt) {
1463             if (mPausedNs > 0) {
1464                 // TODO check return value and handle or log
1465                 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1466             } else {
1467                 // TODO check return value and handle or log
1468                 mMyCond.wait(mMyLock);
1469             }
1470             mPausedInt = false;
1471             return true;
1472         }
1473     }
1474     if (exitPending()) {
1475         return false;
1476     }
1477     nsecs_t ns =  mReceiver.processAudioBuffer();
1478     switch (ns) {
1479     case 0:
1480         return true;
1481     case NS_INACTIVE:
1482         pauseInternal();
1483         return true;
1484     case NS_NEVER:
1485         return false;
1486     case NS_WHENEVER:
1487         // Event driven: call wake() when callback notifications conditions change.
1488         ns = INT64_MAX;
1489         FALLTHROUGH_INTENDED;
1490     default:
1491         LOG_ALWAYS_FATAL_IF(ns < 0, "%s() returned %lld", __func__, (long long)ns);
1492         pauseInternal(ns);
1493         return true;
1494     }
1495 }
1496 
requestExit()1497 void AudioRecord::AudioRecordThread::requestExit()
1498 {
1499     // must be in this order to avoid a race condition
1500     Thread::requestExit();
1501     resume();
1502 }
1503 
pause()1504 void AudioRecord::AudioRecordThread::pause()
1505 {
1506     AutoMutex _l(mMyLock);
1507     mPaused = true;
1508 }
1509 
resume()1510 void AudioRecord::AudioRecordThread::resume()
1511 {
1512     AutoMutex _l(mMyLock);
1513     mIgnoreNextPausedInt = true;
1514     if (mPaused || mPausedInt) {
1515         mPaused = false;
1516         mPausedInt = false;
1517         mMyCond.signal();
1518     }
1519 }
1520 
wake()1521 void AudioRecord::AudioRecordThread::wake()
1522 {
1523     AutoMutex _l(mMyLock);
1524     if (!mPaused) {
1525         // wake() might be called while servicing a callback - ignore the next
1526         // pause time and call processAudioBuffer.
1527         mIgnoreNextPausedInt = true;
1528         if (mPausedInt && mPausedNs > 0) {
1529             // audio record is active and internally paused with timeout.
1530             mPausedInt = false;
1531             mMyCond.signal();
1532         }
1533     }
1534 }
1535 
pauseInternal(nsecs_t ns)1536 void AudioRecord::AudioRecordThread::pauseInternal(nsecs_t ns)
1537 {
1538     AutoMutex _l(mMyLock);
1539     mPausedInt = true;
1540     mPausedNs = ns;
1541 }
1542 
1543 // -------------------------------------------------------------------------
1544 
1545 } // namespace android
1546