1 /*
2 **
3 ** Copyright 2012, 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 
19 #define LOG_TAG "AudioFlinger"
20 //#define LOG_NDEBUG 0
21 #define ATRACE_TAG ATRACE_TAG_AUDIO
22 
23 #include "Configuration.h"
24 #include <linux/futex.h>
25 #include <math.h>
26 #include <sys/syscall.h>
27 #include <utils/Log.h>
28 #include <utils/Trace.h>
29 
30 #include <private/media/AudioTrackShared.h>
31 
32 #include "AudioFlinger.h"
33 
34 #include <media/nbaio/Pipe.h>
35 #include <media/nbaio/PipeReader.h>
36 #include <media/RecordBufferConverter.h>
37 #include <mediautils/ServiceUtilities.h>
38 #include <audio_utils/minifloat.h>
39 
40 // ----------------------------------------------------------------------------
41 
42 // Note: the following macro is used for extremely verbose logging message.  In
43 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
44 // 0; but one side effect of this is to turn all LOGV's as well.  Some messages
45 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
46 // turned on.  Do not uncomment the #def below unless you really know what you
47 // are doing and want to see all of the extremely verbose messages.
48 //#define VERY_VERY_VERBOSE_LOGGING
49 #ifdef VERY_VERY_VERBOSE_LOGGING
50 #define ALOGVV ALOGV
51 #else
52 #define ALOGVV(a...) do { } while(0)
53 #endif
54 
55 namespace android {
56 
57 using media::VolumeShaper;
58 // ----------------------------------------------------------------------------
59 //      TrackBase
60 // ----------------------------------------------------------------------------
61 #undef LOG_TAG
62 #define LOG_TAG "AF::TrackBase"
63 
64 static volatile int32_t nextTrackId = 55;
65 
66 // TrackBase constructor must be called with AudioFlinger::mLock held
TrackBase(ThreadBase * thread,const sp<Client> & client,const audio_attributes_t & attr,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,void * buffer,size_t bufferSize,audio_session_t sessionId,pid_t creatorPid,uid_t clientUid,bool isOut,alloc_type alloc,track_type type,audio_port_handle_t portId)67 AudioFlinger::ThreadBase::TrackBase::TrackBase(
68             ThreadBase *thread,
69             const sp<Client>& client,
70             const audio_attributes_t& attr,
71             uint32_t sampleRate,
72             audio_format_t format,
73             audio_channel_mask_t channelMask,
74             size_t frameCount,
75             void *buffer,
76             size_t bufferSize,
77             audio_session_t sessionId,
78             pid_t creatorPid,
79             uid_t clientUid,
80             bool isOut,
81             alloc_type alloc,
82             track_type type,
83             audio_port_handle_t portId)
84     :   RefBase(),
85         mThread(thread),
86         mClient(client),
87         mCblk(NULL),
88         // mBuffer, mBufferSize
89         mState(IDLE),
90         mAttr(attr),
91         mSampleRate(sampleRate),
92         mFormat(format),
93         mChannelMask(channelMask),
94         mChannelCount(isOut ?
95                 audio_channel_count_from_out_mask(channelMask) :
96                 audio_channel_count_from_in_mask(channelMask)),
97         mFrameSize(audio_has_proportional_frames(format) ?
98                 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
99         mFrameCount(frameCount),
100         mSessionId(sessionId),
101         mIsOut(isOut),
102         mId(android_atomic_inc(&nextTrackId)),
103         mTerminated(false),
104         mType(type),
105         mThreadIoHandle(thread ? thread->id() : AUDIO_IO_HANDLE_NONE),
106         mPortId(portId),
107         mIsInvalid(false),
108         mCreatorPid(creatorPid)
109 {
110     const uid_t callingUid = IPCThreadState::self()->getCallingUid();
111     if (!isAudioServerOrMediaServerUid(callingUid) || clientUid == AUDIO_UID_INVALID) {
112         ALOGW_IF(clientUid != AUDIO_UID_INVALID && clientUid != callingUid,
113                 "%s(%d): uid %d tried to pass itself off as %d",
114                  __func__, mId, callingUid, clientUid);
115         clientUid = callingUid;
116     }
117     // clientUid contains the uid of the app that is responsible for this track, so we can blame
118     // battery usage on it.
119     mUid = clientUid;
120 
121     // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
122 
123     size_t minBufferSize = buffer == NULL ? roundup(frameCount) : frameCount;
124     // check overflow when computing bufferSize due to multiplication by mFrameSize.
125     if (minBufferSize < frameCount  // roundup rounds down for values above UINT_MAX / 2
126             || mFrameSize == 0   // format needs to be correct
127             || minBufferSize > SIZE_MAX / mFrameSize) {
128         android_errorWriteLog(0x534e4554, "34749571");
129         return;
130     }
131     minBufferSize *= mFrameSize;
132 
133     if (buffer == nullptr) {
134         bufferSize = minBufferSize; // allocated here.
135     } else if (minBufferSize > bufferSize) {
136         android_errorWriteLog(0x534e4554, "38340117");
137         return;
138     }
139 
140     size_t size = sizeof(audio_track_cblk_t);
141     if (buffer == NULL && alloc == ALLOC_CBLK) {
142         // check overflow when computing allocation size for streaming tracks.
143         if (size > SIZE_MAX - bufferSize) {
144             android_errorWriteLog(0x534e4554, "34749571");
145             return;
146         }
147         size += bufferSize;
148     }
149 
150     if (client != 0) {
151         mCblkMemory = client->heap()->allocate(size);
152         if (mCblkMemory == 0 ||
153                 (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
154             ALOGE("%s(%d): not enough memory for AudioTrack size=%zu", __func__, mId, size);
155             client->heap()->dump("AudioTrack");
156             mCblkMemory.clear();
157             return;
158         }
159     } else {
160         mCblk = (audio_track_cblk_t *) malloc(size);
161         if (mCblk == NULL) {
162             ALOGE("%s(%d): not enough memory for AudioTrack size=%zu", __func__, mId, size);
163             return;
164         }
165     }
166 
167     // construct the shared structure in-place.
168     if (mCblk != NULL) {
169         new(mCblk) audio_track_cblk_t();
170         switch (alloc) {
171         case ALLOC_READONLY: {
172             const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
173             if (roHeap == 0 ||
174                     (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
175                     (mBuffer = mBufferMemory->pointer()) == NULL) {
176                 ALOGE("%s(%d): not enough memory for read-only buffer size=%zu",
177                         __func__, mId, bufferSize);
178                 if (roHeap != 0) {
179                     roHeap->dump("buffer");
180                 }
181                 mCblkMemory.clear();
182                 mBufferMemory.clear();
183                 return;
184             }
185             memset(mBuffer, 0, bufferSize);
186             } break;
187         case ALLOC_PIPE:
188             mBufferMemory = thread->pipeMemory();
189             // mBuffer is the virtual address as seen from current process (mediaserver),
190             // and should normally be coming from mBufferMemory->pointer().
191             // However in this case the TrackBase does not reference the buffer directly.
192             // It should references the buffer via the pipe.
193             // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
194             mBuffer = NULL;
195             bufferSize = 0;
196             break;
197         case ALLOC_CBLK:
198             // clear all buffers
199             if (buffer == NULL) {
200                 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
201                 memset(mBuffer, 0, bufferSize);
202             } else {
203                 mBuffer = buffer;
204 #if 0
205                 mCblk->mFlags = CBLK_FORCEREADY;    // FIXME hack, need to fix the track ready logic
206 #endif
207             }
208             break;
209         case ALLOC_LOCAL:
210             mBuffer = calloc(1, bufferSize);
211             break;
212         case ALLOC_NONE:
213             mBuffer = buffer;
214             break;
215         default:
216             LOG_ALWAYS_FATAL("%s(%d): invalid allocation type: %d", __func__, mId, (int)alloc);
217         }
218         mBufferSize = bufferSize;
219 
220 #ifdef TEE_SINK
221         mTee.set(sampleRate, mChannelCount, format, NBAIO_Tee::TEE_FLAG_TRACK);
222 #endif
223 
224     }
225 }
226 
initCheck() const227 status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
228 {
229     status_t status;
230     if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
231         status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
232     } else {
233         status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
234     }
235     return status;
236 }
237 
~TrackBase()238 AudioFlinger::ThreadBase::TrackBase::~TrackBase()
239 {
240     // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
241     mServerProxy.clear();
242     if (mCblk != NULL) {
243         mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
244         if (mClient == 0) {
245             free(mCblk);
246         }
247     }
248     mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
249     if (mClient != 0) {
250         // Client destructor must run with AudioFlinger client mutex locked
251         Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
252         // If the client's reference count drops to zero, the associated destructor
253         // must run with AudioFlinger lock held. Thus the explicit clear() rather than
254         // relying on the automatic clear() at end of scope.
255         mClient.clear();
256     }
257     // flush the binder command buffer
258     IPCThreadState::self()->flushCommands();
259 }
260 
261 // AudioBufferProvider interface
262 // getNextBuffer() = 0;
263 // This implementation of releaseBuffer() is used by Track and RecordTrack
releaseBuffer(AudioBufferProvider::Buffer * buffer)264 void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
265 {
266 #ifdef TEE_SINK
267     mTee.write(buffer->raw, buffer->frameCount);
268 #endif
269 
270     ServerProxy::Buffer buf;
271     buf.mFrameCount = buffer->frameCount;
272     buf.mRaw = buffer->raw;
273     buffer->frameCount = 0;
274     buffer->raw = NULL;
275     mServerProxy->releaseBuffer(&buf);
276 }
277 
setSyncEvent(const sp<SyncEvent> & event)278 status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
279 {
280     mSyncEvents.add(event);
281     return NO_ERROR;
282 }
283 
PatchTrackBase(sp<ClientProxy> proxy,const ThreadBase & thread,const Timeout & timeout)284 AudioFlinger::ThreadBase::PatchTrackBase::PatchTrackBase(sp<ClientProxy> proxy,
285                                                          const ThreadBase& thread,
286                                                          const Timeout& timeout)
287     : mProxy(proxy)
288 {
289     if (timeout) {
290         setPeerTimeout(*timeout);
291     } else {
292         // Double buffer mixer
293         uint64_t mixBufferNs = ((uint64_t)2 * thread.frameCount() * 1000000000) /
294                                               thread.sampleRate();
295         setPeerTimeout(std::chrono::nanoseconds{mixBufferNs});
296     }
297 }
298 
setPeerTimeout(std::chrono::nanoseconds timeout)299 void AudioFlinger::ThreadBase::PatchTrackBase::setPeerTimeout(std::chrono::nanoseconds timeout) {
300     mPeerTimeout.tv_sec = timeout.count() / std::nano::den;
301     mPeerTimeout.tv_nsec = timeout.count() % std::nano::den;
302 }
303 
304 
305 // ----------------------------------------------------------------------------
306 //      Playback
307 // ----------------------------------------------------------------------------
308 #undef LOG_TAG
309 #define LOG_TAG "AF::TrackHandle"
310 
TrackHandle(const sp<AudioFlinger::PlaybackThread::Track> & track)311 AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
312     : BnAudioTrack(),
313       mTrack(track)
314 {
315 }
316 
~TrackHandle()317 AudioFlinger::TrackHandle::~TrackHandle() {
318     // just stop the track on deletion, associated resources
319     // will be freed from the main thread once all pending buffers have
320     // been played. Unless it's not in the active track list, in which
321     // case we free everything now...
322     mTrack->destroy();
323 }
324 
getCblk() const325 sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
326     return mTrack->getCblk();
327 }
328 
start()329 status_t AudioFlinger::TrackHandle::start() {
330     return mTrack->start();
331 }
332 
stop()333 void AudioFlinger::TrackHandle::stop() {
334     mTrack->stop();
335 }
336 
flush()337 void AudioFlinger::TrackHandle::flush() {
338     mTrack->flush();
339 }
340 
pause()341 void AudioFlinger::TrackHandle::pause() {
342     mTrack->pause();
343 }
344 
attachAuxEffect(int EffectId)345 status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
346 {
347     return mTrack->attachAuxEffect(EffectId);
348 }
349 
setParameters(const String8 & keyValuePairs)350 status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
351     return mTrack->setParameters(keyValuePairs);
352 }
353 
selectPresentation(int presentationId,int programId)354 status_t AudioFlinger::TrackHandle::selectPresentation(int presentationId, int programId) {
355     return mTrack->selectPresentation(presentationId, programId);
356 }
357 
applyVolumeShaper(const sp<VolumeShaper::Configuration> & configuration,const sp<VolumeShaper::Operation> & operation)358 VolumeShaper::Status AudioFlinger::TrackHandle::applyVolumeShaper(
359         const sp<VolumeShaper::Configuration>& configuration,
360         const sp<VolumeShaper::Operation>& operation) {
361     return mTrack->applyVolumeShaper(configuration, operation);
362 }
363 
getVolumeShaperState(int id)364 sp<VolumeShaper::State> AudioFlinger::TrackHandle::getVolumeShaperState(int id) {
365     return mTrack->getVolumeShaperState(id);
366 }
367 
getTimestamp(AudioTimestamp & timestamp)368 status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
369 {
370     return mTrack->getTimestamp(timestamp);
371 }
372 
373 
signal()374 void AudioFlinger::TrackHandle::signal()
375 {
376     return mTrack->signal();
377 }
378 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)379 status_t AudioFlinger::TrackHandle::onTransact(
380     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
381 {
382     return BnAudioTrack::onTransact(code, data, reply, flags);
383 }
384 
385 // ----------------------------------------------------------------------------
386 //      AppOp for audio playback
387 // -------------------------------
388 
389 // static
390 sp<AudioFlinger::PlaybackThread::OpPlayAudioMonitor>
createIfNeeded(uid_t uid,const audio_attributes_t & attr,int id,audio_stream_type_t streamType)391 AudioFlinger::PlaybackThread::OpPlayAudioMonitor::createIfNeeded(
392             uid_t uid, const audio_attributes_t& attr, int id, audio_stream_type_t streamType)
393 {
394     if (isServiceUid(uid)) {
395         Vector <String16> packages;
396         getPackagesForUid(uid, packages);
397         if (packages.isEmpty()) {
398             ALOGD("OpPlayAudio: not muting track:%d usage:%d for service UID %d",
399                   id,
400                   attr.usage,
401                   uid);
402             return nullptr;
403         }
404     }
405     // stream type has been filtered by audio policy to indicate whether it can be muted
406     if (streamType == AUDIO_STREAM_ENFORCED_AUDIBLE) {
407         ALOGD("OpPlayAudio: not muting track:%d usage:%d ENFORCED_AUDIBLE", id, attr.usage);
408         return nullptr;
409     }
410     if ((attr.flags & AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY)
411             == AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY) {
412         ALOGD("OpPlayAudio: not muting track:%d flags %#x have FLAG_BYPASS_INTERRUPTION_POLICY",
413             id, attr.flags);
414         return nullptr;
415     }
416     return new OpPlayAudioMonitor(uid, attr.usage, id);
417 }
418 
OpPlayAudioMonitor(uid_t uid,audio_usage_t usage,int id)419 AudioFlinger::PlaybackThread::OpPlayAudioMonitor::OpPlayAudioMonitor(
420         uid_t uid, audio_usage_t usage, int id)
421         : mHasOpPlayAudio(true), mUid(uid), mUsage((int32_t) usage), mId(id)
422 {
423 }
424 
~OpPlayAudioMonitor()425 AudioFlinger::PlaybackThread::OpPlayAudioMonitor::~OpPlayAudioMonitor()
426 {
427     if (mOpCallback != 0) {
428         mAppOpsManager.stopWatchingMode(mOpCallback);
429     }
430     mOpCallback.clear();
431 }
432 
onFirstRef()433 void AudioFlinger::PlaybackThread::OpPlayAudioMonitor::onFirstRef()
434 {
435     getPackagesForUid(mUid, mPackages);
436     checkPlayAudioForUsage();
437     if (!mPackages.isEmpty()) {
438         mOpCallback = new PlayAudioOpCallback(this);
439         mAppOpsManager.startWatchingMode(AppOpsManager::OP_PLAY_AUDIO, mPackages[0], mOpCallback);
440     }
441 }
442 
hasOpPlayAudio() const443 bool AudioFlinger::PlaybackThread::OpPlayAudioMonitor::hasOpPlayAudio() const {
444     return mHasOpPlayAudio.load();
445 }
446 
447 // Note this method is never called (and never to be) for audio server / patch record track
448 // - not called from constructor due to check on UID,
449 // - not called from PlayAudioOpCallback because the callback is not installed in this case
checkPlayAudioForUsage()450 void AudioFlinger::PlaybackThread::OpPlayAudioMonitor::checkPlayAudioForUsage()
451 {
452     if (mPackages.isEmpty()) {
453         mHasOpPlayAudio.store(false);
454     } else {
455         bool hasIt = true;
456         for (const String16& packageName : mPackages) {
457             const int32_t mode = mAppOpsManager.checkAudioOpNoThrow(AppOpsManager::OP_PLAY_AUDIO,
458                     mUsage, mUid, packageName);
459             if (mode != AppOpsManager::MODE_ALLOWED) {
460                 hasIt = false;
461                 break;
462             }
463         }
464         ALOGD("OpPlayAudio: track:%d usage:%d %smuted", mId, mUsage, hasIt ? "not " : "");
465         mHasOpPlayAudio.store(hasIt);
466     }
467 }
468 
PlayAudioOpCallback(const wp<OpPlayAudioMonitor> & monitor)469 AudioFlinger::PlaybackThread::OpPlayAudioMonitor::PlayAudioOpCallback::PlayAudioOpCallback(
470         const wp<OpPlayAudioMonitor>& monitor) : mMonitor(monitor)
471 { }
472 
opChanged(int32_t op,const String16 & packageName)473 void AudioFlinger::PlaybackThread::OpPlayAudioMonitor::PlayAudioOpCallback::opChanged(int32_t op,
474             const String16& packageName) {
475     // we only have uid, so we need to check all package names anyway
476     UNUSED(packageName);
477     if (op != AppOpsManager::OP_PLAY_AUDIO) {
478         return;
479     }
480     sp<OpPlayAudioMonitor> monitor = mMonitor.promote();
481     if (monitor != NULL) {
482         monitor->checkPlayAudioForUsage();
483     }
484 }
485 
486 // static
getPackagesForUid(uid_t uid,Vector<String16> & packages)487 void AudioFlinger::PlaybackThread::OpPlayAudioMonitor::getPackagesForUid(
488     uid_t uid, Vector<String16>& packages)
489 {
490     PermissionController permissionController;
491     permissionController.getPackagesForUid(uid, packages);
492 }
493 
494 // ----------------------------------------------------------------------------
495 #undef LOG_TAG
496 #define LOG_TAG "AF::Track"
497 
498 // Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
Track(PlaybackThread * thread,const sp<Client> & client,audio_stream_type_t streamType,const audio_attributes_t & attr,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,void * buffer,size_t bufferSize,const sp<IMemory> & sharedBuffer,audio_session_t sessionId,pid_t creatorPid,uid_t uid,audio_output_flags_t flags,track_type type,audio_port_handle_t portId,size_t frameCountToBeReady)499 AudioFlinger::PlaybackThread::Track::Track(
500             PlaybackThread *thread,
501             const sp<Client>& client,
502             audio_stream_type_t streamType,
503             const audio_attributes_t& attr,
504             uint32_t sampleRate,
505             audio_format_t format,
506             audio_channel_mask_t channelMask,
507             size_t frameCount,
508             void *buffer,
509             size_t bufferSize,
510             const sp<IMemory>& sharedBuffer,
511             audio_session_t sessionId,
512             pid_t creatorPid,
513             uid_t uid,
514             audio_output_flags_t flags,
515             track_type type,
516             audio_port_handle_t portId,
517             size_t frameCountToBeReady)
518     :   TrackBase(thread, client, attr, sampleRate, format, channelMask, frameCount,
519                   (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
520                   (sharedBuffer != 0) ? sharedBuffer->size() : bufferSize,
521                   sessionId, creatorPid, uid, true /*isOut*/,
522                   (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
523                   type, portId),
524     mFillingUpStatus(FS_INVALID),
525     // mRetryCount initialized later when needed
526     mSharedBuffer(sharedBuffer),
527     mStreamType(streamType),
528     mMainBuffer(thread->sinkBuffer()),
529     mAuxBuffer(NULL),
530     mAuxEffectId(0), mHasVolumeController(false),
531     mPresentationCompleteFrames(0),
532     mFrameMap(16 /* sink-frame-to-track-frame map memory */),
533     mVolumeHandler(new media::VolumeHandler(sampleRate)),
534     mOpPlayAudioMonitor(OpPlayAudioMonitor::createIfNeeded(uid, attr, id(), streamType)),
535     // mSinkTimestamp
536     mFrameCountToBeReady(frameCountToBeReady),
537     mFastIndex(-1),
538     mCachedVolume(1.0),
539     /* The track might not play immediately after being active, similarly as if its volume was 0.
540      * When the track starts playing, its volume will be computed. */
541     mFinalVolume(0.f),
542     mResumeToStopping(false),
543     mFlushHwPending(false),
544     mFlags(flags)
545 {
546     // client == 0 implies sharedBuffer == 0
547     ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
548 
549     ALOGV_IF(sharedBuffer != 0, "%s(%d): sharedBuffer: %p, size: %zu",
550             __func__, mId, sharedBuffer->pointer(), sharedBuffer->size());
551 
552     if (mCblk == NULL) {
553         return;
554     }
555 
556     if (sharedBuffer == 0) {
557         mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
558                 mFrameSize, !isExternalTrack(), sampleRate);
559     } else {
560         mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
561                 mFrameSize);
562     }
563     mServerProxy = mAudioTrackServerProxy;
564 
565     if (!thread->isTrackAllowed_l(channelMask, format, sessionId, uid)) {
566         ALOGE("%s(%d): no more tracks available", __func__, mId);
567         return;
568     }
569     // only allocate a fast track index if we were able to allocate a normal track name
570     if (flags & AUDIO_OUTPUT_FLAG_FAST) {
571         // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
572         // race with setSyncEvent(). However, if we call it, we cannot properly start
573         // static fast tracks (SoundPool) immediately after stopping.
574         //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
575         ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
576         int i = __builtin_ctz(thread->mFastTrackAvailMask);
577         ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
578         // FIXME This is too eager.  We allocate a fast track index before the
579         //       fast track becomes active.  Since fast tracks are a scarce resource,
580         //       this means we are potentially denying other more important fast tracks from
581         //       being created.  It would be better to allocate the index dynamically.
582         mFastIndex = i;
583         thread->mFastTrackAvailMask &= ~(1 << i);
584     }
585 
586     mServerLatencySupported = thread->type() == ThreadBase::MIXER
587             || thread->type() == ThreadBase::DUPLICATING;
588 #ifdef TEE_SINK
589     mTee.setId(std::string("_") + std::to_string(mThreadIoHandle)
590             + "_" + std::to_string(mId) + "_T");
591 #endif
592 
593     if (channelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
594         mAudioVibrationController = new AudioVibrationController(this);
595         mExternalVibration = new os::ExternalVibration(
596                 mUid, "" /* pkg */, mAttr, mAudioVibrationController);
597     }
598 }
599 
~Track()600 AudioFlinger::PlaybackThread::Track::~Track()
601 {
602     ALOGV("%s(%d)", __func__, mId);
603 
604     // The destructor would clear mSharedBuffer,
605     // but it will not push the decremented reference count,
606     // leaving the client's IMemory dangling indefinitely.
607     // This prevents that leak.
608     if (mSharedBuffer != 0) {
609         mSharedBuffer.clear();
610     }
611 }
612 
initCheck() const613 status_t AudioFlinger::PlaybackThread::Track::initCheck() const
614 {
615     status_t status = TrackBase::initCheck();
616     if (status == NO_ERROR && mCblk == nullptr) {
617         status = NO_MEMORY;
618     }
619     return status;
620 }
621 
destroy()622 void AudioFlinger::PlaybackThread::Track::destroy()
623 {
624     // NOTE: destroyTrack_l() can remove a strong reference to this Track
625     // by removing it from mTracks vector, so there is a risk that this Tracks's
626     // destructor is called. As the destructor needs to lock mLock,
627     // we must acquire a strong reference on this Track before locking mLock
628     // here so that the destructor is called only when exiting this function.
629     // On the other hand, as long as Track::destroy() is only called by
630     // TrackHandle destructor, the TrackHandle still holds a strong ref on
631     // this Track with its member mTrack.
632     sp<Track> keep(this);
633     { // scope for mLock
634         bool wasActive = false;
635         sp<ThreadBase> thread = mThread.promote();
636         if (thread != 0) {
637             Mutex::Autolock _l(thread->mLock);
638             PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
639             wasActive = playbackThread->destroyTrack_l(this);
640         }
641         if (isExternalTrack() && !wasActive) {
642             AudioSystem::releaseOutput(mPortId);
643         }
644     }
645     forEachTeePatchTrack([](auto patchTrack) { patchTrack->destroy(); });
646 }
647 
appendDumpHeader(String8 & result)648 void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
649 {
650     result.appendFormat("Type     Id Active Client Session Port Id S  Flags "
651                         "  Format Chn mask  SRate "
652                         "ST Usg CT "
653                         " G db  L dB  R dB  VS dB "
654                         "  Server FrmCnt  FrmRdy F Underruns  Flushed"
655                         "%s\n",
656                         isServerLatencySupported() ? "   Latency" : "");
657 }
658 
appendDump(String8 & result,bool active)659 void AudioFlinger::PlaybackThread::Track::appendDump(String8& result, bool active)
660 {
661     char trackType;
662     switch (mType) {
663     case TYPE_DEFAULT:
664     case TYPE_OUTPUT:
665         if (isStatic()) {
666             trackType = 'S'; // static
667         } else {
668             trackType = ' '; // normal
669         }
670         break;
671     case TYPE_PATCH:
672         trackType = 'P';
673         break;
674     default:
675         trackType = '?';
676     }
677 
678     if (isFastTrack()) {
679         result.appendFormat("F%d %c %6d", mFastIndex, trackType, mId);
680     } else {
681         result.appendFormat("   %c %6d", trackType, mId);
682     }
683 
684     char nowInUnderrun;
685     switch (mObservedUnderruns.mBitFields.mMostRecent) {
686     case UNDERRUN_FULL:
687         nowInUnderrun = ' ';
688         break;
689     case UNDERRUN_PARTIAL:
690         nowInUnderrun = '<';
691         break;
692     case UNDERRUN_EMPTY:
693         nowInUnderrun = '*';
694         break;
695     default:
696         nowInUnderrun = '?';
697         break;
698     }
699 
700     char fillingStatus;
701     switch (mFillingUpStatus) {
702     case FS_INVALID:
703         fillingStatus = 'I';
704         break;
705     case FS_FILLING:
706         fillingStatus = 'f';
707         break;
708     case FS_FILLED:
709         fillingStatus = 'F';
710         break;
711     case FS_ACTIVE:
712         fillingStatus = 'A';
713         break;
714     default:
715         fillingStatus = '?';
716         break;
717     }
718 
719     // clip framesReadySafe to max representation in dump
720     const size_t framesReadySafe =
721             std::min(mAudioTrackServerProxy->framesReadySafe(), (size_t)99999999);
722 
723     // obtain volumes
724     const gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
725     const std::pair<float /* volume */, bool /* active */> vsVolume =
726             mVolumeHandler->getLastVolume();
727 
728     // Our effective frame count is obtained by ServerProxy::getBufferSizeInFrames()
729     // as it may be reduced by the application.
730     const size_t bufferSizeInFrames = (size_t)mAudioTrackServerProxy->getBufferSizeInFrames();
731     // Check whether the buffer size has been modified by the app.
732     const char modifiedBufferChar = bufferSizeInFrames < mFrameCount
733             ? 'r' /* buffer reduced */: bufferSizeInFrames > mFrameCount
734                     ? 'e' /* error */ : ' ' /* identical */;
735 
736     result.appendFormat("%7s %6u %7u %7u %2s 0x%03X "
737                         "%08X %08X %6u "
738                         "%2u %3x %2x "
739                         "%5.2g %5.2g %5.2g %5.2g%c "
740                         "%08X %6zu%c %6zu %c %9u%c %7u",
741             active ? "yes" : "no",
742             (mClient == 0) ? getpid() : mClient->pid(),
743             mSessionId,
744             mPortId,
745             getTrackStateString(),
746             mCblk->mFlags,
747 
748             mFormat,
749             mChannelMask,
750             sampleRate(),
751 
752             mStreamType,
753             mAttr.usage,
754             mAttr.content_type,
755 
756             20.0 * log10(mFinalVolume),
757             20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
758             20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
759             20.0 * log10(vsVolume.first), // VolumeShaper(s) total volume
760             vsVolume.second ? 'A' : ' ',  // if any VolumeShapers active
761 
762             mCblk->mServer,
763             bufferSizeInFrames,
764             modifiedBufferChar,
765             framesReadySafe,
766             fillingStatus,
767             mAudioTrackServerProxy->getUnderrunFrames(),
768             nowInUnderrun,
769             (unsigned)mAudioTrackServerProxy->framesFlushed() % 10000000
770             );
771 
772     if (isServerLatencySupported()) {
773         double latencyMs;
774         bool fromTrack;
775         if (getTrackLatencyMs(&latencyMs, &fromTrack) == OK) {
776             // Show latency in msec, followed by 't' if from track timestamp (the most accurate)
777             // or 'k' if estimated from kernel because track frames haven't been presented yet.
778             result.appendFormat(" %7.2lf %c", latencyMs, fromTrack ? 't' : 'k');
779         } else {
780             result.appendFormat("%10s", mCblk->mServer != 0 ? "unavail" : "new");
781         }
782     }
783     result.append("\n");
784 }
785 
sampleRate() const786 uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
787     return mAudioTrackServerProxy->getSampleRate();
788 }
789 
790 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer)791 status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
792 {
793     ServerProxy::Buffer buf;
794     size_t desiredFrames = buffer->frameCount;
795     buf.mFrameCount = desiredFrames;
796     status_t status = mServerProxy->obtainBuffer(&buf);
797     buffer->frameCount = buf.mFrameCount;
798     buffer->raw = buf.mRaw;
799     if (buf.mFrameCount == 0 && !isStopping() && !isStopped() && !isPaused()) {
800         ALOGV("%s(%d): underrun,  framesReady(%zu) < framesDesired(%zd), state: %d",
801                 __func__, mId, buf.mFrameCount, desiredFrames, mState);
802         mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
803     } else {
804         mAudioTrackServerProxy->tallyUnderrunFrames(0);
805     }
806     return status;
807 }
808 
releaseBuffer(AudioBufferProvider::Buffer * buffer)809 void AudioFlinger::PlaybackThread::Track::releaseBuffer(AudioBufferProvider::Buffer* buffer)
810 {
811     interceptBuffer(*buffer);
812     TrackBase::releaseBuffer(buffer);
813 }
814 
815 // TODO: compensate for time shift between HW modules.
interceptBuffer(const AudioBufferProvider::Buffer & sourceBuffer)816 void AudioFlinger::PlaybackThread::Track::interceptBuffer(
817         const AudioBufferProvider::Buffer& sourceBuffer) {
818     auto start = std::chrono::steady_clock::now();
819     const size_t frameCount = sourceBuffer.frameCount;
820     if (frameCount == 0) {
821         return;  // No audio to intercept.
822         // Additionally PatchProxyBufferProvider::obtainBuffer (called by PathTrack::getNextBuffer)
823         // does not allow 0 frame size request contrary to getNextBuffer
824     }
825     for (auto& teePatch : mTeePatches) {
826         RecordThread::PatchRecord* patchRecord = teePatch.patchRecord.get();
827         const size_t framesWritten = patchRecord->writeFrames(
828                 sourceBuffer.i8, frameCount, mFrameSize);
829         const size_t framesLeft = frameCount - framesWritten;
830         ALOGW_IF(framesLeft != 0, "%s(%d) PatchRecord %d can not provide big enough "
831                  "buffer %zu/%zu, dropping %zu frames", __func__, mId, patchRecord->mId,
832                  framesWritten, frameCount, framesLeft);
833     }
834     auto spent = ceil<std::chrono::microseconds>(std::chrono::steady_clock::now() - start);
835     using namespace std::chrono_literals;
836     // Average is ~20us per track, this should virtually never be logged (Logging takes >200us)
837     ALOGD_IF(spent > 500us, "%s: took %lldus to intercept %zu tracks", __func__,
838              spent.count(), mTeePatches.size());
839 }
840 
841 // ExtendedAudioBufferProvider interface
842 
843 // framesReady() may return an approximation of the number of frames if called
844 // from a different thread than the one calling Proxy->obtainBuffer() and
845 // Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
846 // AudioTrackServerProxy so be especially careful calling with FastTracks.
framesReady() const847 size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
848     if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
849         // Static tracks return zero frames immediately upon stopping (for FastTracks).
850         // The remainder of the buffer is not drained.
851         return 0;
852     }
853     return mAudioTrackServerProxy->framesReady();
854 }
855 
framesReleased() const856 int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
857 {
858     return mAudioTrackServerProxy->framesReleased();
859 }
860 
onTimestamp(const ExtendedTimestamp & timestamp)861 void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
862 {
863     // This call comes from a FastTrack and should be kept lockless.
864     // The server side frames are already translated to client frames.
865     mAudioTrackServerProxy->setTimestamp(timestamp);
866 
867     // We do not set drained here, as FastTrack timestamp may not go to very last frame.
868 
869     // Compute latency.
870     // TODO: Consider whether the server latency may be passed in by FastMixer
871     // as a constant for all active FastTracks.
872     const double latencyMs = timestamp.getOutputServerLatencyMs(sampleRate());
873     mServerLatencyFromTrack.store(true);
874     mServerLatencyMs.store(latencyMs);
875 }
876 
877 // Don't call for fast tracks; the framesReady() could result in priority inversion
isReady() const878 bool AudioFlinger::PlaybackThread::Track::isReady() const {
879     if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
880         return true;
881     }
882 
883     if (isStopping()) {
884         if (framesReady() > 0) {
885             mFillingUpStatus = FS_FILLED;
886         }
887         return true;
888     }
889 
890     size_t bufferSizeInFrames = mServerProxy->getBufferSizeInFrames();
891     size_t framesToBeReady = std::min(mFrameCountToBeReady, bufferSizeInFrames);
892 
893     if (framesReady() >= framesToBeReady || (mCblk->mFlags & CBLK_FORCEREADY)) {
894         ALOGV("%s(%d): consider track ready with %zu/%zu, target was %zu)",
895               __func__, mId, framesReady(), bufferSizeInFrames, framesToBeReady);
896         mFillingUpStatus = FS_FILLED;
897         android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
898         return true;
899     }
900     return false;
901 }
902 
start(AudioSystem::sync_event_t event __unused,audio_session_t triggerSession __unused)903 status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
904                                                     audio_session_t triggerSession __unused)
905 {
906     status_t status = NO_ERROR;
907     ALOGV("%s(%d): calling pid %d session %d",
908             __func__, mId, IPCThreadState::self()->getCallingPid(), mSessionId);
909 
910     sp<ThreadBase> thread = mThread.promote();
911     if (thread != 0) {
912         if (isOffloaded()) {
913             Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
914             Mutex::Autolock _lth(thread->mLock);
915             sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
916             if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
917                     (ec != 0 && ec->isNonOffloadableEnabled())) {
918                 invalidate();
919                 return PERMISSION_DENIED;
920             }
921         }
922         Mutex::Autolock _lth(thread->mLock);
923         track_state state = mState;
924         // here the track could be either new, or restarted
925         // in both cases "unstop" the track
926 
927         // initial state-stopping. next state-pausing.
928         // What if resume is called ?
929 
930         if (state == PAUSED || state == PAUSING) {
931             if (mResumeToStopping) {
932                 // happened we need to resume to STOPPING_1
933                 mState = TrackBase::STOPPING_1;
934                 ALOGV("%s(%d): PAUSED => STOPPING_1 on thread %d",
935                         __func__, mId, (int)mThreadIoHandle);
936             } else {
937                 mState = TrackBase::RESUMING;
938                 ALOGV("%s(%d): PAUSED => RESUMING on thread %d",
939                         __func__,  mId, (int)mThreadIoHandle);
940             }
941         } else {
942             mState = TrackBase::ACTIVE;
943             ALOGV("%s(%d): ? => ACTIVE on thread %d",
944                     __func__, mId, (int)mThreadIoHandle);
945         }
946 
947         // states to reset position info for non-offloaded/direct tracks
948         if (!isOffloaded() && !isDirect()
949                 && (state == IDLE || state == STOPPED || state == FLUSHED)) {
950             mFrameMap.reset();
951         }
952         PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
953         if (isFastTrack()) {
954             // refresh fast track underruns on start because that field is never cleared
955             // by the fast mixer; furthermore, the same track can be recycled, i.e. start
956             // after stop.
957             mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
958         }
959         status = playbackThread->addTrack_l(this);
960         if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
961             triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
962             //  restore previous state if start was rejected by policy manager
963             if (status == PERMISSION_DENIED) {
964                 mState = state;
965             }
966         }
967 
968         if (status == NO_ERROR || status == ALREADY_EXISTS) {
969             // for streaming tracks, remove the buffer read stop limit.
970             mAudioTrackServerProxy->start();
971         }
972 
973         // track was already in the active list, not a problem
974         if (status == ALREADY_EXISTS) {
975             status = NO_ERROR;
976         } else {
977             // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
978             // It is usually unsafe to access the server proxy from a binder thread.
979             // But in this case we know the mixer thread (whether normal mixer or fast mixer)
980             // isn't looking at this track yet:  we still hold the normal mixer thread lock,
981             // and for fast tracks the track is not yet in the fast mixer thread's active set.
982             // For static tracks, this is used to acknowledge change in position or loop.
983             ServerProxy::Buffer buffer;
984             buffer.mFrameCount = 1;
985             (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
986         }
987     } else {
988         status = BAD_VALUE;
989     }
990     if (status == NO_ERROR) {
991         forEachTeePatchTrack([](auto patchTrack) { patchTrack->start(); });
992     }
993     return status;
994 }
995 
stop()996 void AudioFlinger::PlaybackThread::Track::stop()
997 {
998     ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
999     sp<ThreadBase> thread = mThread.promote();
1000     if (thread != 0) {
1001         Mutex::Autolock _l(thread->mLock);
1002         track_state state = mState;
1003         if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
1004             // If the track is not active (PAUSED and buffers full), flush buffers
1005             PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1006             if (playbackThread->mActiveTracks.indexOf(this) < 0) {
1007                 reset();
1008                 mState = STOPPED;
1009             } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
1010                 mState = STOPPED;
1011             } else {
1012                 // For fast tracks prepareTracks_l() will set state to STOPPING_2
1013                 // presentation is complete
1014                 // For an offloaded track this starts a drain and state will
1015                 // move to STOPPING_2 when drain completes and then STOPPED
1016                 mState = STOPPING_1;
1017                 if (isOffloaded()) {
1018                     mRetryCount = PlaybackThread::kMaxTrackStopRetriesOffload;
1019                 }
1020             }
1021             playbackThread->broadcast_l();
1022             ALOGV("%s(%d): not stopping/stopped => stopping/stopped on thread %d",
1023                     __func__, mId, (int)mThreadIoHandle);
1024         }
1025     }
1026     forEachTeePatchTrack([](auto patchTrack) { patchTrack->stop(); });
1027 }
1028 
pause()1029 void AudioFlinger::PlaybackThread::Track::pause()
1030 {
1031     ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
1032     sp<ThreadBase> thread = mThread.promote();
1033     if (thread != 0) {
1034         Mutex::Autolock _l(thread->mLock);
1035         PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1036         switch (mState) {
1037         case STOPPING_1:
1038         case STOPPING_2:
1039             if (!isOffloaded()) {
1040                 /* nothing to do if track is not offloaded */
1041                 break;
1042             }
1043 
1044             // Offloaded track was draining, we need to carry on draining when resumed
1045             mResumeToStopping = true;
1046             FALLTHROUGH_INTENDED;
1047         case ACTIVE:
1048         case RESUMING:
1049             mState = PAUSING;
1050             ALOGV("%s(%d): ACTIVE/RESUMING => PAUSING on thread %d",
1051                     __func__, mId, (int)mThreadIoHandle);
1052             playbackThread->broadcast_l();
1053             break;
1054 
1055         default:
1056             break;
1057         }
1058     }
1059     // Pausing the TeePatch to avoid a glitch on underrun, at the cost of buffered audio loss.
1060     forEachTeePatchTrack([](auto patchTrack) { patchTrack->pause(); });
1061 }
1062 
flush()1063 void AudioFlinger::PlaybackThread::Track::flush()
1064 {
1065     ALOGV("%s(%d)", __func__, mId);
1066     sp<ThreadBase> thread = mThread.promote();
1067     if (thread != 0) {
1068         Mutex::Autolock _l(thread->mLock);
1069         PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1070 
1071         // Flush the ring buffer now if the track is not active in the PlaybackThread.
1072         // Otherwise the flush would not be done until the track is resumed.
1073         // Requires FastTrack removal be BLOCK_UNTIL_ACKED
1074         if (playbackThread->mActiveTracks.indexOf(this) < 0) {
1075             (void)mServerProxy->flushBufferIfNeeded();
1076         }
1077 
1078         if (isOffloaded()) {
1079             // If offloaded we allow flush during any state except terminated
1080             // and keep the track active to avoid problems if user is seeking
1081             // rapidly and underlying hardware has a significant delay handling
1082             // a pause
1083             if (isTerminated()) {
1084                 return;
1085             }
1086 
1087             ALOGV("%s(%d): offload flush", __func__, mId);
1088             reset();
1089 
1090             if (mState == STOPPING_1 || mState == STOPPING_2) {
1091                 ALOGV("%s(%d): flushed in STOPPING_1 or 2 state, change state to ACTIVE",
1092                         __func__, mId);
1093                 mState = ACTIVE;
1094             }
1095 
1096             mFlushHwPending = true;
1097             mResumeToStopping = false;
1098         } else {
1099             if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
1100                     mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
1101                 return;
1102             }
1103             // No point remaining in PAUSED state after a flush => go to
1104             // FLUSHED state
1105             mState = FLUSHED;
1106             // do not reset the track if it is still in the process of being stopped or paused.
1107             // this will be done by prepareTracks_l() when the track is stopped.
1108             // prepareTracks_l() will see mState == FLUSHED, then
1109             // remove from active track list, reset(), and trigger presentation complete
1110             if (isDirect()) {
1111                 mFlushHwPending = true;
1112             }
1113             if (playbackThread->mActiveTracks.indexOf(this) < 0) {
1114                 reset();
1115             }
1116         }
1117         // Prevent flush being lost if the track is flushed and then resumed
1118         // before mixer thread can run. This is important when offloading
1119         // because the hardware buffer could hold a large amount of audio
1120         playbackThread->broadcast_l();
1121     }
1122     // Flush the Tee to avoid on resume playing old data and glitching on the transition to new data
1123     forEachTeePatchTrack([](auto patchTrack) { patchTrack->flush(); });
1124 }
1125 
1126 // must be called with thread lock held
flushAck()1127 void AudioFlinger::PlaybackThread::Track::flushAck()
1128 {
1129     if (!isOffloaded() && !isDirect())
1130         return;
1131 
1132     // Clear the client ring buffer so that the app can prime the buffer while paused.
1133     // Otherwise it might not get cleared until playback is resumed and obtainBuffer() is called.
1134     mServerProxy->flushBufferIfNeeded();
1135 
1136     mFlushHwPending = false;
1137 }
1138 
reset()1139 void AudioFlinger::PlaybackThread::Track::reset()
1140 {
1141     // Do not reset twice to avoid discarding data written just after a flush and before
1142     // the audioflinger thread detects the track is stopped.
1143     if (!mResetDone) {
1144         // Force underrun condition to avoid false underrun callback until first data is
1145         // written to buffer
1146         android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
1147         mFillingUpStatus = FS_FILLING;
1148         mResetDone = true;
1149         if (mState == FLUSHED) {
1150             mState = IDLE;
1151         }
1152     }
1153 }
1154 
setParameters(const String8 & keyValuePairs)1155 status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
1156 {
1157     sp<ThreadBase> thread = mThread.promote();
1158     if (thread == 0) {
1159         ALOGE("%s(%d): thread is dead", __func__, mId);
1160         return FAILED_TRANSACTION;
1161     } else if ((thread->type() == ThreadBase::DIRECT) ||
1162                     (thread->type() == ThreadBase::OFFLOAD)) {
1163         return thread->setParameters(keyValuePairs);
1164     } else {
1165         return PERMISSION_DENIED;
1166     }
1167 }
1168 
selectPresentation(int presentationId,int programId)1169 status_t AudioFlinger::PlaybackThread::Track::selectPresentation(int presentationId,
1170         int programId) {
1171     sp<ThreadBase> thread = mThread.promote();
1172     if (thread == 0) {
1173         ALOGE("thread is dead");
1174         return FAILED_TRANSACTION;
1175     } else if ((thread->type() == ThreadBase::DIRECT) || (thread->type() == ThreadBase::OFFLOAD)) {
1176         DirectOutputThread *directOutputThread = static_cast<DirectOutputThread*>(thread.get());
1177         return directOutputThread->selectPresentation(presentationId, programId);
1178     }
1179     return INVALID_OPERATION;
1180 }
1181 
applyVolumeShaper(const sp<VolumeShaper::Configuration> & configuration,const sp<VolumeShaper::Operation> & operation)1182 VolumeShaper::Status AudioFlinger::PlaybackThread::Track::applyVolumeShaper(
1183         const sp<VolumeShaper::Configuration>& configuration,
1184         const sp<VolumeShaper::Operation>& operation)
1185 {
1186     sp<VolumeShaper::Configuration> newConfiguration;
1187 
1188     if (isOffloadedOrDirect()) {
1189         const VolumeShaper::Configuration::OptionFlag optionFlag
1190             = configuration->getOptionFlags();
1191         if ((optionFlag & VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME) == 0) {
1192             ALOGW("%s(%d): %s tracks do not support frame counted VolumeShaper,"
1193                     " using clock time instead",
1194                     __func__, mId,
1195                     isOffloaded() ? "Offload" : "Direct");
1196             newConfiguration = new VolumeShaper::Configuration(*configuration);
1197             newConfiguration->setOptionFlags(
1198                 VolumeShaper::Configuration::OptionFlag(optionFlag
1199                         | VolumeShaper::Configuration::OPTION_FLAG_CLOCK_TIME));
1200         }
1201     }
1202 
1203     VolumeShaper::Status status = mVolumeHandler->applyVolumeShaper(
1204             (newConfiguration.get() != nullptr ? newConfiguration : configuration), operation);
1205 
1206     if (isOffloadedOrDirect()) {
1207         // Signal thread to fetch new volume.
1208         sp<ThreadBase> thread = mThread.promote();
1209         if (thread != 0) {
1210             Mutex::Autolock _l(thread->mLock);
1211             thread->broadcast_l();
1212         }
1213     }
1214     return status;
1215 }
1216 
getVolumeShaperState(int id)1217 sp<VolumeShaper::State> AudioFlinger::PlaybackThread::Track::getVolumeShaperState(int id)
1218 {
1219     // Note: We don't check if Thread exists.
1220 
1221     // mVolumeHandler is thread safe.
1222     return mVolumeHandler->getVolumeShaperState(id);
1223 }
1224 
setFinalVolume(float volume)1225 void AudioFlinger::PlaybackThread::Track::setFinalVolume(float volume)
1226 {
1227     if (mFinalVolume != volume) { // Compare to an epsilon if too many meaningless updates
1228         mFinalVolume = volume;
1229         setMetadataHasChanged();
1230     }
1231 }
1232 
copyMetadataTo(MetadataInserter & backInserter) const1233 void AudioFlinger::PlaybackThread::Track::copyMetadataTo(MetadataInserter& backInserter) const
1234 {
1235     *backInserter++ = {
1236             .usage = mAttr.usage,
1237             .content_type = mAttr.content_type,
1238             .gain = mFinalVolume,
1239     };
1240 }
1241 
setTeePatches(TeePatches teePatches)1242 void AudioFlinger::PlaybackThread::Track::setTeePatches(TeePatches teePatches) {
1243     forEachTeePatchTrack([](auto patchTrack) { patchTrack->destroy(); });
1244     mTeePatches = std::move(teePatches);
1245 }
1246 
getTimestamp(AudioTimestamp & timestamp)1247 status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
1248 {
1249     if (!isOffloaded() && !isDirect()) {
1250         return INVALID_OPERATION; // normal tracks handled through SSQ
1251     }
1252     sp<ThreadBase> thread = mThread.promote();
1253     if (thread == 0) {
1254         return INVALID_OPERATION;
1255     }
1256 
1257     Mutex::Autolock _l(thread->mLock);
1258     PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1259     return playbackThread->getTimestamp_l(timestamp);
1260 }
1261 
attachAuxEffect(int EffectId)1262 status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
1263 {
1264     sp<ThreadBase> thread = mThread.promote();
1265     if (thread == nullptr) {
1266         return DEAD_OBJECT;
1267     }
1268 
1269     sp<PlaybackThread> dstThread = (PlaybackThread *)thread.get();
1270     sp<PlaybackThread> srcThread; // srcThread is initialized by call to moveAuxEffectToIo()
1271     sp<AudioFlinger> af = mClient->audioFlinger();
1272     status_t status = af->moveAuxEffectToIo(EffectId, dstThread, &srcThread);
1273 
1274     if (EffectId != 0 && status == NO_ERROR) {
1275         status = dstThread->attachAuxEffect(this, EffectId);
1276         if (status == NO_ERROR) {
1277             AudioSystem::moveEffectsToIo(std::vector<int>(EffectId), dstThread->id());
1278         }
1279     }
1280 
1281     if (status != NO_ERROR && srcThread != nullptr) {
1282         af->moveAuxEffectToIo(EffectId, srcThread, &dstThread);
1283     }
1284     return status;
1285 }
1286 
setAuxBuffer(int EffectId,int32_t * buffer)1287 void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
1288 {
1289     mAuxEffectId = EffectId;
1290     mAuxBuffer = buffer;
1291 }
1292 
presentationComplete(int64_t framesWritten,size_t audioHalFrames)1293 bool AudioFlinger::PlaybackThread::Track::presentationComplete(
1294         int64_t framesWritten, size_t audioHalFrames)
1295 {
1296     // TODO: improve this based on FrameMap if it exists, to ensure full drain.
1297     // This assists in proper timestamp computation as well as wakelock management.
1298 
1299     // a track is considered presented when the total number of frames written to audio HAL
1300     // corresponds to the number of frames written when presentationComplete() is called for the
1301     // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
1302     // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
1303     // to detect when all frames have been played. In this case framesWritten isn't
1304     // useful because it doesn't always reflect whether there is data in the h/w
1305     // buffers, particularly if a track has been paused and resumed during draining
1306     ALOGV("%s(%d): presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
1307             __func__, mId,
1308             (long long)mPresentationCompleteFrames, (long long)framesWritten);
1309     if (mPresentationCompleteFrames == 0) {
1310         mPresentationCompleteFrames = framesWritten + audioHalFrames;
1311         ALOGV("%s(%d): presentationComplete() reset:"
1312                 " mPresentationCompleteFrames %lld audioHalFrames %zu",
1313                 __func__, mId,
1314                 (long long)mPresentationCompleteFrames, audioHalFrames);
1315     }
1316 
1317     bool complete;
1318     if (isOffloaded()) {
1319         complete = true;
1320     } else if (isDirect() || isFastTrack()) { // these do not go through linear map
1321         complete = framesWritten >= (int64_t) mPresentationCompleteFrames;
1322     } else {  // Normal tracks, OutputTracks, and PatchTracks
1323         complete = framesWritten >= (int64_t) mPresentationCompleteFrames
1324                 && mAudioTrackServerProxy->isDrained();
1325     }
1326 
1327     if (complete) {
1328         triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1329         mAudioTrackServerProxy->setStreamEndDone();
1330         return true;
1331     }
1332     return false;
1333 }
1334 
triggerEvents(AudioSystem::sync_event_t type)1335 void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
1336 {
1337     for (size_t i = 0; i < mSyncEvents.size();) {
1338         if (mSyncEvents[i]->type() == type) {
1339             mSyncEvents[i]->trigger();
1340             mSyncEvents.removeAt(i);
1341         } else {
1342             ++i;
1343         }
1344     }
1345 }
1346 
1347 // implement VolumeBufferProvider interface
1348 
getVolumeLR()1349 gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
1350 {
1351     // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
1352     ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
1353     gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
1354     float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
1355     float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
1356     // track volumes come from shared memory, so can't be trusted and must be clamped
1357     if (vl > GAIN_FLOAT_UNITY) {
1358         vl = GAIN_FLOAT_UNITY;
1359     }
1360     if (vr > GAIN_FLOAT_UNITY) {
1361         vr = GAIN_FLOAT_UNITY;
1362     }
1363     // now apply the cached master volume and stream type volume;
1364     // this is trusted but lacks any synchronization or barrier so may be stale
1365     float v = mCachedVolume;
1366     vl *= v;
1367     vr *= v;
1368     // re-combine into packed minifloat
1369     vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
1370     // FIXME look at mute, pause, and stop flags
1371     return vlr;
1372 }
1373 
setSyncEvent(const sp<SyncEvent> & event)1374 status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1375 {
1376     if (isTerminated() || mState == PAUSED ||
1377             ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1378                                       (mState == STOPPED)))) {
1379         ALOGW("%s(%d): in invalid state %d on session %d %s mode, framesReady %zu",
1380               __func__, mId,
1381               mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1382         event->cancel();
1383         return INVALID_OPERATION;
1384     }
1385     (void) TrackBase::setSyncEvent(event);
1386     return NO_ERROR;
1387 }
1388 
invalidate()1389 void AudioFlinger::PlaybackThread::Track::invalidate()
1390 {
1391     TrackBase::invalidate();
1392     signalClientFlag(CBLK_INVALID);
1393 }
1394 
disable()1395 void AudioFlinger::PlaybackThread::Track::disable()
1396 {
1397     // TODO(b/142394888): the filling status should also be reset to filling
1398     signalClientFlag(CBLK_DISABLED);
1399 }
1400 
signalClientFlag(int32_t flag)1401 void AudioFlinger::PlaybackThread::Track::signalClientFlag(int32_t flag)
1402 {
1403     // FIXME should use proxy, and needs work
1404     audio_track_cblk_t* cblk = mCblk;
1405     android_atomic_or(flag, &cblk->mFlags);
1406     android_atomic_release_store(0x40000000, &cblk->mFutex);
1407     // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1408     (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
1409 }
1410 
signal()1411 void AudioFlinger::PlaybackThread::Track::signal()
1412 {
1413     sp<ThreadBase> thread = mThread.promote();
1414     if (thread != 0) {
1415         PlaybackThread *t = (PlaybackThread *)thread.get();
1416         Mutex::Autolock _l(t->mLock);
1417         t->broadcast_l();
1418     }
1419 }
1420 
1421 //To be called with thread lock held
isResumePending()1422 bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1423 
1424     if (mState == RESUMING)
1425         return true;
1426     /* Resume is pending if track was stopping before pause was called */
1427     if (mState == STOPPING_1 &&
1428         mResumeToStopping)
1429         return true;
1430 
1431     return false;
1432 }
1433 
1434 //To be called with thread lock held
resumeAck()1435 void AudioFlinger::PlaybackThread::Track::resumeAck() {
1436 
1437 
1438     if (mState == RESUMING)
1439         mState = ACTIVE;
1440 
1441     // Other possibility of  pending resume is stopping_1 state
1442     // Do not update the state from stopping as this prevents
1443     // drain being called.
1444     if (mState == STOPPING_1) {
1445         mResumeToStopping = false;
1446     }
1447 }
1448 
1449 //To be called with thread lock held
updateTrackFrameInfo(int64_t trackFramesReleased,int64_t sinkFramesWritten,uint32_t halSampleRate,const ExtendedTimestamp & timeStamp)1450 void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
1451         int64_t trackFramesReleased, int64_t sinkFramesWritten,
1452         uint32_t halSampleRate, const ExtendedTimestamp &timeStamp) {
1453    // Make the kernel frametime available.
1454     const FrameTime ft{
1455             timeStamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
1456             timeStamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]};
1457     // ALOGD("FrameTime: %lld %lld", (long long)ft.frames, (long long)ft.timeNs);
1458     mKernelFrameTime.store(ft);
1459     if (!audio_is_linear_pcm(mFormat)) {
1460         return;
1461     }
1462 
1463     //update frame map
1464     mFrameMap.push(trackFramesReleased, sinkFramesWritten);
1465 
1466     // adjust server times and set drained state.
1467     //
1468     // Our timestamps are only updated when the track is on the Thread active list.
1469     // We need to ensure that tracks are not removed before full drain.
1470     ExtendedTimestamp local = timeStamp;
1471     bool drained = true; // default assume drained, if no server info found
1472     bool checked = false;
1473     for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1474             i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1475         // Lookup the track frame corresponding to the sink frame position.
1476         if (local.mTimeNs[i] > 0) {
1477             local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1478             // check drain state from the latest stage in the pipeline.
1479             if (!checked && i <= ExtendedTimestamp::LOCATION_KERNEL) {
1480                 drained = local.mPosition[i] >= mAudioTrackServerProxy->framesReleased();
1481                 checked = true;
1482             }
1483         }
1484     }
1485 
1486     mAudioTrackServerProxy->setDrained(drained);
1487     // Set correction for flushed frames that are not accounted for in released.
1488     local.mFlushed = mAudioTrackServerProxy->framesFlushed();
1489     mServerProxy->setTimestamp(local);
1490 
1491     // Compute latency info.
1492     const bool useTrackTimestamp = !drained;
1493     const double latencyMs = useTrackTimestamp
1494             ? local.getOutputServerLatencyMs(sampleRate())
1495             : timeStamp.getOutputServerLatencyMs(halSampleRate);
1496 
1497     mServerLatencyFromTrack.store(useTrackTimestamp);
1498     mServerLatencyMs.store(latencyMs);
1499 }
1500 
mute(bool * ret)1501 binder::Status AudioFlinger::PlaybackThread::Track::AudioVibrationController::mute(
1502         /*out*/ bool *ret) {
1503     *ret = false;
1504     sp<ThreadBase> thread = mTrack->mThread.promote();
1505     if (thread != 0) {
1506         // Lock for updating mHapticPlaybackEnabled.
1507         Mutex::Autolock _l(thread->mLock);
1508         PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1509         if ((mTrack->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
1510                 && playbackThread->mHapticChannelCount > 0) {
1511             mTrack->setHapticPlaybackEnabled(false);
1512             *ret = true;
1513         }
1514     }
1515     return binder::Status::ok();
1516 }
1517 
unmute(bool * ret)1518 binder::Status AudioFlinger::PlaybackThread::Track::AudioVibrationController::unmute(
1519         /*out*/ bool *ret) {
1520     *ret = false;
1521     sp<ThreadBase> thread = mTrack->mThread.promote();
1522     if (thread != 0) {
1523         // Lock for updating mHapticPlaybackEnabled.
1524         Mutex::Autolock _l(thread->mLock);
1525         PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1526         if ((mTrack->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
1527                 && playbackThread->mHapticChannelCount > 0) {
1528             mTrack->setHapticPlaybackEnabled(true);
1529             *ret = true;
1530         }
1531     }
1532     return binder::Status::ok();
1533 }
1534 
1535 // ----------------------------------------------------------------------------
1536 #undef LOG_TAG
1537 #define LOG_TAG "AF::OutputTrack"
1538 
OutputTrack(PlaybackThread * playbackThread,DuplicatingThread * sourceThread,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,uid_t uid)1539 AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1540             PlaybackThread *playbackThread,
1541             DuplicatingThread *sourceThread,
1542             uint32_t sampleRate,
1543             audio_format_t format,
1544             audio_channel_mask_t channelMask,
1545             size_t frameCount,
1546             uid_t uid)
1547     :   Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1548               audio_attributes_t{} /* currently unused for output track */,
1549               sampleRate, format, channelMask, frameCount,
1550               nullptr /* buffer */, (size_t)0 /* bufferSize */, nullptr /* sharedBuffer */,
1551               AUDIO_SESSION_NONE, getpid(), uid, AUDIO_OUTPUT_FLAG_NONE,
1552               TYPE_OUTPUT),
1553     mActive(false), mSourceThread(sourceThread)
1554 {
1555 
1556     if (mCblk != NULL) {
1557         mOutBuffer.frameCount = 0;
1558         playbackThread->mTracks.add(this);
1559         ALOGV("%s(): mCblk %p, mBuffer %p, "
1560                 "frameCount %zu, mChannelMask 0x%08x",
1561                 __func__, mCblk, mBuffer,
1562                 frameCount, mChannelMask);
1563         // since client and server are in the same process,
1564         // the buffer has the same virtual address on both sides
1565         mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1566                 true /*clientInServer*/);
1567         mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
1568         mClientProxy->setSendLevel(0.0);
1569         mClientProxy->setSampleRate(sampleRate);
1570     } else {
1571         ALOGW("%s(%d): Error creating output track on thread %d",
1572                 __func__, mId, (int)mThreadIoHandle);
1573     }
1574 }
1575 
~OutputTrack()1576 AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1577 {
1578     clearBufferQueue();
1579     // superclass destructor will now delete the server proxy and shared memory both refer to
1580 }
1581 
start(AudioSystem::sync_event_t event,audio_session_t triggerSession)1582 status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1583                                                           audio_session_t triggerSession)
1584 {
1585     status_t status = Track::start(event, triggerSession);
1586     if (status != NO_ERROR) {
1587         return status;
1588     }
1589 
1590     mActive = true;
1591     mRetryCount = 127;
1592     return status;
1593 }
1594 
stop()1595 void AudioFlinger::PlaybackThread::OutputTrack::stop()
1596 {
1597     Track::stop();
1598     clearBufferQueue();
1599     mOutBuffer.frameCount = 0;
1600     mActive = false;
1601 }
1602 
write(void * data,uint32_t frames)1603 ssize_t AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
1604 {
1605     Buffer *pInBuffer;
1606     Buffer inBuffer;
1607     bool outputBufferFull = false;
1608     inBuffer.frameCount = frames;
1609     inBuffer.raw = data;
1610 
1611     uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1612 
1613     if (!mActive && frames != 0) {
1614         (void) start();
1615     }
1616 
1617     while (waitTimeLeftMs) {
1618         // First write pending buffers, then new data
1619         if (mBufferQueue.size()) {
1620             pInBuffer = mBufferQueue.itemAt(0);
1621         } else {
1622             pInBuffer = &inBuffer;
1623         }
1624 
1625         if (pInBuffer->frameCount == 0) {
1626             break;
1627         }
1628 
1629         if (mOutBuffer.frameCount == 0) {
1630             mOutBuffer.frameCount = pInBuffer->frameCount;
1631             nsecs_t startTime = systemTime();
1632             status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1633             if (status != NO_ERROR && status != NOT_ENOUGH_DATA) {
1634                 ALOGV("%s(%d): thread %d no more output buffers; status %d",
1635                         __func__, mId,
1636                         (int)mThreadIoHandle, status);
1637                 outputBufferFull = true;
1638                 break;
1639             }
1640             uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1641             if (waitTimeLeftMs >= waitTimeMs) {
1642                 waitTimeLeftMs -= waitTimeMs;
1643             } else {
1644                 waitTimeLeftMs = 0;
1645             }
1646             if (status == NOT_ENOUGH_DATA) {
1647                 restartIfDisabled();
1648                 continue;
1649             }
1650         }
1651 
1652         uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1653                 pInBuffer->frameCount;
1654         memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
1655         Proxy::Buffer buf;
1656         buf.mFrameCount = outFrames;
1657         buf.mRaw = NULL;
1658         mClientProxy->releaseBuffer(&buf);
1659         restartIfDisabled();
1660         pInBuffer->frameCount -= outFrames;
1661         pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
1662         mOutBuffer.frameCount -= outFrames;
1663         mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
1664 
1665         if (pInBuffer->frameCount == 0) {
1666             if (mBufferQueue.size()) {
1667                 mBufferQueue.removeAt(0);
1668                 free(pInBuffer->mBuffer);
1669                 if (pInBuffer != &inBuffer) {
1670                     delete pInBuffer;
1671                 }
1672                 ALOGV("%s(%d): thread %d released overflow buffer %zu",
1673                         __func__, mId,
1674                         (int)mThreadIoHandle, mBufferQueue.size());
1675             } else {
1676                 break;
1677             }
1678         }
1679     }
1680 
1681     // If we could not write all frames, allocate a buffer and queue it for next time.
1682     if (inBuffer.frameCount) {
1683         sp<ThreadBase> thread = mThread.promote();
1684         if (thread != 0 && !thread->standby()) {
1685             if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1686                 pInBuffer = new Buffer;
1687                 pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
1688                 pInBuffer->frameCount = inBuffer.frameCount;
1689                 pInBuffer->raw = pInBuffer->mBuffer;
1690                 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
1691                 mBufferQueue.add(pInBuffer);
1692                 ALOGV("%s(%d): thread %d adding overflow buffer %zu", __func__, mId,
1693                         (int)mThreadIoHandle, mBufferQueue.size());
1694                 // audio data is consumed (stored locally); set frameCount to 0.
1695                 inBuffer.frameCount = 0;
1696             } else {
1697                 ALOGW("%s(%d): thread %d no more overflow buffers",
1698                         __func__, mId, (int)mThreadIoHandle);
1699                 // TODO: return error for this.
1700             }
1701         }
1702     }
1703 
1704     // Calling write() with a 0 length buffer means that no more data will be written:
1705     // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1706     if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1707         stop();
1708     }
1709 
1710     return frames - inBuffer.frameCount;  // number of frames consumed.
1711 }
1712 
copyMetadataTo(MetadataInserter & backInserter) const1713 void AudioFlinger::PlaybackThread::OutputTrack::copyMetadataTo(MetadataInserter& backInserter) const
1714 {
1715     std::lock_guard<std::mutex> lock(mTrackMetadatasMutex);
1716     backInserter = std::copy(mTrackMetadatas.begin(), mTrackMetadatas.end(), backInserter);
1717 }
1718 
setMetadatas(const SourceMetadatas & metadatas)1719 void AudioFlinger::PlaybackThread::OutputTrack::setMetadatas(const SourceMetadatas& metadatas) {
1720     {
1721         std::lock_guard<std::mutex> lock(mTrackMetadatasMutex);
1722         mTrackMetadatas = metadatas;
1723     }
1724     // No need to adjust metadata track volumes as OutputTrack volumes are always 0dBFS.
1725     setMetadataHasChanged();
1726 }
1727 
obtainBuffer(AudioBufferProvider::Buffer * buffer,uint32_t waitTimeMs)1728 status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1729         AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1730 {
1731     ClientProxy::Buffer buf;
1732     buf.mFrameCount = buffer->frameCount;
1733     struct timespec timeout;
1734     timeout.tv_sec = waitTimeMs / 1000;
1735     timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1736     status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1737     buffer->frameCount = buf.mFrameCount;
1738     buffer->raw = buf.mRaw;
1739     return status;
1740 }
1741 
clearBufferQueue()1742 void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1743 {
1744     size_t size = mBufferQueue.size();
1745 
1746     for (size_t i = 0; i < size; i++) {
1747         Buffer *pBuffer = mBufferQueue.itemAt(i);
1748         free(pBuffer->mBuffer);
1749         delete pBuffer;
1750     }
1751     mBufferQueue.clear();
1752 }
1753 
restartIfDisabled()1754 void AudioFlinger::PlaybackThread::OutputTrack::restartIfDisabled()
1755 {
1756     int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1757     if (mActive && (flags & CBLK_DISABLED)) {
1758         start();
1759     }
1760 }
1761 
1762 // ----------------------------------------------------------------------------
1763 #undef LOG_TAG
1764 #define LOG_TAG "AF::PatchTrack"
1765 
PatchTrack(PlaybackThread * playbackThread,audio_stream_type_t streamType,uint32_t sampleRate,audio_channel_mask_t channelMask,audio_format_t format,size_t frameCount,void * buffer,size_t bufferSize,audio_output_flags_t flags,const Timeout & timeout,size_t frameCountToBeReady)1766 AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
1767                                                      audio_stream_type_t streamType,
1768                                                      uint32_t sampleRate,
1769                                                      audio_channel_mask_t channelMask,
1770                                                      audio_format_t format,
1771                                                      size_t frameCount,
1772                                                      void *buffer,
1773                                                      size_t bufferSize,
1774                                                      audio_output_flags_t flags,
1775                                                      const Timeout& timeout,
1776                                                      size_t frameCountToBeReady)
1777     :   Track(playbackThread, NULL, streamType,
1778               audio_attributes_t{} /* currently unused for patch track */,
1779               sampleRate, format, channelMask, frameCount,
1780               buffer, bufferSize, nullptr /* sharedBuffer */,
1781               AUDIO_SESSION_NONE, getpid(), AID_AUDIOSERVER, flags, TYPE_PATCH,
1782               AUDIO_PORT_HANDLE_NONE, frameCountToBeReady),
1783         PatchTrackBase(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true),
1784                        *playbackThread, timeout)
1785 {
1786     ALOGV("%s(%d): sampleRate %d mPeerTimeout %d.%03d sec",
1787                                       __func__, mId, sampleRate,
1788                                       (int)mPeerTimeout.tv_sec,
1789                                       (int)(mPeerTimeout.tv_nsec / 1000000));
1790 }
1791 
~PatchTrack()1792 AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1793 {
1794     ALOGV("%s(%d)", __func__, mId);
1795 }
1796 
framesReady() const1797 size_t AudioFlinger::PlaybackThread::PatchTrack::framesReady() const
1798 {
1799     if (mPeerProxy && mPeerProxy->producesBufferOnDemand()) {
1800         return std::numeric_limits<size_t>::max();
1801     } else {
1802         return Track::framesReady();
1803     }
1804 }
1805 
start(AudioSystem::sync_event_t event,audio_session_t triggerSession)1806 status_t AudioFlinger::PlaybackThread::PatchTrack::start(AudioSystem::sync_event_t event,
1807                                                          audio_session_t triggerSession)
1808 {
1809     status_t status = Track::start(event, triggerSession);
1810     if (status != NO_ERROR) {
1811         return status;
1812     }
1813     android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
1814     return status;
1815 }
1816 
1817 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer)1818 status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1819         AudioBufferProvider::Buffer* buffer)
1820 {
1821     ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
1822     Proxy::Buffer buf;
1823     buf.mFrameCount = buffer->frameCount;
1824     if (ATRACE_ENABLED()) {
1825         std::string traceName("PTnReq");
1826         traceName += std::to_string(id());
1827         ATRACE_INT(traceName.c_str(), buf.mFrameCount);
1828     }
1829     status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1830     ALOGV_IF(status != NO_ERROR, "%s(%d): getNextBuffer status %d", __func__, mId, status);
1831     buffer->frameCount = buf.mFrameCount;
1832     if (ATRACE_ENABLED()) {
1833         std::string traceName("PTnObt");
1834         traceName += std::to_string(id());
1835         ATRACE_INT(traceName.c_str(), buf.mFrameCount);
1836     }
1837     if (buf.mFrameCount == 0) {
1838         return WOULD_BLOCK;
1839     }
1840     status = Track::getNextBuffer(buffer);
1841     return status;
1842 }
1843 
releaseBuffer(AudioBufferProvider::Buffer * buffer)1844 void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1845 {
1846     ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
1847     Proxy::Buffer buf;
1848     buf.mFrameCount = buffer->frameCount;
1849     buf.mRaw = buffer->raw;
1850     mPeerProxy->releaseBuffer(&buf);
1851     TrackBase::releaseBuffer(buffer);
1852 }
1853 
obtainBuffer(Proxy::Buffer * buffer,const struct timespec * timeOut)1854 status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1855                                                                 const struct timespec *timeOut)
1856 {
1857     status_t status = NO_ERROR;
1858     static const int32_t kMaxTries = 5;
1859     int32_t tryCounter = kMaxTries;
1860     const size_t originalFrameCount = buffer->mFrameCount;
1861     do {
1862         if (status == NOT_ENOUGH_DATA) {
1863             restartIfDisabled();
1864             buffer->mFrameCount = originalFrameCount; // cleared on error, must be restored.
1865         }
1866         status = mProxy->obtainBuffer(buffer, timeOut);
1867     } while ((status == NOT_ENOUGH_DATA) && (tryCounter-- > 0));
1868     return status;
1869 }
1870 
releaseBuffer(Proxy::Buffer * buffer)1871 void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1872 {
1873     mProxy->releaseBuffer(buffer);
1874     restartIfDisabled();
1875 
1876     // Check if the PatchTrack has enough data to write once in releaseBuffer().
1877     // If not, prevent an underrun from occurring by moving the track into FS_FILLING;
1878     // this logic avoids glitches when suspending A2DP with AudioPlaybackCapture.
1879     // TODO: perhaps underrun avoidance could be a track property checked in isReady() instead.
1880     if (mFillingUpStatus == FS_ACTIVE
1881             && audio_is_linear_pcm(mFormat)
1882             && !isOffloadedOrDirect()) {
1883         if (sp<ThreadBase> thread = mThread.promote();
1884             thread != 0) {
1885             PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1886             const size_t frameCount = playbackThread->frameCount() * sampleRate()
1887                     / playbackThread->sampleRate();
1888             if (framesReady() < frameCount) {
1889                 ALOGD("%s(%d) Not enough data, wait for buffer to fill", __func__, mId);
1890                 mFillingUpStatus = FS_FILLING;
1891             }
1892         }
1893     }
1894 }
1895 
restartIfDisabled()1896 void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
1897 {
1898     if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1899         ALOGW("%s(%d): disabled due to previous underrun, restarting", __func__, mId);
1900         start();
1901     }
1902 }
1903 
1904 // ----------------------------------------------------------------------------
1905 //      Record
1906 // ----------------------------------------------------------------------------
1907 
1908 
1909 // ----------------------------------------------------------------------------
1910 //      AppOp for audio recording
1911 // -------------------------------
1912 
1913 #undef LOG_TAG
1914 #define LOG_TAG "AF::OpRecordAudioMonitor"
1915 
1916 // static
1917 sp<AudioFlinger::RecordThread::OpRecordAudioMonitor>
createIfNeeded(uid_t uid,const String16 & opPackageName)1918 AudioFlinger::RecordThread::OpRecordAudioMonitor::createIfNeeded(
1919             uid_t uid, const String16& opPackageName)
1920 {
1921     if (isServiceUid(uid)) {
1922         ALOGV("not silencing record for service uid:%d pack:%s",
1923                 uid, String8(opPackageName).string());
1924         return nullptr;
1925     }
1926 
1927     if (opPackageName.size() == 0) {
1928         Vector<String16> packages;
1929         // no package name, happens with SL ES clients
1930         // query package manager to find one
1931         PermissionController permissionController;
1932         permissionController.getPackagesForUid(uid, packages);
1933         if (packages.isEmpty()) {
1934             return nullptr;
1935         } else {
1936             ALOGV("using pack:%s for uid:%d", String8(packages[0]).string(), uid);
1937             return new OpRecordAudioMonitor(uid, packages[0]);
1938         }
1939     }
1940 
1941     return new OpRecordAudioMonitor(uid, opPackageName);
1942 }
1943 
OpRecordAudioMonitor(uid_t uid,const String16 & opPackageName)1944 AudioFlinger::RecordThread::OpRecordAudioMonitor::OpRecordAudioMonitor(
1945         uid_t uid, const String16& opPackageName)
1946         : mHasOpRecordAudio(true), mUid(uid), mPackage(opPackageName)
1947 {
1948 }
1949 
~OpRecordAudioMonitor()1950 AudioFlinger::RecordThread::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1951 {
1952     if (mOpCallback != 0) {
1953         mAppOpsManager.stopWatchingMode(mOpCallback);
1954     }
1955     mOpCallback.clear();
1956 }
1957 
onFirstRef()1958 void AudioFlinger::RecordThread::OpRecordAudioMonitor::onFirstRef()
1959 {
1960     checkRecordAudio();
1961     mOpCallback = new RecordAudioOpCallback(this);
1962     ALOGV("start watching OP_RECORD_AUDIO for pack:%s", String8(mPackage).string());
1963     mAppOpsManager.startWatchingMode(AppOpsManager::OP_RECORD_AUDIO, mPackage, mOpCallback);
1964 }
1965 
hasOpRecordAudio() const1966 bool AudioFlinger::RecordThread::OpRecordAudioMonitor::hasOpRecordAudio() const {
1967     return mHasOpRecordAudio.load();
1968 }
1969 
1970 // Called by RecordAudioOpCallback when OP_RECORD_AUDIO is updated in AppOp callback
1971 // and in onFirstRef()
1972 // Note this method is never called (and never to be) for audio server / root track
1973 // due to the UID in createIfNeeded(). As a result for those record track, it's:
1974 // - not called from constructor,
1975 // - not called from RecordAudioOpCallback because the callback is not installed in this case
checkRecordAudio()1976 void AudioFlinger::RecordThread::OpRecordAudioMonitor::checkRecordAudio()
1977 {
1978     const int32_t mode = mAppOpsManager.checkOp(AppOpsManager::OP_RECORD_AUDIO,
1979             mUid, mPackage);
1980     const bool hasIt =  (mode == AppOpsManager::MODE_ALLOWED);
1981     // verbose logging only log when appOp changed
1982     ALOGI_IF(hasIt != mHasOpRecordAudio.load(),
1983             "OP_RECORD_AUDIO missing, %ssilencing record uid%d pack:%s",
1984             hasIt ? "un" : "", mUid, String8(mPackage).string());
1985     mHasOpRecordAudio.store(hasIt);
1986 }
1987 
RecordAudioOpCallback(const wp<OpRecordAudioMonitor> & monitor)1988 AudioFlinger::RecordThread::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1989         const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1990 { }
1991 
opChanged(int32_t op,const String16 & packageName)1992 void AudioFlinger::RecordThread::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
1993             const String16& packageName) {
1994     UNUSED(packageName);
1995     if (op != AppOpsManager::OP_RECORD_AUDIO) {
1996         return;
1997     }
1998     sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
1999     if (monitor != NULL) {
2000         monitor->checkRecordAudio();
2001     }
2002 }
2003 
2004 
2005 
2006 #undef LOG_TAG
2007 #define LOG_TAG "AF::RecordHandle"
2008 
RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack> & recordTrack)2009 AudioFlinger::RecordHandle::RecordHandle(
2010         const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
2011     : BnAudioRecord(),
2012     mRecordTrack(recordTrack)
2013 {
2014 }
2015 
~RecordHandle()2016 AudioFlinger::RecordHandle::~RecordHandle() {
2017     stop_nonvirtual();
2018     mRecordTrack->destroy();
2019 }
2020 
start(int event,int triggerSession)2021 binder::Status AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
2022         int /*audio_session_t*/ triggerSession) {
2023     ALOGV("%s()", __func__);
2024     return binder::Status::fromStatusT(
2025         mRecordTrack->start((AudioSystem::sync_event_t)event, (audio_session_t) triggerSession));
2026 }
2027 
stop()2028 binder::Status AudioFlinger::RecordHandle::stop() {
2029     stop_nonvirtual();
2030     return binder::Status::ok();
2031 }
2032 
stop_nonvirtual()2033 void AudioFlinger::RecordHandle::stop_nonvirtual() {
2034     ALOGV("%s()", __func__);
2035     mRecordTrack->stop();
2036 }
2037 
getActiveMicrophones(std::vector<media::MicrophoneInfo> * activeMicrophones)2038 binder::Status AudioFlinger::RecordHandle::getActiveMicrophones(
2039         std::vector<media::MicrophoneInfo>* activeMicrophones) {
2040     ALOGV("%s()", __func__);
2041     return binder::Status::fromStatusT(
2042             mRecordTrack->getActiveMicrophones(activeMicrophones));
2043 }
2044 
setPreferredMicrophoneDirection(int direction)2045 binder::Status AudioFlinger::RecordHandle::setPreferredMicrophoneDirection(
2046         int /*audio_microphone_direction_t*/ direction) {
2047     ALOGV("%s()", __func__);
2048     return binder::Status::fromStatusT(mRecordTrack->setPreferredMicrophoneDirection(
2049             static_cast<audio_microphone_direction_t>(direction)));
2050 }
2051 
setPreferredMicrophoneFieldDimension(float zoom)2052 binder::Status AudioFlinger::RecordHandle::setPreferredMicrophoneFieldDimension(float zoom) {
2053     ALOGV("%s()", __func__);
2054     return binder::Status::fromStatusT(mRecordTrack->setPreferredMicrophoneFieldDimension(zoom));
2055 }
2056 
2057 // ----------------------------------------------------------------------------
2058 #undef LOG_TAG
2059 #define LOG_TAG "AF::RecordTrack"
2060 
2061 // RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
RecordTrack(RecordThread * thread,const sp<Client> & client,const audio_attributes_t & attr,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t frameCount,void * buffer,size_t bufferSize,audio_session_t sessionId,pid_t creatorPid,uid_t uid,audio_input_flags_t flags,track_type type,const String16 & opPackageName,audio_port_handle_t portId)2062 AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2063             RecordThread *thread,
2064             const sp<Client>& client,
2065             const audio_attributes_t& attr,
2066             uint32_t sampleRate,
2067             audio_format_t format,
2068             audio_channel_mask_t channelMask,
2069             size_t frameCount,
2070             void *buffer,
2071             size_t bufferSize,
2072             audio_session_t sessionId,
2073             pid_t creatorPid,
2074             uid_t uid,
2075             audio_input_flags_t flags,
2076             track_type type,
2077             const String16& opPackageName,
2078             audio_port_handle_t portId)
2079     :   TrackBase(thread, client, attr, sampleRate, format,
2080                   channelMask, frameCount, buffer, bufferSize, sessionId,
2081                   creatorPid, uid, false /*isOut*/,
2082                   (type == TYPE_DEFAULT) ?
2083                           ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
2084                           ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
2085                   type, portId),
2086         mOverflow(false),
2087         mFramesToDrop(0),
2088         mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
2089         mRecordBufferConverter(NULL),
2090         mFlags(flags),
2091         mSilenced(false),
2092         mOpRecordAudioMonitor(OpRecordAudioMonitor::createIfNeeded(uid, opPackageName))
2093 {
2094     if (mCblk == NULL) {
2095         return;
2096     }
2097 
2098     if (!isDirect()) {
2099         mRecordBufferConverter = new RecordBufferConverter(
2100                 thread->mChannelMask, thread->mFormat, thread->mSampleRate,
2101                 channelMask, format, sampleRate);
2102         // Check if the RecordBufferConverter construction was successful.
2103         // If not, don't continue with construction.
2104         //
2105         // NOTE: It would be extremely rare that the record track cannot be created
2106         // for the current device, but a pending or future device change would make
2107         // the record track configuration valid.
2108         if (mRecordBufferConverter->initCheck() != NO_ERROR) {
2109             ALOGE("%s(%d): RecordTrack unable to create record buffer converter", __func__, mId);
2110             return;
2111         }
2112     }
2113 
2114     mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
2115             mFrameSize, !isExternalTrack());
2116 
2117     mResamplerBufferProvider = new ResamplerBufferProvider(this);
2118 
2119     if (flags & AUDIO_INPUT_FLAG_FAST) {
2120         ALOG_ASSERT(thread->mFastTrackAvail);
2121         thread->mFastTrackAvail = false;
2122     } else {
2123         // TODO: only Normal Record has timestamps (Fast Record does not).
2124         mServerLatencySupported = checkServerLatencySupported(mFormat, flags);
2125     }
2126 #ifdef TEE_SINK
2127     mTee.setId(std::string("_") + std::to_string(mThreadIoHandle)
2128             + "_" + std::to_string(mId)
2129             + "_R");
2130 #endif
2131 }
2132 
~RecordTrack()2133 AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
2134 {
2135     ALOGV("%s()", __func__);
2136     delete mRecordBufferConverter;
2137     delete mResamplerBufferProvider;
2138 }
2139 
initCheck() const2140 status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
2141 {
2142     status_t status = TrackBase::initCheck();
2143     if (status == NO_ERROR && mServerProxy == 0) {
2144         status = BAD_VALUE;
2145     }
2146     return status;
2147 }
2148 
2149 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer)2150 status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
2151 {
2152     ServerProxy::Buffer buf;
2153     buf.mFrameCount = buffer->frameCount;
2154     status_t status = mServerProxy->obtainBuffer(&buf);
2155     buffer->frameCount = buf.mFrameCount;
2156     buffer->raw = buf.mRaw;
2157     if (buf.mFrameCount == 0) {
2158         // FIXME also wake futex so that overrun is noticed more quickly
2159         (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
2160     }
2161     return status;
2162 }
2163 
start(AudioSystem::sync_event_t event,audio_session_t triggerSession)2164 status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
2165                                                         audio_session_t triggerSession)
2166 {
2167     sp<ThreadBase> thread = mThread.promote();
2168     if (thread != 0) {
2169         RecordThread *recordThread = (RecordThread *)thread.get();
2170         return recordThread->start(this, event, triggerSession);
2171     } else {
2172         return BAD_VALUE;
2173     }
2174 }
2175 
stop()2176 void AudioFlinger::RecordThread::RecordTrack::stop()
2177 {
2178     sp<ThreadBase> thread = mThread.promote();
2179     if (thread != 0) {
2180         RecordThread *recordThread = (RecordThread *)thread.get();
2181         if (recordThread->stop(this) && isExternalTrack()) {
2182             AudioSystem::stopInput(mPortId);
2183         }
2184     }
2185 }
2186 
destroy()2187 void AudioFlinger::RecordThread::RecordTrack::destroy()
2188 {
2189     // see comments at AudioFlinger::PlaybackThread::Track::destroy()
2190     sp<RecordTrack> keep(this);
2191     {
2192         track_state priorState = mState;
2193         sp<ThreadBase> thread = mThread.promote();
2194         if (thread != 0) {
2195             Mutex::Autolock _l(thread->mLock);
2196             RecordThread *recordThread = (RecordThread *) thread.get();
2197             priorState = mState;
2198             recordThread->destroyTrack_l(this); // move mState to STOPPED, terminate
2199         }
2200         // APM portid/client management done outside of lock.
2201         // NOTE: if thread doesn't exist, the input descriptor probably doesn't either.
2202         if (isExternalTrack()) {
2203             switch (priorState) {
2204             case ACTIVE:     // invalidated while still active
2205             case STARTING_2: // invalidated/start-aborted after startInput successfully called
2206             case PAUSING:    // invalidated while in the middle of stop() pausing (still active)
2207                 AudioSystem::stopInput(mPortId);
2208                 break;
2209 
2210             case STARTING_1: // invalidated/start-aborted and startInput not successful
2211             case PAUSED:     // OK, not active
2212             case IDLE:       // OK, not active
2213                 break;
2214 
2215             case STOPPED:    // unexpected (destroyed)
2216             default:
2217                 LOG_ALWAYS_FATAL("%s(%d): invalid prior state: %d", __func__, mId, priorState);
2218             }
2219             AudioSystem::releaseInput(mPortId);
2220         }
2221     }
2222 }
2223 
invalidate()2224 void AudioFlinger::RecordThread::RecordTrack::invalidate()
2225 {
2226     TrackBase::invalidate();
2227     // FIXME should use proxy, and needs work
2228     audio_track_cblk_t* cblk = mCblk;
2229     android_atomic_or(CBLK_INVALID, &cblk->mFlags);
2230     android_atomic_release_store(0x40000000, &cblk->mFutex);
2231     // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
2232     (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
2233 }
2234 
2235 
appendDumpHeader(String8 & result)2236 void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
2237 {
2238     result.appendFormat("Active     Id Client Session Port Id  S  Flags  "
2239                         " Format Chn mask  SRate Source  "
2240                         " Server FrmCnt FrmRdy Sil%s\n",
2241                         isServerLatencySupported() ? "   Latency" : "");
2242 }
2243 
appendDump(String8 & result,bool active)2244 void AudioFlinger::RecordThread::RecordTrack::appendDump(String8& result, bool active)
2245 {
2246     result.appendFormat("%c%5s %6d %6u %7u %7u  %2s 0x%03X "
2247             "%08X %08X %6u %6X "
2248             "%08X %6zu %6zu %3c",
2249             isFastTrack() ? 'F' : ' ',
2250             active ? "yes" : "no",
2251             mId,
2252             (mClient == 0) ? getpid() : mClient->pid(),
2253             mSessionId,
2254             mPortId,
2255             getTrackStateString(),
2256             mCblk->mFlags,
2257 
2258             mFormat,
2259             mChannelMask,
2260             mSampleRate,
2261             mAttr.source,
2262 
2263             mCblk->mServer,
2264             mFrameCount,
2265             mServerProxy->framesReadySafe(),
2266             isSilenced() ? 's' : 'n'
2267             );
2268     if (isServerLatencySupported()) {
2269         double latencyMs;
2270         bool fromTrack;
2271         if (getTrackLatencyMs(&latencyMs, &fromTrack) == OK) {
2272             // Show latency in msec, followed by 't' if from track timestamp (the most accurate)
2273             // or 'k' if estimated from kernel (usually for debugging).
2274             result.appendFormat(" %7.2lf %c", latencyMs, fromTrack ? 't' : 'k');
2275         } else {
2276             result.appendFormat("%10s", mCblk->mServer != 0 ? "unavail" : "new");
2277         }
2278     }
2279     result.append("\n");
2280 }
2281 
handleSyncStartEvent(const sp<SyncEvent> & event)2282 void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
2283 {
2284     if (event == mSyncStartEvent) {
2285         ssize_t framesToDrop = 0;
2286         sp<ThreadBase> threadBase = mThread.promote();
2287         if (threadBase != 0) {
2288             // TODO: use actual buffer filling status instead of 2 buffers when info is available
2289             // from audio HAL
2290             framesToDrop = threadBase->mFrameCount * 2;
2291         }
2292         mFramesToDrop = framesToDrop;
2293     }
2294 }
2295 
clearSyncStartEvent()2296 void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
2297 {
2298     if (mSyncStartEvent != 0) {
2299         mSyncStartEvent->cancel();
2300         mSyncStartEvent.clear();
2301     }
2302     mFramesToDrop = 0;
2303 }
2304 
updateTrackFrameInfo(int64_t trackFramesReleased,int64_t sourceFramesRead,uint32_t halSampleRate,const ExtendedTimestamp & timestamp)2305 void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
2306         int64_t trackFramesReleased, int64_t sourceFramesRead,
2307         uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
2308 {
2309    // Make the kernel frametime available.
2310     const FrameTime ft{
2311             timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
2312             timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]};
2313     // ALOGD("FrameTime: %lld %lld", (long long)ft.frames, (long long)ft.timeNs);
2314     mKernelFrameTime.store(ft);
2315     if (!audio_is_linear_pcm(mFormat)) {
2316         return;
2317     }
2318 
2319     ExtendedTimestamp local = timestamp;
2320 
2321     // Convert HAL frames to server-side track frames at track sample rate.
2322     // We use trackFramesReleased and sourceFramesRead as an anchor point.
2323     for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
2324         if (local.mTimeNs[i] != 0) {
2325             const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
2326             const int64_t relativeTrackFrames = relativeServerFrames
2327                     * mSampleRate / halSampleRate; // TODO: potential computation overflow
2328             local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
2329         }
2330     }
2331     mServerProxy->setTimestamp(local);
2332 
2333     // Compute latency info.
2334     const bool useTrackTimestamp = true; // use track unless debugging.
2335     const double latencyMs = - (useTrackTimestamp
2336             ? local.getOutputServerLatencyMs(sampleRate())
2337             : timestamp.getOutputServerLatencyMs(halSampleRate));
2338 
2339     mServerLatencyFromTrack.store(useTrackTimestamp);
2340     mServerLatencyMs.store(latencyMs);
2341 }
2342 
isSilenced() const2343 bool AudioFlinger::RecordThread::RecordTrack::isSilenced() const {
2344     if (mSilenced) {
2345         return true;
2346     }
2347     // The monitor is only created for record tracks that can be silenced.
2348     return mOpRecordAudioMonitor ? !mOpRecordAudioMonitor->hasOpRecordAudio() : false;
2349 }
2350 
getActiveMicrophones(std::vector<media::MicrophoneInfo> * activeMicrophones)2351 status_t AudioFlinger::RecordThread::RecordTrack::getActiveMicrophones(
2352         std::vector<media::MicrophoneInfo>* activeMicrophones)
2353 {
2354     sp<ThreadBase> thread = mThread.promote();
2355     if (thread != 0) {
2356         RecordThread *recordThread = (RecordThread *)thread.get();
2357         return recordThread->getActiveMicrophones(activeMicrophones);
2358     } else {
2359         return BAD_VALUE;
2360     }
2361 }
2362 
setPreferredMicrophoneDirection(audio_microphone_direction_t direction)2363 status_t AudioFlinger::RecordThread::RecordTrack::setPreferredMicrophoneDirection(
2364         audio_microphone_direction_t direction) {
2365     sp<ThreadBase> thread = mThread.promote();
2366     if (thread != 0) {
2367         RecordThread *recordThread = (RecordThread *)thread.get();
2368         return recordThread->setPreferredMicrophoneDirection(direction);
2369     } else {
2370         return BAD_VALUE;
2371     }
2372 }
2373 
setPreferredMicrophoneFieldDimension(float zoom)2374 status_t AudioFlinger::RecordThread::RecordTrack::setPreferredMicrophoneFieldDimension(float zoom) {
2375     sp<ThreadBase> thread = mThread.promote();
2376     if (thread != 0) {
2377         RecordThread *recordThread = (RecordThread *)thread.get();
2378         return recordThread->setPreferredMicrophoneFieldDimension(zoom);
2379     } else {
2380         return BAD_VALUE;
2381     }
2382 }
2383 
2384 // ----------------------------------------------------------------------------
2385 #undef LOG_TAG
2386 #define LOG_TAG "AF::PatchRecord"
2387 
PatchRecord(RecordThread * recordThread,uint32_t sampleRate,audio_channel_mask_t channelMask,audio_format_t format,size_t frameCount,void * buffer,size_t bufferSize,audio_input_flags_t flags,const Timeout & timeout)2388 AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
2389                                                      uint32_t sampleRate,
2390                                                      audio_channel_mask_t channelMask,
2391                                                      audio_format_t format,
2392                                                      size_t frameCount,
2393                                                      void *buffer,
2394                                                      size_t bufferSize,
2395                                                      audio_input_flags_t flags,
2396                                                      const Timeout& timeout)
2397     :   RecordTrack(recordThread, NULL,
2398                 audio_attributes_t{} /* currently unused for patch track */,
2399                 sampleRate, format, channelMask, frameCount,
2400                 buffer, bufferSize, AUDIO_SESSION_NONE, getpid(), AID_AUDIOSERVER,
2401                 flags, TYPE_PATCH, String16()),
2402         PatchTrackBase(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true),
2403                        *recordThread, timeout)
2404 {
2405     ALOGV("%s(%d): sampleRate %d mPeerTimeout %d.%03d sec",
2406                                       __func__, mId, sampleRate,
2407                                       (int)mPeerTimeout.tv_sec,
2408                                       (int)(mPeerTimeout.tv_nsec / 1000000));
2409 }
2410 
~PatchRecord()2411 AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
2412 {
2413     ALOGV("%s(%d)", __func__, mId);
2414 }
2415 
writeFramesHelper(AudioBufferProvider * dest,const void * src,size_t frameCount,size_t frameSize)2416 static size_t writeFramesHelper(
2417         AudioBufferProvider* dest, const void* src, size_t frameCount, size_t frameSize)
2418 {
2419     AudioBufferProvider::Buffer patchBuffer;
2420     patchBuffer.frameCount = frameCount;
2421     auto status = dest->getNextBuffer(&patchBuffer);
2422     if (status != NO_ERROR) {
2423        ALOGW("%s PathRecord getNextBuffer failed with error %d: %s",
2424              __func__, status, strerror(-status));
2425        return 0;
2426     }
2427     ALOG_ASSERT(patchBuffer.frameCount <= frameCount);
2428     memcpy(patchBuffer.raw, src, patchBuffer.frameCount * frameSize);
2429     size_t framesWritten = patchBuffer.frameCount;
2430     dest->releaseBuffer(&patchBuffer);
2431     return framesWritten;
2432 }
2433 
2434 // static
writeFrames(AudioBufferProvider * dest,const void * src,size_t frameCount,size_t frameSize)2435 size_t AudioFlinger::RecordThread::PatchRecord::writeFrames(
2436         AudioBufferProvider* dest, const void* src, size_t frameCount, size_t frameSize)
2437 {
2438     size_t framesWritten = writeFramesHelper(dest, src, frameCount, frameSize);
2439     // On buffer wrap, the buffer frame count will be less than requested,
2440     // when this happens a second buffer needs to be used to write the leftover audio
2441     const size_t framesLeft = frameCount - framesWritten;
2442     if (framesWritten != 0 && framesLeft != 0) {
2443         framesWritten += writeFramesHelper(dest, (const char*)src + framesWritten * frameSize,
2444                         framesLeft, frameSize);
2445     }
2446     return framesWritten;
2447 }
2448 
2449 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer)2450 status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
2451                                                   AudioBufferProvider::Buffer* buffer)
2452 {
2453     ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
2454     Proxy::Buffer buf;
2455     buf.mFrameCount = buffer->frameCount;
2456     status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
2457     ALOGV_IF(status != NO_ERROR,
2458              "%s(%d): mPeerProxy->obtainBuffer status %d", __func__, mId, status);
2459     buffer->frameCount = buf.mFrameCount;
2460     if (ATRACE_ENABLED()) {
2461         std::string traceName("PRnObt");
2462         traceName += std::to_string(id());
2463         ATRACE_INT(traceName.c_str(), buf.mFrameCount);
2464     }
2465     if (buf.mFrameCount == 0) {
2466         return WOULD_BLOCK;
2467     }
2468     status = RecordTrack::getNextBuffer(buffer);
2469     return status;
2470 }
2471 
releaseBuffer(AudioBufferProvider::Buffer * buffer)2472 void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2473 {
2474     ALOG_ASSERT(mPeerProxy != 0, "%s(%d): called without peer proxy", __func__, mId);
2475     Proxy::Buffer buf;
2476     buf.mFrameCount = buffer->frameCount;
2477     buf.mRaw = buffer->raw;
2478     mPeerProxy->releaseBuffer(&buf);
2479     TrackBase::releaseBuffer(buffer);
2480 }
2481 
obtainBuffer(Proxy::Buffer * buffer,const struct timespec * timeOut)2482 status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
2483                                                                const struct timespec *timeOut)
2484 {
2485     return mProxy->obtainBuffer(buffer, timeOut);
2486 }
2487 
releaseBuffer(Proxy::Buffer * buffer)2488 void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2489 {
2490     mProxy->releaseBuffer(buffer);
2491 }
2492 
2493 #undef LOG_TAG
2494 #define LOG_TAG "AF::PthrPatchRecord"
2495 
allocAligned(size_t alignment,size_t size)2496 static std::unique_ptr<void, decltype(free)*> allocAligned(size_t alignment, size_t size)
2497 {
2498     void *ptr = nullptr;
2499     (void)posix_memalign(&ptr, alignment, size);
2500     return std::unique_ptr<void, decltype(free)*>(ptr, free);
2501 }
2502 
PassthruPatchRecord(RecordThread * recordThread,uint32_t sampleRate,audio_channel_mask_t channelMask,audio_format_t format,size_t frameCount,audio_input_flags_t flags)2503 AudioFlinger::RecordThread::PassthruPatchRecord::PassthruPatchRecord(
2504         RecordThread *recordThread,
2505         uint32_t sampleRate,
2506         audio_channel_mask_t channelMask,
2507         audio_format_t format,
2508         size_t frameCount,
2509         audio_input_flags_t flags)
2510         : PatchRecord(recordThread, sampleRate, channelMask, format, frameCount,
2511                 nullptr /*buffer*/, 0 /*bufferSize*/, flags),
2512           mPatchRecordAudioBufferProvider(*this),
2513           mSinkBuffer(allocAligned(32, mFrameCount * mFrameSize)),
2514           mStubBuffer(allocAligned(32, mFrameCount * mFrameSize))
2515 {
2516     memset(mStubBuffer.get(), 0, mFrameCount * mFrameSize);
2517 }
2518 
obtainStream(sp<ThreadBase> * thread)2519 sp<StreamInHalInterface> AudioFlinger::RecordThread::PassthruPatchRecord::obtainStream(
2520         sp<ThreadBase>* thread)
2521 {
2522     *thread = mThread.promote();
2523     if (!*thread) return nullptr;
2524     RecordThread *recordThread = static_cast<RecordThread*>((*thread).get());
2525     Mutex::Autolock _l(recordThread->mLock);
2526     return recordThread->mInput ? recordThread->mInput->stream : nullptr;
2527 }
2528 
2529 // PatchProxyBufferProvider methods are called on DirectOutputThread
obtainBuffer(Proxy::Buffer * buffer,const struct timespec * timeOut)2530 status_t AudioFlinger::RecordThread::PassthruPatchRecord::obtainBuffer(
2531         Proxy::Buffer* buffer, const struct timespec* timeOut)
2532 {
2533     if (mUnconsumedFrames) {
2534         buffer->mFrameCount = std::min(buffer->mFrameCount, mUnconsumedFrames);
2535         // mUnconsumedFrames is decreased in releaseBuffer to use actual frame consumption figure.
2536         return PatchRecord::obtainBuffer(buffer, timeOut);
2537     }
2538 
2539     // Otherwise, execute a read from HAL and write into the buffer.
2540     nsecs_t startTimeNs = 0;
2541     if (timeOut && (timeOut->tv_sec != 0 || timeOut->tv_nsec != 0) && timeOut->tv_sec != INT_MAX) {
2542         // Will need to correct timeOut by elapsed time.
2543         startTimeNs = systemTime();
2544     }
2545     const size_t framesToRead = std::min(buffer->mFrameCount, mFrameCount);
2546     buffer->mFrameCount = 0;
2547     buffer->mRaw = nullptr;
2548     sp<ThreadBase> thread;
2549     sp<StreamInHalInterface> stream = obtainStream(&thread);
2550     if (!stream) return NO_INIT;  // If there is no stream, RecordThread is not reading.
2551 
2552     status_t result = NO_ERROR;
2553     size_t bytesRead = 0;
2554     {
2555         ATRACE_NAME("read");
2556         result = stream->read(mSinkBuffer.get(), framesToRead * mFrameSize, &bytesRead);
2557         if (result != NO_ERROR) goto stream_error;
2558         if (bytesRead == 0) return NO_ERROR;
2559     }
2560 
2561     {
2562         std::lock_guard<std::mutex> lock(mReadLock);
2563         mReadBytes += bytesRead;
2564         mReadError = NO_ERROR;
2565     }
2566     mReadCV.notify_one();
2567     // writeFrames handles wraparound and should write all the provided frames.
2568     // If it couldn't, there is something wrong with the client/server buffer of the software patch.
2569     buffer->mFrameCount = writeFrames(
2570             &mPatchRecordAudioBufferProvider,
2571             mSinkBuffer.get(), bytesRead / mFrameSize, mFrameSize);
2572     ALOGW_IF(buffer->mFrameCount < bytesRead / mFrameSize,
2573             "Lost %zu frames obtained from HAL", bytesRead / mFrameSize - buffer->mFrameCount);
2574     mUnconsumedFrames = buffer->mFrameCount;
2575     struct timespec newTimeOut;
2576     if (startTimeNs) {
2577         // Correct the timeout by elapsed time.
2578         nsecs_t newTimeOutNs = audio_utils_ns_from_timespec(timeOut) - (systemTime() - startTimeNs);
2579         if (newTimeOutNs < 0) newTimeOutNs = 0;
2580         newTimeOut.tv_sec = newTimeOutNs / NANOS_PER_SECOND;
2581         newTimeOut.tv_nsec = newTimeOutNs - newTimeOut.tv_sec * NANOS_PER_SECOND;
2582         timeOut = &newTimeOut;
2583     }
2584     return PatchRecord::obtainBuffer(buffer, timeOut);
2585 
2586 stream_error:
2587     stream->standby();
2588     {
2589         std::lock_guard<std::mutex> lock(mReadLock);
2590         mReadError = result;
2591     }
2592     mReadCV.notify_one();
2593     return result;
2594 }
2595 
releaseBuffer(Proxy::Buffer * buffer)2596 void AudioFlinger::RecordThread::PassthruPatchRecord::releaseBuffer(Proxy::Buffer* buffer)
2597 {
2598     if (buffer->mFrameCount <= mUnconsumedFrames) {
2599         mUnconsumedFrames -= buffer->mFrameCount;
2600     } else {
2601         ALOGW("Write side has consumed more frames than we had: %zu > %zu",
2602                 buffer->mFrameCount, mUnconsumedFrames);
2603         mUnconsumedFrames = 0;
2604     }
2605     PatchRecord::releaseBuffer(buffer);
2606 }
2607 
2608 // AudioBufferProvider and Source methods are called on RecordThread
2609 // 'read' emulates actual audio data with 0's. This is OK as 'getNextBuffer'
2610 // and 'releaseBuffer' are stubbed out and ignore their input.
2611 // It's not possible to retrieve actual data here w/o blocking 'obtainBuffer'
2612 // until we copy it.
read(void * buffer,size_t bytes,size_t * read)2613 status_t AudioFlinger::RecordThread::PassthruPatchRecord::read(
2614         void* buffer, size_t bytes, size_t* read)
2615 {
2616     bytes = std::min(bytes, mFrameCount * mFrameSize);
2617     {
2618         std::unique_lock<std::mutex> lock(mReadLock);
2619         mReadCV.wait(lock, [&]{ return mReadError != NO_ERROR || mReadBytes != 0; });
2620         if (mReadError != NO_ERROR) {
2621             mLastReadFrames = 0;
2622             return mReadError;
2623         }
2624         *read = std::min(bytes, mReadBytes);
2625         mReadBytes -= *read;
2626     }
2627     mLastReadFrames = *read / mFrameSize;
2628     memset(buffer, 0, *read);
2629     return 0;
2630 }
2631 
getCapturePosition(int64_t * frames,int64_t * time)2632 status_t AudioFlinger::RecordThread::PassthruPatchRecord::getCapturePosition(
2633         int64_t* frames, int64_t* time)
2634 {
2635     sp<ThreadBase> thread;
2636     sp<StreamInHalInterface> stream = obtainStream(&thread);
2637     return stream ? stream->getCapturePosition(frames, time) : NO_INIT;
2638 }
2639 
standby()2640 status_t AudioFlinger::RecordThread::PassthruPatchRecord::standby()
2641 {
2642     // RecordThread issues 'standby' command in two major cases:
2643     // 1. Error on read--this case is handled in 'obtainBuffer'.
2644     // 2. Track is stopping--as PassthruPatchRecord assumes continuous
2645     //    output, this can only happen when the software patch
2646     //    is being torn down. In this case, the RecordThread
2647     //    will terminate and close the HAL stream.
2648     return 0;
2649 }
2650 
2651 // As the buffer gets filled in obtainBuffer, here we only simulate data consumption.
getNextBuffer(AudioBufferProvider::Buffer * buffer)2652 status_t AudioFlinger::RecordThread::PassthruPatchRecord::getNextBuffer(
2653         AudioBufferProvider::Buffer* buffer)
2654 {
2655     buffer->frameCount = mLastReadFrames;
2656     buffer->raw = buffer->frameCount != 0 ? mStubBuffer.get() : nullptr;
2657     return NO_ERROR;
2658 }
2659 
releaseBuffer(AudioBufferProvider::Buffer * buffer)2660 void AudioFlinger::RecordThread::PassthruPatchRecord::releaseBuffer(
2661         AudioBufferProvider::Buffer* buffer)
2662 {
2663     buffer->frameCount = 0;
2664     buffer->raw = nullptr;
2665 }
2666 
2667 // ----------------------------------------------------------------------------
2668 #undef LOG_TAG
2669 #define LOG_TAG "AF::MmapTrack"
2670 
MmapTrack(ThreadBase * thread,const audio_attributes_t & attr,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,audio_session_t sessionId,bool isOut,uid_t uid,pid_t pid,pid_t creatorPid,audio_port_handle_t portId)2671 AudioFlinger::MmapThread::MmapTrack::MmapTrack(ThreadBase *thread,
2672         const audio_attributes_t& attr,
2673         uint32_t sampleRate,
2674         audio_format_t format,
2675         audio_channel_mask_t channelMask,
2676         audio_session_t sessionId,
2677         bool isOut,
2678         uid_t uid,
2679         pid_t pid,
2680         pid_t creatorPid,
2681         audio_port_handle_t portId)
2682     :   TrackBase(thread, NULL, attr, sampleRate, format,
2683                   channelMask, (size_t)0 /* frameCount */,
2684                   nullptr /* buffer */, (size_t)0 /* bufferSize */,
2685                   sessionId, creatorPid, uid, isOut,
2686                   ALLOC_NONE,
2687                   TYPE_DEFAULT, portId),
2688         mPid(pid), mSilenced(false), mSilencedNotified(false)
2689 {
2690 }
2691 
~MmapTrack()2692 AudioFlinger::MmapThread::MmapTrack::~MmapTrack()
2693 {
2694 }
2695 
initCheck() const2696 status_t AudioFlinger::MmapThread::MmapTrack::initCheck() const
2697 {
2698     return NO_ERROR;
2699 }
2700 
start(AudioSystem::sync_event_t event __unused,audio_session_t triggerSession __unused)2701 status_t AudioFlinger::MmapThread::MmapTrack::start(AudioSystem::sync_event_t event __unused,
2702                                                     audio_session_t triggerSession __unused)
2703 {
2704     return NO_ERROR;
2705 }
2706 
stop()2707 void AudioFlinger::MmapThread::MmapTrack::stop()
2708 {
2709 }
2710 
2711 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer)2712 status_t AudioFlinger::MmapThread::MmapTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
2713 {
2714     buffer->frameCount = 0;
2715     buffer->raw = nullptr;
2716     return INVALID_OPERATION;
2717 }
2718 
2719 // ExtendedAudioBufferProvider interface
framesReady() const2720 size_t AudioFlinger::MmapThread::MmapTrack::framesReady() const {
2721     return 0;
2722 }
2723 
framesReleased() const2724 int64_t AudioFlinger::MmapThread::MmapTrack::framesReleased() const
2725 {
2726     return 0;
2727 }
2728 
onTimestamp(const ExtendedTimestamp & timestamp __unused)2729 void AudioFlinger::MmapThread::MmapTrack::onTimestamp(const ExtendedTimestamp &timestamp __unused)
2730 {
2731 }
2732 
appendDumpHeader(String8 & result)2733 void AudioFlinger::MmapThread::MmapTrack::appendDumpHeader(String8& result)
2734 {
2735     result.appendFormat("Client Session Port Id  Format Chn mask  SRate Flags %s\n",
2736                         isOut() ? "Usg CT": "Source");
2737 }
2738 
appendDump(String8 & result,bool active __unused)2739 void AudioFlinger::MmapThread::MmapTrack::appendDump(String8& result, bool active __unused)
2740 {
2741     result.appendFormat("%6u %7u %7u %08X %08X %6u 0x%03X ",
2742             mPid,
2743             mSessionId,
2744             mPortId,
2745             mFormat,
2746             mChannelMask,
2747             mSampleRate,
2748             mAttr.flags);
2749     if (isOut()) {
2750         result.appendFormat("%3x %2x", mAttr.usage, mAttr.content_type);
2751     } else {
2752         result.appendFormat("%6x", mAttr.source);
2753     }
2754     result.append("\n");
2755 }
2756 
2757 } // namespace android
2758