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