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