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