• 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 #define ATRACE_TAG ATRACE_TAG_AUDIO
22 
23 #include "Configuration.h"
24 #include <math.h>
25 #include <fcntl.h>
26 #include <memory>
27 #include <sstream>
28 #include <string>
29 #include <linux/futex.h>
30 #include <sys/stat.h>
31 #include <sys/syscall.h>
32 #include <cutils/bitops.h>
33 #include <cutils/properties.h>
34 #include <media/AudioContainers.h>
35 #include <media/AudioDeviceTypeAddr.h>
36 #include <media/AudioParameter.h>
37 #include <media/AudioResamplerPublic.h>
38 #include <media/RecordBufferConverter.h>
39 #include <media/TypeConverter.h>
40 #include <utils/Log.h>
41 #include <utils/Trace.h>
42 
43 #include <private/media/AudioTrackShared.h>
44 #include <private/android_filesystem_config.h>
45 #include <audio_utils/Balance.h>
46 #include <audio_utils/Metadata.h>
47 #include <audio_utils/channels.h>
48 #include <audio_utils/mono_blend.h>
49 #include <audio_utils/primitives.h>
50 #include <audio_utils/format.h>
51 #include <audio_utils/minifloat.h>
52 #include <audio_utils/safe_math.h>
53 #include <system/audio_effects/effect_ns.h>
54 #include <system/audio_effects/effect_aec.h>
55 #include <system/audio.h>
56 
57 // NBAIO implementations
58 #include <media/nbaio/AudioStreamInSource.h>
59 #include <media/nbaio/AudioStreamOutSink.h>
60 #include <media/nbaio/MonoPipe.h>
61 #include <media/nbaio/MonoPipeReader.h>
62 #include <media/nbaio/Pipe.h>
63 #include <media/nbaio/PipeReader.h>
64 #include <media/nbaio/SourceAudioBufferProvider.h>
65 #include <mediautils/BatteryNotifier.h>
66 
67 #include <audiomanager/AudioManager.h>
68 #include <powermanager/PowerManager.h>
69 
70 #include <media/audiohal/EffectsFactoryHalInterface.h>
71 #include <media/audiohal/StreamHalInterface.h>
72 
73 #include "AudioFlinger.h"
74 #include "FastMixer.h"
75 #include "FastCapture.h"
76 #include <mediautils/SchedulingPolicyService.h>
77 #include <mediautils/ServiceUtilities.h>
78 
79 #ifdef ADD_BATTERY_DATA
80 #include <media/IMediaPlayerService.h>
81 #include <media/IMediaDeathNotifier.h>
82 #endif
83 
84 #ifdef DEBUG_CPU_USAGE
85 #include <audio_utils/Statistics.h>
86 #include <cpustats/ThreadCpuUsage.h>
87 #endif
88 
89 #include "AutoPark.h"
90 
91 #include <pthread.h>
92 #include "TypedLogger.h"
93 
94 // ----------------------------------------------------------------------------
95 
96 // Note: the following macro is used for extremely verbose logging message.  In
97 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
98 // 0; but one side effect of this is to turn all LOGV's as well.  Some messages
99 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
100 // turned on.  Do not uncomment the #def below unless you really know what you
101 // are doing and want to see all of the extremely verbose messages.
102 //#define VERY_VERY_VERBOSE_LOGGING
103 #ifdef VERY_VERY_VERBOSE_LOGGING
104 #define ALOGVV ALOGV
105 #else
106 #define ALOGVV(a...) do { } while(0)
107 #endif
108 
109 // TODO: Move these macro/inlines to a header file.
110 #define max(a, b) ((a) > (b) ? (a) : (b))
111 
112 template <typename T>
min(const T & a,const T & b)113 static inline T min(const T& a, const T& b)
114 {
115     return a < b ? a : b;
116 }
117 
118 namespace android {
119 
120 using media::IEffectClient;
121 using content::AttributionSourceState;
122 
123 // retry counts for buffer fill timeout
124 // 50 * ~20msecs = 1 second
125 static const int8_t kMaxTrackRetries = 50;
126 static const int8_t kMaxTrackStartupRetries = 50;
127 
128 // allow less retry attempts on direct output thread.
129 // direct outputs can be a scarce resource in audio hardware and should
130 // be released as quickly as possible.
131 // Notes:
132 // 1) The retry duration kMaxTrackRetriesDirectMs may be increased
133 //    in case the data write is bursty for the AudioTrack.  The application
134 //    should endeavor to write at least once every kMaxTrackRetriesDirectMs
135 //    to prevent an underrun situation.  If the data is bursty, then
136 //    the application can also throttle the data sent to be even.
137 // 2) For compressed audio data, any data present in the AudioTrack buffer
138 //    will be sent and reset the retry count.  This delivers data as
139 //    it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
140 // 3) For linear PCM or proportional PCM, we wait one period for a period's worth
141 //    of data to be available, then any remaining data is delivered.
142 //    This is required to ensure the last bit of data is delivered before underrun.
143 //
144 // Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
145 // or the size of the HAL period for proportional / linear PCM tracks.
146 static const int32_t kMaxTrackRetriesDirectMs = 200;
147 
148 // don't warn about blocked writes or record buffer overflows more often than this
149 static const nsecs_t kWarningThrottleNs = seconds(5);
150 
151 // RecordThread loop sleep time upon application overrun or audio HAL read error
152 static const int kRecordThreadSleepUs = 5000;
153 
154 // maximum time to wait in sendConfigEvent_l() for a status to be received
155 static const nsecs_t kConfigEventTimeoutNs = seconds(2);
156 
157 // minimum sleep time for the mixer thread loop when tracks are active but in underrun
158 static const uint32_t kMinThreadSleepTimeUs = 5000;
159 // maximum divider applied to the active sleep time in the mixer thread loop
160 static const uint32_t kMaxThreadSleepTimeShift = 2;
161 
162 // minimum normal sink buffer size, expressed in milliseconds rather than frames
163 // FIXME This should be based on experimentally observed scheduling jitter
164 static const uint32_t kMinNormalSinkBufferSizeMs = 20;
165 // maximum normal sink buffer size
166 static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
167 
168 // minimum capture buffer size in milliseconds to _not_ need a fast capture thread
169 // FIXME This should be based on experimentally observed scheduling jitter
170 static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
171 
172 // Offloaded output thread standby delay: allows track transition without going to standby
173 static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
174 
175 // Direct output thread minimum sleep time in idle or active(underrun) state
176 static const nsecs_t kDirectMinSleepTimeUs = 10000;
177 
178 // The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
179 // balance between power consumption and latency, and allows threads to be scheduled reliably
180 // by the CFS scheduler.
181 // FIXME Express other hardcoded references to 20ms with references to this constant and move
182 // it appropriately.
183 #define FMS_20 20
184 
185 // Whether to use fast mixer
186 static const enum {
187     FastMixer_Never,    // never initialize or use: for debugging only
188     FastMixer_Always,   // always initialize and use, even if not needed: for debugging only
189                         // normal mixer multiplier is 1
190     FastMixer_Static,   // initialize if needed, then use all the time if initialized,
191                         // multiplier is calculated based on min & max normal mixer buffer size
192     FastMixer_Dynamic,  // initialize if needed, then use dynamically depending on track load,
193                         // multiplier is calculated based on min & max normal mixer buffer size
194     // FIXME for FastMixer_Dynamic:
195     //  Supporting this option will require fixing HALs that can't handle large writes.
196     //  For example, one HAL implementation returns an error from a large write,
197     //  and another HAL implementation corrupts memory, possibly in the sample rate converter.
198     //  We could either fix the HAL implementations, or provide a wrapper that breaks
199     //  up large writes into smaller ones, and the wrapper would need to deal with scheduler.
200 } kUseFastMixer = FastMixer_Static;
201 
202 // Whether to use fast capture
203 static const enum {
204     FastCapture_Never,  // never initialize or use: for debugging only
205     FastCapture_Always, // always initialize and use, even if not needed: for debugging only
206     FastCapture_Static, // initialize if needed, then use all the time if initialized
207 } kUseFastCapture = FastCapture_Static;
208 
209 // Priorities for requestPriority
210 static const int kPriorityAudioApp = 2;
211 static const int kPriorityFastMixer = 3;
212 static const int kPriorityFastCapture = 3;
213 
214 // IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
215 // track buffer in shared memory.  Zero on input means to use a default value.  For fast tracks,
216 // AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
217 
218 // This is the default value, if not specified by property.
219 static const int kFastTrackMultiplier = 2;
220 
221 // The minimum and maximum allowed values
222 static const int kFastTrackMultiplierMin = 1;
223 static const int kFastTrackMultiplierMax = 2;
224 
225 // The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
226 static int sFastTrackMultiplier = kFastTrackMultiplier;
227 
228 // See Thread::readOnlyHeap().
229 // Initially this heap is used to allocate client buffers for "fast" AudioRecord.
230 // Eventually it will be the single buffer that FastCapture writes into via HAL read(),
231 // and that all "fast" AudioRecord clients read from.  In either case, the size can be small.
232 static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
233 
234 // ----------------------------------------------------------------------------
235 
236 // TODO: move all toString helpers to audio.h
237 // under  #ifdef __cplusplus #endif
patchSinksToString(const struct audio_patch * patch)238 static std::string patchSinksToString(const struct audio_patch *patch)
239 {
240     std::stringstream ss;
241     for (size_t i = 0; i < patch->num_sinks; ++i) {
242         if (i > 0) {
243             ss << "|";
244         }
245         ss << "(" << toString(patch->sinks[i].ext.device.type)
246             << ", " << patch->sinks[i].ext.device.address << ")";
247     }
248     return ss.str();
249 }
250 
patchSourcesToString(const struct audio_patch * patch)251 static std::string patchSourcesToString(const struct audio_patch *patch)
252 {
253     std::stringstream ss;
254     for (size_t i = 0; i < patch->num_sources; ++i) {
255         if (i > 0) {
256             ss << "|";
257         }
258         ss << "(" << toString(patch->sources[i].ext.device.type)
259             << ", " << patch->sources[i].ext.device.address << ")";
260     }
261     return ss.str();
262 }
263 
264 static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
265 
sFastTrackMultiplierInit()266 static void sFastTrackMultiplierInit()
267 {
268     char value[PROPERTY_VALUE_MAX];
269     if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
270         char *endptr;
271         unsigned long ul = strtoul(value, &endptr, 0);
272         if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
273             sFastTrackMultiplier = (int) ul;
274         }
275     }
276 }
277 
278 // ----------------------------------------------------------------------------
279 
280 #ifdef ADD_BATTERY_DATA
281 // To collect the amplifier usage
addBatteryData(uint32_t params)282 static void addBatteryData(uint32_t params) {
283     sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
284     if (service == NULL) {
285         // it already logged
286         return;
287     }
288 
289     service->addBatteryData(params);
290 }
291 #endif
292 
293 // Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
294 struct {
295     // call when you acquire a partial wakelock
acquireandroid::__anon9b3e2cb30308296     void acquire(const sp<IBinder> &wakeLockToken) {
297         pthread_mutex_lock(&mLock);
298         if (wakeLockToken.get() == nullptr) {
299             adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
300         } else {
301             if (mCount == 0) {
302                 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
303             }
304             ++mCount;
305         }
306         pthread_mutex_unlock(&mLock);
307     }
308 
309     // call when you release a partial wakelock.
releaseandroid::__anon9b3e2cb30308310     void release(const sp<IBinder> &wakeLockToken) {
311         if (wakeLockToken.get() == nullptr) {
312             return;
313         }
314         pthread_mutex_lock(&mLock);
315         if (--mCount < 0) {
316             ALOGE("negative wakelock count");
317             mCount = 0;
318         }
319         pthread_mutex_unlock(&mLock);
320     }
321 
322     // retrieves the boottime timebase offset from monotonic.
getBoottimeOffsetandroid::__anon9b3e2cb30308323     int64_t getBoottimeOffset() {
324         pthread_mutex_lock(&mLock);
325         int64_t boottimeOffset = mBoottimeOffset;
326         pthread_mutex_unlock(&mLock);
327         return boottimeOffset;
328     }
329 
330     // Adjusts the timebase offset between TIMEBASE_MONOTONIC
331     // and the selected timebase.
332     // Currently only TIMEBASE_BOOTTIME is allowed.
333     //
334     // This only needs to be called upon acquiring the first partial wakelock
335     // after all other partial wakelocks are released.
336     //
337     // We do an empirical measurement of the offset rather than parsing
338     // /proc/timer_list since the latter is not a formal kernel ABI.
adjustTimebaseOffsetandroid::__anon9b3e2cb30308339     static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
340         int clockbase;
341         switch (timebase) {
342         case ExtendedTimestamp::TIMEBASE_BOOTTIME:
343             clockbase = SYSTEM_TIME_BOOTTIME;
344             break;
345         default:
346             LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
347             break;
348         }
349         // try three times to get the clock offset, choose the one
350         // with the minimum gap in measurements.
351         const int tries = 3;
352         nsecs_t bestGap, measured;
353         for (int i = 0; i < tries; ++i) {
354             const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
355             const nsecs_t tbase = systemTime(clockbase);
356             const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
357             const nsecs_t gap = tmono2 - tmono;
358             if (i == 0 || gap < bestGap) {
359                 bestGap = gap;
360                 measured = tbase - ((tmono + tmono2) >> 1);
361             }
362         }
363 
364         // to avoid micro-adjusting, we don't change the timebase
365         // unless it is significantly different.
366         //
367         // Assumption: It probably takes more than toleranceNs to
368         // suspend and resume the device.
369         static int64_t toleranceNs = 10000; // 10 us
370         if (llabs(*offset - measured) > toleranceNs) {
371             ALOGV("Adjusting timebase offset old: %lld  new: %lld",
372                     (long long)*offset, (long long)measured);
373             *offset = measured;
374         }
375     }
376 
377     pthread_mutex_t mLock;
378     int32_t mCount;
379     int64_t mBoottimeOffset;
380 } gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
381 
382 // ----------------------------------------------------------------------------
383 //      CPU Stats
384 // ----------------------------------------------------------------------------
385 
386 class CpuStats {
387 public:
388     CpuStats();
389     void sample(const String8 &title);
390 #ifdef DEBUG_CPU_USAGE
391 private:
392     ThreadCpuUsage mCpuUsage;           // instantaneous thread CPU usage in wall clock ns
393     audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
394 
395     audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
396 
397     int mCpuNum;                        // thread's current CPU number
398     int mCpukHz;                        // frequency of thread's current CPU in kHz
399 #endif
400 };
401 
CpuStats()402 CpuStats::CpuStats()
403 #ifdef DEBUG_CPU_USAGE
404     : mCpuNum(-1), mCpukHz(-1)
405 #endif
406 {
407 }
408 
sample(const String8 & title __unused)409 void CpuStats::sample(const String8 &title
410 #ifndef DEBUG_CPU_USAGE
411                 __unused
412 #endif
413         ) {
414 #ifdef DEBUG_CPU_USAGE
415     // get current thread's delta CPU time in wall clock ns
416     double wcNs;
417     bool valid = mCpuUsage.sampleAndEnable(wcNs);
418 
419     // record sample for wall clock statistics
420     if (valid) {
421         mWcStats.add(wcNs);
422     }
423 
424     // get the current CPU number
425     int cpuNum = sched_getcpu();
426 
427     // get the current CPU frequency in kHz
428     int cpukHz = mCpuUsage.getCpukHz(cpuNum);
429 
430     // check if either CPU number or frequency changed
431     if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
432         mCpuNum = cpuNum;
433         mCpukHz = cpukHz;
434         // ignore sample for purposes of cycles
435         valid = false;
436     }
437 
438     // if no change in CPU number or frequency, then record sample for cycle statistics
439     if (valid && mCpukHz > 0) {
440         const double cycles = wcNs * cpukHz * 0.000001;
441         mHzStats.add(cycles);
442     }
443 
444     const unsigned n = mWcStats.getN();
445     // mCpuUsage.elapsed() is expensive, so don't call it every loop
446     if ((n & 127) == 1) {
447         const long long elapsed = mCpuUsage.elapsed();
448         if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
449             const double perLoop = elapsed / (double) n;
450             const double perLoop100 = perLoop * 0.01;
451             const double perLoop1k = perLoop * 0.001;
452             const double mean = mWcStats.getMean();
453             const double stddev = mWcStats.getStdDev();
454             const double minimum = mWcStats.getMin();
455             const double maximum = mWcStats.getMax();
456             const double meanCycles = mHzStats.getMean();
457             const double stddevCycles = mHzStats.getStdDev();
458             const double minCycles = mHzStats.getMin();
459             const double maxCycles = mHzStats.getMax();
460             mCpuUsage.resetElapsed();
461             mWcStats.reset();
462             mHzStats.reset();
463             ALOGD("CPU usage for %s over past %.1f secs\n"
464                 "  (%u mixer loops at %.1f mean ms per loop):\n"
465                 "  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
466                 "  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
467                 "  MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
468                     title.string(),
469                     elapsed * .000000001, n, perLoop * .000001,
470                     mean * .001,
471                     stddev * .001,
472                     minimum * .001,
473                     maximum * .001,
474                     mean / perLoop100,
475                     stddev / perLoop100,
476                     minimum / perLoop100,
477                     maximum / perLoop100,
478                     meanCycles / perLoop1k,
479                     stddevCycles / perLoop1k,
480                     minCycles / perLoop1k,
481                     maxCycles / perLoop1k);
482 
483         }
484     }
485 #endif
486 };
487 
488 // ----------------------------------------------------------------------------
489 //      ThreadBase
490 // ----------------------------------------------------------------------------
491 
492 // static
threadTypeToString(AudioFlinger::ThreadBase::type_t type)493 const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
494 {
495     switch (type) {
496     case MIXER:
497         return "MIXER";
498     case DIRECT:
499         return "DIRECT";
500     case DUPLICATING:
501         return "DUPLICATING";
502     case RECORD:
503         return "RECORD";
504     case OFFLOAD:
505         return "OFFLOAD";
506     case MMAP_PLAYBACK:
507         return "MMAP_PLAYBACK";
508     case MMAP_CAPTURE:
509         return "MMAP_CAPTURE";
510     default:
511         return "unknown";
512     }
513 }
514 
ThreadBase(const sp<AudioFlinger> & audioFlinger,audio_io_handle_t id,type_t type,bool systemReady,bool isOut)515 AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
516         type_t type, bool systemReady, bool isOut)
517     :   Thread(false /*canCallJava*/),
518         mType(type),
519         mAudioFlinger(audioFlinger),
520         mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
521                isOut),
522         mIsOut(isOut),
523         // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
524         // are set by PlaybackThread::readOutputParameters_l() or
525         // RecordThread::readInputParameters_l()
526         //FIXME: mStandby should be true here. Is this some kind of hack?
527         mStandby(false),
528         mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
529         // mName will be set by concrete (non-virtual) subclass
530         mDeathRecipient(new PMDeathRecipient(this)),
531         mSystemReady(systemReady),
532         mSignalPending(false)
533 {
534     mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
535     memset(&mPatch, 0, sizeof(struct audio_patch));
536 }
537 
~ThreadBase()538 AudioFlinger::ThreadBase::~ThreadBase()
539 {
540     // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
541     mConfigEvents.clear();
542 
543     // do not lock the mutex in destructor
544     releaseWakeLock_l();
545     if (mPowerManager != 0) {
546         sp<IBinder> binder = IInterface::asBinder(mPowerManager);
547         binder->unlinkToDeath(mDeathRecipient);
548     }
549 
550     sendStatistics(true /* force */);
551 }
552 
readyToRun()553 status_t AudioFlinger::ThreadBase::readyToRun()
554 {
555     status_t status = initCheck();
556     if (status == NO_ERROR) {
557         ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
558     } else {
559         ALOGE("No working audio driver found.");
560     }
561     return status;
562 }
563 
exit()564 void AudioFlinger::ThreadBase::exit()
565 {
566     ALOGV("ThreadBase::exit");
567     // do any cleanup required for exit to succeed
568     preExit();
569     {
570         // This lock prevents the following race in thread (uniprocessor for illustration):
571         //  if (!exitPending()) {
572         //      // context switch from here to exit()
573         //      // exit() calls requestExit(), what exitPending() observes
574         //      // exit() calls signal(), which is dropped since no waiters
575         //      // context switch back from exit() to here
576         //      mWaitWorkCV.wait(...);
577         //      // now thread is hung
578         //  }
579         AutoMutex lock(mLock);
580         requestExit();
581         mWaitWorkCV.broadcast();
582     }
583     // When Thread::requestExitAndWait is made virtual and this method is renamed to
584     // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
585     requestExitAndWait();
586 }
587 
setParameters(const String8 & keyValuePairs)588 status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
589 {
590     ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
591     Mutex::Autolock _l(mLock);
592 
593     return sendSetParameterConfigEvent_l(keyValuePairs);
594 }
595 
596 // sendConfigEvent_l() must be called with ThreadBase::mLock held
597 // Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
sendConfigEvent_l(sp<ConfigEvent> & event)598 status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
599 {
600     status_t status = NO_ERROR;
601 
602     if (event->mRequiresSystemReady && !mSystemReady) {
603         event->mWaitStatus = false;
604         mPendingConfigEvents.add(event);
605         return status;
606     }
607     mConfigEvents.add(event);
608     ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
609     mWaitWorkCV.signal();
610     mLock.unlock();
611     {
612         Mutex::Autolock _l(event->mLock);
613         while (event->mWaitStatus) {
614             if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
615                 event->mStatus = TIMED_OUT;
616                 event->mWaitStatus = false;
617             }
618         }
619         status = event->mStatus;
620     }
621     mLock.lock();
622     return status;
623 }
624 
sendIoConfigEvent(audio_io_config_event event,pid_t pid,audio_port_handle_t portId)625 void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
626                                                  audio_port_handle_t portId)
627 {
628     Mutex::Autolock _l(mLock);
629     sendIoConfigEvent_l(event, pid, portId);
630 }
631 
632 // sendIoConfigEvent_l() must be called with ThreadBase::mLock held
sendIoConfigEvent_l(audio_io_config_event event,pid_t pid,audio_port_handle_t portId)633 void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
634                                                    audio_port_handle_t portId)
635 {
636     // The audio statistics history is exponentially weighted to forget events
637     // about five or more seconds in the past.  In order to have
638     // crisper statistics for mediametrics, we reset the statistics on
639     // an IoConfigEvent, to reflect different properties for a new device.
640     mIoJitterMs.reset();
641     mLatencyMs.reset();
642     mProcessTimeMs.reset();
643     mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
644 
645     sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
646     sendConfigEvent_l(configEvent);
647 }
648 
sendPrioConfigEvent(pid_t pid,pid_t tid,int32_t prio,bool forApp)649 void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
650 {
651     Mutex::Autolock _l(mLock);
652     sendPrioConfigEvent_l(pid, tid, prio, forApp);
653 }
654 
655 // sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
sendPrioConfigEvent_l(pid_t pid,pid_t tid,int32_t prio,bool forApp)656 void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
657         pid_t pid, pid_t tid, int32_t prio, bool forApp)
658 {
659     sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
660     sendConfigEvent_l(configEvent);
661 }
662 
663 // sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
sendSetParameterConfigEvent_l(const String8 & keyValuePair)664 status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
665 {
666     sp<ConfigEvent> configEvent;
667     AudioParameter param(keyValuePair);
668     int value;
669     if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
670         setMasterMono_l(value != 0);
671         if (param.size() == 1) {
672             return NO_ERROR; // should be a solo parameter - we don't pass down
673         }
674         param.remove(String8(AudioParameter::keyMonoOutput));
675         configEvent = new SetParameterConfigEvent(param.toString());
676     } else {
677         configEvent = new SetParameterConfigEvent(keyValuePair);
678     }
679     return sendConfigEvent_l(configEvent);
680 }
681 
sendCreateAudioPatchConfigEvent(const struct audio_patch * patch,audio_patch_handle_t * handle)682 status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
683                                                         const struct audio_patch *patch,
684                                                         audio_patch_handle_t *handle)
685 {
686     Mutex::Autolock _l(mLock);
687     sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
688     status_t status = sendConfigEvent_l(configEvent);
689     if (status == NO_ERROR) {
690         CreateAudioPatchConfigEventData *data =
691                                         (CreateAudioPatchConfigEventData *)configEvent->mData.get();
692         *handle = data->mHandle;
693     }
694     return status;
695 }
696 
sendReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle)697 status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
698                                                                 const audio_patch_handle_t handle)
699 {
700     Mutex::Autolock _l(mLock);
701     sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
702     return sendConfigEvent_l(configEvent);
703 }
704 
sendUpdateOutDeviceConfigEvent(const DeviceDescriptorBaseVector & outDevices)705 status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
706         const DeviceDescriptorBaseVector& outDevices)
707 {
708     if (type() != RECORD) {
709         // The update out device operation is only for record thread.
710         return INVALID_OPERATION;
711     }
712     Mutex::Autolock _l(mLock);
713     sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
714     return sendConfigEvent_l(configEvent);
715 }
716 
sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)717 void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
718 {
719     ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
720     sp<ConfigEvent> configEvent =
721             (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
722     sendConfigEvent_l(configEvent);
723 }
724 
725 // post condition: mConfigEvents.isEmpty()
processConfigEvents_l()726 void AudioFlinger::ThreadBase::processConfigEvents_l()
727 {
728     bool configChanged = false;
729 
730     while (!mConfigEvents.isEmpty()) {
731         ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
732         sp<ConfigEvent> event = mConfigEvents[0];
733         mConfigEvents.removeAt(0);
734         switch (event->mType) {
735         case CFG_EVENT_PRIO: {
736             PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
737             // FIXME Need to understand why this has to be done asynchronously
738             int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
739                     true /*asynchronous*/);
740             if (err != 0) {
741                 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
742                       data->mPrio, data->mPid, data->mTid, err);
743             }
744         } break;
745         case CFG_EVENT_IO: {
746             IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
747             ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
748         } break;
749         case CFG_EVENT_SET_PARAMETER: {
750             SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
751             if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
752                 configChanged = true;
753                 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
754                         data->mKeyValuePairs.string());
755             }
756         } break;
757         case CFG_EVENT_CREATE_AUDIO_PATCH: {
758             const DeviceTypeSet oldDevices = getDeviceTypes();
759             CreateAudioPatchConfigEventData *data =
760                                             (CreateAudioPatchConfigEventData *)event->mData.get();
761             event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
762             const DeviceTypeSet newDevices = getDeviceTypes();
763             mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
764                     dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
765                     dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
766         } break;
767         case CFG_EVENT_RELEASE_AUDIO_PATCH: {
768             const DeviceTypeSet oldDevices = getDeviceTypes();
769             ReleaseAudioPatchConfigEventData *data =
770                                             (ReleaseAudioPatchConfigEventData *)event->mData.get();
771             event->mStatus = releaseAudioPatch_l(data->mHandle);
772             const DeviceTypeSet newDevices = getDeviceTypes();
773             mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
774                     dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
775                     dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
776         } break;
777         case CFG_EVENT_UPDATE_OUT_DEVICE: {
778             UpdateOutDevicesConfigEventData *data =
779                     (UpdateOutDevicesConfigEventData *)event->mData.get();
780             updateOutDevices(data->mOutDevices);
781         } break;
782         case CFG_EVENT_RESIZE_BUFFER: {
783             ResizeBufferConfigEventData *data =
784                     (ResizeBufferConfigEventData *)event->mData.get();
785             resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
786         } break;
787         default:
788             ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
789             break;
790         }
791         {
792             Mutex::Autolock _l(event->mLock);
793             if (event->mWaitStatus) {
794                 event->mWaitStatus = false;
795                 event->mCond.signal();
796             }
797         }
798         ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
799     }
800 
801     if (configChanged) {
802         cacheParameters_l();
803     }
804 }
805 
channelMaskToString(audio_channel_mask_t mask,bool output)806 String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
807     String8 s;
808     const audio_channel_representation_t representation =
809             audio_channel_mask_get_representation(mask);
810 
811     switch (representation) {
812     // Travel all single bit channel mask to convert channel mask to string.
813     case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
814         if (output) {
815             if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
816             if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
817             if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
818             if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
819             if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
820             if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
821             if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
822             if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
823             if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
824             if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
825             if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
826             if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
827             if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
828             if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
829             if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
830             if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
831             if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
832             if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
833             if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
834             if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
835             if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
836             if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
837             if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
838             if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
839             if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
840             if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
841             if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown,  ");
842         } else {
843             if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
844             if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
845             if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
846             if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
847             if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
848             if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
849             if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
850             if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
851             if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
852             if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
853             if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
854             if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
855             if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
856             if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
857             if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
858             if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
859             if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
860             if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
861             if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
862             if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
863             if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown,  ");
864         }
865         const int len = s.length();
866         if (len > 2) {
867             (void) s.lockBuffer(len);      // needed?
868             s.unlockBuffer(len - 2);       // remove trailing ", "
869         }
870         return s;
871     }
872     case AUDIO_CHANNEL_REPRESENTATION_INDEX:
873         s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
874         return s;
875     default:
876         s.appendFormat("unknown mask, representation:%d  bits:%#x",
877                 representation, audio_channel_mask_get_bits(mask));
878         return s;
879     }
880 }
881 
dump(int fd,const Vector<String16> & args)882 void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
883 {
884     dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
885             this, mThreadName, getTid(), type(), threadTypeToString(type()));
886 
887     bool locked = AudioFlinger::dumpTryLock(mLock);
888     if (!locked) {
889         dprintf(fd, "  Thread may be deadlocked\n");
890     }
891 
892     dumpBase_l(fd, args);
893     dumpInternals_l(fd, args);
894     dumpTracks_l(fd, args);
895     dumpEffectChains_l(fd, args);
896 
897     if (locked) {
898         mLock.unlock();
899     }
900 
901     dprintf(fd, "  Local log:\n");
902     mLocalLog.dump(fd, "   " /* prefix */, 40 /* lines */);
903 }
904 
dumpBase_l(int fd,const Vector<String16> & args __unused)905 void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
906 {
907     dprintf(fd, "  I/O handle: %d\n", mId);
908     dprintf(fd, "  Standby: %s\n", mStandby ? "yes" : "no");
909     dprintf(fd, "  Sample rate: %u Hz\n", mSampleRate);
910     dprintf(fd, "  HAL frame count: %zu\n", mFrameCount);
911     dprintf(fd, "  HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
912     dprintf(fd, "  HAL buffer size: %zu bytes\n", mBufferSize);
913     dprintf(fd, "  Channel count: %u\n", mChannelCount);
914     dprintf(fd, "  Channel mask: 0x%08x (%s)\n", mChannelMask,
915             channelMaskToString(mChannelMask, mType != RECORD).string());
916     dprintf(fd, "  Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
917     dprintf(fd, "  Processing frame size: %zu bytes\n", mFrameSize);
918     dprintf(fd, "  Pending config events:");
919     size_t numConfig = mConfigEvents.size();
920     if (numConfig) {
921         const size_t SIZE = 256;
922         char buffer[SIZE];
923         for (size_t i = 0; i < numConfig; i++) {
924             mConfigEvents[i]->dump(buffer, SIZE);
925             dprintf(fd, "\n    %s", buffer);
926         }
927         dprintf(fd, "\n");
928     } else {
929         dprintf(fd, " none\n");
930     }
931     // Note: output device may be used by capture threads for effects such as AEC.
932     dprintf(fd, "  Output devices: %s (%s)\n",
933             dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
934     dprintf(fd, "  Input device: %#x (%s)\n",
935             inDeviceType(), toString(inDeviceType()).c_str());
936     dprintf(fd, "  Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
937 
938     // Dump timestamp statistics for the Thread types that support it.
939     if (mType == RECORD
940             || mType == MIXER
941             || mType == DUPLICATING
942             || mType == DIRECT
943             || mType == OFFLOAD) {
944         dprintf(fd, "  Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
945         dprintf(fd, "  Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
946     }
947 
948     if (mLastIoBeginNs > 0) { // MMAP may not set this
949         dprintf(fd, "  Last %s occurred (msecs): %lld\n",
950                 isOutput() ? "write" : "read",
951                 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
952     }
953 
954     if (mProcessTimeMs.getN() > 0) {
955         dprintf(fd, "  Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
956     }
957 
958     if (mIoJitterMs.getN() > 0) {
959         dprintf(fd, "  Hal %s jitter ms stats: %s\n",
960                 isOutput() ? "write" : "read",
961                 mIoJitterMs.toString().c_str());
962     }
963 
964     if (mLatencyMs.getN() > 0) {
965         dprintf(fd, "  Threadloop %s latency stats: %s\n",
966                 isOutput() ? "write" : "read",
967                 mLatencyMs.toString().c_str());
968     }
969 }
970 
dumpEffectChains_l(int fd,const Vector<String16> & args)971 void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
972 {
973     const size_t SIZE = 256;
974     char buffer[SIZE];
975 
976     size_t numEffectChains = mEffectChains.size();
977     snprintf(buffer, SIZE, "  %zu Effect Chains\n", numEffectChains);
978     write(fd, buffer, strlen(buffer));
979 
980     for (size_t i = 0; i < numEffectChains; ++i) {
981         sp<EffectChain> chain = mEffectChains[i];
982         if (chain != 0) {
983             chain->dump(fd, args);
984         }
985     }
986 }
987 
acquireWakeLock()988 void AudioFlinger::ThreadBase::acquireWakeLock()
989 {
990     Mutex::Autolock _l(mLock);
991     acquireWakeLock_l();
992 }
993 
getWakeLockTag()994 String16 AudioFlinger::ThreadBase::getWakeLockTag()
995 {
996     switch (mType) {
997     case MIXER:
998         return String16("AudioMix");
999     case DIRECT:
1000         return String16("AudioDirectOut");
1001     case DUPLICATING:
1002         return String16("AudioDup");
1003     case RECORD:
1004         return String16("AudioIn");
1005     case OFFLOAD:
1006         return String16("AudioOffload");
1007     case MMAP_PLAYBACK:
1008         return String16("MmapPlayback");
1009     case MMAP_CAPTURE:
1010         return String16("MmapCapture");
1011     default:
1012         ALOG_ASSERT(false);
1013         return String16("AudioUnknown");
1014     }
1015 }
1016 
acquireWakeLock_l()1017 void AudioFlinger::ThreadBase::acquireWakeLock_l()
1018 {
1019     getPowerManager_l();
1020     if (mPowerManager != 0) {
1021         sp<IBinder> binder = new BBinder();
1022         // Uses AID_AUDIOSERVER for wakelock.  updateWakeLockUids_l() updates with client uids.
1023         binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1024                     POWERMANAGER_PARTIAL_WAKE_LOCK,
1025                     getWakeLockTag(),
1026                     String16("audioserver"),
1027                     {} /* workSource */,
1028                     {} /* historyTag */);
1029         if (status.isOk()) {
1030             mWakeLockToken = binder;
1031         }
1032         ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
1033     }
1034 
1035     gBoottime.acquire(mWakeLockToken);
1036     mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1037             gBoottime.getBoottimeOffset();
1038 }
1039 
releaseWakeLock()1040 void AudioFlinger::ThreadBase::releaseWakeLock()
1041 {
1042     Mutex::Autolock _l(mLock);
1043     releaseWakeLock_l();
1044 }
1045 
releaseWakeLock_l()1046 void AudioFlinger::ThreadBase::releaseWakeLock_l()
1047 {
1048     gBoottime.release(mWakeLockToken);
1049     if (mWakeLockToken != 0) {
1050         ALOGV("releaseWakeLock_l() %s", mThreadName);
1051         if (mPowerManager != 0) {
1052             mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
1053         }
1054         mWakeLockToken.clear();
1055     }
1056 }
1057 
getPowerManager_l()1058 void AudioFlinger::ThreadBase::getPowerManager_l() {
1059     if (mSystemReady && mPowerManager == 0) {
1060         // use checkService() to avoid blocking if power service is not up yet
1061         sp<IBinder> binder =
1062             defaultServiceManager()->checkService(String16("power"));
1063         if (binder == 0) {
1064             ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
1065         } else {
1066             mPowerManager = interface_cast<os::IPowerManager>(binder);
1067             binder->linkToDeath(mDeathRecipient);
1068         }
1069     }
1070 }
1071 
updateWakeLockUids_l(const SortedVector<uid_t> & uids)1072 void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
1073     getPowerManager_l();
1074 
1075 #if !LOG_NDEBUG
1076     std::stringstream s;
1077     for (uid_t uid : uids) {
1078         s << uid << " ";
1079     }
1080     ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1081 #endif
1082 
1083     if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1084         if (mSystemReady) {
1085             ALOGE("no wake lock to update, but system ready!");
1086         } else {
1087             ALOGW("no wake lock to update, system not ready yet");
1088         }
1089         return;
1090     }
1091     if (mPowerManager != 0) {
1092         std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
1093         binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1094                 mWakeLockToken, uidsAsInt);
1095         ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
1096     }
1097 }
1098 
clearPowerManager()1099 void AudioFlinger::ThreadBase::clearPowerManager()
1100 {
1101     Mutex::Autolock _l(mLock);
1102     releaseWakeLock_l();
1103     mPowerManager.clear();
1104 }
1105 
updateOutDevices(const DeviceDescriptorBaseVector & outDevices __unused)1106 void AudioFlinger::ThreadBase::updateOutDevices(
1107         const DeviceDescriptorBaseVector& outDevices __unused)
1108 {
1109     ALOGE("%s should only be called in RecordThread", __func__);
1110 }
1111 
resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)1112 void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1113 {
1114     ALOGE("%s should only be called in RecordThread", __func__);
1115 }
1116 
binderDied(const wp<IBinder> & who __unused)1117 void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
1118 {
1119     sp<ThreadBase> thread = mThread.promote();
1120     if (thread != 0) {
1121         thread->clearPowerManager();
1122     }
1123     ALOGW("power manager service died !!!");
1124 }
1125 
setEffectSuspended_l(const effect_uuid_t * type,bool suspend,audio_session_t sessionId)1126 void AudioFlinger::ThreadBase::setEffectSuspended_l(
1127         const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
1128 {
1129     sp<EffectChain> chain = getEffectChain_l(sessionId);
1130     if (chain != 0) {
1131         if (type != NULL) {
1132             chain->setEffectSuspended_l(type, suspend);
1133         } else {
1134             chain->setEffectSuspendedAll_l(suspend);
1135         }
1136     }
1137 
1138     updateSuspendedSessions_l(type, suspend, sessionId);
1139 }
1140 
checkSuspendOnAddEffectChain_l(const sp<EffectChain> & chain)1141 void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1142 {
1143     ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1144     if (index < 0) {
1145         return;
1146     }
1147 
1148     const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1149             mSuspendedSessions.valueAt(index);
1150 
1151     for (size_t i = 0; i < sessionEffects.size(); i++) {
1152         const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
1153         for (int j = 0; j < desc->mRefCount; j++) {
1154             if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1155                 chain->setEffectSuspendedAll_l(true);
1156             } else {
1157                 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1158                     desc->mType.timeLow);
1159                 chain->setEffectSuspended_l(&desc->mType, true);
1160             }
1161         }
1162     }
1163 }
1164 
updateSuspendedSessions_l(const effect_uuid_t * type,bool suspend,audio_session_t sessionId)1165 void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1166                                                          bool suspend,
1167                                                          audio_session_t sessionId)
1168 {
1169     ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1170 
1171     KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1172 
1173     if (suspend) {
1174         if (index >= 0) {
1175             sessionEffects = mSuspendedSessions.valueAt(index);
1176         } else {
1177             mSuspendedSessions.add(sessionId, sessionEffects);
1178         }
1179     } else {
1180         if (index < 0) {
1181             return;
1182         }
1183         sessionEffects = mSuspendedSessions.valueAt(index);
1184     }
1185 
1186 
1187     int key = EffectChain::kKeyForSuspendAll;
1188     if (type != NULL) {
1189         key = type->timeLow;
1190     }
1191     index = sessionEffects.indexOfKey(key);
1192 
1193     sp<SuspendedSessionDesc> desc;
1194     if (suspend) {
1195         if (index >= 0) {
1196             desc = sessionEffects.valueAt(index);
1197         } else {
1198             desc = new SuspendedSessionDesc();
1199             if (type != NULL) {
1200                 desc->mType = *type;
1201             }
1202             sessionEffects.add(key, desc);
1203             ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1204         }
1205         desc->mRefCount++;
1206     } else {
1207         if (index < 0) {
1208             return;
1209         }
1210         desc = sessionEffects.valueAt(index);
1211         if (--desc->mRefCount == 0) {
1212             ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1213             sessionEffects.removeItemsAt(index);
1214             if (sessionEffects.isEmpty()) {
1215                 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1216                                  sessionId);
1217                 mSuspendedSessions.removeItem(sessionId);
1218             }
1219         }
1220     }
1221     if (!sessionEffects.isEmpty()) {
1222         mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1223     }
1224 }
1225 
checkSuspendOnEffectEnabled(bool enabled,audio_session_t sessionId,bool threadLocked)1226 void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1227                                                            audio_session_t sessionId,
1228                                                            bool threadLocked) {
1229     if (!threadLocked) {
1230         mLock.lock();
1231     }
1232 
1233     if (mType != RECORD) {
1234         // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1235         // another session. This gives the priority to well behaved effect control panels
1236         // and applications not using global effects.
1237         // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1238         // global effects
1239         if (!audio_is_global_session(sessionId)) {
1240             setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1241         }
1242     }
1243 
1244     if (!threadLocked) {
1245         mLock.unlock();
1246     }
1247 }
1248 
1249 // checkEffectCompatibility_l() must be called with ThreadBase::mLock held
checkEffectCompatibility_l(const effect_descriptor_t * desc,audio_session_t sessionId)1250 status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1251         const effect_descriptor_t *desc, audio_session_t sessionId)
1252 {
1253     // No global output effect sessions on record threads
1254     if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1255             || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1256         ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1257                 desc->name, mThreadName);
1258         return BAD_VALUE;
1259     }
1260     // only pre processing effects on record thread
1261     if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1262         ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1263                 desc->name, mThreadName);
1264         return BAD_VALUE;
1265     }
1266 
1267     // always allow effects without processing load or latency
1268     if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1269         return NO_ERROR;
1270     }
1271 
1272     audio_input_flags_t flags = mInput->flags;
1273     if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1274         if (flags & AUDIO_INPUT_FLAG_RAW) {
1275             ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1276                   desc->name, mThreadName);
1277             return BAD_VALUE;
1278         }
1279         if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1280             ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1281                   desc->name, mThreadName);
1282             return BAD_VALUE;
1283         }
1284     }
1285 
1286     if (EffectModule::isHapticGenerator(&desc->type)) {
1287         ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1288         return BAD_VALUE;
1289     }
1290     return NO_ERROR;
1291 }
1292 
1293 // checkEffectCompatibility_l() must be called with ThreadBase::mLock held
checkEffectCompatibility_l(const effect_descriptor_t * desc,audio_session_t sessionId)1294 status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1295         const effect_descriptor_t *desc, audio_session_t sessionId)
1296 {
1297     // no preprocessing on playback threads
1298     if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1299         ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1300                 " thread %s", desc->name, mThreadName);
1301         return BAD_VALUE;
1302     }
1303 
1304     // always allow effects without processing load or latency
1305     if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1306         return NO_ERROR;
1307     }
1308 
1309     if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1310         ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1311                 __func__);
1312         return BAD_VALUE;
1313     }
1314 
1315     switch (mType) {
1316     case MIXER: {
1317 #ifndef MULTICHANNEL_EFFECT_CHAIN
1318         // Reject any effect on mixer multichannel sinks.
1319         // TODO: fix both format and multichannel issues with effects.
1320         if (mChannelCount != FCC_2) {
1321             ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1322                     " thread %s", desc->name, mChannelCount, mThreadName);
1323             return BAD_VALUE;
1324         }
1325 #endif
1326         audio_output_flags_t flags = mOutput->flags;
1327         if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1328             if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1329                 // global effects are applied only to non fast tracks if they are SW
1330                 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1331                     break;
1332                 }
1333             } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1334                 // only post processing on output stage session
1335                 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1336                     ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1337                             " on output stage session", desc->name);
1338                     return BAD_VALUE;
1339                 }
1340             } else if (sessionId == AUDIO_SESSION_DEVICE) {
1341                 // only post processing on output stage session
1342                 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1343                     ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1344                             " on device session", desc->name);
1345                     return BAD_VALUE;
1346                 }
1347             } else {
1348                 // no restriction on effects applied on non fast tracks
1349                 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1350                     break;
1351                 }
1352             }
1353 
1354             if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1355                 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1356                       desc->name);
1357                 return BAD_VALUE;
1358             }
1359             if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1360                 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1361                         " in fast mode", desc->name);
1362                 return BAD_VALUE;
1363             }
1364         }
1365     } break;
1366     case OFFLOAD:
1367         // nothing actionable on offload threads, if the effect:
1368         //   - is offloadable: the effect can be created
1369         //   - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1370         //     will take care of invalidating the tracks of the thread
1371         break;
1372     case DIRECT:
1373         // Reject any effect on Direct output threads for now, since the format of
1374         // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1375         ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1376                 desc->name, mThreadName);
1377         return BAD_VALUE;
1378     case DUPLICATING:
1379 #ifndef MULTICHANNEL_EFFECT_CHAIN
1380         // Reject any effect on mixer multichannel sinks.
1381         // TODO: fix both format and multichannel issues with effects.
1382         if (mChannelCount != FCC_2) {
1383             ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1384                     " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1385             return BAD_VALUE;
1386         }
1387 #endif
1388         if (audio_is_global_session(sessionId)) {
1389             ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1390                     " thread %s", desc->name, mThreadName);
1391             return BAD_VALUE;
1392         }
1393         if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1394             ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1395                     " DUPLICATING thread %s", desc->name, mThreadName);
1396             return BAD_VALUE;
1397         }
1398         if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1399             ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1400                     " DUPLICATING thread %s", desc->name, mThreadName);
1401             return BAD_VALUE;
1402         }
1403         break;
1404     default:
1405         LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1406     }
1407 
1408     return NO_ERROR;
1409 }
1410 
1411 // ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
createEffect_l(const sp<AudioFlinger::Client> & client,const sp<IEffectClient> & effectClient,int32_t priority,audio_session_t sessionId,effect_descriptor_t * desc,int * enabled,status_t * status,bool pinned,bool probe)1412 sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1413         const sp<AudioFlinger::Client>& client,
1414         const sp<IEffectClient>& effectClient,
1415         int32_t priority,
1416         audio_session_t sessionId,
1417         effect_descriptor_t *desc,
1418         int *enabled,
1419         status_t *status,
1420         bool pinned,
1421         bool probe)
1422 {
1423     sp<EffectModule> effect;
1424     sp<EffectHandle> handle;
1425     status_t lStatus;
1426     sp<EffectChain> chain;
1427     bool chainCreated = false;
1428     bool effectCreated = false;
1429     audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
1430 
1431     lStatus = initCheck();
1432     if (lStatus != NO_ERROR) {
1433         ALOGW("createEffect_l() Audio driver not initialized.");
1434         goto Exit;
1435     }
1436 
1437     ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1438 
1439     { // scope for mLock
1440         Mutex::Autolock _l(mLock);
1441 
1442         lStatus = checkEffectCompatibility_l(desc, sessionId);
1443         if (probe || lStatus != NO_ERROR) {
1444             goto Exit;
1445         }
1446 
1447         // check for existing effect chain with the requested audio session
1448         chain = getEffectChain_l(sessionId);
1449         if (chain == 0) {
1450             // create a new chain for this session
1451             ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1452             chain = new EffectChain(this, sessionId);
1453             addEffectChain_l(chain);
1454             chain->setStrategy(getStrategyForSession_l(sessionId));
1455             chainCreated = true;
1456         } else {
1457             effect = chain->getEffectFromDesc_l(desc);
1458         }
1459 
1460         ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1461 
1462         if (effect == 0) {
1463             effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
1464             // create a new effect module if none present in the chain
1465             lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
1466             if (lStatus != NO_ERROR) {
1467                 goto Exit;
1468             }
1469             effectCreated = true;
1470 
1471             // FIXME: use vector of device and address when effect interface is ready.
1472             effect->setDevices(outDeviceTypeAddrs());
1473             effect->setInputDevice(inDeviceTypeAddr());
1474             effect->setMode(mAudioFlinger->getMode());
1475             effect->setAudioSource(mAudioSource);
1476         }
1477         if (effect->isHapticGenerator()) {
1478             // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1479             // for the HapticGenerator.
1480             const media::AudioVibratorInfo* defaultVibratorInfo =
1481                     mAudioFlinger->getDefaultVibratorInfo_l();
1482             if (defaultVibratorInfo != nullptr) {
1483                 // Only set the vibrator info when it is a valid one.
1484                 effect->setVibratorInfo(defaultVibratorInfo);
1485             }
1486         }
1487         // create effect handle and connect it to effect module
1488         handle = new EffectHandle(effect, client, effectClient, priority);
1489         lStatus = handle->initCheck();
1490         if (lStatus == OK) {
1491             lStatus = effect->addHandle(handle.get());
1492         }
1493         if (enabled != NULL) {
1494             *enabled = (int)effect->isEnabled();
1495         }
1496     }
1497 
1498 Exit:
1499     if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1500         Mutex::Autolock _l(mLock);
1501         if (effectCreated) {
1502             chain->removeEffect_l(effect);
1503         }
1504         if (chainCreated) {
1505             removeEffectChain_l(chain);
1506         }
1507         // handle must be cleared by caller to avoid deadlock.
1508     }
1509 
1510     *status = lStatus;
1511     return handle;
1512 }
1513 
disconnectEffectHandle(EffectHandle * handle,bool unpinIfLast)1514 void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1515                                                       bool unpinIfLast)
1516 {
1517     bool remove = false;
1518     sp<EffectModule> effect;
1519     {
1520         Mutex::Autolock _l(mLock);
1521         sp<EffectBase> effectBase = handle->effect().promote();
1522         if (effectBase == nullptr) {
1523             return;
1524         }
1525         effect = effectBase->asEffectModule();
1526         if (effect == nullptr) {
1527             return;
1528         }
1529         // restore suspended effects if the disconnected handle was enabled and the last one.
1530         remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1531         if (remove) {
1532             removeEffect_l(effect, true);
1533         }
1534     }
1535     if (remove) {
1536         mAudioFlinger->updateOrphanEffectChains(effect);
1537         if (handle->enabled()) {
1538             effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
1539         }
1540     }
1541 }
1542 
onEffectEnable(const sp<EffectModule> & effect)1543 void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
1544     if (isOffloadOrMmap()) {
1545         Mutex::Autolock _l(mLock);
1546         broadcast_l();
1547     }
1548     if (!effect->isOffloadable()) {
1549         if (mType == ThreadBase::OFFLOAD) {
1550             PlaybackThread *t = (PlaybackThread *)this;
1551             t->invalidateTracks(AUDIO_STREAM_MUSIC);
1552         }
1553         if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1554             mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1555         }
1556     }
1557 }
1558 
onEffectDisable()1559 void AudioFlinger::ThreadBase::onEffectDisable() {
1560     if (isOffloadOrMmap()) {
1561         Mutex::Autolock _l(mLock);
1562         broadcast_l();
1563     }
1564 }
1565 
getEffect(audio_session_t sessionId,int effectId)1566 sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1567         int effectId)
1568 {
1569     Mutex::Autolock _l(mLock);
1570     return getEffect_l(sessionId, effectId);
1571 }
1572 
getEffect_l(audio_session_t sessionId,int effectId)1573 sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1574         int effectId)
1575 {
1576     sp<EffectChain> chain = getEffectChain_l(sessionId);
1577     return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1578 }
1579 
getEffectIds_l(audio_session_t sessionId)1580 std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1581 {
1582     sp<EffectChain> chain = getEffectChain_l(sessionId);
1583     return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1584 }
1585 
1586 // PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1587 // PlaybackThread::mLock held
addEffect_l(const sp<EffectModule> & effect)1588 status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1589 {
1590     // check for existing effect chain with the requested audio session
1591     audio_session_t sessionId = effect->sessionId();
1592     sp<EffectChain> chain = getEffectChain_l(sessionId);
1593     bool chainCreated = false;
1594 
1595     ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1596              "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
1597                     this, effect->desc().name, effect->desc().flags);
1598 
1599     if (chain == 0) {
1600         // create a new chain for this session
1601         ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1602         chain = new EffectChain(this, sessionId);
1603         addEffectChain_l(chain);
1604         chain->setStrategy(getStrategyForSession_l(sessionId));
1605         chainCreated = true;
1606     }
1607     ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1608 
1609     if (chain->getEffectFromId_l(effect->id()) != 0) {
1610         ALOGW("addEffect_l() %p effect %s already present in chain %p",
1611                 this, effect->desc().name, chain.get());
1612         return BAD_VALUE;
1613     }
1614 
1615     effect->setOffloaded(mType == OFFLOAD, mId);
1616 
1617     status_t status = chain->addEffect_l(effect);
1618     if (status != NO_ERROR) {
1619         if (chainCreated) {
1620             removeEffectChain_l(chain);
1621         }
1622         return status;
1623     }
1624 
1625     effect->setDevices(outDeviceTypeAddrs());
1626     effect->setInputDevice(inDeviceTypeAddr());
1627     effect->setMode(mAudioFlinger->getMode());
1628     effect->setAudioSource(mAudioSource);
1629 
1630     return NO_ERROR;
1631 }
1632 
removeEffect_l(const sp<EffectModule> & effect,bool release)1633 void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
1634 
1635     ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
1636     effect_descriptor_t desc = effect->desc();
1637     if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1638         detachAuxEffect_l(effect->id());
1639     }
1640 
1641     sp<EffectChain> chain = effect->getCallback()->chain().promote();
1642     if (chain != 0) {
1643         // remove effect chain if removing last effect
1644         if (chain->removeEffect_l(effect, release) == 0) {
1645             removeEffectChain_l(chain);
1646         }
1647     } else {
1648         ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1649     }
1650 }
1651 
lockEffectChains_l(Vector<sp<AudioFlinger::EffectChain>> & effectChains)1652 void AudioFlinger::ThreadBase::lockEffectChains_l(
1653         Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1654 {
1655     effectChains = mEffectChains;
1656     for (size_t i = 0; i < mEffectChains.size(); i++) {
1657         mEffectChains[i]->lock();
1658     }
1659 }
1660 
unlockEffectChains(const Vector<sp<AudioFlinger::EffectChain>> & effectChains)1661 void AudioFlinger::ThreadBase::unlockEffectChains(
1662         const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1663 {
1664     for (size_t i = 0; i < effectChains.size(); i++) {
1665         effectChains[i]->unlock();
1666     }
1667 }
1668 
getEffectChain(audio_session_t sessionId)1669 sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
1670 {
1671     Mutex::Autolock _l(mLock);
1672     return getEffectChain_l(sessionId);
1673 }
1674 
getEffectChain_l(audio_session_t sessionId) const1675 sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1676         const
1677 {
1678     size_t size = mEffectChains.size();
1679     for (size_t i = 0; i < size; i++) {
1680         if (mEffectChains[i]->sessionId() == sessionId) {
1681             return mEffectChains[i];
1682         }
1683     }
1684     return 0;
1685 }
1686 
setMode(audio_mode_t mode)1687 void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1688 {
1689     Mutex::Autolock _l(mLock);
1690     size_t size = mEffectChains.size();
1691     for (size_t i = 0; i < size; i++) {
1692         mEffectChains[i]->setMode_l(mode);
1693     }
1694 }
1695 
toAudioPortConfig(struct audio_port_config * config)1696 void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
1697 {
1698     config->type = AUDIO_PORT_TYPE_MIX;
1699     config->ext.mix.handle = mId;
1700     config->sample_rate = mSampleRate;
1701     config->format = mFormat;
1702     config->channel_mask = mChannelMask;
1703     config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1704                             AUDIO_PORT_CONFIG_FORMAT;
1705 }
1706 
systemReady()1707 void AudioFlinger::ThreadBase::systemReady()
1708 {
1709     Mutex::Autolock _l(mLock);
1710     if (mSystemReady) {
1711         return;
1712     }
1713     mSystemReady = true;
1714 
1715     for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1716         sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1717     }
1718     mPendingConfigEvents.clear();
1719 }
1720 
1721 template <typename T>
add(const sp<T> & track)1722 ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1723     ssize_t index = mActiveTracks.indexOf(track);
1724     if (index >= 0) {
1725         ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1726         return index;
1727     }
1728     logTrack("add", track);
1729     mActiveTracksGeneration++;
1730     mLatestActiveTrack = track;
1731     ++mBatteryCounter[track->uid()].second;
1732     mHasChanged = true;
1733     return mActiveTracks.add(track);
1734 }
1735 
1736 template <typename T>
remove(const sp<T> & track)1737 ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1738     ssize_t index = mActiveTracks.remove(track);
1739     if (index < 0) {
1740         ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1741         return index;
1742     }
1743     logTrack("remove", track);
1744     mActiveTracksGeneration++;
1745     --mBatteryCounter[track->uid()].second;
1746     // mLatestActiveTrack is not cleared even if is the same as track.
1747     mHasChanged = true;
1748 #ifdef TEE_SINK
1749     track->dumpTee(-1 /* fd */, "_REMOVE");
1750 #endif
1751     track->logEndInterval(); // log to MediaMetrics
1752     return index;
1753 }
1754 
1755 template <typename T>
clear()1756 void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1757     for (const sp<T> &track : mActiveTracks) {
1758         BatteryNotifier::getInstance().noteStopAudio(track->uid());
1759         logTrack("clear", track);
1760     }
1761     mLastActiveTracksGeneration = mActiveTracksGeneration;
1762     if (!mActiveTracks.empty()) { mHasChanged = true; }
1763     mActiveTracks.clear();
1764     mLatestActiveTrack.clear();
1765     mBatteryCounter.clear();
1766 }
1767 
1768 template <typename T>
updatePowerState(sp<ThreadBase> thread,bool force)1769 void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1770         sp<ThreadBase> thread, bool force) {
1771     // Updates ActiveTracks client uids to the thread wakelock.
1772     if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1773         thread->updateWakeLockUids_l(getWakeLockUids());
1774         mLastActiveTracksGeneration = mActiveTracksGeneration;
1775     }
1776 
1777     // Updates BatteryNotifier uids
1778     for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1779         const uid_t uid = it->first;
1780         ssize_t &previous = it->second.first;
1781         ssize_t &current = it->second.second;
1782         if (current > 0) {
1783             if (previous == 0) {
1784                 BatteryNotifier::getInstance().noteStartAudio(uid);
1785             }
1786             previous = current;
1787             ++it;
1788         } else if (current == 0) {
1789             if (previous > 0) {
1790                 BatteryNotifier::getInstance().noteStopAudio(uid);
1791             }
1792             it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1793         } else /* (current < 0) */ {
1794             LOG_ALWAYS_FATAL("negative battery count %zd", current);
1795         }
1796     }
1797 }
1798 
1799 template <typename T>
readAndClearHasChanged()1800 bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1801     bool hasChanged = mHasChanged;
1802     mHasChanged = false;
1803 
1804     for (const sp<T> &track : mActiveTracks) {
1805         // Do not short-circuit as all hasChanged states must be reset
1806         // as all the metadata are going to be sent
1807         hasChanged |= track->readAndClearHasChanged();
1808     }
1809     return hasChanged;
1810 }
1811 
1812 template <typename T>
logTrack(const char * funcName,const sp<T> & track) const1813 void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1814         const char *funcName, const sp<T> &track) const {
1815     if (mLocalLog != nullptr) {
1816         String8 result;
1817         track->appendDump(result, false /* active */);
1818         mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1819     }
1820 }
1821 
broadcast_l()1822 void AudioFlinger::ThreadBase::broadcast_l()
1823 {
1824     // Thread could be blocked waiting for async
1825     // so signal it to handle state changes immediately
1826     // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1827     // be lost so we also flag to prevent it blocking on mWaitWorkCV
1828     mSignalPending = true;
1829     mWaitWorkCV.broadcast();
1830 }
1831 
1832 // Call only from threadLoop() or when it is idle.
1833 // Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
sendStatistics(bool force)1834 void AudioFlinger::ThreadBase::sendStatistics(bool force)
1835 {
1836     // Do not log if we have no stats.
1837     // We choose the timestamp verifier because it is the most likely item to be present.
1838     const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1839     if (nstats == 0) {
1840         return;
1841     }
1842 
1843     // Don't log more frequently than once per 12 hours.
1844     // We use BOOTTIME to include suspend time.
1845     const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1846     const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1847     if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1848         return;
1849     }
1850 
1851     mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1852     mLastRecordedTimeNs = timeNs;
1853 
1854     std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
1855 
1856 #define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1857 
1858     // thread configuration
1859     item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1860     // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1861     item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1862     item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1863     item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1864     item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1865     item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
1866     item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1867     item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
1868 
1869     // thread statistics
1870     if (mIoJitterMs.getN() > 0) {
1871         item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1872         item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1873     }
1874     if (mProcessTimeMs.getN() > 0) {
1875         item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1876         item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1877     }
1878     const auto tsjitter = mTimestampVerifier.getJitterMs();
1879     if (tsjitter.getN() > 0) {
1880         item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1881         item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1882     }
1883     if (mLatencyMs.getN() > 0) {
1884         item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1885         item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1886     }
1887 
1888     item->selfrecord();
1889 }
1890 
1891 // ----------------------------------------------------------------------------
1892 //      Playback
1893 // ----------------------------------------------------------------------------
1894 
PlaybackThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,type_t type,bool systemReady)1895 AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1896                                              AudioStreamOut* output,
1897                                              audio_io_handle_t id,
1898                                              type_t type,
1899                                              bool systemReady)
1900     :   ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
1901         mNormalFrameCount(0), mSinkBuffer(NULL),
1902         mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
1903         mMixerBuffer(NULL),
1904         mMixerBufferSize(0),
1905         mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1906         mMixerBufferValid(false),
1907         mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
1908         mEffectBuffer(NULL),
1909         mEffectBufferSize(0),
1910         mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1911         mEffectBufferValid(false),
1912         mSuspended(0), mBytesWritten(0),
1913         mFramesWritten(0),
1914         mSuspendedFrames(0),
1915         mActiveTracks(&this->mLocalLog),
1916         // mStreamTypes[] initialized in constructor body
1917         mTracks(type == MIXER),
1918         mOutput(output),
1919         mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1920         mMixerStatus(MIXER_IDLE),
1921         mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1922         mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
1923         mBytesRemaining(0),
1924         mCurrentWriteLength(0),
1925         mUseAsyncWrite(false),
1926         mWriteAckSequence(0),
1927         mDrainSequence(0),
1928         mScreenState(AudioFlinger::mScreenState),
1929         // index 0 is reserved for normal mixer's submix
1930         mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
1931         mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1932         mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1933         mDownStreamPatch{}
1934 {
1935     snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1936     mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
1937 
1938     // Assumes constructor is called by AudioFlinger with it's mLock held, but
1939     // it would be safer to explicitly pass initial masterVolume/masterMute as
1940     // parameter.
1941     //
1942     // If the HAL we are using has support for master volume or master mute,
1943     // then do not attenuate or mute during mixing (just leave the volume at 1.0
1944     // and the mute set to false).
1945     mMasterVolume = audioFlinger->masterVolume_l();
1946     mMasterMute = audioFlinger->masterMute_l();
1947     if (mOutput->audioHwDev) {
1948         if (mOutput->audioHwDev->canSetMasterVolume()) {
1949             mMasterVolume = 1.0;
1950         }
1951 
1952         if (mOutput->audioHwDev->canSetMasterMute()) {
1953             mMasterMute = false;
1954         }
1955         mIsMsdDevice = strcmp(
1956                 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
1957     }
1958 
1959     readOutputParameters_l();
1960 
1961     // TODO: We may also match on address as well as device type for
1962     // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
1963     if (type == MIXER || type == DIRECT || type == OFFLOAD) {
1964         // TODO: This property should be ensure that only contains one single device type.
1965         mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1966                 "audio.timestamp.corrected_output_device",
1967                 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1968                                        : AUDIO_DEVICE_NONE));
1969     }
1970 
1971     for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
1972         const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
1973         mStreamTypes[stream].volume = 0.0f;
1974         mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1975     }
1976     // Audio patch and call assistant volume are always max
1977     mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1978     mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
1979     mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
1980     mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
1981 }
1982 
~PlaybackThread()1983 AudioFlinger::PlaybackThread::~PlaybackThread()
1984 {
1985     mAudioFlinger->unregisterWriter(mNBLogWriter);
1986     free(mSinkBuffer);
1987     free(mMixerBuffer);
1988     free(mEffectBuffer);
1989 }
1990 
1991 // Thread virtuals
1992 
onFirstRef()1993 void AudioFlinger::PlaybackThread::onFirstRef()
1994 {
1995     if (!isStreamInitialized()) {
1996         ALOGE("The stream is not open yet"); // This should not happen.
1997     } else {
1998         // setEventCallback will need a strong pointer as a parameter. Calling it
1999         // here instead of constructor of PlaybackThread so that the onFirstRef
2000         // callback would not be made on an incompletely constructed object.
2001         if (mOutput->stream->setEventCallback(this) != OK) {
2002             ALOGD("Failed to add event callback");
2003         }
2004     }
2005     run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
2006 }
2007 
2008 // ThreadBase virtuals
preExit()2009 void AudioFlinger::PlaybackThread::preExit()
2010 {
2011     ALOGV("  preExit()");
2012     // FIXME this is using hard-coded strings but in the future, this functionality will be
2013     //       converted to use audio HAL extensions required to support tunneling
2014     status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2015     ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2016 }
2017 
dumpTracks_l(int fd,const Vector<String16> & args __unused)2018 void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
2019 {
2020     String8 result;
2021 
2022     result.appendFormat("  Stream volumes in dB: ");
2023     for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2024         const stream_type_t *st = &mStreamTypes[i];
2025         if (i > 0) {
2026             result.appendFormat(", ");
2027         }
2028         result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2029         if (st->mute) {
2030             result.append("M");
2031         }
2032     }
2033     result.append("\n");
2034     write(fd, result.string(), result.length());
2035     result.clear();
2036 
2037     // These values are "raw"; they will wrap around.  See prepareTracks_l() for a better way.
2038     FastTrackUnderruns underruns = getFastTrackUnderruns(0);
2039     dprintf(fd, "  Normal mixer raw underrun counters: partial=%u empty=%u\n",
2040             underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
2041 
2042     size_t numtracks = mTracks.size();
2043     size_t numactive = mActiveTracks.size();
2044     dprintf(fd, "  %zu Tracks", numtracks);
2045     size_t numactiveseen = 0;
2046     const char *prefix = "    ";
2047     if (numtracks) {
2048         dprintf(fd, " of which %zu are active\n", numactive);
2049         result.append(prefix);
2050         mTracks[0]->appendDumpHeader(result);
2051         for (size_t i = 0; i < numtracks; ++i) {
2052             sp<Track> track = mTracks[i];
2053             if (track != 0) {
2054                 bool active = mActiveTracks.indexOf(track) >= 0;
2055                 if (active) {
2056                     numactiveseen++;
2057                 }
2058                 result.append(prefix);
2059                 track->appendDump(result, active);
2060             }
2061         }
2062     } else {
2063         result.append("\n");
2064     }
2065     if (numactiveseen != numactive) {
2066         // some tracks in the active list were not in the tracks list
2067         result.append("  The following tracks are in the active list but"
2068                 " not in the track list\n");
2069         result.append(prefix);
2070         mActiveTracks[0]->appendDumpHeader(result);
2071         for (size_t i = 0; i < numactive; ++i) {
2072             sp<Track> track = mActiveTracks[i];
2073             if (mTracks.indexOf(track) < 0) {
2074                 result.append(prefix);
2075                 track->appendDump(result, true /* active */);
2076             }
2077         }
2078     }
2079 
2080     write(fd, result.string(), result.size());
2081 }
2082 
dumpInternals_l(int fd,const Vector<String16> & args __unused)2083 void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
2084 {
2085     dprintf(fd, "  Master volume: %f\n", mMasterVolume);
2086     dprintf(fd, "  Master mute: %s\n", mMasterMute ? "on" : "off");
2087     if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2088         dprintf(fd, "  Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2089                 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2090     }
2091     dprintf(fd, "  Normal frame count: %zu\n", mNormalFrameCount);
2092     dprintf(fd, "  Total writes: %d\n", mNumWrites);
2093     dprintf(fd, "  Delayed writes: %d\n", mNumDelayedWrites);
2094     dprintf(fd, "  Blocked in write: %s\n", mInWrite ? "yes" : "no");
2095     dprintf(fd, "  Suspend count: %d\n", mSuspended);
2096     dprintf(fd, "  Sink buffer : %p\n", mSinkBuffer);
2097     dprintf(fd, "  Mixer buffer: %p\n", mMixerBuffer);
2098     dprintf(fd, "  Effect buffer: %p\n", mEffectBuffer);
2099     dprintf(fd, "  Fast track availMask=%#x\n", mFastTrackAvailMask);
2100     dprintf(fd, "  Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
2101     AudioStreamOut *output = mOutput;
2102     audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
2103     dprintf(fd, "  AudioStreamOut: %p flags %#x (%s)\n",
2104             output, flags, toString(flags).c_str());
2105     dprintf(fd, "  Frames written: %lld\n", (long long)mFramesWritten);
2106     dprintf(fd, "  Suspended frames: %lld\n", (long long)mSuspendedFrames);
2107     if (mPipeSink.get() != nullptr) {
2108         dprintf(fd, "  PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2109     }
2110     if (output != nullptr) {
2111         dprintf(fd, "  Hal stream dump:\n");
2112         (void)output->stream->dump(fd);
2113     }
2114 }
2115 
2116 // PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
createTrack_l(const sp<AudioFlinger::Client> & client,audio_stream_type_t streamType,const audio_attributes_t & attr,uint32_t * pSampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t * pFrameCount,size_t * pNotificationFrameCount,uint32_t notificationsPerBuffer,float speed,const sp<IMemory> & sharedBuffer,audio_session_t sessionId,audio_output_flags_t * flags,pid_t creatorPid,const AttributionSourceState & attributionSource,pid_t tid,status_t * status,audio_port_handle_t portId,const sp<media::IAudioTrackCallback> & callback)2117 sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2118         const sp<AudioFlinger::Client>& client,
2119         audio_stream_type_t streamType,
2120         const audio_attributes_t& attr,
2121         uint32_t *pSampleRate,
2122         audio_format_t format,
2123         audio_channel_mask_t channelMask,
2124         size_t *pFrameCount,
2125         size_t *pNotificationFrameCount,
2126         uint32_t notificationsPerBuffer,
2127         float speed,
2128         const sp<IMemory>& sharedBuffer,
2129         audio_session_t sessionId,
2130         audio_output_flags_t *flags,
2131         pid_t creatorPid,
2132         const AttributionSourceState& attributionSource,
2133         pid_t tid,
2134         status_t *status,
2135         audio_port_handle_t portId,
2136         const sp<media::IAudioTrackCallback>& callback)
2137 {
2138     size_t frameCount = *pFrameCount;
2139     size_t notificationFrameCount = *pNotificationFrameCount;
2140     sp<Track> track;
2141     status_t lStatus;
2142     audio_output_flags_t outputFlags = mOutput->flags;
2143     audio_output_flags_t requestedFlags = *flags;
2144     uint32_t sampleRate;
2145 
2146     if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2147         lStatus = BAD_VALUE;
2148         goto Exit;
2149     }
2150 
2151     if (*pSampleRate == 0) {
2152         *pSampleRate = mSampleRate;
2153     }
2154     sampleRate = *pSampleRate;
2155 
2156     // special case for FAST flag considered OK if fast mixer is present
2157     if (hasFastMixer()) {
2158         outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2159     }
2160 
2161     // Check if requested flags are compatible with output stream flags
2162     if ((*flags & outputFlags) != *flags) {
2163         ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2164               *flags, outputFlags);
2165         *flags = (audio_output_flags_t)(*flags & outputFlags);
2166     }
2167 
2168     // client expresses a preference for FAST, but we get the final say
2169     if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2170       if (
2171             // PCM data
2172             audio_is_linear_pcm(format) &&
2173             // TODO: extract as a data library function that checks that a computationally
2174             // expensive downmixer is not required: isFastOutputChannelConversion()
2175             (channelMask == (mChannelMask | mHapticChannelMask) ||
2176                     mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2177                     (channelMask == AUDIO_CHANNEL_OUT_MONO
2178                             /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
2179             // hardware sample rate
2180             (sampleRate == mSampleRate) &&
2181             // normal mixer has an associated fast mixer
2182             hasFastMixer() &&
2183             // there are sufficient fast track slots available
2184             (mFastTrackAvailMask != 0)
2185             // FIXME test that MixerThread for this fast track has a capable output HAL
2186             // FIXME add a permission test also?
2187         ) {
2188         // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2189         if (sharedBuffer == 0) {
2190             // read the fast track multiplier property the first time it is needed
2191             int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2192             if (ok != 0) {
2193                 ALOGE("%s pthread_once failed: %d", __func__, ok);
2194             }
2195             frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
2196         }
2197 
2198         // check compatibility with audio effects.
2199         { // scope for mLock
2200             Mutex::Autolock _l(mLock);
2201             for (audio_session_t session : {
2202                     AUDIO_SESSION_DEVICE,
2203                     AUDIO_SESSION_OUTPUT_STAGE,
2204                     AUDIO_SESSION_OUTPUT_MIX,
2205                     sessionId,
2206                 }) {
2207                 sp<EffectChain> chain = getEffectChain_l(session);
2208                 if (chain.get() != nullptr) {
2209                     audio_output_flags_t old = *flags;
2210                     chain->checkOutputFlagCompatibility(flags);
2211                     if (old != *flags) {
2212                         ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2213                                 (int)session, (int)old, (int)*flags);
2214                     }
2215                 }
2216             }
2217         }
2218         ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
2219                  "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2220                  frameCount, mFrameCount);
2221       } else {
2222         ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2223                 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
2224                 "sampleRate=%u mSampleRate=%u "
2225                 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
2226                 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
2227                 audio_is_linear_pcm(format), channelMask, sampleRate,
2228                 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
2229         *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
2230       }
2231     }
2232 
2233     if (!audio_has_proportional_frames(format)) {
2234         if (sharedBuffer != 0) {
2235             // Same comment as below about ignoring frameCount parameter for set()
2236             frameCount = sharedBuffer->size();
2237         } else if (frameCount == 0) {
2238             frameCount = mNormalFrameCount;
2239         }
2240         if (notificationFrameCount != frameCount) {
2241             notificationFrameCount = frameCount;
2242         }
2243     } else if (sharedBuffer != 0) {
2244         // FIXME: Ensure client side memory buffers need
2245         // not have additional alignment beyond sample
2246         // (e.g. 16 bit stereo accessed as 32 bit frame).
2247         size_t alignment = audio_bytes_per_sample(format);
2248         if (alignment & 1) {
2249             // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2250             alignment = 1;
2251         }
2252         uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2253         size_t frameSize = channelCount * audio_bytes_per_sample(format);
2254         if (channelCount > 1) {
2255             // More than 2 channels does not require stronger alignment than stereo
2256             alignment <<= 1;
2257         }
2258         if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
2259             ALOGE("Invalid buffer alignment: address %p, channel count %u",
2260                   sharedBuffer->unsecurePointer(), channelCount);
2261             lStatus = BAD_VALUE;
2262             goto Exit;
2263         }
2264 
2265         // When initializing a shared buffer AudioTrack via constructors,
2266         // there's no frameCount parameter.
2267         // But when initializing a shared buffer AudioTrack via set(),
2268         // there _is_ a frameCount parameter.  We silently ignore it.
2269         frameCount = sharedBuffer->size() / frameSize;
2270     } else {
2271         size_t minFrameCount = 0;
2272         // For fast tracks we try to respect the application's request for notifications per buffer.
2273         if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2274             if (notificationsPerBuffer > 0) {
2275                 // Avoid possible arithmetic overflow during multiplication.
2276                 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2277                     ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2278                           notificationsPerBuffer, mFrameCount);
2279                 } else {
2280                     minFrameCount = mFrameCount * notificationsPerBuffer;
2281                 }
2282             }
2283         } else {
2284             // For normal PCM streaming tracks, update minimum frame count.
2285             // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2286             // cover audio hardware latency.
2287             // This is probably too conservative, but legacy application code may depend on it.
2288             // If you change this calculation, also review the start threshold which is related.
2289             uint32_t latencyMs = latency_l();
2290             if (latencyMs == 0) {
2291                 ALOGE("Error when retrieving output stream latency");
2292                 lStatus = UNKNOWN_ERROR;
2293                 goto Exit;
2294             }
2295 
2296             minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2297                                 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2298 
2299         }
2300         if (frameCount < minFrameCount) {
2301             frameCount = minFrameCount;
2302         }
2303     }
2304 
2305     // Make sure that application is notified with sufficient margin before underrun.
2306     // The client can divide the AudioTrack buffer into sub-buffers,
2307     // and expresses its desire to server as the notification frame count.
2308     if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2309         size_t maxNotificationFrames;
2310         if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2311             // notify every HAL buffer, regardless of the size of the track buffer
2312             maxNotificationFrames = mFrameCount;
2313         } else {
2314             // Triple buffer the notification period for a triple buffered mixer period;
2315             // otherwise, double buffering for the notification period is fine.
2316             //
2317             // TODO: This should be moved to AudioTrack to modify the notification period
2318             // on AudioTrack::setBufferSizeInFrames() changes.
2319             const int nBuffering =
2320                     (uint64_t{frameCount} * mSampleRate)
2321                             / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2322 
2323             maxNotificationFrames = frameCount / nBuffering;
2324             // If client requested a fast track but this was denied, then use the smaller maximum.
2325             if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2326                 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2327                 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2328                     maxNotificationFrames = maxNotificationFramesFastDenied;
2329                 }
2330             }
2331         }
2332         if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2333             if (notificationFrameCount == 0) {
2334                 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2335                     maxNotificationFrames, frameCount);
2336             } else {
2337                 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2338                       notificationFrameCount, maxNotificationFrames, frameCount);
2339             }
2340             notificationFrameCount = maxNotificationFrames;
2341         }
2342     }
2343 
2344     *pFrameCount = frameCount;
2345     *pNotificationFrameCount = notificationFrameCount;
2346 
2347     switch (mType) {
2348 
2349     case DIRECT:
2350         if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
2351             if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2352                 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2353                         "for output %p with format %#x",
2354                         sampleRate, format, channelMask, mOutput, mFormat);
2355                 lStatus = BAD_VALUE;
2356                 goto Exit;
2357             }
2358         }
2359         break;
2360 
2361     case OFFLOAD:
2362         if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2363             ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2364                     "for output %p with format %#x",
2365                     sampleRate, format, channelMask, mOutput, mFormat);
2366             lStatus = BAD_VALUE;
2367             goto Exit;
2368         }
2369         break;
2370 
2371     default:
2372         if (!audio_is_linear_pcm(format)) {
2373                 ALOGE("createTrack_l() Bad parameter: format %#x \""
2374                         "for output %p with format %#x",
2375                         format, mOutput, mFormat);
2376                 lStatus = BAD_VALUE;
2377                 goto Exit;
2378         }
2379         if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
2380             ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2381             lStatus = BAD_VALUE;
2382             goto Exit;
2383         }
2384         break;
2385 
2386     }
2387 
2388     lStatus = initCheck();
2389     if (lStatus != NO_ERROR) {
2390         ALOGE("createTrack_l() audio driver not initialized");
2391         goto Exit;
2392     }
2393 
2394     { // scope for mLock
2395         Mutex::Autolock _l(mLock);
2396 
2397         // all tracks in same audio session must share the same routing strategy otherwise
2398         // conflicts will happen when tracks are moved from one output to another by audio policy
2399         // manager
2400         product_strategy_t strategy = AudioSystem::getStrategyForStream(streamType);
2401         for (size_t i = 0; i < mTracks.size(); ++i) {
2402             sp<Track> t = mTracks[i];
2403             if (t != 0 && t->isExternalTrack()) {
2404                 product_strategy_t actual = AudioSystem::getStrategyForStream(t->streamType());
2405                 if (sessionId == t->sessionId() && strategy != actual) {
2406                     ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2407                             strategy, actual);
2408                     lStatus = BAD_VALUE;
2409                     goto Exit;
2410                 }
2411             }
2412         }
2413 
2414         // Set DIRECT flag if current thread is DirectOutputThread. This can
2415         // happen when the playback is rerouted to direct output thread by
2416         // dynamic audio policy.
2417         // Do NOT report the flag changes back to client, since the client
2418         // doesn't explicitly request a direct flag.
2419         audio_output_flags_t trackFlags = *flags;
2420         if (mType == DIRECT) {
2421             trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2422         }
2423 
2424         track = new Track(this, client, streamType, attr, sampleRate, format,
2425                           channelMask, frameCount,
2426                           nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
2427                           sessionId, creatorPid, attributionSource, trackFlags,
2428                           TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/, speed);
2429 
2430         lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2431         if (lStatus != NO_ERROR) {
2432             ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
2433             // track must be cleared from the caller as the caller has the AF lock
2434             goto Exit;
2435         }
2436         mTracks.add(track);
2437         {
2438             Mutex::Autolock _atCbL(mAudioTrackCbLock);
2439             if (callback.get() != nullptr) {
2440                 mAudioTrackCallbacks.emplace(track, callback);
2441             }
2442         }
2443 
2444         sp<EffectChain> chain = getEffectChain_l(sessionId);
2445         if (chain != 0) {
2446             ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2447             track->setMainBuffer(chain->inBuffer());
2448             chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2449             chain->incTrackCnt();
2450         }
2451 
2452         if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
2453             pid_t callingPid = IPCThreadState::self()->getCallingPid();
2454             // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2455             // so ask activity manager to do this on our behalf
2456             sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
2457         }
2458     }
2459 
2460     lStatus = NO_ERROR;
2461 
2462 Exit:
2463     *status = lStatus;
2464     return track;
2465 }
2466 
2467 template<typename T>
remove(const sp<T> & track)2468 ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2469 {
2470     const int trackId = track->id();
2471     const ssize_t index = mTracks.remove(track);
2472     if (index >= 0) {
2473         if (mSaveDeletedTrackIds) {
2474             // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2475             // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
2476             // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2477             mDeletedTrackIds.emplace(trackId);
2478         }
2479     }
2480     return index;
2481 }
2482 
correctLatency_l(uint32_t latency) const2483 uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2484 {
2485     return latency;
2486 }
2487 
latency() const2488 uint32_t AudioFlinger::PlaybackThread::latency() const
2489 {
2490     Mutex::Autolock _l(mLock);
2491     return latency_l();
2492 }
latency_l() const2493 uint32_t AudioFlinger::PlaybackThread::latency_l() const
2494 {
2495     uint32_t latency;
2496     if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2497         return correctLatency_l(latency);
2498     }
2499     return 0;
2500 }
2501 
setMasterVolume(float value)2502 void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2503 {
2504     Mutex::Autolock _l(mLock);
2505     // Don't apply master volume in SW if our HAL can do it for us.
2506     if (mOutput && mOutput->audioHwDev &&
2507         mOutput->audioHwDev->canSetMasterVolume()) {
2508         mMasterVolume = 1.0;
2509     } else {
2510         mMasterVolume = value;
2511     }
2512 }
2513 
setMasterBalance(float balance)2514 void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2515 {
2516     mMasterBalance.store(balance);
2517 }
2518 
setMasterMute(bool muted)2519 void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2520 {
2521     if (isDuplicating()) {
2522         return;
2523     }
2524     Mutex::Autolock _l(mLock);
2525     // Don't apply master mute in SW if our HAL can do it for us.
2526     if (mOutput && mOutput->audioHwDev &&
2527         mOutput->audioHwDev->canSetMasterMute()) {
2528         mMasterMute = false;
2529     } else {
2530         mMasterMute = muted;
2531     }
2532 }
2533 
setStreamVolume(audio_stream_type_t stream,float value)2534 void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2535 {
2536     Mutex::Autolock _l(mLock);
2537     mStreamTypes[stream].volume = value;
2538     broadcast_l();
2539 }
2540 
setStreamMute(audio_stream_type_t stream,bool muted)2541 void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2542 {
2543     Mutex::Autolock _l(mLock);
2544     mStreamTypes[stream].mute = muted;
2545     broadcast_l();
2546 }
2547 
streamVolume(audio_stream_type_t stream) const2548 float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2549 {
2550     Mutex::Autolock _l(mLock);
2551     return mStreamTypes[stream].volume;
2552 }
2553 
setVolumeForOutput_l(float left,float right) const2554 void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2555 {
2556     mOutput->stream->setVolume(left, right);
2557 }
2558 
2559 // addTrack_l() must be called with ThreadBase::mLock held
addTrack_l(const sp<Track> & track)2560 status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2561 {
2562     status_t status = ALREADY_EXISTS;
2563 
2564     if (mActiveTracks.indexOf(track) < 0) {
2565         // the track is newly added, make sure it fills up all its
2566         // buffers before playing. This is to ensure the client will
2567         // effectively get the latency it requested.
2568         if (track->isExternalTrack()) {
2569             TrackBase::track_state state = track->mState;
2570             mLock.unlock();
2571             status = AudioSystem::startOutput(track->portId());
2572             mLock.lock();
2573             // abort track was stopped/paused while we released the lock
2574             if (state != track->mState) {
2575                 if (status == NO_ERROR) {
2576                     mLock.unlock();
2577                     AudioSystem::stopOutput(track->portId());
2578                     mLock.lock();
2579                 }
2580                 return INVALID_OPERATION;
2581             }
2582             // abort if start is rejected by audio policy manager
2583             if (status != NO_ERROR) {
2584                 return PERMISSION_DENIED;
2585             }
2586 #ifdef ADD_BATTERY_DATA
2587             // to track the speaker usage
2588             addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2589 #endif
2590             sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
2591         }
2592 
2593         // set retry count for buffer fill
2594         if (track->isOffloaded()) {
2595             if (track->isStopping_1()) {
2596                 track->mRetryCount = kMaxTrackStopRetriesOffload;
2597             } else {
2598                 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2599             }
2600             track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
2601         } else {
2602             track->mRetryCount = kMaxTrackStartupRetries;
2603             track->mFillingUpStatus =
2604                     track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
2605         }
2606 
2607         sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2608         if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2609                 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2610                         || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
2611             // Unlock due to VibratorService will lock for this call and will
2612             // call Tracks.mute/unmute which also require thread's lock.
2613             mLock.unlock();
2614             const int intensity = AudioFlinger::onExternalVibrationStart(
2615                     track->getExternalVibration());
2616             mLock.lock();
2617             track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
2618             // Haptic playback should be enabled by vibrator service.
2619             if (track->getHapticPlaybackEnabled()) {
2620                 // Disable haptic playback of all active track to ensure only
2621                 // one track playing haptic if current track should play haptic.
2622                 for (const auto &t : mActiveTracks) {
2623                     t->setHapticPlaybackEnabled(false);
2624                 }
2625             }
2626 
2627             // Set haptic intensity for effect
2628             if (chain != nullptr) {
2629                 chain->setHapticIntensity_l(track->id(), intensity);
2630             }
2631         }
2632 
2633         track->mResetDone = false;
2634         track->resetPresentationComplete();
2635         mActiveTracks.add(track);
2636         if (chain != 0) {
2637             ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2638                     track->sessionId());
2639             chain->incActiveTrackCnt();
2640         }
2641 
2642         track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
2643         status = NO_ERROR;
2644     }
2645 
2646     onAddNewTrack_l();
2647     return status;
2648 }
2649 
destroyTrack_l(const sp<Track> & track)2650 bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
2651 {
2652     track->terminate();
2653     // active tracks are removed by threadLoop()
2654     bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2655     track->mState = TrackBase::STOPPED;
2656     if (!trackActive) {
2657         removeTrack_l(track);
2658     } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
2659         track->mState = TrackBase::STOPPING_1;
2660     }
2661 
2662     return trackActive;
2663 }
2664 
removeTrack_l(const sp<Track> & track)2665 void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2666 {
2667     track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2668 
2669     String8 result;
2670     track->appendDump(result, false /* active */);
2671     mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
2672 
2673     mTracks.remove(track);
2674     {
2675         Mutex::Autolock _atCbL(mAudioTrackCbLock);
2676         mAudioTrackCallbacks.erase(track);
2677     }
2678     if (track->isFastTrack()) {
2679         int index = track->mFastIndex;
2680         ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
2681         ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2682         mFastTrackAvailMask |= 1 << index;
2683         // redundant as track is about to be destroyed, for dumpsys only
2684         track->mFastIndex = -1;
2685     }
2686     sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2687     if (chain != 0) {
2688         chain->decTrackCnt();
2689     }
2690 }
2691 
getParameters(const String8 & keys)2692 String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2693 {
2694     Mutex::Autolock _l(mLock);
2695     String8 out_s8;
2696     if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2697         return out_s8;
2698     }
2699     return String8();
2700 }
2701 
selectPresentation(int presentationId,int programId)2702 status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2703     Mutex::Autolock _l(mLock);
2704     if (!isStreamInitialized()) {
2705         return NO_INIT;
2706     }
2707     return mOutput->stream->selectPresentation(presentationId, programId);
2708 }
2709 
ioConfigChanged(audio_io_config_event event,pid_t pid,audio_port_handle_t portId)2710 void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2711                                                    audio_port_handle_t portId) {
2712     sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2713     ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
2714 
2715     desc->mIoHandle = mId;
2716     struct audio_patch patch = mPatch;
2717     if (isMsdDevice()) {
2718         patch = mDownStreamPatch;
2719     }
2720 
2721     switch (event) {
2722     case AUDIO_OUTPUT_OPENED:
2723     case AUDIO_OUTPUT_REGISTERED:
2724     case AUDIO_OUTPUT_CONFIG_CHANGED:
2725         desc->mPatch = patch;
2726         desc->mChannelMask = mChannelMask;
2727         desc->mSamplingRate = mSampleRate;
2728         desc->mFormat = mFormat;
2729         desc->mFrameCount = mNormalFrameCount; // FIXME see
2730                                              // AudioFlinger::frameCount(audio_io_handle_t)
2731         desc->mFrameCountHAL = mFrameCount;
2732         desc->mLatency = latency_l();
2733         break;
2734     case AUDIO_CLIENT_STARTED:
2735         desc->mPatch = patch;
2736         desc->mPortId = portId;
2737         break;
2738     case AUDIO_OUTPUT_CLOSED:
2739     default:
2740         break;
2741     }
2742     mAudioFlinger->ioConfigChanged(event, desc, pid);
2743 }
2744 
onWriteReady()2745 void AudioFlinger::PlaybackThread::onWriteReady()
2746 {
2747     mCallbackThread->resetWriteBlocked();
2748 }
2749 
onDrainReady()2750 void AudioFlinger::PlaybackThread::onDrainReady()
2751 {
2752     mCallbackThread->resetDraining();
2753 }
2754 
onError()2755 void AudioFlinger::PlaybackThread::onError()
2756 {
2757     mCallbackThread->setAsyncError();
2758 }
2759 
onCodecFormatChanged(const std::basic_string<uint8_t> & metadataBs)2760 void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2761         const std::basic_string<uint8_t>& metadataBs)
2762 {
2763     std::thread([this, metadataBs]() {
2764             audio_utils::metadata::Data metadata =
2765                     audio_utils::metadata::dataFromByteString(metadataBs);
2766             if (metadata.empty()) {
2767                 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2768                       reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2769                       (int)metadataBs.size());
2770                 return;
2771             }
2772 
2773             audio_utils::metadata::ByteString metaDataStr =
2774                     audio_utils::metadata::byteStringFromData(metadata);
2775             std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2776             Mutex::Autolock _l(mAudioTrackCbLock);
2777             for (const auto& callbackPair : mAudioTrackCallbacks) {
2778                 callbackPair.second->onCodecFormatChanged(metadataVec);
2779             }
2780     }).detach();
2781 }
2782 
resetWriteBlocked(uint32_t sequence)2783 void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
2784 {
2785     Mutex::Autolock _l(mLock);
2786     // reject out of sequence requests
2787     if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2788         mWriteAckSequence &= ~1;
2789         mWaitWorkCV.signal();
2790     }
2791 }
2792 
resetDraining(uint32_t sequence)2793 void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
2794 {
2795     Mutex::Autolock _l(mLock);
2796     // reject out of sequence requests
2797     if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2798         // Register discontinuity when HW drain is completed because that can cause
2799         // the timestamp frame position to reset to 0 for direct and offload threads.
2800         // (Out of sequence requests are ignored, since the discontinuity would be handled
2801         // elsewhere, e.g. in flush).
2802         mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
2803         mDrainSequence &= ~1;
2804         mWaitWorkCV.signal();
2805     }
2806 }
2807 
readOutputParameters_l()2808 void AudioFlinger::PlaybackThread::readOutputParameters_l()
2809 {
2810     // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
2811     const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2812     mSampleRate = audioConfig.sample_rate;
2813     mChannelMask = audioConfig.channel_mask;
2814     if (!audio_is_output_channel(mChannelMask)) {
2815         LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
2816     }
2817     if ((mType == MIXER || mType == DUPLICATING)
2818             && !isValidPcmSinkChannelMask(mChannelMask)) {
2819         LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2820                 mChannelMask);
2821     }
2822     mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
2823     mBalance.setChannelMask(mChannelMask);
2824 
2825     // Get actual HAL format.
2826     status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
2827     LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
2828     // Get format from the shim, which will be different than the HAL format
2829     // if playing compressed audio over HDMI passthrough.
2830     mFormat = audioConfig.format;
2831     if (!audio_is_valid_format(mFormat)) {
2832         LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
2833     }
2834     if ((mType == MIXER || mType == DUPLICATING)
2835             && !isValidPcmSinkFormat(mFormat)) {
2836         LOG_FATAL("HAL format %#x not supported for mixed output",
2837                 mFormat);
2838     }
2839     mFrameSize = mOutput->getFrameSize();
2840     result = mOutput->stream->getBufferSize(&mBufferSize);
2841     LOG_ALWAYS_FATAL_IF(result != OK,
2842             "Error when retrieving output stream buffer size: %d", result);
2843     mFrameCount = mBufferSize / mFrameSize;
2844     if ((mType == MIXER || mType == DUPLICATING) && (mFrameCount & 15)) {
2845         ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
2846                 mFrameCount);
2847     }
2848 
2849     if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2850         if (mOutput->stream->setCallback(this) == OK) {
2851             mUseAsyncWrite = true;
2852             mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
2853         }
2854     }
2855 
2856     mHwSupportsPause = false;
2857     if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2858         bool supportsPause = false, supportsResume = false;
2859         if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2860             if (supportsPause && supportsResume) {
2861                 mHwSupportsPause = true;
2862             } else if (supportsPause) {
2863                 ALOGW("direct output implements pause but not resume");
2864             } else if (supportsResume) {
2865                 ALOGW("direct output implements resume but not pause");
2866             }
2867         }
2868     }
2869     if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2870         LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2871     }
2872 
2873     if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2874         // For best precision, we use float instead of the associated output
2875         // device format (typically PCM 16 bit).
2876 
2877         mFormat = AUDIO_FORMAT_PCM_FLOAT;
2878         mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2879         mBufferSize = mFrameSize * mFrameCount;
2880 
2881         // TODO: We currently use the associated output device channel mask and sample rate.
2882         // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2883         // (if a valid mask) to avoid premature downmix.
2884         // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2885         // instead of the output device sample rate to avoid loss of high frequency information.
2886         // This may need to be updated as MixerThread/OutputTracks are added and not here.
2887     }
2888 
2889     // Calculate size of normal sink buffer relative to the HAL output buffer size
2890     double multiplier = 1.0;
2891     if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2892             kUseFastMixer == FastMixer_Dynamic)) {
2893         size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2894         size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
2895 
2896         // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2897         minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2898         maxNormalFrameCount = maxNormalFrameCount & ~15;
2899         if (maxNormalFrameCount < minNormalFrameCount) {
2900             maxNormalFrameCount = minNormalFrameCount;
2901         }
2902         multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2903         if (multiplier <= 1.0) {
2904             multiplier = 1.0;
2905         } else if (multiplier <= 2.0) {
2906             if (2 * mFrameCount <= maxNormalFrameCount) {
2907                 multiplier = 2.0;
2908             } else {
2909                 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2910             }
2911         } else {
2912             multiplier = floor(multiplier);
2913         }
2914     }
2915     mNormalFrameCount = multiplier * mFrameCount;
2916     // round up to nearest 16 frames to satisfy AudioMixer
2917     if (mType == MIXER || mType == DUPLICATING) {
2918         mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2919     }
2920     ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
2921             mNormalFrameCount);
2922 
2923     // Check if we want to throttle the processing to no more than 2x normal rate
2924     mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
2925     mThreadThrottleTimeMs = 0;
2926     mThreadThrottleEndMs = 0;
2927     mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2928 
2929     // mSinkBuffer is the sink buffer.  Size is always multiple-of-16 frames.
2930     // Originally this was int16_t[] array, need to remove legacy implications.
2931     free(mSinkBuffer);
2932     mSinkBuffer = NULL;
2933     // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2934     // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2935     const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2936     (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2937 
2938     // We resize the mMixerBuffer according to the requirements of the sink buffer which
2939     // drives the output.
2940     free(mMixerBuffer);
2941     mMixerBuffer = NULL;
2942     if (mMixerBufferEnabled) {
2943         mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
2944         mMixerBufferSize = mNormalFrameCount * mChannelCount
2945                 * audio_bytes_per_sample(mMixerBufferFormat);
2946         (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2947     }
2948     free(mEffectBuffer);
2949     mEffectBuffer = NULL;
2950     if (mEffectBufferEnabled) {
2951         mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
2952         mEffectBufferSize = mNormalFrameCount * mChannelCount
2953                 * audio_bytes_per_sample(mEffectBufferFormat);
2954         (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2955     }
2956 
2957     mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2958     mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
2959     mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2960     mChannelCount -= mHapticChannelCount;
2961 
2962     // force reconfiguration of effect chains and engines to take new buffer size and audio
2963     // parameters into account
2964     // Note that mLock is not held when readOutputParameters_l() is called from the constructor
2965     // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2966     // matter.
2967     // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2968     Vector< sp<EffectChain> > effectChains = mEffectChains;
2969     for (size_t i = 0; i < effectChains.size(); i ++) {
2970         mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2971             this/* srcThread */, this/* dstThread */);
2972     }
2973 
2974     audio_output_flags_t flags = mOutput->flags;
2975     mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
2976     item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
2977         .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
2978         .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
2979         .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
2980         .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
2981         .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
2982         .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
2983         .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
2984                 (int32_t)mHapticChannelMask)
2985         .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
2986                 (int32_t)mHapticChannelCount)
2987         .set(AMEDIAMETRICS_PROP_PREFIX_HAL    AMEDIAMETRICS_PROP_ENCODING,
2988                 formatToString(mHALFormat).c_str())
2989         .set(AMEDIAMETRICS_PROP_PREFIX_HAL    AMEDIAMETRICS_PROP_FRAMECOUNT,
2990                 (int32_t)mFrameCount) // sic - added HAL
2991         ;
2992     uint32_t latencyMs;
2993     if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
2994         item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
2995     }
2996     item.record();
2997 }
2998 
updateMetadata_l()2999 void AudioFlinger::PlaybackThread::updateMetadata_l()
3000 {
3001     if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
3002         return; // nothing to do
3003     }
3004     StreamOutHalInterface::SourceMetadata metadata;
3005     auto backInserter = std::back_inserter(metadata.tracks);
3006     for (const sp<Track> &track : mActiveTracks) {
3007         // No track is invalid as this is called after prepareTrack_l in the same critical section
3008         // Do not forward metadata for PatchTrack with unspecified stream type
3009         if (track->streamType() != AUDIO_STREAM_PATCH) {
3010             track->copyMetadataTo(backInserter);
3011         }
3012     }
3013     sendMetadataToBackend_l(metadata);
3014 }
3015 
sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata & metadata)3016 void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3017         const StreamOutHalInterface::SourceMetadata& metadata)
3018 {
3019     mOutput->stream->updateSourceMetadata(metadata);
3020 };
3021 
getRenderPosition(uint32_t * halFrames,uint32_t * dspFrames)3022 status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
3023 {
3024     if (halFrames == NULL || dspFrames == NULL) {
3025         return BAD_VALUE;
3026     }
3027     Mutex::Autolock _l(mLock);
3028     if (initCheck() != NO_ERROR) {
3029         return INVALID_OPERATION;
3030     }
3031     int64_t framesWritten = mBytesWritten / mFrameSize;
3032     *halFrames = framesWritten;
3033 
3034     if (isSuspended()) {
3035         // return an estimation of rendered frames when the output is suspended
3036         size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
3037         *dspFrames = (uint32_t)
3038                 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
3039         return NO_ERROR;
3040     } else {
3041         status_t status;
3042         uint32_t frames;
3043         status = mOutput->getRenderPosition(&frames);
3044         *dspFrames = (size_t)frames;
3045         return status;
3046     }
3047 }
3048 
getStrategyForSession_l(audio_session_t sessionId)3049 product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
3050 {
3051     // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3052     // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3053     if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3054         return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3055     }
3056     for (size_t i = 0; i < mTracks.size(); i++) {
3057         sp<Track> track = mTracks[i];
3058         if (sessionId == track->sessionId() && !track->isInvalid()) {
3059             return AudioSystem::getStrategyForStream(track->streamType());
3060         }
3061     }
3062     return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
3063 }
3064 
3065 
getOutput() const3066 AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
3067 {
3068     Mutex::Autolock _l(mLock);
3069     return mOutput;
3070 }
3071 
clearOutput()3072 AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
3073 {
3074     Mutex::Autolock _l(mLock);
3075     AudioStreamOut *output = mOutput;
3076     mOutput = NULL;
3077     // FIXME FastMixer might also have a raw ptr to mOutputSink;
3078     //       must push a NULL and wait for ack
3079     mOutputSink.clear();
3080     mPipeSink.clear();
3081     mNormalSink.clear();
3082     return output;
3083 }
3084 
3085 // this method must always be called either with ThreadBase mLock held or inside the thread loop
stream() const3086 sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
3087 {
3088     if (mOutput == NULL) {
3089         return NULL;
3090     }
3091     return mOutput->stream;
3092 }
3093 
activeSleepTimeUs() const3094 uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3095 {
3096     return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3097 }
3098 
setSyncEvent(const sp<SyncEvent> & event)3099 status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3100 {
3101     if (!isValidSyncEvent(event)) {
3102         return BAD_VALUE;
3103     }
3104 
3105     Mutex::Autolock _l(mLock);
3106 
3107     for (size_t i = 0; i < mTracks.size(); ++i) {
3108         sp<Track> track = mTracks[i];
3109         if (event->triggerSession() == track->sessionId()) {
3110             (void) track->setSyncEvent(event);
3111             return NO_ERROR;
3112         }
3113     }
3114 
3115     return NAME_NOT_FOUND;
3116 }
3117 
isValidSyncEvent(const sp<SyncEvent> & event) const3118 bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3119 {
3120     return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3121 }
3122 
threadLoop_removeTracks(const Vector<sp<Track>> & tracksToRemove)3123 void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3124         const Vector< sp<Track> >& tracksToRemove)
3125 {
3126     // Miscellaneous track cleanup when removed from the active list,
3127     // called without Thread lock but synchronized with threadLoop processing.
3128 #ifdef ADD_BATTERY_DATA
3129     for (const auto& track : tracksToRemove) {
3130         if (track->isExternalTrack()) {
3131             // to track the speaker usage
3132             addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3133         }
3134     }
3135 #else
3136     (void)tracksToRemove; // suppress unused warning
3137 #endif
3138 }
3139 
checkSilentMode_l()3140 void AudioFlinger::PlaybackThread::checkSilentMode_l()
3141 {
3142     if (!mMasterMute) {
3143         char value[PROPERTY_VALUE_MAX];
3144         if (mOutDeviceTypeAddrs.empty()) {
3145             ALOGD("ro.audio.silent is ignored since no output device is set");
3146             return;
3147         }
3148         if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
3149             ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3150             return;
3151         }
3152         if (property_get("ro.audio.silent", value, "0") > 0) {
3153             char *endptr;
3154             unsigned long ul = strtoul(value, &endptr, 0);
3155             if (*endptr == '\0' && ul != 0) {
3156                 ALOGD("Silence is golden");
3157                 // The setprop command will not allow a property to be changed after
3158                 // the first time it is set, so we don't have to worry about un-muting.
3159                 setMasterMute_l(true);
3160             }
3161         }
3162     }
3163 }
3164 
3165 // shared by MIXER and DIRECT, overridden by DUPLICATING
threadLoop_write()3166 ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
3167 {
3168     LOG_HIST_TS();
3169     mInWrite = true;
3170     ssize_t bytesWritten;
3171     const size_t offset = mCurrentWriteLength - mBytesRemaining;
3172 
3173     // If an NBAIO sink is present, use it to write the normal mixer's submix
3174     if (mNormalSink != 0) {
3175 
3176         const size_t count = mBytesRemaining / mFrameSize;
3177 
3178         ATRACE_BEGIN("write");
3179         // update the setpoint when AudioFlinger::mScreenState changes
3180         uint32_t screenState = AudioFlinger::mScreenState;
3181         if (screenState != mScreenState) {
3182             mScreenState = screenState;
3183             MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3184             if (pipe != NULL) {
3185                 pipe->setAvgFrames((mScreenState & 1) ?
3186                         (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3187             }
3188         }
3189         ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
3190         ATRACE_END();
3191         if (framesWritten > 0) {
3192             bytesWritten = framesWritten * mFrameSize;
3193 #ifdef TEE_SINK
3194             mTee.write((char *)mSinkBuffer + offset, framesWritten);
3195 #endif
3196         } else {
3197             bytesWritten = framesWritten;
3198         }
3199     // otherwise use the HAL / AudioStreamOut directly
3200     } else {
3201         // Direct output and offload threads
3202 
3203         if (mUseAsyncWrite) {
3204             ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3205             mWriteAckSequence += 2;
3206             mWriteAckSequence |= 1;
3207             ALOG_ASSERT(mCallbackThread != 0);
3208             mCallbackThread->setWriteBlocked(mWriteAckSequence);
3209         }
3210         ATRACE_BEGIN("write");
3211         // FIXME We should have an implementation of timestamps for direct output threads.
3212         // They are used e.g for multichannel PCM playback over HDMI.
3213         bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
3214         ATRACE_END();
3215 
3216         if (mUseAsyncWrite &&
3217                 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3218             // do not wait for async callback in case of error of full write
3219             mWriteAckSequence &= ~1;
3220             ALOG_ASSERT(mCallbackThread != 0);
3221             mCallbackThread->setWriteBlocked(mWriteAckSequence);
3222         }
3223     }
3224 
3225     mNumWrites++;
3226     mInWrite = false;
3227     if (mStandby) {
3228         mThreadMetrics.logBeginInterval();
3229         mStandby = false;
3230     }
3231     return bytesWritten;
3232 }
3233 
threadLoop_drain()3234 void AudioFlinger::PlaybackThread::threadLoop_drain()
3235 {
3236     bool supportsDrain = false;
3237     if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
3238         ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3239         if (mUseAsyncWrite) {
3240             ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3241             mDrainSequence |= 1;
3242             ALOG_ASSERT(mCallbackThread != 0);
3243             mCallbackThread->setDraining(mDrainSequence);
3244         }
3245         status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
3246         ALOGE_IF(result != OK, "Error when draining stream: %d", result);
3247     }
3248 }
3249 
threadLoop_exit()3250 void AudioFlinger::PlaybackThread::threadLoop_exit()
3251 {
3252     {
3253         Mutex::Autolock _l(mLock);
3254         for (size_t i = 0; i < mTracks.size(); i++) {
3255             sp<Track> track = mTracks[i];
3256             track->invalidate();
3257         }
3258         // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3259         // After we exit there are no more track changes sent to BatteryNotifier
3260         // because that requires an active threadLoop.
3261         // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3262         mActiveTracks.clear();
3263     }
3264 }
3265 
3266 /*
3267 The derived values that are cached:
3268  - mSinkBufferSize from frame count * frame size
3269  - mActiveSleepTimeUs from activeSleepTimeUs()
3270  - mIdleSleepTimeUs from idleSleepTimeUs()
3271  - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3272    kDefaultStandbyTimeInNsecs when connected to an A2DP device.
3273  - maxPeriod from frame count and sample rate (MIXER only)
3274 
3275 The parameters that affect these derived values are:
3276  - frame count
3277  - frame size
3278  - sample rate
3279  - device type: A2DP or not
3280  - device latency
3281  - format: PCM or not
3282  - active sleep time
3283  - idle sleep time
3284 */
3285 
cacheParameters_l()3286 void AudioFlinger::PlaybackThread::cacheParameters_l()
3287 {
3288     mSinkBufferSize = mNormalFrameCount * mFrameSize;
3289     mActiveSleepTimeUs = activeSleepTimeUs();
3290     mIdleSleepTimeUs = idleSleepTimeUs();
3291 
3292     // make sure standby delay is not too short when connected to an A2DP sink to avoid
3293     // truncating audio when going to standby.
3294     mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
3295     if (!Intersection(outDeviceTypes(),  getAudioDeviceOutAllA2dpSet()).empty()) {
3296         if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3297             mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3298         }
3299     }
3300 }
3301 
invalidateTracks_l(audio_stream_type_t streamType)3302 bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
3303 {
3304     ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
3305             this,  streamType, mTracks.size());
3306     bool trackMatch = false;
3307     size_t size = mTracks.size();
3308     for (size_t i = 0; i < size; i++) {
3309         sp<Track> t = mTracks[i];
3310         if (t->streamType() == streamType && t->isExternalTrack()) {
3311             t->invalidate();
3312             trackMatch = true;
3313         }
3314     }
3315     return trackMatch;
3316 }
3317 
invalidateTracks(audio_stream_type_t streamType)3318 void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3319 {
3320     Mutex::Autolock _l(mLock);
3321     invalidateTracks_l(streamType);
3322 }
3323 
3324 // getTrackById_l must be called with holding thread lock
getTrackById_l(audio_port_handle_t trackPortId)3325 AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3326         audio_port_handle_t trackPortId) {
3327     for (size_t i = 0; i < mTracks.size(); i++) {
3328         if (mTracks[i]->portId() == trackPortId) {
3329             return mTracks[i].get();
3330         }
3331     }
3332     return nullptr;
3333 }
3334 
addEffectChain_l(const sp<EffectChain> & chain)3335 status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3336 {
3337     audio_session_t session = chain->sessionId();
3338     sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
3339     status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3340             mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3341             mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3342             &halInBuffer);
3343     if (result != OK) return result;
3344     halOutBuffer = halInBuffer;
3345     effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
3346     ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3347     if (!audio_is_global_session(session)) {
3348         // Only one effect chain can be present in direct output thread and it uses
3349         // the sink buffer as input
3350         if (mType != DIRECT) {
3351             size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
3352             status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
3353                     numSamples * sizeof(effect_buffer_t),
3354                     &halInBuffer);
3355             if (result != OK) return result;
3356 #ifdef FLOAT_EFFECT_CHAIN
3357             buffer = halInBuffer->audioBuffer()->f32;
3358 #else
3359             buffer = halInBuffer->audioBuffer()->s16;
3360 #endif
3361             ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3362                     buffer, session);
3363         }
3364 
3365         // Attach all tracks with same session ID to this chain.
3366         for (size_t i = 0; i < mTracks.size(); ++i) {
3367             sp<Track> track = mTracks[i];
3368             if (session == track->sessionId()) {
3369                 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3370                         buffer);
3371                 track->setMainBuffer(buffer);
3372                 chain->incTrackCnt();
3373             }
3374         }
3375 
3376         // indicate all active tracks in the chain
3377         for (const sp<Track> &track : mActiveTracks) {
3378             if (session == track->sessionId()) {
3379                 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3380                 chain->incActiveTrackCnt();
3381             }
3382         }
3383     }
3384     chain->setThread(this);
3385     chain->setInBuffer(halInBuffer);
3386     chain->setOutBuffer(halOutBuffer);
3387     // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3388     // chains list in order to be processed last as it contains output device effects.
3389     // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3390     // processing effects specific to an output stream before effects applied to all streams
3391     // routed to a given device.
3392     // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3393     // session AUDIO_SESSION_OUTPUT_STAGE to be processed
3394     // after track specific effects and before output stage.
3395     // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
3396     // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
3397     // Effect chain for other sessions are inserted at beginning of effect
3398     // chains list to be processed before output mix effects. Relative order between other
3399     // sessions is not important.
3400     static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3401             AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3402             AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
3403             "audio_session_t constants misdefined");
3404     size_t size = mEffectChains.size();
3405     size_t i = 0;
3406     for (i = 0; i < size; i++) {
3407         if (mEffectChains[i]->sessionId() < session) {
3408             break;
3409         }
3410     }
3411     mEffectChains.insertAt(chain, i);
3412     checkSuspendOnAddEffectChain_l(chain);
3413 
3414     return NO_ERROR;
3415 }
3416 
removeEffectChain_l(const sp<EffectChain> & chain)3417 size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3418 {
3419     audio_session_t session = chain->sessionId();
3420 
3421     ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3422 
3423     for (size_t i = 0; i < mEffectChains.size(); i++) {
3424         if (chain == mEffectChains[i]) {
3425             mEffectChains.removeAt(i);
3426             // detach all active tracks from the chain
3427             for (const sp<Track> &track : mActiveTracks) {
3428                 if (session == track->sessionId()) {
3429                     ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3430                             chain.get(), session);
3431                     chain->decActiveTrackCnt();
3432                 }
3433             }
3434 
3435             // detach all tracks with same session ID from this chain
3436             for (size_t i = 0; i < mTracks.size(); ++i) {
3437                 sp<Track> track = mTracks[i];
3438                 if (session == track->sessionId()) {
3439                     track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
3440                     chain->decTrackCnt();
3441                 }
3442             }
3443             break;
3444         }
3445     }
3446     return mEffectChains.size();
3447 }
3448 
attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> & track,int EffectId)3449 status_t AudioFlinger::PlaybackThread::attachAuxEffect(
3450         const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
3451 {
3452     Mutex::Autolock _l(mLock);
3453     return attachAuxEffect_l(track, EffectId);
3454 }
3455 
attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> & track,int EffectId)3456 status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
3457         const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
3458 {
3459     status_t status = NO_ERROR;
3460 
3461     if (EffectId == 0) {
3462         track->setAuxBuffer(0, NULL);
3463     } else {
3464         // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3465         sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3466         if (effect != 0) {
3467             if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3468                 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3469             } else {
3470                 status = INVALID_OPERATION;
3471             }
3472         } else {
3473             status = BAD_VALUE;
3474         }
3475     }
3476     return status;
3477 }
3478 
detachAuxEffect_l(int effectId)3479 void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3480 {
3481     for (size_t i = 0; i < mTracks.size(); ++i) {
3482         sp<Track> track = mTracks[i];
3483         if (track->auxEffectId() == effectId) {
3484             attachAuxEffect_l(track, 0);
3485         }
3486     }
3487 }
3488 
threadLoop()3489 bool AudioFlinger::PlaybackThread::threadLoop()
3490 {
3491     tlNBLogWriter = mNBLogWriter.get();
3492 
3493     Vector< sp<Track> > tracksToRemove;
3494 
3495     mStandbyTimeNs = systemTime();
3496     int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
3497 
3498     // MIXER
3499     nsecs_t lastWarning = 0;
3500 
3501     // DUPLICATING
3502     // FIXME could this be made local to while loop?
3503     writeFrames = 0;
3504 
3505     cacheParameters_l();
3506     mSleepTimeUs = mIdleSleepTimeUs;
3507 
3508     if (mType == MIXER) {
3509         sleepTimeShift = 0;
3510     }
3511 
3512     CpuStats cpuStats;
3513     const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3514 
3515     acquireWakeLock();
3516 
3517     // mNBLogWriter logging APIs can only be called by a single thread, typically the
3518     // thread associated with this PlaybackThread.
3519     // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3520     // then all such threads must agree to hold a common mutex before logging.
3521     // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3522     // and then that string will be logged at the next convenient opportunity.
3523     // See reference to logString below.
3524     const char *logString = NULL;
3525 
3526     // Estimated time for next buffer to be written to hal. This is used only on
3527     // suspended mode (for now) to help schedule the wait time until next iteration.
3528     nsecs_t timeLoopNextNs = 0;
3529 
3530     checkSilentMode_l();
3531 
3532     audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3533 
3534     // loopCount is used for statistics and diagnostics.
3535     for (int64_t loopCount = 0; !exitPending(); ++loopCount)
3536     {
3537         // Log merge requests are performed during AudioFlinger binder transactions, but
3538         // that does not cover audio playback. It's requested here for that reason.
3539         mAudioFlinger->requestLogMerge();
3540 
3541         cpuStats.sample(myName);
3542 
3543         Vector< sp<EffectChain> > effectChains;
3544         audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
3545         std::vector<sp<Track>> activeTracks;
3546 
3547         // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3548         //
3549         // Note: we access outDeviceTypes() outside of mLock.
3550         if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
3551             // Here, we try for the AF lock, but do not block on it as the latency
3552             // is more informational.
3553             if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3554                 std::vector<PatchPanel::SoftwarePatch> swPatches;
3555                 double latencyMs;
3556                 status_t status = INVALID_OPERATION;
3557                 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3558                 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3559                         && swPatches.size() > 0) {
3560                         status = swPatches[0].getLatencyMs_l(&latencyMs);
3561                         downstreamPatchHandle = swPatches[0].getPatchHandle();
3562                 }
3563                 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
3564                     mDownstreamLatencyStatMs.reset();
3565                     lastDownstreamPatchHandle = downstreamPatchHandle;
3566                 }
3567                 if (status == OK) {
3568                     // verify downstream latency (we assume a max reasonable
3569                     // latency of 5 seconds).
3570                     const double minLatency = 0., maxLatency = 5000.;
3571                     if (latencyMs >= minLatency && latencyMs <= maxLatency) {
3572                         ALOGVV("new downstream latency %lf ms", latencyMs);
3573                     } else {
3574                         ALOGD("out of range downstream latency %lf ms", latencyMs);
3575                         if (latencyMs < minLatency) latencyMs = minLatency;
3576                         else if (latencyMs > maxLatency) latencyMs = maxLatency;
3577                     }
3578                     mDownstreamLatencyStatMs.add(latencyMs);
3579                 }
3580                 mAudioFlinger->mLock.unlock();
3581             }
3582         } else {
3583             if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3584                 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
3585                 mDownstreamLatencyStatMs.reset();
3586                 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3587             }
3588         }
3589 
3590         { // scope for mLock
3591 
3592             Mutex::Autolock _l(mLock);
3593 
3594             processConfigEvents_l();
3595 
3596             // See comment at declaration of logString for why this is done under mLock
3597             if (logString != NULL) {
3598                 mNBLogWriter->logTimestamp();
3599                 mNBLogWriter->log(logString);
3600                 logString = NULL;
3601             }
3602 
3603             collectTimestamps_l();
3604 
3605             saveOutputTracks();
3606             if (mSignalPending) {
3607                 // A signal was raised while we were unlocked
3608                 mSignalPending = false;
3609             } else if (waitingAsyncCallback_l()) {
3610                 if (exitPending()) {
3611                     break;
3612                 }
3613                 bool released = false;
3614                 if (!keepWakeLock()) {
3615                     releaseWakeLock_l();
3616                     released = true;
3617                 }
3618 
3619                 const int64_t waitNs = computeWaitTimeNs_l();
3620                 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3621                 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3622                 if (status == TIMED_OUT) {
3623                     mSignalPending = true; // if timeout recheck everything
3624                 }
3625                 ALOGV("async completion/wake");
3626                 if (released) {
3627                     acquireWakeLock_l();
3628                 }
3629                 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3630                 mSleepTimeUs = 0;
3631 
3632                 continue;
3633             }
3634             if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
3635                                    isSuspended()) {
3636                 // put audio hardware into standby after short delay
3637                 if (shouldStandby_l()) {
3638 
3639                     threadLoop_standby();
3640 
3641                     // This is where we go into standby
3642                     if (!mStandby) {
3643                         LOG_AUDIO_STATE();
3644                         mThreadMetrics.logEndInterval();
3645                         mStandby = true;
3646                     }
3647                     sendStatistics(false /* force */);
3648                 }
3649 
3650                 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
3651                     // we're about to wait, flush the binder command buffer
3652                     IPCThreadState::self()->flushCommands();
3653 
3654                     clearOutputTracks();
3655 
3656                     if (exitPending()) {
3657                         break;
3658                     }
3659 
3660                     releaseWakeLock_l();
3661                     // wait until we have something to do...
3662                     ALOGV("%s going to sleep", myName.string());
3663                     mWaitWorkCV.wait(mLock);
3664                     ALOGV("%s waking up", myName.string());
3665                     acquireWakeLock_l();
3666 
3667                     mMixerStatus = MIXER_IDLE;
3668                     mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3669                     mBytesWritten = 0;
3670                     mBytesRemaining = 0;
3671                     checkSilentMode_l();
3672 
3673                     mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3674                     mSleepTimeUs = mIdleSleepTimeUs;
3675                     if (mType == MIXER) {
3676                         sleepTimeShift = 0;
3677                     }
3678 
3679                     continue;
3680                 }
3681             }
3682             // mMixerStatusIgnoringFastTracks is also updated internally
3683             mMixerStatus = prepareTracks_l(&tracksToRemove);
3684 
3685             mActiveTracks.updatePowerState(this);
3686 
3687             updateMetadata_l();
3688 
3689             // prevent any changes in effect chain list and in each effect chain
3690             // during mixing and effect process as the audio buffers could be deleted
3691             // or modified if an effect is created or deleted
3692             lockEffectChains_l(effectChains);
3693 
3694             // Determine which session to pick up haptic data.
3695             // This must be done under the same lock as prepareTracks_l().
3696             // The haptic data from the effect is at a higher priority than the one from track.
3697             // TODO: Write haptic data directly to sink buffer when mixing.
3698             if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3699                 for (const auto& track : mActiveTracks) {
3700                     sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3701                     if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3702                         activeHapticSessionId = track->sessionId();
3703                         break;
3704                     }
3705                     if (track->getHapticPlaybackEnabled()) {
3706                         activeHapticSessionId = track->sessionId();
3707                         break;
3708                     }
3709                 }
3710             }
3711 
3712             // Acquire a local copy of active tracks with lock (release w/o lock).
3713             //
3714             // Control methods on the track acquire the ThreadBase lock (e.g. start()
3715             // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3716             // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3717             activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
3718         } // mLock scope ends
3719 
3720         if (mBytesRemaining == 0) {
3721             mCurrentWriteLength = 0;
3722             if (mMixerStatus == MIXER_TRACKS_READY) {
3723                 // threadLoop_mix() sets mCurrentWriteLength
3724                 threadLoop_mix();
3725             } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3726                         && (mMixerStatus != MIXER_DRAIN_ALL)) {
3727                 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
3728                 // must be written to HAL
3729                 threadLoop_sleepTime();
3730                 if (mSleepTimeUs == 0) {
3731                     mCurrentWriteLength = mSinkBufferSize;
3732 
3733                     // Tally underrun frames as we are inserting 0s here.
3734                     for (const auto& track : activeTracks) {
3735                         if (track->mFillingUpStatus == Track::FS_ACTIVE
3736                                 && !track->isStopped()
3737                                 && !track->isPaused()
3738                                 && !track->isTerminated()) {
3739                             ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3740                                     __func__, track->id(), track->getTrackStateAsString(),
3741                                     mNormalFrameCount);
3742                             track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3743                         }
3744                     }
3745                 }
3746             }
3747             // Either threadLoop_mix() or threadLoop_sleepTime() should have set
3748             // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
3749             // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3750             // or mSinkBuffer (if there are no effects).
3751             //
3752             // This is done pre-effects computation; if effects change to
3753             // support higher precision, this needs to move.
3754             //
3755             // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
3756             // TODO use mSleepTimeUs == 0 as an additional condition.
3757             if (mMixerBufferValid) {
3758                 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3759                 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3760 
3761                 // mono blend occurs for mixer threads only (not direct or offloaded)
3762                 // and is handled here if we're going directly to the sink.
3763                 if (requireMonoBlend() && !mEffectBufferValid) {
3764                     mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3765                                true /*limit*/);
3766                 }
3767 
3768                 if (!hasFastMixer()) {
3769                     // Balance must take effect after mono conversion.
3770                     // We do it here if there is no FastMixer.
3771                     // mBalance detects zero balance within the class for speed (not needed here).
3772                     mBalance.setBalance(mMasterBalance.load());
3773                     mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3774                 }
3775 
3776                 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3777                         mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3778 
3779                 // If we're going directly to the sink and there are haptic channels,
3780                 // we should adjust channels as the sample data is partially interleaved
3781                 // in this case.
3782                 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3783                     adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3784                             mChannelCount + mHapticChannelCount,
3785                             audio_bytes_per_sample(format),
3786                             audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3787                 }
3788             }
3789 
3790             mBytesRemaining = mCurrentWriteLength;
3791             if (isSuspended()) {
3792                 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3793                 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3794                 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3795                 mBytesWritten += mBytesRemaining;
3796                 mFramesWritten += framesRemaining;
3797                 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
3798                 mBytesRemaining = 0;
3799             }
3800 
3801             // only process effects if we're going to write
3802             if (mSleepTimeUs == 0 && mType != OFFLOAD) {
3803                 for (size_t i = 0; i < effectChains.size(); i ++) {
3804                     effectChains[i]->process_l();
3805                     // TODO: Write haptic data directly to sink buffer when mixing.
3806                     if (activeHapticSessionId != AUDIO_SESSION_NONE
3807                             && activeHapticSessionId == effectChains[i]->sessionId()) {
3808                         // Haptic data is active in this case, copy it directly from
3809                         // in buffer to out buffer.
3810                         const size_t audioBufferSize = mNormalFrameCount
3811                                 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3812                         memcpy_by_audio_format(
3813                                 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3814                                 EFFECT_BUFFER_FORMAT,
3815                                 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3816                                 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3817                     }
3818                 }
3819             }
3820         }
3821         // Process effect chains for offloaded thread even if no audio
3822         // was read from audio track: process only updates effect state
3823         // and thus does have to be synchronized with audio writes but may have
3824         // to be called while waiting for async write callback
3825         if (mType == OFFLOAD) {
3826             for (size_t i = 0; i < effectChains.size(); i ++) {
3827                 effectChains[i]->process_l();
3828             }
3829         }
3830 
3831         // Only if the Effects buffer is enabled and there is data in the
3832         // Effects buffer (buffer valid), we need to
3833         // copy into the sink buffer.
3834         // TODO use mSleepTimeUs == 0 as an additional condition.
3835         if (mEffectBufferValid) {
3836             //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
3837 
3838             if (requireMonoBlend()) {
3839                 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3840                            true /*limit*/);
3841             }
3842 
3843             if (!hasFastMixer()) {
3844                 // Balance must take effect after mono conversion.
3845                 // We do it here if there is no FastMixer.
3846                 // mBalance detects zero balance within the class for speed (not needed here).
3847                 mBalance.setBalance(mMasterBalance.load());
3848                 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3849             }
3850 
3851             memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3852                     mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3853             // The sample data is partially interleaved when haptic channels exist,
3854             // we need to adjust channels here.
3855             if (mHapticChannelCount > 0) {
3856                 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3857                         mChannelCount + mHapticChannelCount,
3858                         audio_bytes_per_sample(mFormat),
3859                         audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3860             }
3861         }
3862 
3863         // enable changes in effect chain
3864         unlockEffectChains(effectChains);
3865 
3866         if (!waitingAsyncCallback()) {
3867             // mSleepTimeUs == 0 means we must write to audio hardware
3868             if (mSleepTimeUs == 0) {
3869                 ssize_t ret = 0;
3870                 // writePeriodNs is updated >= 0 when ret > 0.
3871                 int64_t writePeriodNs = -1;
3872                 if (mBytesRemaining) {
3873                     // FIXME rewrite to reduce number of system calls
3874                     const int64_t lastIoBeginNs = systemTime();
3875                     ret = threadLoop_write();
3876                     const int64_t lastIoEndNs = systemTime();
3877                     if (ret < 0) {
3878                         mBytesRemaining = 0;
3879                     } else if (ret > 0) {
3880                         mBytesWritten += ret;
3881                         mBytesRemaining -= ret;
3882                         const int64_t frames = ret / mFrameSize;
3883                         mFramesWritten += frames;
3884 
3885                         writePeriodNs = lastIoEndNs - mLastIoEndNs;
3886                         // process information relating to write time.
3887                         if (audio_has_proportional_frames(mFormat)) {
3888                             // we are in a continuous mixing cycle
3889                             if (mMixerStatus == MIXER_TRACKS_READY &&
3890                                     loopCount == lastLoopCountWritten + 1) {
3891 
3892                                 const double jitterMs =
3893                                         TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3894                                                 {frames, writePeriodNs},
3895                                                 {0, 0} /* lastTimestamp */, mSampleRate);
3896                                 const double processMs =
3897                                        (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3898 
3899                                 Mutex::Autolock _l(mLock);
3900                                 mIoJitterMs.add(jitterMs);
3901                                 mProcessTimeMs.add(processMs);
3902                             }
3903 
3904                             // write blocked detection
3905                             const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3906                             if (mType == MIXER && deltaWriteNs > maxPeriod) {
3907                                 mNumDelayedWrites++;
3908                                 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3909                                     ATRACE_NAME("underrun");
3910                                     ALOGW("write blocked for %lld msecs, "
3911                                             "%d delayed writes, thread %d",
3912                                             (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3913                                             mNumDelayedWrites, mId);
3914                                     lastWarning = lastIoEndNs;
3915                                 }
3916                             }
3917                         }
3918                         // update timing info.
3919                         mLastIoBeginNs = lastIoBeginNs;
3920                         mLastIoEndNs = lastIoEndNs;
3921                         lastLoopCountWritten = loopCount;
3922                     }
3923                 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3924                         (mMixerStatus == MIXER_DRAIN_ALL)) {
3925                     threadLoop_drain();
3926                 }
3927                 if (mType == MIXER && !mStandby) {
3928 
3929                     if (mThreadThrottle
3930                             && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3931                             && writePeriodNs > 0) {               // we have write period info
3932                         // Limit MixerThread data processing to no more than twice the
3933                         // expected processing rate.
3934                         //
3935                         // This helps prevent underruns with NuPlayer and other applications
3936                         // which may set up buffers that are close to the minimum size, or use
3937                         // deep buffers, and rely on a double-buffering sleep strategy to fill.
3938                         //
3939                         // The throttle smooths out sudden large data drains from the device,
3940                         // e.g. when it comes out of standby, which often causes problems with
3941                         // (1) mixer threads without a fast mixer (which has its own warm-up)
3942                         // (2) minimum buffer sized tracks (even if the track is full,
3943                         //     the app won't fill fast enough to handle the sudden draw).
3944                         //
3945                         // Total time spent in last processing cycle equals time spent in
3946                         // 1. threadLoop_write, as well as time spent in
3947                         // 2. threadLoop_mix (significant for heavy mixing, especially
3948                         //                    on low tier processors)
3949 
3950                         // it's OK if deltaMs is an overestimate.
3951 
3952                         const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
3953 
3954                         const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
3955                         if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3956                             mThreadMetrics.logThrottleMs((double)throttleMs);
3957 
3958                             usleep(throttleMs * 1000);
3959                             // notify of throttle start on verbose log
3960                             ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3961                                     "mixer(%p) throttle begin:"
3962                                     " ret(%zd) deltaMs(%d) requires sleep %d ms",
3963                                     this, ret, deltaMs, throttleMs);
3964                             mThreadThrottleTimeMs += throttleMs;
3965                             // Throttle must be attributed to the previous mixer loop's write time
3966                             // to allow back-to-back throttling.
3967                             // This also ensures proper timing statistics.
3968                             mLastIoEndNs = systemTime();  // we fetch the write end time again.
3969                         } else {
3970                             uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3971                             if (diff > 0) {
3972                                 // notify of throttle end on debug log
3973                                 // but prevent spamming for bluetooth
3974                                 ALOGD_IF(!isSingleDeviceType(
3975                                                  outDeviceTypes(), audio_is_a2dp_out_device) &&
3976                                          !isSingleDeviceType(
3977                                                  outDeviceTypes(), audio_is_hearing_aid_out_device),
3978                                         "mixer(%p) throttle end: throttle time(%u)", this, diff);
3979                                 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3980                             }
3981                         }
3982                     }
3983                 }
3984 
3985             } else {
3986                 ATRACE_BEGIN("sleep");
3987                 Mutex::Autolock _l(mLock);
3988                 // suspended requires accurate metering of sleep time.
3989                 if (isSuspended()) {
3990                     // advance by expected sleepTime
3991                     timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3992                     const nsecs_t nowNs = systemTime();
3993 
3994                     // compute expected next time vs current time.
3995                     // (negative deltas are treated as delays).
3996                     nsecs_t deltaNs = timeLoopNextNs - nowNs;
3997                     if (deltaNs < -kMaxNextBufferDelayNs) {
3998                         // Delays longer than the max allowed trigger a reset.
3999                         ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4000                         deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4001                         timeLoopNextNs = nowNs + deltaNs;
4002                     } else if (deltaNs < 0) {
4003                         // Delays within the max delay allowed: zero the delta/sleepTime
4004                         // to help the system catch up in the next iteration(s)
4005                         ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4006                         deltaNs = 0;
4007                     }
4008                     // update sleep time (which is >= 0)
4009                     mSleepTimeUs = deltaNs / 1000;
4010                 }
4011                 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4012                     mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
4013                 }
4014                 ATRACE_END();
4015             }
4016         }
4017 
4018         // Finally let go of removed track(s), without the lock held
4019         // since we can't guarantee the destructors won't acquire that
4020         // same lock.  This will also mutate and push a new fast mixer state.
4021         threadLoop_removeTracks(tracksToRemove);
4022         tracksToRemove.clear();
4023 
4024         // FIXME I don't understand the need for this here;
4025         //       it was in the original code but maybe the
4026         //       assignment in saveOutputTracks() makes this unnecessary?
4027         clearOutputTracks();
4028 
4029         // Effect chains will be actually deleted here if they were removed from
4030         // mEffectChains list during mixing or effects processing
4031         effectChains.clear();
4032 
4033         // FIXME Note that the above .clear() is no longer necessary since effectChains
4034         // is now local to this block, but will keep it for now (at least until merge done).
4035     }
4036 
4037     threadLoop_exit();
4038 
4039     if (!mStandby) {
4040         threadLoop_standby();
4041         mStandby = true;
4042     }
4043 
4044     releaseWakeLock();
4045 
4046     ALOGV("Thread %p type %d exiting", this, mType);
4047     return false;
4048 }
4049 
collectTimestamps_l()4050 void AudioFlinger::PlaybackThread::collectTimestamps_l()
4051 {
4052     // Collect timestamp statistics for the Playback Thread types that support it.
4053     if (mType != MIXER
4054             && mType != DUPLICATING
4055             && mType != DIRECT
4056             && mType != OFFLOAD) {
4057         return;
4058     }
4059     if (mStandby) {
4060         mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4061         return;
4062     } else if (mHwPaused) {
4063         mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4064         return;
4065     }
4066 
4067     // Gather the framesReleased counters for all active tracks,
4068     // and associate with the sink frames written out.  We need
4069     // this to convert the sink timestamp to the track timestamp.
4070     bool kernelLocationUpdate = false;
4071     ExtendedTimestamp timestamp; // use private copy to fetch
4072 
4073     // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4074     // HAL may be draining some small duration buffered data for fade out.
4075     if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4076         mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4077                 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4078                 mSampleRate);
4079 
4080         if (isTimestampCorrectionEnabled()) {
4081             ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4082                     (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4083                     (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4084             auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4085             timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4086                     = correctedTimestamp.mFrames;
4087             timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4088                     = correctedTimestamp.mTimeNs;
4089             ALOGVV("TS_AFTER: %d %lld %lld", id(),
4090                     (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4091                     (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4092 
4093             // Note: Downstream latency only added if timestamp correction enabled.
4094             if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4095                 const int64_t newPosition =
4096                         timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4097                         - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4098                 // prevent retrograde
4099                 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4100                         newPosition,
4101                         (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4102                                 - mSuspendedFrames));
4103             }
4104         }
4105 
4106         // We always fetch the timestamp here because often the downstream
4107         // sink will block while writing.
4108 
4109         // We keep track of the last valid kernel position in case we are in underrun
4110         // and the normal mixer period is the same as the fast mixer period, or there
4111         // is some error from the HAL.
4112         if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4113             mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4114                     mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4115             mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4116                     mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4117 
4118             mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4119                     mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4120             mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4121                     mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4122         }
4123 
4124         if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4125             kernelLocationUpdate = true;
4126         } else {
4127             ALOGVV("getTimestamp error - no valid kernel position");
4128         }
4129 
4130         // copy over kernel info
4131         mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4132                 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4133                 + mSuspendedFrames; // add frames discarded when suspended
4134         mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4135                 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4136     } else {
4137         mTimestampVerifier.error();
4138     }
4139 
4140     // mFramesWritten for non-offloaded tracks are contiguous
4141     // even after standby() is called. This is useful for the track frame
4142     // to sink frame mapping.
4143     bool serverLocationUpdate = false;
4144     if (mFramesWritten != mLastFramesWritten) {
4145         serverLocationUpdate = true;
4146         mLastFramesWritten = mFramesWritten;
4147     }
4148     // Only update timestamps if there is a meaningful change.
4149     // Either the kernel timestamp must be valid or we have written something.
4150     if (kernelLocationUpdate || serverLocationUpdate) {
4151         if (serverLocationUpdate) {
4152             // use the time before we called the HAL write - it is a bit more accurate
4153             // to when the server last read data than the current time here.
4154             //
4155             // If we haven't written anything, mLastIoBeginNs will be -1
4156             // and we use systemTime().
4157             mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4158             mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4159                     ? systemTime() : mLastIoBeginNs;
4160         }
4161 
4162         for (const sp<Track> &t : mActiveTracks) {
4163             if (!t->isFastTrack()) {
4164                 t->updateTrackFrameInfo(
4165                         t->mAudioTrackServerProxy->framesReleased(),
4166                         mFramesWritten,
4167                         mSampleRate,
4168                         mTimestamp);
4169             }
4170         }
4171     }
4172 
4173     if (audio_has_proportional_frames(mFormat)) {
4174         const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4175         if (latencyMs != 0.) { // note 0. means timestamp is empty.
4176             mLatencyMs.add(latencyMs);
4177         }
4178     }
4179 #if 0
4180     // logFormat example
4181     if (z % 100 == 0) {
4182         timespec ts;
4183         clock_gettime(CLOCK_MONOTONIC, &ts);
4184         LOGT("This is an integer %d, this is a float %f, this is my "
4185             "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4186         LOGT("A deceptive null-terminated string %\0");
4187     }
4188     ++z;
4189 #endif
4190 }
4191 
4192 // removeTracks_l() must be called with ThreadBase::mLock held
removeTracks_l(const Vector<sp<Track>> & tracksToRemove)4193 void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4194 {
4195     for (const auto& track : tracksToRemove) {
4196         mActiveTracks.remove(track);
4197         ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4198         sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4199         if (chain != 0) {
4200             ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4201                     __func__, track->id(), chain.get(), track->sessionId());
4202             chain->decActiveTrackCnt();
4203         }
4204         // If an external client track, inform APM we're no longer active, and remove if needed.
4205         // We do this under lock so that the state is consistent if the Track is destroyed.
4206         if (track->isExternalTrack()) {
4207             AudioSystem::stopOutput(track->portId());
4208             if (track->isTerminated()) {
4209                 AudioSystem::releaseOutput(track->portId());
4210             }
4211         }
4212         if (track->isTerminated()) {
4213             // remove from our tracks vector
4214             removeTrack_l(track);
4215         }
4216         if (mHapticChannelCount > 0 &&
4217                 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4218                         || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
4219             mLock.unlock();
4220             // Unlock due to VibratorService will lock for this call and will
4221             // call Tracks.mute/unmute which also require thread's lock.
4222             AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4223             mLock.lock();
4224 
4225             // When the track is stop, set the haptic intensity as MUTE
4226             // for the HapticGenerator effect.
4227             if (chain != nullptr) {
4228                 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4229             }
4230         }
4231     }
4232 }
4233 
getTimestamp_l(AudioTimestamp & timestamp)4234 status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4235 {
4236     if (mNormalSink != 0) {
4237         ExtendedTimestamp ets;
4238         status_t status = mNormalSink->getTimestamp(ets);
4239         if (status == NO_ERROR) {
4240             status = ets.getBestTimestamp(&timestamp);
4241         }
4242         return status;
4243     }
4244     if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
4245         collectTimestamps_l();
4246         if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4247             return INVALID_OPERATION;
4248         }
4249         timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4250         const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4251         timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4252         timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4253         return NO_ERROR;
4254     }
4255     return INVALID_OPERATION;
4256 }
4257 
4258 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4259 // still applied by the mixer.
4260 // All tracks attached to a mixer with flag VOIP_RX are tied to the same
4261 // stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4262 // if more than one track are active
handleVoipVolume_l(float * volume)4263 status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4264 {
4265     status_t result = NO_ERROR;
4266     if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4267         if (*volume != mLeftVolFloat) {
4268             result = mOutput->stream->setVolume(*volume, *volume);
4269             ALOGE_IF(result != OK,
4270                      "Error when setting output stream volume: %d", result);
4271             if (result == NO_ERROR) {
4272                 mLeftVolFloat = *volume;
4273             }
4274         }
4275         // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4276         // remove stream volume contribution from software volume.
4277         if (mLeftVolFloat == *volume) {
4278             *volume = 1.0f;
4279         }
4280     }
4281     return result;
4282 }
4283 
createAudioPatch_l(const struct audio_patch * patch,audio_patch_handle_t * handle)4284 status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4285                                                           audio_patch_handle_t *handle)
4286 {
4287     status_t status;
4288     if (property_get_bool("af.patch_park", false /* default_value */)) {
4289         // Park FastMixer to avoid potential DOS issues with writing to the HAL
4290         // or if HAL does not properly lock against access.
4291         AutoPark<FastMixer> park(mFastMixer);
4292         status = PlaybackThread::createAudioPatch_l(patch, handle);
4293     } else {
4294         status = PlaybackThread::createAudioPatch_l(patch, handle);
4295     }
4296     return status;
4297 }
4298 
createAudioPatch_l(const struct audio_patch * patch,audio_patch_handle_t * handle)4299 status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4300                                                           audio_patch_handle_t *handle)
4301 {
4302     status_t status = NO_ERROR;
4303 
4304     // store new device and send to effects
4305     audio_devices_t type = AUDIO_DEVICE_NONE;
4306     AudioDeviceTypeAddrVector deviceTypeAddrs;
4307     for (unsigned int i = 0; i < patch->num_sinks; i++) {
4308         LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4309                             && !mOutput->audioHwDev->supportsAudioPatches(),
4310                             "Enumerated device type(%#x) must not be used "
4311                             "as it does not support audio patches",
4312                             patch->sinks[i].ext.device.type);
4313         type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
4314         deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4315                 patch->sinks[i].ext.device.address));
4316     }
4317 
4318     audio_port_handle_t sinkPortId = patch->sinks[0].id;
4319 #ifdef ADD_BATTERY_DATA
4320     // when changing the audio output device, call addBatteryData to notify
4321     // the change
4322     if (outDeviceTypes() != deviceTypes) {
4323         uint32_t params = 0;
4324         // check whether speaker is on
4325         if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
4326             params |= IMediaPlayerService::kBatteryDataSpeakerOn;
4327         }
4328 
4329         // check if any other device (except speaker) is on
4330         if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
4331             params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4332         }
4333 
4334         if (params != 0) {
4335             addBatteryData(params);
4336         }
4337     }
4338 #endif
4339 
4340     for (size_t i = 0; i < mEffectChains.size(); i++) {
4341         mEffectChains[i]->setDevices_l(deviceTypeAddrs);
4342     }
4343 
4344     // mPatch.num_sinks is not set when the thread is created so that
4345     // the first patch creation triggers an ioConfigChanged callback
4346     bool configChanged = (mPatch.num_sinks == 0) ||
4347                          (mPatch.sinks[0].id != sinkPortId);
4348     mPatch = *patch;
4349     mOutDeviceTypeAddrs = deviceTypeAddrs;
4350     checkSilentMode_l();
4351 
4352     if (mOutput->audioHwDev->supportsAudioPatches()) {
4353         sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4354         status = hwDevice->createAudioPatch(patch->num_sources,
4355                                             patch->sources,
4356                                             patch->num_sinks,
4357                                             patch->sinks,
4358                                             handle);
4359     } else {
4360         char *address;
4361         if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4362             //FIXME: we only support address on first sink with HAL version < 3.0
4363             address = audio_device_address_to_parameter(
4364                                                         patch->sinks[0].ext.device.type,
4365                                                         patch->sinks[0].ext.device.address);
4366         } else {
4367             address = (char *)calloc(1, 1);
4368         }
4369         AudioParameter param = AudioParameter(String8(address));
4370         free(address);
4371         param.addInt(String8(AudioParameter::keyRouting), (int)type);
4372         status = mOutput->stream->setParameters(param.toString());
4373         *handle = AUDIO_PATCH_HANDLE_NONE;
4374     }
4375     const std::string patchSinksAsString = patchSinksToString(patch);
4376 
4377     mThreadMetrics.logEndInterval();
4378     mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
4379     mThreadMetrics.logBeginInterval();
4380     // also dispatch to active AudioTracks for MediaMetrics
4381     for (const auto &track : mActiveTracks) {
4382         track->logEndInterval();
4383         track->logBeginInterval(patchSinksAsString);
4384     }
4385 
4386     if (configChanged) {
4387         sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4388     }
4389     return status;
4390 }
4391 
releaseAudioPatch_l(const audio_patch_handle_t handle)4392 status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4393 {
4394     status_t status;
4395     if (property_get_bool("af.patch_park", false /* default_value */)) {
4396         // Park FastMixer to avoid potential DOS issues with writing to the HAL
4397         // or if HAL does not properly lock against access.
4398         AutoPark<FastMixer> park(mFastMixer);
4399         status = PlaybackThread::releaseAudioPatch_l(handle);
4400     } else {
4401         status = PlaybackThread::releaseAudioPatch_l(handle);
4402     }
4403     return status;
4404 }
4405 
releaseAudioPatch_l(const audio_patch_handle_t handle)4406 status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4407 {
4408     status_t status = NO_ERROR;
4409 
4410     mPatch = audio_patch{};
4411     mOutDeviceTypeAddrs.clear();
4412 
4413     if (mOutput->audioHwDev->supportsAudioPatches()) {
4414         sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4415         status = hwDevice->releaseAudioPatch(handle);
4416     } else {
4417         AudioParameter param;
4418         param.addInt(String8(AudioParameter::keyRouting), 0);
4419         status = mOutput->stream->setParameters(param.toString());
4420     }
4421     return status;
4422 }
4423 
addPatchTrack(const sp<PatchTrack> & track)4424 void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4425 {
4426     Mutex::Autolock _l(mLock);
4427     mTracks.add(track);
4428 }
4429 
deletePatchTrack(const sp<PatchTrack> & track)4430 void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4431 {
4432     Mutex::Autolock _l(mLock);
4433     destroyTrack_l(track);
4434 }
4435 
toAudioPortConfig(struct audio_port_config * config)4436 void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
4437 {
4438     ThreadBase::toAudioPortConfig(config);
4439     config->role = AUDIO_PORT_ROLE_SOURCE;
4440     config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4441     config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
4442     if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4443         config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4444         config->flags.output = mOutput->flags;
4445     }
4446 }
4447 
4448 // ----------------------------------------------------------------------------
4449 
MixerThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,bool systemReady,type_t type)4450 AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
4451         audio_io_handle_t id, bool systemReady, type_t type)
4452     :   PlaybackThread(audioFlinger, output, id, type, systemReady),
4453         // mAudioMixer below
4454         // mFastMixer below
4455         mFastMixerFutex(0),
4456         mMasterMono(false)
4457         // mOutputSink below
4458         // mPipeSink below
4459         // mNormalSink below
4460 {
4461     setMasterBalance(audioFlinger->getMasterBalance_l());
4462     ALOGV("MixerThread() id=%d type=%d", id, type);
4463     ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
4464             "mFrameCount=%zu, mNormalFrameCount=%zu",
4465             mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4466             mNormalFrameCount);
4467     mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4468 
4469     if (type == DUPLICATING) {
4470         // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4471         // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4472         // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4473         return;
4474     }
4475     // create an NBAIO sink for the HAL output stream, and negotiate
4476     mOutputSink = new AudioStreamOutSink(output->stream);
4477     size_t numCounterOffers = 0;
4478     const NBAIO_Format offers[1] = {Format_from_SR_C(
4479             mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
4480 #if !LOG_NDEBUG
4481     ssize_t index =
4482 #else
4483     (void)
4484 #endif
4485             mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
4486     ALOG_ASSERT(index == 0);
4487 
4488     // initialize fast mixer depending on configuration
4489     bool initFastMixer;
4490     switch (kUseFastMixer) {
4491     case FastMixer_Never:
4492         initFastMixer = false;
4493         break;
4494     case FastMixer_Always:
4495         initFastMixer = true;
4496         break;
4497     case FastMixer_Static:
4498     case FastMixer_Dynamic:
4499         // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4500         // where the period is less than an experimentally determined threshold that can be
4501         // scheduled reliably with CFS. However, the BT A2DP HAL is
4502         // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4503         initFastMixer = mFrameCount < mNormalFrameCount
4504                 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
4505         break;
4506     }
4507     ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4508             "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4509             mFrameCount, mNormalFrameCount);
4510     if (initFastMixer) {
4511         audio_format_t fastMixerFormat;
4512         if (mMixerBufferEnabled && mEffectBufferEnabled) {
4513             fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4514         } else {
4515             fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4516         }
4517         if (mFormat != fastMixerFormat) {
4518             // change our Sink format to accept our intermediate precision
4519             mFormat = fastMixerFormat;
4520             free(mSinkBuffer);
4521             mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
4522             const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4523             (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4524         }
4525 
4526         // create a MonoPipe to connect our submix to FastMixer
4527         NBAIO_Format format = mOutputSink->format();
4528 
4529         // adjust format to match that of the Fast Mixer
4530         ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
4531         format.mFormat = fastMixerFormat;
4532         format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4533 
4534         // This pipe depth compensates for scheduling latency of the normal mixer thread.
4535         // When it wakes up after a maximum latency, it runs a few cycles quickly before
4536         // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
4537         MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4538         const NBAIO_Format offers[1] = {format};
4539         size_t numCounterOffers = 0;
4540 #if !LOG_NDEBUG
4541         ssize_t index =
4542 #else
4543         (void)
4544 #endif
4545                 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
4546         ALOG_ASSERT(index == 0);
4547         monoPipe->setAvgFrames((mScreenState & 1) ?
4548                 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4549         mPipeSink = monoPipe;
4550 
4551         // create fast mixer and configure it initially with just one fast track for our submix
4552         mFastMixer = new FastMixer(mId);
4553         FastMixerStateQueue *sq = mFastMixer->sq();
4554 #ifdef STATE_QUEUE_DUMP
4555         sq->setObserverDump(&mStateQueueObserverDump);
4556         sq->setMutatorDump(&mStateQueueMutatorDump);
4557 #endif
4558         FastMixerState *state = sq->begin();
4559         FastTrack *fastTrack = &state->mFastTracks[0];
4560         // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4561         fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4562         fastTrack->mVolumeProvider = NULL;
4563         fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4564                 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4565                                                     // audio to FastMixer
4566         fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
4567         fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
4568         fastTrack->mHapticIntensity = os::HapticScale::NONE;
4569         fastTrack->mGeneration++;
4570         state->mFastTracksGen++;
4571         state->mTrackMask = 1;
4572         // fast mixer will use the HAL output sink
4573         state->mOutputSink = mOutputSink.get();
4574         state->mOutputSinkGen++;
4575         state->mFrameCount = mFrameCount;
4576         // specify sink channel mask when haptic channel mask present as it can not
4577         // be calculated directly from channel count
4578         state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4579                 ? AUDIO_CHANNEL_NONE
4580                 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
4581         state->mCommand = FastMixerState::COLD_IDLE;
4582         // already done in constructor initialization list
4583         //mFastMixerFutex = 0;
4584         state->mColdFutexAddr = &mFastMixerFutex;
4585         state->mColdGen++;
4586         state->mDumpState = &mFastMixerDumpState;
4587         mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4588         state->mNBLogWriter = mFastMixerNBLogWriter.get();
4589         sq->end();
4590         sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4591 
4592         NBLog::thread_info_t info;
4593         info.id = mId;
4594         info.type = NBLog::FASTMIXER;
4595         mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4596 
4597         // start the fast mixer
4598         mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4599         pid_t tid = mFastMixer->getTid();
4600         sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
4601         stream()->setHalThreadPriority(kPriorityFastMixer);
4602 
4603 #ifdef AUDIO_WATCHDOG
4604         // create and start the watchdog
4605         mAudioWatchdog = new AudioWatchdog();
4606         mAudioWatchdog->setDump(&mAudioWatchdogDump);
4607         mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4608         tid = mAudioWatchdog->getTid();
4609         sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
4610 #endif
4611     } else {
4612 #ifdef TEE_SINK
4613         // Only use the MixerThread tee if there is no FastMixer.
4614         mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4615         mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4616 #endif
4617     }
4618 
4619     switch (kUseFastMixer) {
4620     case FastMixer_Never:
4621     case FastMixer_Dynamic:
4622         mNormalSink = mOutputSink;
4623         break;
4624     case FastMixer_Always:
4625         mNormalSink = mPipeSink;
4626         break;
4627     case FastMixer_Static:
4628         mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4629         break;
4630     }
4631 }
4632 
~MixerThread()4633 AudioFlinger::MixerThread::~MixerThread()
4634 {
4635     if (mFastMixer != 0) {
4636         FastMixerStateQueue *sq = mFastMixer->sq();
4637         FastMixerState *state = sq->begin();
4638         if (state->mCommand == FastMixerState::COLD_IDLE) {
4639             int32_t old = android_atomic_inc(&mFastMixerFutex);
4640             if (old == -1) {
4641                 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
4642             }
4643         }
4644         state->mCommand = FastMixerState::EXIT;
4645         sq->end();
4646         sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4647         mFastMixer->join();
4648         // Though the fast mixer thread has exited, it's state queue is still valid.
4649         // We'll use that extract the final state which contains one remaining fast track
4650         // corresponding to our sub-mix.
4651         state = sq->begin();
4652         ALOG_ASSERT(state->mTrackMask == 1);
4653         FastTrack *fastTrack = &state->mFastTracks[0];
4654         ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4655         delete fastTrack->mBufferProvider;
4656         sq->end(false /*didModify*/);
4657         mFastMixer.clear();
4658 #ifdef AUDIO_WATCHDOG
4659         if (mAudioWatchdog != 0) {
4660             mAudioWatchdog->requestExit();
4661             mAudioWatchdog->requestExitAndWait();
4662             mAudioWatchdog.clear();
4663         }
4664 #endif
4665     }
4666     mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
4667     delete mAudioMixer;
4668 }
4669 
4670 
correctLatency_l(uint32_t latency) const4671 uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4672 {
4673     if (mFastMixer != 0) {
4674         MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4675         latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4676     }
4677     return latency;
4678 }
4679 
threadLoop_write()4680 ssize_t AudioFlinger::MixerThread::threadLoop_write()
4681 {
4682     // FIXME we should only do one push per cycle; confirm this is true
4683     // Start the fast mixer if it's not already running
4684     if (mFastMixer != 0) {
4685         FastMixerStateQueue *sq = mFastMixer->sq();
4686         FastMixerState *state = sq->begin();
4687         if (state->mCommand != FastMixerState::MIX_WRITE &&
4688                 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4689             if (state->mCommand == FastMixerState::COLD_IDLE) {
4690 
4691                 // FIXME workaround for first HAL write being CPU bound on some devices
4692                 ATRACE_BEGIN("write");
4693                 mOutput->write((char *)mSinkBuffer, 0);
4694                 ATRACE_END();
4695 
4696                 int32_t old = android_atomic_inc(&mFastMixerFutex);
4697                 if (old == -1) {
4698                     (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
4699                 }
4700 #ifdef AUDIO_WATCHDOG
4701                 if (mAudioWatchdog != 0) {
4702                     mAudioWatchdog->resume();
4703                 }
4704 #endif
4705             }
4706             state->mCommand = FastMixerState::MIX_WRITE;
4707 #ifdef FAST_THREAD_STATISTICS
4708             mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
4709                 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
4710 #endif
4711             sq->end();
4712             sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4713             if (kUseFastMixer == FastMixer_Dynamic) {
4714                 mNormalSink = mPipeSink;
4715             }
4716         } else {
4717             sq->end(false /*didModify*/);
4718         }
4719     }
4720     return PlaybackThread::threadLoop_write();
4721 }
4722 
threadLoop_standby()4723 void AudioFlinger::MixerThread::threadLoop_standby()
4724 {
4725     // Idle the fast mixer if it's currently running
4726     if (mFastMixer != 0) {
4727         FastMixerStateQueue *sq = mFastMixer->sq();
4728         FastMixerState *state = sq->begin();
4729         if (!(state->mCommand & FastMixerState::IDLE)) {
4730             // Report any frames trapped in the Monopipe
4731             MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4732             const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4733             mLocalLog.log("threadLoop_standby: framesWritten:%lld  suspendedFrames:%lld  "
4734                     "monoPipeWritten:%lld  monoPipeLeft:%lld",
4735                     (long long)mFramesWritten, (long long)mSuspendedFrames,
4736                     (long long)mPipeSink->framesWritten(), pipeFrames);
4737             mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4738 
4739             state->mCommand = FastMixerState::COLD_IDLE;
4740             state->mColdFutexAddr = &mFastMixerFutex;
4741             state->mColdGen++;
4742             mFastMixerFutex = 0;
4743             sq->end();
4744             // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4745             sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4746             if (kUseFastMixer == FastMixer_Dynamic) {
4747                 mNormalSink = mOutputSink;
4748             }
4749 #ifdef AUDIO_WATCHDOG
4750             if (mAudioWatchdog != 0) {
4751                 mAudioWatchdog->pause();
4752             }
4753 #endif
4754         } else {
4755             sq->end(false /*didModify*/);
4756         }
4757     }
4758     PlaybackThread::threadLoop_standby();
4759 }
4760 
waitingAsyncCallback_l()4761 bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4762 {
4763     return false;
4764 }
4765 
shouldStandby_l()4766 bool AudioFlinger::PlaybackThread::shouldStandby_l()
4767 {
4768     return !mStandby;
4769 }
4770 
waitingAsyncCallback()4771 bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4772 {
4773     Mutex::Autolock _l(mLock);
4774     return waitingAsyncCallback_l();
4775 }
4776 
4777 // shared by MIXER and DIRECT, overridden by DUPLICATING
threadLoop_standby()4778 void AudioFlinger::PlaybackThread::threadLoop_standby()
4779 {
4780     ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
4781     mOutput->standby();
4782     if (mUseAsyncWrite != 0) {
4783         // discard any pending drain or write ack by incrementing sequence
4784         mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4785         mDrainSequence = (mDrainSequence + 2) & ~1;
4786         ALOG_ASSERT(mCallbackThread != 0);
4787         mCallbackThread->setWriteBlocked(mWriteAckSequence);
4788         mCallbackThread->setDraining(mDrainSequence);
4789     }
4790     mHwPaused = false;
4791 }
4792 
onAddNewTrack_l()4793 void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4794 {
4795     ALOGV("signal playback thread");
4796     broadcast_l();
4797 }
4798 
onAsyncError()4799 void AudioFlinger::PlaybackThread::onAsyncError()
4800 {
4801     for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4802         invalidateTracks((audio_stream_type_t)i);
4803     }
4804 }
4805 
threadLoop_mix()4806 void AudioFlinger::MixerThread::threadLoop_mix()
4807 {
4808     // mix buffers...
4809     mAudioMixer->process();
4810     mCurrentWriteLength = mSinkBufferSize;
4811     // increase sleep time progressively when application underrun condition clears.
4812     // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4813     // that a steady state of alternating ready/not ready conditions keeps the sleep time
4814     // such that we would underrun the audio HAL.
4815     if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
4816         sleepTimeShift--;
4817     }
4818     mSleepTimeUs = 0;
4819     mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4820     //TODO: delay standby when effects have a tail
4821 
4822 }
4823 
threadLoop_sleepTime()4824 void AudioFlinger::MixerThread::threadLoop_sleepTime()
4825 {
4826     // If no tracks are ready, sleep once for the duration of an output
4827     // buffer size, then write 0s to the output
4828     if (mSleepTimeUs == 0) {
4829         if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4830             if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4831                 // Using the Monopipe availableToWrite, we estimate the
4832                 // sleep time to retry for more data (before we underrun).
4833                 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4834                 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4835                 const size_t pipeFrames = monoPipe->maxFrames();
4836                 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4837                 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4838                 const size_t framesDelay = std::min(
4839                         mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4840                 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4841                         pipeFrames, framesLeft, framesDelay);
4842                 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4843             } else {
4844                 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4845                 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4846                     mSleepTimeUs = kMinThreadSleepTimeUs;
4847                 }
4848                 // reduce sleep time in case of consecutive application underruns to avoid
4849                 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4850                 // duration we would end up writing less data than needed by the audio HAL if
4851                 // the condition persists.
4852                 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4853                     sleepTimeShift++;
4854                 }
4855             }
4856         } else {
4857             mSleepTimeUs = mIdleSleepTimeUs;
4858         }
4859     } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
4860         // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4861         // before effects processing or output.
4862         if (mMixerBufferValid) {
4863             memset(mMixerBuffer, 0, mMixerBufferSize);
4864         } else {
4865             memset(mSinkBuffer, 0, mSinkBufferSize);
4866         }
4867         mSleepTimeUs = 0;
4868         ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4869                 "anticipated start");
4870     }
4871     // TODO add standby time extension fct of effect tail
4872 }
4873 
4874 // prepareTracks_l() must be called with ThreadBase::mLock held
prepareTracks_l(Vector<sp<Track>> * tracksToRemove)4875 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4876         Vector< sp<Track> > *tracksToRemove)
4877 {
4878     // clean up deleted track ids in AudioMixer before allocating new tracks
4879     (void)mTracks.processDeletedTrackIds([this](int trackId) {
4880         // for each trackId, destroy it in the AudioMixer
4881         if (mAudioMixer->exists(trackId)) {
4882             mAudioMixer->destroy(trackId);
4883         }
4884     });
4885     mTracks.clearDeletedTrackIds();
4886 
4887     mixer_state mixerStatus = MIXER_IDLE;
4888     // find out which tracks need to be processed
4889     size_t count = mActiveTracks.size();
4890     size_t mixedTracks = 0;
4891     size_t tracksWithEffect = 0;
4892     // counts only _active_ fast tracks
4893     size_t fastTracks = 0;
4894     uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4895 
4896     float masterVolume = mMasterVolume;
4897     bool masterMute = mMasterMute;
4898 
4899     if (masterMute) {
4900         masterVolume = 0;
4901     }
4902     // Delegate master volume control to effect in output mix effect chain if needed
4903     sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4904     if (chain != 0) {
4905         uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4906         chain->setVolume_l(&v, &v);
4907         masterVolume = (float)((v + (1 << 23)) >> 24);
4908         chain.clear();
4909     }
4910 
4911     // prepare a new state to push
4912     FastMixerStateQueue *sq = NULL;
4913     FastMixerState *state = NULL;
4914     bool didModify = false;
4915     FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
4916     bool coldIdle = false;
4917     if (mFastMixer != 0) {
4918         sq = mFastMixer->sq();
4919         state = sq->begin();
4920         coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
4921     }
4922 
4923     mMixerBufferValid = false;  // mMixerBuffer has no valid data until appropriate tracks found.
4924     mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
4925 
4926     // DeferredOperations handles statistics after setting mixerStatus.
4927     class DeferredOperations {
4928     public:
4929         DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
4930             : mMixerStatus(mixerStatus)
4931             , mThreadMetrics(threadMetrics) {}
4932 
4933         // when leaving scope, tally frames properly.
4934         ~DeferredOperations() {
4935             // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4936             // because that is when the underrun occurs.
4937             // We do not distinguish between FastTracks and NormalTracks here.
4938             size_t maxUnderrunFrames = 0;
4939             if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
4940                 for (const auto &underrun : mUnderrunFrames) {
4941                     underrun.first->tallyUnderrunFrames(underrun.second);
4942                     maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
4943                 }
4944             }
4945             // send the max underrun frames for this mixer period
4946             mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
4947         }
4948 
4949         // tallyUnderrunFrames() is called to update the track counters
4950         // with the number of underrun frames for a particular mixer period.
4951         // We defer tallying until we know the final mixer status.
4952         void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4953             mUnderrunFrames.emplace_back(track, underrunFrames);
4954         }
4955 
4956     private:
4957         const mixer_state * const mMixerStatus;
4958         ThreadMetrics * const mThreadMetrics;
4959         std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4960     } deferredOperations(&mixerStatus, &mThreadMetrics);
4961     // implicit nested scope for variable capture
4962 
4963     bool noFastHapticTrack = true;
4964     for (size_t i=0 ; i<count ; i++) {
4965         const sp<Track> t = mActiveTracks[i];
4966 
4967         // this const just means the local variable doesn't change
4968         Track* const track = t.get();
4969 
4970         // process fast tracks
4971         if (track->isFastTrack()) {
4972             LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4973                     "%s(%d): FastTrack(%d) present without FastMixer",
4974                      __func__, id(), track->id());
4975 
4976             if (track->getHapticPlaybackEnabled()) {
4977                 noFastHapticTrack = false;
4978             }
4979 
4980             // It's theoretically possible (though unlikely) for a fast track to be created
4981             // and then removed within the same normal mix cycle.  This is not a problem, as
4982             // the track never becomes active so it's fast mixer slot is never touched.
4983             // The converse, of removing an (active) track and then creating a new track
4984             // at the identical fast mixer slot within the same normal mix cycle,
4985             // is impossible because the slot isn't marked available until the end of each cycle.
4986             int j = track->mFastIndex;
4987             ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
4988             ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4989             FastTrack *fastTrack = &state->mFastTracks[j];
4990 
4991             // Determine whether the track is currently in underrun condition,
4992             // and whether it had a recent underrun.
4993             FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4994             FastTrackUnderruns underruns = ftDump->mUnderruns;
4995             uint32_t recentFull = (underruns.mBitFields.mFull -
4996                     track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4997             uint32_t recentPartial = (underruns.mBitFields.mPartial -
4998                     track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4999             uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5000                     track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5001             uint32_t recentUnderruns = recentPartial + recentEmpty;
5002             track->mObservedUnderruns = underruns;
5003             // don't count underruns that occur while stopping or pausing
5004             // or stopped which can occur when flush() is called while active
5005             size_t underrunFrames = 0;
5006             if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5007                     recentUnderruns > 0) {
5008                 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
5009                 underrunFrames = recentUnderruns * mFrameCount;
5010             }
5011             // Immediately account for FastTrack underruns.
5012             track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
5013 
5014             // This is similar to the state machine for normal tracks,
5015             // with a few modifications for fast tracks.
5016             bool isActive = true;
5017             switch (track->mState) {
5018             case TrackBase::STOPPING_1:
5019                 // track stays active in STOPPING_1 state until first underrun
5020                 if (recentUnderruns > 0 || track->isTerminated()) {
5021                     track->mState = TrackBase::STOPPING_2;
5022                 }
5023                 break;
5024             case TrackBase::PAUSING:
5025                 // ramp down is not yet implemented
5026                 track->setPaused();
5027                 break;
5028             case TrackBase::RESUMING:
5029                 // ramp up is not yet implemented
5030                 track->mState = TrackBase::ACTIVE;
5031                 break;
5032             case TrackBase::ACTIVE:
5033                 if (recentFull > 0 || recentPartial > 0) {
5034                     // track has provided at least some frames recently: reset retry count
5035                     track->mRetryCount = kMaxTrackRetries;
5036                 }
5037                 if (recentUnderruns == 0) {
5038                     // no recent underruns: stay active
5039                     break;
5040                 }
5041                 // there has recently been an underrun of some kind
5042                 if (track->sharedBuffer() == 0) {
5043                     // were any of the recent underruns "empty" (no frames available)?
5044                     if (recentEmpty == 0) {
5045                         // no, then ignore the partial underruns as they are allowed indefinitely
5046                         break;
5047                     }
5048                     // there has recently been an "empty" underrun: decrement the retry counter
5049                     if (--(track->mRetryCount) > 0) {
5050                         break;
5051                     }
5052                     // indicate to client process that the track was disabled because of underrun;
5053                     // it will then automatically call start() when data is available
5054                     track->disable();
5055                     // remove from active list, but state remains ACTIVE [confusing but true]
5056                     isActive = false;
5057                     break;
5058                 }
5059                 FALLTHROUGH_INTENDED;
5060             case TrackBase::STOPPING_2:
5061             case TrackBase::PAUSED:
5062             case TrackBase::STOPPED:
5063             case TrackBase::FLUSHED:   // flush() while active
5064                 // Check for presentation complete if track is inactive
5065                 // We have consumed all the buffers of this track.
5066                 // This would be incomplete if we auto-paused on underrun
5067                 {
5068                     uint32_t latency = 0;
5069                     status_t result = mOutput->stream->getLatency(&latency);
5070                     ALOGE_IF(result != OK,
5071                             "Error when retrieving output stream latency: %d", result);
5072                     size_t audioHALFrames = (latency * mSampleRate) / 1000;
5073                     int64_t framesWritten = mBytesWritten / mFrameSize;
5074                     if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5075                         // track stays in active list until presentation is complete
5076                         break;
5077                     }
5078                 }
5079                 if (track->isStopping_2()) {
5080                     track->mState = TrackBase::STOPPED;
5081                 }
5082                 if (track->isStopped()) {
5083                     // Can't reset directly, as fast mixer is still polling this track
5084                     //   track->reset();
5085                     // So instead mark this track as needing to be reset after push with ack
5086                     resetMask |= 1 << i;
5087                 }
5088                 isActive = false;
5089                 break;
5090             case TrackBase::IDLE:
5091             default:
5092                 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
5093             }
5094 
5095             if (isActive) {
5096                 // was it previously inactive?
5097                 if (!(state->mTrackMask & (1 << j))) {
5098                     ExtendedAudioBufferProvider *eabp = track;
5099                     VolumeProvider *vp = track;
5100                     fastTrack->mBufferProvider = eabp;
5101                     fastTrack->mVolumeProvider = vp;
5102                     fastTrack->mChannelMask = track->mChannelMask;
5103                     fastTrack->mFormat = track->mFormat;
5104                     fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5105                     fastTrack->mHapticIntensity = track->getHapticIntensity();
5106                     fastTrack->mGeneration++;
5107                     state->mTrackMask |= 1 << j;
5108                     didModify = true;
5109                     // no acknowledgement required for newly active tracks
5110                 }
5111                 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5112                 float volume;
5113                 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5114                     volume = 0.f;
5115                 } else {
5116                     volume = masterVolume * mStreamTypes[track->streamType()].volume;
5117                 }
5118 
5119                 handleVoipVolume_l(&volume);
5120 
5121                 // cache the combined master volume and stream type volume for fast mixer; this
5122                 // lacks any synchronization or barrier so VolumeProvider may read a stale value
5123                 const float vh = track->getVolumeHandler()->getVolume(
5124                     proxy->framesReleased()).first;
5125                 volume *= vh;
5126                 track->mCachedVolume = volume;
5127                 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5128                 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5129                 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
5130 
5131                 track->setFinalVolume((vlf + vrf) / 2.f);
5132                 ++fastTracks;
5133             } else {
5134                 // was it previously active?
5135                 if (state->mTrackMask & (1 << j)) {
5136                     fastTrack->mBufferProvider = NULL;
5137                     fastTrack->mGeneration++;
5138                     state->mTrackMask &= ~(1 << j);
5139                     didModify = true;
5140                     // If any fast tracks were removed, we must wait for acknowledgement
5141                     // because we're about to decrement the last sp<> on those tracks.
5142                     block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5143                 } else {
5144                     // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5145                     // AudioTrack may start (which may not be with a start() but with a write()
5146                     // after underrun) and immediately paused or released.  In that case the
5147                     // FastTrack state hasn't had time to update.
5148                     // TODO Remove the ALOGW when this theory is confirmed.
5149                     ALOGW("fast track %d should have been active; "
5150                             "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5151                             j, track->mState, state->mTrackMask, recentUnderruns,
5152                             track->sharedBuffer() != 0);
5153                     // Since the FastMixer state already has the track inactive, do nothing here.
5154                 }
5155                 tracksToRemove->add(track);
5156                 // Avoids a misleading display in dumpsys
5157                 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5158             }
5159             if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5160                 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5161                 didModify = true;
5162             }
5163             continue;
5164         }
5165 
5166         {   // local variable scope to avoid goto warning
5167 
5168         audio_track_cblk_t* cblk = track->cblk();
5169 
5170         // The first time a track is added we wait
5171         // for all its buffers to be filled before processing it
5172         const int trackId = track->id();
5173 
5174         // if an active track doesn't exist in the AudioMixer, create it.
5175         // use the trackId as the AudioMixer name.
5176         if (!mAudioMixer->exists(trackId)) {
5177             status_t status = mAudioMixer->create(
5178                     trackId,
5179                     track->mChannelMask,
5180                     track->mFormat,
5181                     track->mSessionId);
5182             if (status != OK) {
5183                 ALOGW("%s(): AudioMixer cannot create track(%d)"
5184                         " mask %#x, format %#x, sessionId %d",
5185                         __func__, trackId,
5186                         track->mChannelMask, track->mFormat, track->mSessionId);
5187                 tracksToRemove->add(track);
5188                 track->invalidate(); // consider it dead.
5189                 continue;
5190             }
5191         }
5192 
5193         // make sure that we have enough frames to mix one full buffer.
5194         // enforce this condition only once to enable draining the buffer in case the client
5195         // app does not call stop() and relies on underrun to stop:
5196         // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5197         // during last round
5198         size_t desiredFrames;
5199         const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
5200         AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
5201 
5202         desiredFrames = sourceFramesNeededWithTimestretch(
5203                 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
5204         // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5205         // add frames already consumed but not yet released by the resampler
5206         // because mAudioTrackServerProxy->framesReady() will include these frames
5207         desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
5208 
5209         uint32_t minFrames = 1;
5210         if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5211                 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
5212             minFrames = desiredFrames;
5213         }
5214 
5215         size_t framesReady = track->framesReady();
5216         if (ATRACE_ENABLED()) {
5217             // I wish we had formatted trace names
5218             std::string traceName("nRdy");
5219             traceName += std::to_string(trackId);
5220             ATRACE_INT(traceName.c_str(), framesReady);
5221         }
5222         if ((framesReady >= minFrames) && track->isReady() &&
5223                 !track->isPaused() && !track->isTerminated())
5224         {
5225             ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
5226 
5227             mixedTracks++;
5228 
5229             // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5230             // there is an effect chain connected to the track
5231             chain.clear();
5232             if (track->mainBuffer() != mSinkBuffer &&
5233                     track->mainBuffer() != mMixerBuffer) {
5234                 if (mEffectBufferEnabled) {
5235                     mEffectBufferValid = true; // Later can set directly.
5236                 }
5237                 chain = getEffectChain_l(track->sessionId());
5238                 // Delegate volume control to effect in track effect chain if needed
5239                 if (chain != 0) {
5240                     tracksWithEffect++;
5241                 } else {
5242                     ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
5243                             "session %d",
5244                             trackId, track->sessionId());
5245                 }
5246             }
5247 
5248 
5249             int param = AudioMixer::VOLUME;
5250             if (track->mFillingUpStatus == Track::FS_FILLED) {
5251                 // no ramp for the first volume setting
5252                 track->mFillingUpStatus = Track::FS_ACTIVE;
5253                 if (track->mState == TrackBase::RESUMING) {
5254                     track->mState = TrackBase::ACTIVE;
5255                     // If a new track is paused immediately after start, do not ramp on resume.
5256                     if (cblk->mServer != 0) {
5257                         param = AudioMixer::RAMP_VOLUME;
5258                     }
5259                 }
5260                 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
5261                 mLeftVolFloat = -1.0;
5262             // FIXME should not make a decision based on mServer
5263             } else if (cblk->mServer != 0) {
5264                 // If the track is stopped before the first frame was mixed,
5265                 // do not apply ramp
5266                 param = AudioMixer::RAMP_VOLUME;
5267             }
5268 
5269             // compute volume for this track
5270             uint32_t vl, vr;       // in U8.24 integer format
5271             float vlf, vrf, vaf;   // in [0.0, 1.0] float format
5272             // read original volumes with volume control
5273             float v = masterVolume * mStreamTypes[track->streamType()].volume;
5274             // Always fetch volumeshaper volume to ensure state is updated.
5275             const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5276             const float vh = track->getVolumeHandler()->getVolume(
5277                     track->mAudioTrackServerProxy->framesReleased()).first;
5278 
5279             if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5280                 v = 0;
5281             }
5282 
5283             handleVoipVolume_l(&v);
5284 
5285             if (track->isPausing()) {
5286                 vl = vr = 0;
5287                 vlf = vrf = vaf = 0.;
5288                 track->setPaused();
5289             } else {
5290                 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5291                 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5292                 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5293                 // track volumes come from shared memory, so can't be trusted and must be clamped
5294                 if (vlf > GAIN_FLOAT_UNITY) {
5295                     ALOGV("Track left volume out of range: %.3g", vlf);
5296                     vlf = GAIN_FLOAT_UNITY;
5297                 }
5298                 if (vrf > GAIN_FLOAT_UNITY) {
5299                     ALOGV("Track right volume out of range: %.3g", vrf);
5300                     vrf = GAIN_FLOAT_UNITY;
5301                 }
5302                 // now apply the master volume and stream type volume and shaper volume
5303                 vlf *= v * vh;
5304                 vrf *= v * vh;
5305                 // assuming master volume and stream type volume each go up to 1.0,
5306                 // then derive vl and vr as U8.24 versions for the effect chain
5307                 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5308                 vl = (uint32_t) (scaleto8_24 * vlf);
5309                 vr = (uint32_t) (scaleto8_24 * vrf);
5310                 // vl and vr are now in U8.24 format
5311                 uint16_t sendLevel = proxy->getSendLevel_U4_12();
5312                 // send level comes from shared memory and so may be corrupt
5313                 if (sendLevel > MAX_GAIN_INT) {
5314                     ALOGV("Track send level out of range: %04X", sendLevel);
5315                     sendLevel = MAX_GAIN_INT;
5316                 }
5317                 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5318                 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
5319             }
5320 
5321             track->setFinalVolume((vrf + vlf) / 2.f);
5322 
5323             // Delegate volume control to effect in track effect chain if needed
5324             if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5325                 // Do not ramp volume if volume is controlled by effect
5326                 param = AudioMixer::VOLUME;
5327                 // Update remaining floating point volume levels
5328                 vlf = (float)vl / (1 << 24);
5329                 vrf = (float)vr / (1 << 24);
5330                 track->mHasVolumeController = true;
5331             } else {
5332                 // force no volume ramp when volume controller was just disabled or removed
5333                 // from effect chain to avoid volume spike
5334                 if (track->mHasVolumeController) {
5335                     param = AudioMixer::VOLUME;
5336                 }
5337                 track->mHasVolumeController = false;
5338             }
5339 
5340             // XXX: these things DON'T need to be done each time
5341             mAudioMixer->setBufferProvider(trackId, track);
5342             mAudioMixer->enable(trackId);
5343 
5344             mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5345             mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5346             mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
5347             mAudioMixer->setParameter(
5348                 trackId,
5349                 AudioMixer::TRACK,
5350                 AudioMixer::FORMAT, (void *)track->format());
5351             mAudioMixer->setParameter(
5352                 trackId,
5353                 AudioMixer::TRACK,
5354                 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
5355             mAudioMixer->setParameter(
5356                 trackId,
5357                 AudioMixer::TRACK,
5358                 AudioMixer::MIXER_CHANNEL_MASK,
5359                 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5360             // limit track sample rate to 2 x output sample rate, which changes at re-configuration
5361             uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
5362             uint32_t reqSampleRate = proxy->getSampleRate();
5363             if (reqSampleRate == 0) {
5364                 reqSampleRate = mSampleRate;
5365             } else if (reqSampleRate > maxSampleRate) {
5366                 reqSampleRate = maxSampleRate;
5367             }
5368             mAudioMixer->setParameter(
5369                 trackId,
5370                 AudioMixer::RESAMPLE,
5371                 AudioMixer::SAMPLE_RATE,
5372                 (void *)(uintptr_t)reqSampleRate);
5373 
5374             AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
5375             mAudioMixer->setParameter(
5376                 trackId,
5377                 AudioMixer::TIMESTRETCH,
5378                 AudioMixer::PLAYBACK_RATE,
5379                 &playbackRate);
5380 
5381             /*
5382              * Select the appropriate output buffer for the track.
5383              *
5384              * Tracks with effects go into their own effects chain buffer
5385              * and from there into either mEffectBuffer or mSinkBuffer.
5386              *
5387              * Other tracks can use mMixerBuffer for higher precision
5388              * channel accumulation.  If this buffer is enabled
5389              * (mMixerBufferEnabled true), then selected tracks will accumulate
5390              * into it.
5391              *
5392              */
5393             if (mMixerBufferEnabled
5394                     && (track->mainBuffer() == mSinkBuffer
5395                             || track->mainBuffer() == mMixerBuffer)) {
5396                 mAudioMixer->setParameter(
5397                         trackId,
5398                         AudioMixer::TRACK,
5399                         AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5400                 mAudioMixer->setParameter(
5401                         trackId,
5402                         AudioMixer::TRACK,
5403                         AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5404                 // TODO: override track->mainBuffer()?
5405                 mMixerBufferValid = true;
5406             } else {
5407                 mAudioMixer->setParameter(
5408                         trackId,
5409                         AudioMixer::TRACK,
5410                         AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
5411                 mAudioMixer->setParameter(
5412                         trackId,
5413                         AudioMixer::TRACK,
5414                         AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5415             }
5416             mAudioMixer->setParameter(
5417                 trackId,
5418                 AudioMixer::TRACK,
5419                 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
5420             mAudioMixer->setParameter(
5421                 trackId,
5422                 AudioMixer::TRACK,
5423                 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
5424             mAudioMixer->setParameter(
5425                 trackId,
5426                 AudioMixer::TRACK,
5427                 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
5428 
5429             // reset retry count
5430             track->mRetryCount = kMaxTrackRetries;
5431 
5432             // If one track is ready, set the mixer ready if:
5433             //  - the mixer was not ready during previous round OR
5434             //  - no other track is not ready
5435             if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5436                     mixerStatus != MIXER_TRACKS_ENABLED) {
5437                 mixerStatus = MIXER_TRACKS_READY;
5438             }
5439 
5440             // Enable the next few lines to instrument a test for underrun log handling.
5441             // TODO: Remove when we have a better way of testing the underrun log.
5442 #if 0
5443             static int i;
5444             if ((++i & 0xf) == 0) {
5445                 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5446             }
5447 #endif
5448         } else {
5449             size_t underrunFrames = 0;
5450             if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
5451                 ALOGV("track(%d) underrun, track state %s  framesReady(%zu) < framesDesired(%zd)",
5452                         trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
5453                 underrunFrames = desiredFrames;
5454             }
5455             deferredOperations.tallyUnderrunFrames(track, underrunFrames);
5456 
5457             // clear effect chain input buffer if an active track underruns to avoid sending
5458             // previous audio buffer again to effects
5459             chain = getEffectChain_l(track->sessionId());
5460             if (chain != 0) {
5461                 chain->clearInputBuffer();
5462             }
5463 
5464             ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
5465             if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5466                     track->isStopped() || track->isPaused()) {
5467                 // We have consumed all the buffers of this track.
5468                 // Remove it from the list of active tracks.
5469                 // TODO: use actual buffer filling status instead of latency when available from
5470                 // audio HAL
5471                 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
5472                 int64_t framesWritten = mBytesWritten / mFrameSize;
5473                 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5474                     if (track->isStopped()) {
5475                         track->reset();
5476                     }
5477                     tracksToRemove->add(track);
5478                 }
5479             } else {
5480                 // No buffers for this track. Give it a few chances to
5481                 // fill a buffer, then remove it from active list.
5482                 if (--(track->mRetryCount) <= 0) {
5483                     ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5484                             trackId, this);
5485                     tracksToRemove->add(track);
5486                     // indicate to client process that the track was disabled because of underrun;
5487                     // it will then automatically call start() when data is available
5488                     track->disable();
5489                 // If one track is not ready, mark the mixer also not ready if:
5490                 //  - the mixer was ready during previous round OR
5491                 //  - no other track is ready
5492                 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5493                                 mixerStatus != MIXER_TRACKS_READY) {
5494                     mixerStatus = MIXER_TRACKS_ENABLED;
5495                 }
5496             }
5497             mAudioMixer->disable(trackId);
5498         }
5499 
5500         }   // local variable scope to avoid goto warning
5501 
5502     }
5503 
5504     if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5505         // When there is no fast track playing haptic and FastMixer exists,
5506         // enabling the first FastTrack, which provides mixed data from normal
5507         // tracks, to play haptic data.
5508         FastTrack *fastTrack = &state->mFastTracks[0];
5509         if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5510             fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5511             didModify = true;
5512         }
5513     }
5514 
5515     // Push the new FastMixer state if necessary
5516     bool pauseAudioWatchdog = false;
5517     if (didModify) {
5518         state->mFastTracksGen++;
5519         // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5520         if (kUseFastMixer == FastMixer_Dynamic &&
5521                 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5522             state->mCommand = FastMixerState::COLD_IDLE;
5523             state->mColdFutexAddr = &mFastMixerFutex;
5524             state->mColdGen++;
5525             mFastMixerFutex = 0;
5526             if (kUseFastMixer == FastMixer_Dynamic) {
5527                 mNormalSink = mOutputSink;
5528             }
5529             // If we go into cold idle, need to wait for acknowledgement
5530             // so that fast mixer stops doing I/O.
5531             block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5532             pauseAudioWatchdog = true;
5533         }
5534     }
5535     if (sq != NULL) {
5536         sq->end(didModify);
5537         // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5538         // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5539         // when bringing the output sink into standby.)
5540         //
5541         // We will get the latest FastMixer state when we come out of COLD_IDLE.
5542         //
5543         // This occurs with BT suspend when we idle the FastMixer with
5544         // active tracks, which may be added or removed.
5545         sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
5546     }
5547 #ifdef AUDIO_WATCHDOG
5548     if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5549         mAudioWatchdog->pause();
5550     }
5551 #endif
5552 
5553     // Now perform the deferred reset on fast tracks that have stopped
5554     while (resetMask != 0) {
5555         size_t i = __builtin_ctz(resetMask);
5556         ALOG_ASSERT(i < count);
5557         resetMask &= ~(1 << i);
5558         sp<Track> track = mActiveTracks[i];
5559         ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5560         track->reset();
5561     }
5562 
5563     // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5564     // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5565     // it ceases to be active, to allow safe removal from the AudioMixer at the start
5566     // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5567     // See also the implementation of destroyTrack_l().
5568     for (const auto &track : *tracksToRemove) {
5569         const int trackId = track->id();
5570         if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5571             mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
5572         }
5573     }
5574 
5575     // remove all the tracks that need to be...
5576     removeTracks_l(*tracksToRemove);
5577 
5578     if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5579         mEffectBufferValid = true;
5580     }
5581 
5582     if (mEffectBufferValid) {
5583         // as long as there are effects we should clear the effects buffer, to avoid
5584         // passing a non-clean buffer to the effect chain
5585         memset(mEffectBuffer, 0, mEffectBufferSize);
5586     }
5587     // sink or mix buffer must be cleared if all tracks are connected to an
5588     // effect chain as in this case the mixer will not write to the sink or mix buffer
5589     // and track effects will accumulate into it
5590     if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5591             (mixedTracks == 0 && fastTracks > 0))) {
5592         // FIXME as a performance optimization, should remember previous zero status
5593         if (mMixerBufferValid) {
5594             memset(mMixerBuffer, 0, mMixerBufferSize);
5595             // TODO: In testing, mSinkBuffer below need not be cleared because
5596             // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5597             // after mixing.
5598             //
5599             // To enforce this guarantee:
5600             // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5601             // (mixedTracks == 0 && fastTracks > 0))
5602             // must imply MIXER_TRACKS_READY.
5603             // Later, we may clear buffers regardless, and skip much of this logic.
5604         }
5605         // FIXME as a performance optimization, should remember previous zero status
5606         memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
5607     }
5608 
5609     // if any fast tracks, then status is ready
5610     mMixerStatusIgnoringFastTracks = mixerStatus;
5611     if (fastTracks > 0) {
5612         mixerStatus = MIXER_TRACKS_READY;
5613     }
5614     return mixerStatus;
5615 }
5616 
5617 // trackCountForUid_l() must be called with ThreadBase::mLock held
trackCountForUid_l(uid_t uid) const5618 uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
5619 {
5620     uint32_t trackCount = 0;
5621     for (size_t i = 0; i < mTracks.size() ; i++) {
5622         if (mTracks[i]->uid() == uid) {
5623             trackCount++;
5624         }
5625     }
5626     return trackCount;
5627 }
5628 
5629 // isTrackAllowed_l() must be called with ThreadBase::mLock held
isTrackAllowed_l(audio_channel_mask_t channelMask,audio_format_t format,audio_session_t sessionId,uid_t uid) const5630 bool AudioFlinger::MixerThread::isTrackAllowed_l(
5631         audio_channel_mask_t channelMask, audio_format_t format,
5632         audio_session_t sessionId, uid_t uid) const
5633 {
5634     if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5635         return false;
5636     }
5637     // Check validity as we don't call AudioMixer::create() here.
5638     if (!mAudioMixer->isValidFormat(format)) {
5639         ALOGW("%s: invalid format: %#x", __func__, format);
5640         return false;
5641     }
5642     if (!mAudioMixer->isValidChannelMask(channelMask)) {
5643         ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5644         return false;
5645     }
5646     return true;
5647 }
5648 
5649 // checkForNewParameter_l() must be called with ThreadBase::mLock held
checkForNewParameter_l(const String8 & keyValuePair,status_t & status)5650 bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5651                                                        status_t& status)
5652 {
5653     bool reconfig = false;
5654     status = NO_ERROR;
5655 
5656     AutoPark<FastMixer> park(mFastMixer);
5657 
5658     AudioParameter param = AudioParameter(keyValuePair);
5659     int value;
5660     if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5661         reconfig = true;
5662     }
5663     if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5664         if (!isValidPcmSinkFormat((audio_format_t) value)) {
5665             status = BAD_VALUE;
5666         } else {
5667             // no need to save value, since it's constant
5668             reconfig = true;
5669         }
5670     }
5671     if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5672         if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
5673             status = BAD_VALUE;
5674         } else {
5675             // no need to save value, since it's constant
5676             reconfig = true;
5677         }
5678     }
5679     if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5680         // do not accept frame count changes if tracks are open as the track buffer
5681         // size depends on frame count and correct behavior would not be guaranteed
5682         // if frame count is changed after track creation
5683         if (!mTracks.isEmpty()) {
5684             status = INVALID_OPERATION;
5685         } else {
5686             reconfig = true;
5687         }
5688     }
5689     if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5690         LOG_FATAL("Should not set routing device in MixerThread");
5691     }
5692 
5693     if (status == NO_ERROR) {
5694         status = mOutput->stream->setParameters(keyValuePair);
5695         if (!mStandby && status == INVALID_OPERATION) {
5696             mOutput->standby();
5697             if (!mStandby) {
5698                 mThreadMetrics.logEndInterval();
5699                 mStandby = true;
5700             }
5701             mBytesWritten = 0;
5702             status = mOutput->stream->setParameters(keyValuePair);
5703         }
5704         if (status == NO_ERROR && reconfig) {
5705             readOutputParameters_l();
5706             delete mAudioMixer;
5707             mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5708             for (const auto &track : mTracks) {
5709                 const int trackId = track->id();
5710                 status_t status = mAudioMixer->create(
5711                         trackId,
5712                         track->mChannelMask,
5713                         track->mFormat,
5714                         track->mSessionId);
5715                 ALOGW_IF(status != NO_ERROR,
5716                         "%s(): AudioMixer cannot create track(%d)"
5717                         " mask %#x, format %#x, sessionId %d",
5718                         __func__,
5719                         trackId, track->mChannelMask, track->mFormat, track->mSessionId);
5720             }
5721             sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5722         }
5723     }
5724 
5725     return reconfig;
5726 }
5727 
5728 
dumpInternals_l(int fd,const Vector<String16> & args)5729 void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
5730 {
5731     PlaybackThread::dumpInternals_l(fd, args);
5732     dprintf(fd, "  Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
5733     dprintf(fd, "  AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
5734     dprintf(fd, "  Master mono: %s\n", mMasterMono ? "on" : "off");
5735     dprintf(fd, "  Master balance: %f (%s)\n", mMasterBalance.load(),
5736             (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5737                             : mBalance.toString()).c_str());
5738     if (hasFastMixer()) {
5739         dprintf(fd, "  FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5740 
5741         // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5742         // while we are dumping it.  It may be inconsistent, but it won't mutate!
5743         // This is a large object so we place it on the heap.
5744         // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5745         const std::unique_ptr<FastMixerDumpState> copy =
5746                 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
5747         copy->dump(fd);
5748 
5749 #ifdef STATE_QUEUE_DUMP
5750         // Similar for state queue
5751         StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5752         observerCopy.dump(fd);
5753         StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5754         mutatorCopy.dump(fd);
5755 #endif
5756 
5757 #ifdef AUDIO_WATCHDOG
5758         if (mAudioWatchdog != 0) {
5759             // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5760             AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5761             wdCopy.dump(fd);
5762         }
5763 #endif
5764 
5765     } else {
5766         dprintf(fd, "  No FastMixer\n");
5767     }
5768 }
5769 
idleSleepTimeUs() const5770 uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5771 {
5772     return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5773 }
5774 
suspendSleepTimeUs() const5775 uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5776 {
5777     return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5778 }
5779 
cacheParameters_l()5780 void AudioFlinger::MixerThread::cacheParameters_l()
5781 {
5782     PlaybackThread::cacheParameters_l();
5783 
5784     // FIXME: Relaxed timing because of a certain device that can't meet latency
5785     // Should be reduced to 2x after the vendor fixes the driver issue
5786     // increase threshold again due to low power audio mode. The way this warning
5787     // threshold is calculated and its usefulness should be reconsidered anyway.
5788     maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5789 }
5790 
5791 // ----------------------------------------------------------------------------
5792 
DirectOutputThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,ThreadBase::type_t type,bool systemReady)5793 AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5794         AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5795     :   PlaybackThread(audioFlinger, output, id, type, systemReady)
5796 {
5797     setMasterBalance(audioFlinger->getMasterBalance_l());
5798 }
5799 
~DirectOutputThread()5800 AudioFlinger::DirectOutputThread::~DirectOutputThread()
5801 {
5802 }
5803 
dumpInternals_l(int fd,const Vector<String16> & args)5804 void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
5805 {
5806     PlaybackThread::dumpInternals_l(fd, args);
5807     dprintf(fd, "  Master balance: %f  Left: %f  Right: %f\n",
5808             mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5809 }
5810 
setMasterBalance(float balance)5811 void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5812 {
5813     Mutex::Autolock _l(mLock);
5814     if (mMasterBalance != balance) {
5815         mMasterBalance.store(balance);
5816         mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5817         broadcast_l();
5818     }
5819 }
5820 
processVolume_l(Track * track,bool lastTrack)5821 void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
5822 {
5823     float left, right;
5824 
5825     // Ensure volumeshaper state always advances even when muted.
5826     const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5827     const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5828             proxy->framesReleased());
5829     mVolumeShaperActive = shaperActive;
5830 
5831     if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5832         left = right = 0;
5833     } else {
5834         float typeVolume = mStreamTypes[track->streamType()].volume;
5835         const float v = mMasterVolume * typeVolume * shaperVolume;
5836 
5837         gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5838         left = float_from_gain(gain_minifloat_unpack_left(vlr));
5839         if (left > GAIN_FLOAT_UNITY) {
5840             left = GAIN_FLOAT_UNITY;
5841         }
5842         left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
5843         right = float_from_gain(gain_minifloat_unpack_right(vlr));
5844         if (right > GAIN_FLOAT_UNITY) {
5845             right = GAIN_FLOAT_UNITY;
5846         }
5847         right *= v * mMasterBalanceRight;
5848     }
5849 
5850     if (lastTrack) {
5851         track->setFinalVolume((left + right) / 2.f);
5852         if (left != mLeftVolFloat || right != mRightVolFloat) {
5853             mLeftVolFloat = left;
5854             mRightVolFloat = right;
5855 
5856             // Delegate volume control to effect in track effect chain if needed
5857             // only one effect chain can be present on DirectOutputThread, so if
5858             // there is one, the track is connected to it
5859             if (!mEffectChains.isEmpty()) {
5860                 // if effect chain exists, volume is handled by it.
5861                 // Convert volumes from float to 8.24
5862                 uint32_t vl = (uint32_t)(left * (1 << 24));
5863                 uint32_t vr = (uint32_t)(right * (1 << 24));
5864                 // Direct/Offload effect chains set output volume in setVolume_l().
5865                 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5866             } else {
5867                 // otherwise we directly set the volume.
5868                 setVolumeForOutput_l(left, right);
5869             }
5870         }
5871     }
5872 }
5873 
onAddNewTrack_l()5874 void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5875 {
5876     sp<Track> previousTrack = mPreviousTrack.promote();
5877     sp<Track> latestTrack = mActiveTracks.getLatest();
5878 
5879     if (previousTrack != 0 && latestTrack != 0) {
5880         if (mType == DIRECT) {
5881             if (previousTrack.get() != latestTrack.get()) {
5882                 mFlushPending = true;
5883             }
5884         } else /* mType == OFFLOAD */ {
5885             if (previousTrack->sessionId() != latestTrack->sessionId()) {
5886                 mFlushPending = true;
5887             }
5888         }
5889     } else if (previousTrack == 0) {
5890         // there could be an old track added back during track transition for direct
5891         // output, so always issues flush to flush data of the previous track if it
5892         // was already destroyed with HAL paused, then flush can resume the playback
5893         mFlushPending = true;
5894     }
5895     PlaybackThread::onAddNewTrack_l();
5896 }
5897 
prepareTracks_l(Vector<sp<Track>> * tracksToRemove)5898 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5899     Vector< sp<Track> > *tracksToRemove
5900 )
5901 {
5902     size_t count = mActiveTracks.size();
5903     mixer_state mixerStatus = MIXER_IDLE;
5904     bool doHwPause = false;
5905     bool doHwResume = false;
5906 
5907     // find out which tracks need to be processed
5908     for (const sp<Track> &t : mActiveTracks) {
5909         if (t->isInvalid()) {
5910             ALOGW("An invalidated track shouldn't be in active list");
5911             tracksToRemove->add(t);
5912             continue;
5913         }
5914 
5915         Track* const track = t.get();
5916 #ifdef VERY_VERY_VERBOSE_LOGGING
5917         audio_track_cblk_t* cblk = track->cblk();
5918 #endif
5919         // Only consider last track started for volume and mixer state control.
5920         // In theory an older track could underrun and restart after the new one starts
5921         // but as we only care about the transition phase between two tracks on a
5922         // direct output, it is not a problem to ignore the underrun case.
5923         sp<Track> l = mActiveTracks.getLatest();
5924         bool last = l.get() == track;
5925 
5926         if (track->isPausePending()) {
5927             track->pauseAck();
5928             // It is possible a track might have been flushed or stopped.
5929             // Other operations such as flush pending might occur on the next prepare.
5930             if (track->isPausing()) {
5931                 track->setPaused();
5932             }
5933             // Always perform pause, as an immediate flush will change
5934             // the pause state to be no longer isPausing().
5935             if (mHwSupportsPause && last && !mHwPaused) {
5936                 doHwPause = true;
5937                 mHwPaused = true;
5938             }
5939         } else if (track->isFlushPending()) {
5940             track->flushAck();
5941             if (last) {
5942                 mFlushPending = true;
5943             }
5944         } else if (track->isResumePending()) {
5945             track->resumeAck();
5946             if (last) {
5947                 mLeftVolFloat = mRightVolFloat = -1.0;
5948                 if (mHwPaused) {
5949                     doHwResume = true;
5950                     mHwPaused = false;
5951                 }
5952             }
5953         }
5954 
5955         // The first time a track is added we wait
5956         // for all its buffers to be filled before processing it.
5957         // Allow draining the buffer in case the client
5958         // app does not call stop() and relies on underrun to stop:
5959         // hence the test on (track->mRetryCount > 1).
5960         // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
5961         // so we accept any nonzero amount of data delivered by the AudioTrack (which will
5962         // reset the retry counter).
5963         // Do not use a high threshold for compressed audio.
5964 
5965         // target retry count that we will use is based on the time we wait for retries.
5966         const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
5967         // the retry threshold is when we accept any size for PCM data.  This is slightly
5968         // smaller than the retry count so we can push small bits of data without a glitch.
5969         const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
5970         uint32_t minFrames;
5971         if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
5972             && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
5973             minFrames = mNormalFrameCount;
5974         } else {
5975             minFrames = 1;
5976         }
5977 
5978         const size_t framesReady = track->framesReady();
5979         const int trackId = track->id();
5980         if (ATRACE_ENABLED()) {
5981             std::string traceName("nRdy");
5982             traceName += std::to_string(trackId);
5983             ATRACE_INT(traceName.c_str(), framesReady);
5984         }
5985         if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
5986                 !track->isStopping_2() && !track->isStopped())
5987         {
5988             ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
5989 
5990             if (track->mFillingUpStatus == Track::FS_FILLED) {
5991                 track->mFillingUpStatus = Track::FS_ACTIVE;
5992                 if (last) {
5993                     // make sure processVolume_l() will apply new volume even if 0
5994                     mLeftVolFloat = mRightVolFloat = -1.0;
5995                 }
5996                 if (!mHwSupportsPause) {
5997                     track->resumeAck();
5998                 }
5999             }
6000 
6001             // compute volume for this track
6002             processVolume_l(track, last);
6003             if (last) {
6004                 sp<Track> previousTrack = mPreviousTrack.promote();
6005                 if (previousTrack != 0) {
6006                     if (track != previousTrack.get()) {
6007                         // Flush any data still being written from last track
6008                         mBytesRemaining = 0;
6009                         // Invalidate previous track to force a seek when resuming.
6010                         previousTrack->invalidate();
6011                     }
6012                 }
6013                 mPreviousTrack = track;
6014 
6015                 // reset retry count
6016                 track->mRetryCount = targetRetryCount;
6017                 mActiveTrack = t;
6018                 mixerStatus = MIXER_TRACKS_READY;
6019                 if (mHwPaused) {
6020                     doHwResume = true;
6021                     mHwPaused = false;
6022                 }
6023             }
6024         } else {
6025             // clear effect chain input buffer if the last active track started underruns
6026             // to avoid sending previous audio buffer again to effects
6027             if (!mEffectChains.isEmpty() && last) {
6028                 mEffectChains[0]->clearInputBuffer();
6029             }
6030             if (track->isStopping_1()) {
6031                 track->mState = TrackBase::STOPPING_2;
6032                 if (last && mHwPaused) {
6033                      doHwResume = true;
6034                      mHwPaused = false;
6035                  }
6036             }
6037             if ((track->sharedBuffer() != 0) || track->isStopped() ||
6038                     track->isStopping_2() || track->isPaused()) {
6039                 // We have consumed all the buffers of this track.
6040                 // Remove it from the list of active tracks.
6041                 if (mStandby || !last ||
6042                         track->presentationComplete(latency_l()) ||
6043                         track->isPaused() || mHwPaused) {
6044                     if (track->isStopping_2()) {
6045                         track->mState = TrackBase::STOPPED;
6046                     }
6047                     if (track->isStopped()) {
6048                         track->reset();
6049                     }
6050                     tracksToRemove->add(track);
6051                 }
6052             } else {
6053                 // No buffers for this track. Give it a few chances to
6054                 // fill a buffer, then remove it from active list.
6055                 // Only consider last track started for mixer state control
6056                 if (--(track->mRetryCount) <= 0) {
6057                     ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6058                     tracksToRemove->add(track);
6059                     // indicate to client process that the track was disabled because of underrun;
6060                     // it will then automatically call start() when data is available
6061                     track->disable();
6062                     // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6063                     // unlike mixerthread, HAL can be paused for direct output
6064                     ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6065                             "minFrames = %u, mFormat = %#x",
6066                             framesReady, minFrames, mFormat);
6067                     if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6068                         doHwPause = true;
6069                         mHwPaused = true;
6070                     }
6071                 } else if (last) {
6072                     mixerStatus = MIXER_TRACKS_ENABLED;
6073                 }
6074             }
6075         }
6076     }
6077 
6078     // if an active track did not command a flush, check for pending flush on stopped tracks
6079     if (!mFlushPending) {
6080         for (size_t i = 0; i < mTracks.size(); i++) {
6081             if (mTracks[i]->isFlushPending()) {
6082                 mTracks[i]->flushAck();
6083                 mFlushPending = true;
6084             }
6085         }
6086     }
6087 
6088     // make sure the pause/flush/resume sequence is executed in the right order.
6089     // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6090     // before flush and then resume HW. This can happen in case of pause/flush/resume
6091     // if resume is received before pause is executed.
6092     if (mHwSupportsPause && !mStandby &&
6093             (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
6094         status_t result = mOutput->stream->pause();
6095         ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
6096     }
6097     if (mFlushPending) {
6098         flushHw_l();
6099     }
6100     if (mHwSupportsPause && !mStandby && doHwResume) {
6101         status_t result = mOutput->stream->resume();
6102         ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
6103     }
6104     // remove all the tracks that need to be...
6105     removeTracks_l(*tracksToRemove);
6106 
6107     return mixerStatus;
6108 }
6109 
threadLoop_mix()6110 void AudioFlinger::DirectOutputThread::threadLoop_mix()
6111 {
6112     size_t frameCount = mFrameCount;
6113     int8_t *curBuf = (int8_t *)mSinkBuffer;
6114     // output audio to hardware
6115     while (frameCount) {
6116         AudioBufferProvider::Buffer buffer;
6117         buffer.frameCount = frameCount;
6118         status_t status = mActiveTrack->getNextBuffer(&buffer);
6119         if (status != NO_ERROR || buffer.raw == NULL) {
6120             // no need to pad with 0 for compressed audio
6121             if (audio_has_proportional_frames(mFormat)) {
6122                 memset(curBuf, 0, frameCount * mFrameSize);
6123             }
6124             break;
6125         }
6126         memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6127         frameCount -= buffer.frameCount;
6128         curBuf += buffer.frameCount * mFrameSize;
6129         mActiveTrack->releaseBuffer(&buffer);
6130     }
6131     mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
6132     mSleepTimeUs = 0;
6133     mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6134     mActiveTrack.clear();
6135 }
6136 
threadLoop_sleepTime()6137 void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6138 {
6139     // do not write to HAL when paused
6140     if (mHwPaused || (usesHwAvSync() && mStandby)) {
6141         mSleepTimeUs = mIdleSleepTimeUs;
6142         return;
6143     }
6144     if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6145         mSleepTimeUs = mActiveSleepTimeUs;
6146     } else {
6147         mSleepTimeUs = mIdleSleepTimeUs;
6148     }
6149     // Note: In S or later, we do not write zeroes for
6150     // linear or proportional PCM direct tracks in underrun.
6151 }
6152 
threadLoop_exit()6153 void AudioFlinger::DirectOutputThread::threadLoop_exit()
6154 {
6155     {
6156         Mutex::Autolock _l(mLock);
6157         for (size_t i = 0; i < mTracks.size(); i++) {
6158             if (mTracks[i]->isFlushPending()) {
6159                 mTracks[i]->flushAck();
6160                 mFlushPending = true;
6161             }
6162         }
6163         if (mFlushPending) {
6164             flushHw_l();
6165         }
6166     }
6167     PlaybackThread::threadLoop_exit();
6168 }
6169 
6170 // must be called with thread mutex locked
shouldStandby_l()6171 bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6172 {
6173     bool trackPaused = false;
6174     bool trackStopped = false;
6175 
6176     // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6177     // after a timeout and we will enter standby then.
6178     if (mTracks.size() > 0) {
6179         trackPaused = mTracks[mTracks.size() - 1]->isPaused();
6180         trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6181                            mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
6182     }
6183 
6184     return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
6185 }
6186 
6187 // checkForNewParameter_l() must be called with ThreadBase::mLock held
checkForNewParameter_l(const String8 & keyValuePair,status_t & status)6188 bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6189                                                               status_t& status)
6190 {
6191     bool reconfig = false;
6192     status = NO_ERROR;
6193 
6194     AudioParameter param = AudioParameter(keyValuePair);
6195     int value;
6196     if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6197         LOG_FATAL("Should not set routing device in DirectOutputThread");
6198     }
6199     if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6200         // do not accept frame count changes if tracks are open as the track buffer
6201         // size depends on frame count and correct behavior would not be garantied
6202         // if frame count is changed after track creation
6203         if (!mTracks.isEmpty()) {
6204             status = INVALID_OPERATION;
6205         } else {
6206             reconfig = true;
6207         }
6208     }
6209     if (status == NO_ERROR) {
6210         status = mOutput->stream->setParameters(keyValuePair);
6211         if (!mStandby && status == INVALID_OPERATION) {
6212             mOutput->standby();
6213             if (!mStandby) {
6214                 mThreadMetrics.logEndInterval();
6215                 mStandby = true;
6216             }
6217             mBytesWritten = 0;
6218             status = mOutput->stream->setParameters(keyValuePair);
6219         }
6220         if (status == NO_ERROR && reconfig) {
6221             readOutputParameters_l();
6222             sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
6223         }
6224     }
6225 
6226     return reconfig;
6227 }
6228 
activeSleepTimeUs() const6229 uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6230 {
6231     uint32_t time;
6232     if (audio_has_proportional_frames(mFormat)) {
6233         time = PlaybackThread::activeSleepTimeUs();
6234     } else {
6235         time = kDirectMinSleepTimeUs;
6236     }
6237     return time;
6238 }
6239 
idleSleepTimeUs() const6240 uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6241 {
6242     uint32_t time;
6243     if (audio_has_proportional_frames(mFormat)) {
6244         time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6245     } else {
6246         time = kDirectMinSleepTimeUs;
6247     }
6248     return time;
6249 }
6250 
suspendSleepTimeUs() const6251 uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6252 {
6253     uint32_t time;
6254     if (audio_has_proportional_frames(mFormat)) {
6255         time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6256     } else {
6257         time = kDirectMinSleepTimeUs;
6258     }
6259     return time;
6260 }
6261 
cacheParameters_l()6262 void AudioFlinger::DirectOutputThread::cacheParameters_l()
6263 {
6264     PlaybackThread::cacheParameters_l();
6265 
6266     // use shorter standby delay as on normal output to release
6267     // hardware resources as soon as possible
6268     // no delay on outputs with HW A/V sync
6269     if (usesHwAvSync()) {
6270         mStandbyDelayNs = 0;
6271     } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
6272         mStandbyDelayNs = kOffloadStandbyDelayNs;
6273     } else {
6274         mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
6275     }
6276 }
6277 
flushHw_l()6278 void AudioFlinger::DirectOutputThread::flushHw_l()
6279 {
6280     mOutput->flush();
6281     mHwPaused = false;
6282     mFlushPending = false;
6283     mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
6284     mTimestamp.clear();
6285 }
6286 
computeWaitTimeNs_l() const6287 int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6288     // If a VolumeShaper is active, we must wake up periodically to update volume.
6289     const int64_t NS_PER_MS = 1000000;
6290     return mVolumeShaperActive ?
6291             kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6292 }
6293 
6294 // ----------------------------------------------------------------------------
6295 
AsyncCallbackThread(const wp<AudioFlinger::PlaybackThread> & playbackThread)6296 AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
6297         const wp<AudioFlinger::PlaybackThread>& playbackThread)
6298     :   Thread(false /*canCallJava*/),
6299         mPlaybackThread(playbackThread),
6300         mWriteAckSequence(0),
6301         mDrainSequence(0),
6302         mAsyncError(false)
6303 {
6304 }
6305 
~AsyncCallbackThread()6306 AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6307 {
6308 }
6309 
onFirstRef()6310 void AudioFlinger::AsyncCallbackThread::onFirstRef()
6311 {
6312     run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6313 }
6314 
threadLoop()6315 bool AudioFlinger::AsyncCallbackThread::threadLoop()
6316 {
6317     while (!exitPending()) {
6318         uint32_t writeAckSequence;
6319         uint32_t drainSequence;
6320         bool asyncError;
6321 
6322         {
6323             Mutex::Autolock _l(mLock);
6324             while (!((mWriteAckSequence & 1) ||
6325                      (mDrainSequence & 1) ||
6326                      mAsyncError ||
6327                      exitPending())) {
6328                 mWaitWorkCV.wait(mLock);
6329             }
6330 
6331             if (exitPending()) {
6332                 break;
6333             }
6334             ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6335                   mWriteAckSequence, mDrainSequence);
6336             writeAckSequence = mWriteAckSequence;
6337             mWriteAckSequence &= ~1;
6338             drainSequence = mDrainSequence;
6339             mDrainSequence &= ~1;
6340             asyncError = mAsyncError;
6341             mAsyncError = false;
6342         }
6343         {
6344             sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6345             if (playbackThread != 0) {
6346                 if (writeAckSequence & 1) {
6347                     playbackThread->resetWriteBlocked(writeAckSequence >> 1);
6348                 }
6349                 if (drainSequence & 1) {
6350                     playbackThread->resetDraining(drainSequence >> 1);
6351                 }
6352                 if (asyncError) {
6353                     playbackThread->onAsyncError();
6354                 }
6355             }
6356         }
6357     }
6358     return false;
6359 }
6360 
exit()6361 void AudioFlinger::AsyncCallbackThread::exit()
6362 {
6363     ALOGV("AsyncCallbackThread::exit");
6364     Mutex::Autolock _l(mLock);
6365     requestExit();
6366     mWaitWorkCV.broadcast();
6367 }
6368 
setWriteBlocked(uint32_t sequence)6369 void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
6370 {
6371     Mutex::Autolock _l(mLock);
6372     // bit 0 is cleared
6373     mWriteAckSequence = sequence << 1;
6374 }
6375 
resetWriteBlocked()6376 void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6377 {
6378     Mutex::Autolock _l(mLock);
6379     // ignore unexpected callbacks
6380     if (mWriteAckSequence & 2) {
6381         mWriteAckSequence |= 1;
6382         mWaitWorkCV.signal();
6383     }
6384 }
6385 
setDraining(uint32_t sequence)6386 void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
6387 {
6388     Mutex::Autolock _l(mLock);
6389     // bit 0 is cleared
6390     mDrainSequence = sequence << 1;
6391 }
6392 
resetDraining()6393 void AudioFlinger::AsyncCallbackThread::resetDraining()
6394 {
6395     Mutex::Autolock _l(mLock);
6396     // ignore unexpected callbacks
6397     if (mDrainSequence & 2) {
6398         mDrainSequence |= 1;
6399         mWaitWorkCV.signal();
6400     }
6401 }
6402 
setAsyncError()6403 void AudioFlinger::AsyncCallbackThread::setAsyncError()
6404 {
6405     Mutex::Autolock _l(mLock);
6406     mAsyncError = true;
6407     mWaitWorkCV.signal();
6408 }
6409 
6410 
6411 // ----------------------------------------------------------------------------
OffloadThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,bool systemReady)6412 AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
6413         AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6414     :   DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
6415         mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6416         mOffloadUnderrunPosition(~0LL)
6417 {
6418     //FIXME: mStandby should be set to true by ThreadBase constructo
6419     mStandby = true;
6420     mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
6421 }
6422 
threadLoop_exit()6423 void AudioFlinger::OffloadThread::threadLoop_exit()
6424 {
6425     if (mFlushPending || mHwPaused) {
6426         // If a flush is pending or track was paused, just discard buffered data
6427         flushHw_l();
6428     } else {
6429         mMixerStatus = MIXER_DRAIN_ALL;
6430         threadLoop_drain();
6431     }
6432     if (mUseAsyncWrite) {
6433         ALOG_ASSERT(mCallbackThread != 0);
6434         mCallbackThread->exit();
6435     }
6436     PlaybackThread::threadLoop_exit();
6437 }
6438 
prepareTracks_l(Vector<sp<Track>> * tracksToRemove)6439 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6440     Vector< sp<Track> > *tracksToRemove
6441 )
6442 {
6443     size_t count = mActiveTracks.size();
6444 
6445     mixer_state mixerStatus = MIXER_IDLE;
6446     bool doHwPause = false;
6447     bool doHwResume = false;
6448 
6449     ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
6450 
6451     // find out which tracks need to be processed
6452     for (const sp<Track> &t : mActiveTracks) {
6453         Track* const track = t.get();
6454 #ifdef VERY_VERY_VERBOSE_LOGGING
6455         audio_track_cblk_t* cblk = track->cblk();
6456 #endif
6457         // Only consider last track started for volume and mixer state control.
6458         // In theory an older track could underrun and restart after the new one starts
6459         // but as we only care about the transition phase between two tracks on a
6460         // direct output, it is not a problem to ignore the underrun case.
6461         sp<Track> l = mActiveTracks.getLatest();
6462         bool last = l.get() == track;
6463 
6464         if (track->isInvalid()) {
6465             ALOGW("An invalidated track shouldn't be in active list");
6466             tracksToRemove->add(track);
6467             continue;
6468         }
6469 
6470         if (track->mState == TrackBase::IDLE) {
6471             ALOGW("An idle track shouldn't be in active list");
6472             continue;
6473         }
6474 
6475         if (track->isPausePending()) {
6476             track->pauseAck();
6477             // It is possible a track might have been flushed or stopped.
6478             // Other operations such as flush pending might occur on the next prepare.
6479             if (track->isPausing()) {
6480                 track->setPaused();
6481             }
6482             // Always perform pause if last, as an immediate flush will change
6483             // the pause state to be no longer isPausing().
6484             if (last) {
6485                 if (mHwSupportsPause && !mHwPaused) {
6486                     doHwPause = true;
6487                     mHwPaused = true;
6488                 }
6489                 // If we were part way through writing the mixbuffer to
6490                 // the HAL we must save this until we resume
6491                 // BUG - this will be wrong if a different track is made active,
6492                 // in that case we want to discard the pending data in the
6493                 // mixbuffer and tell the client to present it again when the
6494                 // track is resumed
6495                 mPausedWriteLength = mCurrentWriteLength;
6496                 mPausedBytesRemaining = mBytesRemaining;
6497                 mBytesRemaining = 0;    // stop writing
6498             }
6499             tracksToRemove->add(track);
6500         } else if (track->isFlushPending()) {
6501             if (track->isStopping_1()) {
6502                 track->mRetryCount = kMaxTrackStopRetriesOffload;
6503             } else {
6504                 track->mRetryCount = kMaxTrackRetriesOffload;
6505             }
6506             track->flushAck();
6507             if (last) {
6508                 mFlushPending = true;
6509             }
6510         } else if (track->isResumePending()){
6511             track->resumeAck();
6512             if (last) {
6513                 if (mPausedBytesRemaining) {
6514                     // Need to continue write that was interrupted
6515                     mCurrentWriteLength = mPausedWriteLength;
6516                     mBytesRemaining = mPausedBytesRemaining;
6517                     mPausedBytesRemaining = 0;
6518                 }
6519                 if (mHwPaused) {
6520                     doHwResume = true;
6521                     mHwPaused = false;
6522                     // threadLoop_mix() will handle the case that we need to
6523                     // resume an interrupted write
6524                 }
6525                 // enable write to audio HAL
6526                 mSleepTimeUs = 0;
6527 
6528                 mLeftVolFloat = mRightVolFloat = -1.0;
6529 
6530                 // Do not handle new data in this iteration even if track->framesReady()
6531                 mixerStatus = MIXER_TRACKS_ENABLED;
6532             }
6533         }  else if (track->framesReady() && track->isReady() &&
6534                 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
6535             ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
6536             if (track->mFillingUpStatus == Track::FS_FILLED) {
6537                 track->mFillingUpStatus = Track::FS_ACTIVE;
6538                 if (last) {
6539                     // make sure processVolume_l() will apply new volume even if 0
6540                     mLeftVolFloat = mRightVolFloat = -1.0;
6541                 }
6542             }
6543 
6544             if (last) {
6545                 sp<Track> previousTrack = mPreviousTrack.promote();
6546                 if (previousTrack != 0) {
6547                     if (track != previousTrack.get()) {
6548                         // Flush any data still being written from last track
6549                         mBytesRemaining = 0;
6550                         if (mPausedBytesRemaining) {
6551                             // Last track was paused so we also need to flush saved
6552                             // mixbuffer state and invalidate track so that it will
6553                             // re-submit that unwritten data when it is next resumed
6554                             mPausedBytesRemaining = 0;
6555                             // Invalidate is a bit drastic - would be more efficient
6556                             // to have a flag to tell client that some of the
6557                             // previously written data was lost
6558                             previousTrack->invalidate();
6559                         }
6560                         // flush data already sent to the DSP if changing audio session as audio
6561                         // comes from a different source. Also invalidate previous track to force a
6562                         // seek when resuming.
6563                         if (previousTrack->sessionId() != track->sessionId()) {
6564                             previousTrack->invalidate();
6565                         }
6566                     }
6567                 }
6568                 mPreviousTrack = track;
6569                 // reset retry count
6570                 if (track->isStopping_1()) {
6571                     track->mRetryCount = kMaxTrackStopRetriesOffload;
6572                 } else {
6573                     track->mRetryCount = kMaxTrackRetriesOffload;
6574                 }
6575                 mActiveTrack = t;
6576                 mixerStatus = MIXER_TRACKS_READY;
6577             }
6578         } else {
6579             ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
6580             if (track->isStopping_1()) {
6581                 if (--(track->mRetryCount) <= 0) {
6582                     // Hardware buffer can hold a large amount of audio so we must
6583                     // wait for all current track's data to drain before we say
6584                     // that the track is stopped.
6585                     if (mBytesRemaining == 0) {
6586                         // Only start draining when all data in mixbuffer
6587                         // has been written
6588                         ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6589                         track->mState = TrackBase::STOPPING_2; // so presentation completes after
6590                         // drain do not drain if no data was ever sent to HAL (mStandby == true)
6591                         if (last && !mStandby) {
6592                             // do not modify drain sequence if we are already draining. This happens
6593                             // when resuming from pause after drain.
6594                             if ((mDrainSequence & 1) == 0) {
6595                                 mSleepTimeUs = 0;
6596                                 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6597                                 mixerStatus = MIXER_DRAIN_TRACK;
6598                                 mDrainSequence += 2;
6599                             }
6600                             if (mHwPaused) {
6601                                 // It is possible to move from PAUSED to STOPPING_1 without
6602                                 // a resume so we must ensure hardware is running
6603                                 doHwResume = true;
6604                                 mHwPaused = false;
6605                             }
6606                         }
6607                     }
6608                 } else if (last) {
6609                     ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6610                     mixerStatus = MIXER_TRACKS_ENABLED;
6611                 }
6612             } else if (track->isStopping_2()) {
6613                 // Drain has completed or we are in standby, signal presentation complete
6614                 if (!(mDrainSequence & 1) || !last || mStandby) {
6615                     track->mState = TrackBase::STOPPED;
6616                     track->presentationComplete(latency_l());
6617                     track->reset();
6618                     tracksToRemove->add(track);
6619                     // OFFLOADED stop resets frame counts.
6620                     if (!mUseAsyncWrite) {
6621                         // If we don't get explicit drain notification we must
6622                         // register discontinuity regardless of whether this is
6623                         // the previous (!last) or the upcoming (last) track
6624                         // to avoid skipping the discontinuity.
6625                         mTimestampVerifier.discontinuity(
6626                                 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
6627                     }
6628                 }
6629             } else {
6630                 // No buffers for this track. Give it a few chances to
6631                 // fill a buffer, then remove it from active list.
6632                 if (--(track->mRetryCount) <= 0) {
6633                     bool running = false;
6634                     uint64_t position = 0;
6635                     struct timespec unused;
6636                     // The running check restarts the retry counter at least once.
6637                     status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6638                     if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6639                         running = true;
6640                         mOffloadUnderrunPosition = position;
6641                     }
6642                     if (ret == NO_ERROR) {
6643                         ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6644                                 (long long)position, (long long)mOffloadUnderrunPosition);
6645                     }
6646                     if (running) { // still running, give us more time.
6647                         track->mRetryCount = kMaxTrackRetriesOffload;
6648                     } else {
6649                         ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6650                                 track->id());
6651                         tracksToRemove->add(track);
6652                         // tell client process that the track was disabled because of underrun;
6653                         // it will then automatically call start() when data is available
6654                         track->disable();
6655                     }
6656                 } else if (last){
6657                     mixerStatus = MIXER_TRACKS_ENABLED;
6658                 }
6659             }
6660         }
6661         // compute volume for this track
6662         if (track->isReady()) {  // check ready to prevent premature start.
6663             processVolume_l(track, last);
6664         }
6665     }
6666 
6667     // make sure the pause/flush/resume sequence is executed in the right order.
6668     // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6669     // before flush and then resume HW. This can happen in case of pause/flush/resume
6670     // if resume is received before pause is executed.
6671     if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
6672         status_t result = mOutput->stream->pause();
6673         ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
6674     }
6675     if (mFlushPending) {
6676         flushHw_l();
6677     }
6678     if (!mStandby && doHwResume) {
6679         status_t result = mOutput->stream->resume();
6680         ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
6681     }
6682 
6683     // remove all the tracks that need to be...
6684     removeTracks_l(*tracksToRemove);
6685 
6686     return mixerStatus;
6687 }
6688 
6689 // must be called with thread mutex locked
waitingAsyncCallback_l()6690 bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6691 {
6692     ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6693           mWriteAckSequence, mDrainSequence);
6694     if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
6695         return true;
6696     }
6697     return false;
6698 }
6699 
waitingAsyncCallback()6700 bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6701 {
6702     Mutex::Autolock _l(mLock);
6703     return waitingAsyncCallback_l();
6704 }
6705 
flushHw_l()6706 void AudioFlinger::OffloadThread::flushHw_l()
6707 {
6708     DirectOutputThread::flushHw_l();
6709     // Flush anything still waiting in the mixbuffer
6710     mCurrentWriteLength = 0;
6711     mBytesRemaining = 0;
6712     mPausedWriteLength = 0;
6713     mPausedBytesRemaining = 0;
6714     // reset bytes written count to reflect that DSP buffers are empty after flush.
6715     mBytesWritten = 0;
6716     mOffloadUnderrunPosition = ~0LL;
6717 
6718     if (mUseAsyncWrite) {
6719         // discard any pending drain or write ack by incrementing sequence
6720         mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6721         mDrainSequence = (mDrainSequence + 2) & ~1;
6722         ALOG_ASSERT(mCallbackThread != 0);
6723         mCallbackThread->setWriteBlocked(mWriteAckSequence);
6724         mCallbackThread->setDraining(mDrainSequence);
6725     }
6726 }
6727 
invalidateTracks(audio_stream_type_t streamType)6728 void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6729 {
6730     Mutex::Autolock _l(mLock);
6731     if (PlaybackThread::invalidateTracks_l(streamType)) {
6732         mFlushPending = true;
6733     }
6734 }
6735 
6736 // ----------------------------------------------------------------------------
6737 
DuplicatingThread(const sp<AudioFlinger> & audioFlinger,AudioFlinger::MixerThread * mainThread,audio_io_handle_t id,bool systemReady)6738 AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
6739         AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
6740     :   MixerThread(audioFlinger, mainThread->getOutput(), id,
6741                     systemReady, DUPLICATING),
6742         mWaitTimeMs(UINT_MAX)
6743 {
6744     addOutputTrack(mainThread);
6745 }
6746 
~DuplicatingThread()6747 AudioFlinger::DuplicatingThread::~DuplicatingThread()
6748 {
6749     for (size_t i = 0; i < mOutputTracks.size(); i++) {
6750         mOutputTracks[i]->destroy();
6751     }
6752 }
6753 
threadLoop_mix()6754 void AudioFlinger::DuplicatingThread::threadLoop_mix()
6755 {
6756     // mix buffers...
6757     if (outputsReady(outputTracks)) {
6758         mAudioMixer->process();
6759     } else {
6760         if (mMixerBufferValid) {
6761             memset(mMixerBuffer, 0, mMixerBufferSize);
6762         } else {
6763             memset(mSinkBuffer, 0, mSinkBufferSize);
6764         }
6765     }
6766     mSleepTimeUs = 0;
6767     writeFrames = mNormalFrameCount;
6768     mCurrentWriteLength = mSinkBufferSize;
6769     mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6770 }
6771 
threadLoop_sleepTime()6772 void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6773 {
6774     if (mSleepTimeUs == 0) {
6775         if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6776             mSleepTimeUs = mActiveSleepTimeUs;
6777         } else {
6778             mSleepTimeUs = mIdleSleepTimeUs;
6779         }
6780     } else if (mBytesWritten != 0) {
6781         if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6782             writeFrames = mNormalFrameCount;
6783             memset(mSinkBuffer, 0, mSinkBufferSize);
6784         } else {
6785             // flush remaining overflow buffers in output tracks
6786             writeFrames = 0;
6787         }
6788         mSleepTimeUs = 0;
6789     }
6790 }
6791 
threadLoop_write()6792 ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
6793 {
6794     for (size_t i = 0; i < outputTracks.size(); i++) {
6795         const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6796 
6797         // Consider the first OutputTrack for timestamp and frame counting.
6798 
6799         // The threadLoop() generally assumes writing a full sink buffer size at a time.
6800         // Here, we correct for writeFrames of 0 (a stop) or underruns because
6801         // we always claim success.
6802         if (i == 0) {
6803             const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6804             ALOGD_IF(correction != 0 && writeFrames != 0,
6805                     "%s: writeFrames:%u  actualWritten:%zd  correction:%zd  mFramesWritten:%lld",
6806                     __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6807             mFramesWritten -= correction;
6808         }
6809 
6810         // TODO: Report correction for the other output tracks and show in the dump.
6811     }
6812     if (mStandby) {
6813         mThreadMetrics.logBeginInterval();
6814         mStandby = false;
6815     }
6816     return (ssize_t)mSinkBufferSize;
6817 }
6818 
threadLoop_standby()6819 void AudioFlinger::DuplicatingThread::threadLoop_standby()
6820 {
6821     // DuplicatingThread implements standby by stopping all tracks
6822     for (size_t i = 0; i < outputTracks.size(); i++) {
6823         outputTracks[i]->stop();
6824     }
6825 }
6826 
dumpInternals_l(int fd,const Vector<String16> & args __unused)6827 void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
6828 {
6829     MixerThread::dumpInternals_l(fd, args);
6830 
6831     std::stringstream ss;
6832     const size_t numTracks = mOutputTracks.size();
6833     ss << "  " << numTracks << " OutputTracks";
6834     if (numTracks > 0) {
6835         ss << ":";
6836         for (const auto &track : mOutputTracks) {
6837             const sp<ThreadBase> thread = track->thread().promote();
6838             ss << " (" << track->id() << " : ";
6839             if (thread.get() != nullptr) {
6840                 ss << thread.get() << ", " << thread->id();
6841             } else {
6842                 ss << "null";
6843             }
6844             ss << ")";
6845         }
6846     }
6847     ss << "\n";
6848     std::string result = ss.str();
6849     write(fd, result.c_str(), result.size());
6850 }
6851 
saveOutputTracks()6852 void AudioFlinger::DuplicatingThread::saveOutputTracks()
6853 {
6854     outputTracks = mOutputTracks;
6855 }
6856 
clearOutputTracks()6857 void AudioFlinger::DuplicatingThread::clearOutputTracks()
6858 {
6859     outputTracks.clear();
6860 }
6861 
addOutputTrack(MixerThread * thread)6862 void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6863 {
6864     Mutex::Autolock _l(mLock);
6865     // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6866     // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6867     // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6868     const size_t frameCount =
6869             3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6870     // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6871     // from different OutputTracks and their associated MixerThreads (e.g. one may
6872     // nearly empty and the other may be dropping data).
6873 
6874     // TODO b/182392769: use attribution source util, move to server edge
6875     AttributionSourceState attributionSource = AttributionSourceState();
6876     attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
6877         IPCThreadState::self()->getCallingUid()));
6878     attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
6879       IPCThreadState::self()->getCallingPid()));
6880     attributionSource.token = sp<BBinder>::make();
6881     sp<OutputTrack> outputTrack = new OutputTrack(thread,
6882                                             this,
6883                                             mSampleRate,
6884                                             mFormat,
6885                                             mChannelMask,
6886                                             frameCount,
6887                                             attributionSource);
6888     status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6889     if (status != NO_ERROR) {
6890         ALOGE("addOutputTrack() initCheck failed %d", status);
6891         return;
6892     }
6893     thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6894     mOutputTracks.add(outputTrack);
6895     ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6896     updateWaitTime_l();
6897 }
6898 
removeOutputTrack(MixerThread * thread)6899 void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6900 {
6901     Mutex::Autolock _l(mLock);
6902     for (size_t i = 0; i < mOutputTracks.size(); i++) {
6903         if (mOutputTracks[i]->thread() == thread) {
6904             mOutputTracks[i]->destroy();
6905             mOutputTracks.removeAt(i);
6906             updateWaitTime_l();
6907             if (thread->getOutput() == mOutput) {
6908                 mOutput = NULL;
6909             }
6910             return;
6911         }
6912     }
6913     ALOGV("removeOutputTrack(): unknown thread: %p", thread);
6914 }
6915 
6916 // caller must hold mLock
updateWaitTime_l()6917 void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6918 {
6919     mWaitTimeMs = UINT_MAX;
6920     for (size_t i = 0; i < mOutputTracks.size(); i++) {
6921         sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6922         if (strong != 0) {
6923             uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6924             if (waitTimeMs < mWaitTimeMs) {
6925                 mWaitTimeMs = waitTimeMs;
6926             }
6927         }
6928     }
6929 }
6930 
6931 
outputsReady(const SortedVector<sp<OutputTrack>> & outputTracks)6932 bool AudioFlinger::DuplicatingThread::outputsReady(
6933         const SortedVector< sp<OutputTrack> > &outputTracks)
6934 {
6935     for (size_t i = 0; i < outputTracks.size(); i++) {
6936         sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6937         if (thread == 0) {
6938             ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6939                     outputTracks[i].get());
6940             return false;
6941         }
6942         PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6943         // see note at standby() declaration
6944         if (playbackThread->standby() && !playbackThread->isSuspended()) {
6945             ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6946                     thread.get());
6947             return false;
6948         }
6949     }
6950     return true;
6951 }
6952 
sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata & metadata)6953 void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6954         const StreamOutHalInterface::SourceMetadata& metadata)
6955 {
6956     for (auto& outputTrack : outputTracks) { // not mOutputTracks
6957         outputTrack->setMetadatas(metadata.tracks);
6958     }
6959 }
6960 
activeSleepTimeUs() const6961 uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6962 {
6963     return (mWaitTimeMs * 1000) / 2;
6964 }
6965 
cacheParameters_l()6966 void AudioFlinger::DuplicatingThread::cacheParameters_l()
6967 {
6968     // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6969     updateWaitTime_l();
6970 
6971     MixerThread::cacheParameters_l();
6972 }
6973 
6974 
6975 // ----------------------------------------------------------------------------
6976 //      Record
6977 // ----------------------------------------------------------------------------
6978 
RecordThread(const sp<AudioFlinger> & audioFlinger,AudioStreamIn * input,audio_io_handle_t id,bool systemReady)6979 AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6980                                          AudioStreamIn *input,
6981                                          audio_io_handle_t id,
6982                                          bool systemReady
6983                                          ) :
6984     ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
6985     mInput(input),
6986     mSource(mInput),
6987     mActiveTracks(&this->mLocalLog),
6988     mRsmpInBuffer(NULL),
6989     // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
6990     mRsmpInRear(0)
6991     , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6992             "RecordThreadRO", MemoryHeapBase::READ_ONLY))
6993     // mFastCapture below
6994     , mFastCaptureFutex(0)
6995     // mInputSource
6996     // mPipeSink
6997     // mPipeSource
6998     , mPipeFramesP2(0)
6999     // mPipeMemory
7000     // mFastCaptureNBLogWriter
7001     , mFastTrackAvail(false)
7002     , mBtNrecSuspended(false)
7003 {
7004     snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7005     mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
7006 
7007     if (mInput->audioHwDev != nullptr) {
7008         mIsMsdDevice = strcmp(
7009                 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7010     }
7011 
7012     readInputParameters_l();
7013 
7014     // TODO: We may also match on address as well as device type for
7015     // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
7016     // TODO: This property should be ensure that only contains one single device type.
7017     mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7018             "audio.timestamp.corrected_input_device",
7019             (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7020                                    : AUDIO_DEVICE_NONE));
7021 
7022     // create an NBAIO source for the HAL input stream, and negotiate
7023     mInputSource = new AudioStreamInSource(input->stream);
7024     size_t numCounterOffers = 0;
7025     const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
7026 #if !LOG_NDEBUG
7027     ssize_t index =
7028 #else
7029     (void)
7030 #endif
7031             mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
7032     ALOG_ASSERT(index == 0);
7033 
7034     // initialize fast capture depending on configuration
7035     bool initFastCapture;
7036     switch (kUseFastCapture) {
7037     case FastCapture_Never:
7038         initFastCapture = false;
7039         ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
7040         break;
7041     case FastCapture_Always:
7042         initFastCapture = true;
7043         ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
7044         break;
7045     case FastCapture_Static:
7046         initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7047         ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7048                 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7049                 initFastCapture);
7050         break;
7051     // case FastCapture_Dynamic:
7052     }
7053 
7054     if (initFastCapture) {
7055         // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
7056         NBAIO_Format format = mInputSource->format();
7057         // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7058         size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
7059         size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
7060         void *pipeBuffer = nullptr;
7061         const sp<MemoryDealer> roHeap(readOnlyHeap());
7062         sp<IMemory> pipeMemory;
7063         if ((roHeap == 0) ||
7064                 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
7065                 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
7066             ALOGE("not enough memory for pipe buffer size=%zu; "
7067                     "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7068                     pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7069                     (long long)kRecordThreadReadOnlyHeapSize);
7070             goto failed;
7071         }
7072         // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7073         memset(pipeBuffer, 0, pipeSize);
7074         Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7075         const NBAIO_Format offers[1] = {format};
7076         size_t numCounterOffers = 0;
7077         ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7078         ALOG_ASSERT(index == 0);
7079         mPipeSink = pipe;
7080         PipeReader *pipeReader = new PipeReader(*pipe);
7081         numCounterOffers = 0;
7082         index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7083         ALOG_ASSERT(index == 0);
7084         mPipeSource = pipeReader;
7085         mPipeFramesP2 = pipeFramesP2;
7086         mPipeMemory = pipeMemory;
7087 
7088         // create fast capture
7089         mFastCapture = new FastCapture();
7090         FastCaptureStateQueue *sq = mFastCapture->sq();
7091 #ifdef STATE_QUEUE_DUMP
7092         // FIXME
7093 #endif
7094         FastCaptureState *state = sq->begin();
7095         state->mCblk = NULL;
7096         state->mInputSource = mInputSource.get();
7097         state->mInputSourceGen++;
7098         state->mPipeSink = pipe;
7099         state->mPipeSinkGen++;
7100         state->mFrameCount = mFrameCount;
7101         state->mCommand = FastCaptureState::COLD_IDLE;
7102         // already done in constructor initialization list
7103         //mFastCaptureFutex = 0;
7104         state->mColdFutexAddr = &mFastCaptureFutex;
7105         state->mColdGen++;
7106         state->mDumpState = &mFastCaptureDumpState;
7107 #ifdef TEE_SINK
7108         // FIXME
7109 #endif
7110         mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7111         state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7112         sq->end();
7113         sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7114 
7115         // start the fast capture
7116         mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7117         pid_t tid = mFastCapture->getTid();
7118         sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
7119         stream()->setHalThreadPriority(kPriorityFastCapture);
7120 #ifdef AUDIO_WATCHDOG
7121         // FIXME
7122 #endif
7123 
7124         mFastTrackAvail = true;
7125     }
7126 #ifdef TEE_SINK
7127     mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7128     mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7129 #endif
7130 failed: ;
7131 
7132     // FIXME mNormalSource
7133 }
7134 
~RecordThread()7135 AudioFlinger::RecordThread::~RecordThread()
7136 {
7137     if (mFastCapture != 0) {
7138         FastCaptureStateQueue *sq = mFastCapture->sq();
7139         FastCaptureState *state = sq->begin();
7140         if (state->mCommand == FastCaptureState::COLD_IDLE) {
7141             int32_t old = android_atomic_inc(&mFastCaptureFutex);
7142             if (old == -1) {
7143                 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7144             }
7145         }
7146         state->mCommand = FastCaptureState::EXIT;
7147         sq->end();
7148         sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7149         mFastCapture->join();
7150         mFastCapture.clear();
7151     }
7152     mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
7153     mAudioFlinger->unregisterWriter(mNBLogWriter);
7154     free(mRsmpInBuffer);
7155 }
7156 
onFirstRef()7157 void AudioFlinger::RecordThread::onFirstRef()
7158 {
7159     run(mThreadName, PRIORITY_URGENT_AUDIO);
7160 }
7161 
preExit()7162 void AudioFlinger::RecordThread::preExit()
7163 {
7164     ALOGV("  preExit()");
7165     Mutex::Autolock _l(mLock);
7166     for (size_t i = 0; i < mTracks.size(); i++) {
7167         sp<RecordTrack> track = mTracks[i];
7168         track->invalidate();
7169     }
7170     mActiveTracks.clear();
7171     mStartStopCond.broadcast();
7172 }
7173 
threadLoop()7174 bool AudioFlinger::RecordThread::threadLoop()
7175 {
7176     nsecs_t lastWarning = 0;
7177 
7178     inputStandBy();
7179 
7180 reacquire_wakelock:
7181     sp<RecordTrack> activeTrack;
7182     {
7183         Mutex::Autolock _l(mLock);
7184         acquireWakeLock_l();
7185     }
7186 
7187     // used to request a deferred sleep, to be executed later while mutex is unlocked
7188     uint32_t sleepUs = 0;
7189 
7190     int64_t lastLoopCountRead = -2;  // never matches "previous" loop, when loopCount = 0.
7191 
7192     // loop while there is work to do
7193     for (int64_t loopCount = 0;; ++loopCount) {  // loopCount used for statistics tracking
7194         Vector< sp<EffectChain> > effectChains;
7195 
7196         // activeTracks accumulates a copy of a subset of mActiveTracks
7197         Vector< sp<RecordTrack> > activeTracks;
7198 
7199         // reference to the (first and only) active fast track
7200         sp<RecordTrack> fastTrack;
7201 
7202         // reference to a fast track which is about to be removed
7203         sp<RecordTrack> fastTrackToRemove;
7204 
7205         bool silenceFastCapture = false;
7206 
7207         { // scope for mLock
7208             Mutex::Autolock _l(mLock);
7209 
7210             processConfigEvents_l();
7211 
7212             // check exitPending here because checkForNewParameters_l() and
7213             // checkForNewParameters_l() can temporarily release mLock
7214             if (exitPending()) {
7215                 break;
7216             }
7217 
7218             // sleep with mutex unlocked
7219             if (sleepUs > 0) {
7220                 ATRACE_BEGIN("sleepC");
7221                 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7222                 ATRACE_END();
7223                 sleepUs = 0;
7224                 continue;
7225             }
7226 
7227             // if no active track(s), then standby and release wakelock
7228             size_t size = mActiveTracks.size();
7229             if (size == 0) {
7230                 standbyIfNotAlreadyInStandby();
7231                 // exitPending() can't become true here
7232                 releaseWakeLock_l();
7233                 ALOGV("RecordThread: loop stopping");
7234                 // go to sleep
7235                 mWaitWorkCV.wait(mLock);
7236                 ALOGV("RecordThread: loop starting");
7237                 goto reacquire_wakelock;
7238             }
7239 
7240             bool doBroadcast = false;
7241             bool allStopped = true;
7242             for (size_t i = 0; i < size; ) {
7243 
7244                 activeTrack = mActiveTracks[i];
7245                 if (activeTrack->isTerminated()) {
7246                     if (activeTrack->isFastTrack()) {
7247                         ALOG_ASSERT(fastTrackToRemove == 0);
7248                         fastTrackToRemove = activeTrack;
7249                     }
7250                     removeTrack_l(activeTrack);
7251                     mActiveTracks.remove(activeTrack);
7252                     size--;
7253                     continue;
7254                 }
7255 
7256                 TrackBase::track_state activeTrackState = activeTrack->mState;
7257                 switch (activeTrackState) {
7258 
7259                 case TrackBase::PAUSING:
7260                     mActiveTracks.remove(activeTrack);
7261                     activeTrack->mState = TrackBase::PAUSED;
7262                     doBroadcast = true;
7263                     size--;
7264                     continue;
7265 
7266                 case TrackBase::STARTING_1:
7267                     sleepUs = 10000;
7268                     i++;
7269                     allStopped = false;
7270                     continue;
7271 
7272                 case TrackBase::STARTING_2:
7273                     doBroadcast = true;
7274                     if (mStandby) {
7275                         mThreadMetrics.logBeginInterval();
7276                         mStandby = false;
7277                     }
7278                     activeTrack->mState = TrackBase::ACTIVE;
7279                     allStopped = false;
7280                     break;
7281 
7282                 case TrackBase::ACTIVE:
7283                     allStopped = false;
7284                     break;
7285 
7286                 case TrackBase::IDLE:    // cannot be on ActiveTracks if idle
7287                 case TrackBase::PAUSED:  // cannot be on ActiveTracks if paused
7288                 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
7289                 default:
7290                     LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7291                             __func__, activeTrackState, activeTrack->id(), size);
7292                 }
7293 
7294                 if (activeTrack->isFastTrack()) {
7295                     ALOG_ASSERT(!mFastTrackAvail);
7296                     ALOG_ASSERT(fastTrack == 0);
7297                     // if the active fast track is silenced either:
7298                     // 1) silence the whole capture from fast capture buffer if this is
7299                     //    the only active track
7300                     // 2) invalidate this track: this will cause the client to reconnect and possibly
7301                     //    be invalidated again until unsilenced
7302                     bool invalidate = false;
7303                     if (activeTrack->isSilenced()) {
7304                         if (size > 1) {
7305                             invalidate = true;
7306                         } else {
7307                             silenceFastCapture = true;
7308                         }
7309                     }
7310                     // Invalidate fast tracks if access to audio history is required as this is not
7311                     // possible with fast tracks. Once the fast track has been invalidated, no new
7312                     // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7313                     if (mMaxSharedAudioHistoryMs != 0) {
7314                         invalidate = true;
7315                     }
7316                     if (invalidate) {
7317                         activeTrack->invalidate();
7318                         ALOG_ASSERT(fastTrackToRemove == 0);
7319                         fastTrackToRemove = activeTrack;
7320                         removeTrack_l(activeTrack);
7321                         mActiveTracks.remove(activeTrack);
7322                         size--;
7323                         continue;
7324                     }
7325                     fastTrack = activeTrack;
7326                 }
7327 
7328                 activeTracks.add(activeTrack);
7329                 i++;
7330 
7331             }
7332 
7333             mActiveTracks.updatePowerState(this);
7334 
7335             updateMetadata_l();
7336 
7337             if (allStopped) {
7338                 standbyIfNotAlreadyInStandby();
7339             }
7340             if (doBroadcast) {
7341                 mStartStopCond.broadcast();
7342             }
7343 
7344             // sleep if there are no active tracks to process
7345             if (activeTracks.isEmpty()) {
7346                 if (sleepUs == 0) {
7347                     sleepUs = kRecordThreadSleepUs;
7348                 }
7349                 continue;
7350             }
7351             sleepUs = 0;
7352 
7353             lockEffectChains_l(effectChains);
7354         }
7355 
7356         // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
7357 
7358         size_t size = effectChains.size();
7359         for (size_t i = 0; i < size; i++) {
7360             // thread mutex is not locked, but effect chain is locked
7361             effectChains[i]->process_l();
7362         }
7363 
7364         // Push a new fast capture state if fast capture is not already running, or cblk change
7365         if (mFastCapture != 0) {
7366             FastCaptureStateQueue *sq = mFastCapture->sq();
7367             FastCaptureState *state = sq->begin();
7368             bool didModify = false;
7369             FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
7370             if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7371                     (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7372                 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7373                     int32_t old = android_atomic_inc(&mFastCaptureFutex);
7374                     if (old == -1) {
7375                         (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7376                     }
7377                 }
7378                 state->mCommand = FastCaptureState::READ_WRITE;
7379 #if 0   // FIXME
7380                 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
7381                         FastThreadDumpState::kSamplingNforLowRamDevice :
7382                         FastThreadDumpState::kSamplingN);
7383 #endif
7384                 didModify = true;
7385             }
7386             audio_track_cblk_t *cblkOld = state->mCblk;
7387             audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7388             if (cblkNew != cblkOld) {
7389                 state->mCblk = cblkNew;
7390                 // block until acked if removing a fast track
7391                 if (cblkOld != NULL) {
7392                     block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7393                 }
7394                 didModify = true;
7395             }
7396             AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7397                     reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7398             if (state->mFastPatchRecordBufferProvider != abp) {
7399                 state->mFastPatchRecordBufferProvider = abp;
7400                 state->mFastPatchRecordFormat = fastTrack == 0 ?
7401                         AUDIO_FORMAT_INVALID : fastTrack->format();
7402                 didModify = true;
7403             }
7404             if (state->mSilenceCapture != silenceFastCapture) {
7405                 state->mSilenceCapture = silenceFastCapture;
7406                 didModify = true;
7407             }
7408             sq->end(didModify);
7409             if (didModify) {
7410                 sq->push(block);
7411 #if 0
7412                 if (kUseFastCapture == FastCapture_Dynamic) {
7413                     mNormalSource = mPipeSource;
7414                 }
7415 #endif
7416             }
7417         }
7418 
7419         // now run the fast track destructor with thread mutex unlocked
7420         fastTrackToRemove.clear();
7421 
7422         // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7423         // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7424         // slow, then this RecordThread will overrun by not calling HAL read often enough.
7425         // If destination is non-contiguous, first read past the nominal end of buffer, then
7426         // copy to the right place.  Permitted because mRsmpInBuffer was over-allocated.
7427 
7428         int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
7429         ssize_t framesRead;
7430         const int64_t lastIoBeginNs = systemTime(); // start IO timing
7431 
7432         // If an NBAIO source is present, use it to read the normal capture's data
7433         if (mPipeSource != 0) {
7434             size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
7435 
7436             // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7437             // to the full buffer point (clearing the overflow condition).  Upon OVERRUN error,
7438             // we immediately retry the read() to get data and prevent another overflow.
7439             for (int retries = 0; retries <= 2; ++retries) {
7440                 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7441                 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7442                         framesToRead);
7443                 if (framesRead != OVERRUN) break;
7444             }
7445 
7446             const ssize_t availableToRead = mPipeSource->availableToRead();
7447             if (availableToRead >= 0) {
7448                 // PipeSource is the primary clock.  It is up to the AudioRecord client to keep up.
7449                 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7450                         "more frames to read than fifo size, %zd > %zu",
7451                         availableToRead, mPipeFramesP2);
7452                 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7453                 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7454                 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7455                         mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
7456                 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7457             }
7458             if (framesRead < 0) {
7459                 status_t status = (status_t) framesRead;
7460                 switch (status) {
7461                 case OVERRUN:
7462                     ALOGW("overrun on read from pipe");
7463                     framesRead = 0;
7464                     break;
7465                 case NEGOTIATE:
7466                     ALOGE("re-negotiation is needed");
7467                     framesRead = -1;  // Will cause an attempt to recover.
7468                     break;
7469                 default:
7470                     ALOGE("unknown error %d on read from pipe", status);
7471                     break;
7472                 }
7473             }
7474         // otherwise use the HAL / AudioStreamIn directly
7475         } else {
7476             ATRACE_BEGIN("read");
7477             size_t bytesRead;
7478             status_t result = mSource->read(
7479                     (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
7480             ATRACE_END();
7481             if (result < 0) {
7482                 framesRead = result;
7483             } else {
7484                 framesRead = bytesRead / mFrameSize;
7485             }
7486         }
7487 
7488         const int64_t lastIoEndNs = systemTime(); // end IO timing
7489 
7490         // Update server timestamp with server stats
7491         // systemTime() is optional if the hardware supports timestamps.
7492         if (framesRead >= 0) {
7493             mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7494             mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7495         }
7496 
7497         // Update server timestamp with kernel stats
7498         if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
7499             int64_t position, time;
7500             if (mStandby) {
7501                 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7502                     mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7503                     mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
7504             } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
7505                     && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7506 
7507                 mTimestampVerifier.add(position, time, mSampleRate);
7508 
7509                 // Correct timestamps
7510                 if (isTimestampCorrectionEnabled()) {
7511                     ALOGVV("TS_BEFORE: %d %lld %lld",
7512                             id(), (long long)time, (long long)position);
7513                     auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7514                     position = correctedTimestamp.mFrames;
7515                     time = correctedTimestamp.mTimeNs;
7516                     ALOGVV("TS_AFTER: %d %lld %lld",
7517                             id(), (long long)time, (long long)position);
7518                 }
7519 
7520                 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7521                 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7522                 // Note: In general record buffers should tend to be empty in
7523                 // a properly running pipeline.
7524                 //
7525                 // Also, it is not advantageous to call get_presentation_position during the read
7526                 // as the read obtains a lock, preventing the timestamp call from executing.
7527             } else {
7528                 mTimestampVerifier.error();
7529             }
7530         }
7531 
7532         // From the timestamp, input read latency is negative output write latency.
7533         const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7534         const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7535                 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7536         if (latencyMs != 0.) { // note 0. means timestamp is empty.
7537             mLatencyMs.add(latencyMs);
7538         }
7539 
7540         // Use this to track timestamp information
7541         // ALOGD("%s", mTimestamp.toString().c_str());
7542 
7543         if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
7544             ALOGE("read failed: framesRead=%zd", framesRead);
7545             // Force input into standby so that it tries to recover at next read attempt
7546             inputStandBy();
7547             sleepUs = kRecordThreadSleepUs;
7548         }
7549         if (framesRead <= 0) {
7550             goto unlock;
7551         }
7552         ALOG_ASSERT(framesRead > 0);
7553         mFramesRead += framesRead;
7554 
7555 #ifdef TEE_SINK
7556         (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7557 #endif
7558         // If destination is non-contiguous, we now correct for reading past end of buffer.
7559         {
7560             size_t part1 = mRsmpInFramesP2 - rear;
7561             if ((size_t) framesRead > part1) {
7562                 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
7563                         (framesRead - part1) * mFrameSize);
7564             }
7565         }
7566         mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
7567 
7568         size = activeTracks.size();
7569 
7570         // loop over each active track
7571         for (size_t i = 0; i < size; i++) {
7572             activeTrack = activeTracks[i];
7573 
7574             // skip fast tracks, as those are handled directly by FastCapture
7575             if (activeTrack->isFastTrack()) {
7576                 continue;
7577             }
7578 
7579             // TODO: This code probably should be moved to RecordTrack.
7580             // TODO: Update the activeTrack buffer converter in case of reconfigure.
7581 
7582             enum {
7583                 OVERRUN_UNKNOWN,
7584                 OVERRUN_TRUE,
7585                 OVERRUN_FALSE
7586             } overrun = OVERRUN_UNKNOWN;
7587 
7588             // loop over getNextBuffer to handle circular sink
7589             for (;;) {
7590 
7591                 activeTrack->mSink.frameCount = ~0;
7592                 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7593                 size_t framesOut = activeTrack->mSink.frameCount;
7594                 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7595 
7596                 // check available frames and handle overrun conditions
7597                 // if the record track isn't draining fast enough.
7598                 bool hasOverrun;
7599                 size_t framesIn;
7600                 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7601                 if (hasOverrun) {
7602                     overrun = OVERRUN_TRUE;
7603                 }
7604                 if (framesOut == 0 || framesIn == 0) {
7605                     break;
7606                 }
7607 
7608                 // Don't allow framesOut to be larger than what is possible with resampling
7609                 // from framesIn.
7610                 // This isn't strictly necessary but helps limit buffer resizing in
7611                 // RecordBufferConverter.  TODO: remove when no longer needed.
7612                 framesOut = min(framesOut,
7613                         destinationFramesPossible(
7614                                 framesIn, mSampleRate, activeTrack->mSampleRate));
7615 
7616                 if (activeTrack->isDirect()) {
7617                     // No RecordBufferConverter used for direct streams. Pass
7618                     // straight from RecordThread buffer to RecordTrack buffer.
7619                     AudioBufferProvider::Buffer buffer;
7620                     buffer.frameCount = framesOut;
7621                     status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7622                     if (status == OK && buffer.frameCount != 0) {
7623                         ALOGV_IF(buffer.frameCount != framesOut,
7624                                 "%s() read less than expected (%zu vs %zu)",
7625                                 __func__, buffer.frameCount, framesOut);
7626                         framesOut = buffer.frameCount;
7627                         memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
7628                         activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7629                     } else {
7630                         framesOut = 0;
7631                         ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7632                             __func__, status, buffer.frameCount);
7633                     }
7634                 } else {
7635                     // process frames from the RecordThread buffer provider to the RecordTrack
7636                     // buffer
7637                     framesOut = activeTrack->mRecordBufferConverter->convert(
7638                             activeTrack->mSink.raw,
7639                             activeTrack->mResamplerBufferProvider,
7640                             framesOut);
7641                 }
7642 
7643                 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7644                     overrun = OVERRUN_FALSE;
7645                 }
7646 
7647                 if (activeTrack->mFramesToDrop == 0) {
7648                     if (framesOut > 0) {
7649                         activeTrack->mSink.frameCount = framesOut;
7650                         // Sanitize before releasing if the track has no access to the source data
7651                         // An idle UID receives silence from non virtual devices until active
7652                         if (activeTrack->isSilenced()) {
7653                             memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
7654                         }
7655                         activeTrack->releaseBuffer(&activeTrack->mSink);
7656                     }
7657                 } else {
7658                     // FIXME could do a partial drop of framesOut
7659                     if (activeTrack->mFramesToDrop > 0) {
7660                         activeTrack->mFramesToDrop -= (ssize_t)framesOut;
7661                         if (activeTrack->mFramesToDrop <= 0) {
7662                             activeTrack->clearSyncStartEvent();
7663                         }
7664                     } else {
7665                         activeTrack->mFramesToDrop += framesOut;
7666                         if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7667                                 activeTrack->mSyncStartEvent->isCancelled()) {
7668                             ALOGW("Synced record %s, session %d, trigger session %d",
7669                                   (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7670                                   activeTrack->sessionId(),
7671                                   (activeTrack->mSyncStartEvent != 0) ?
7672                                           activeTrack->mSyncStartEvent->triggerSession() :
7673                                           AUDIO_SESSION_NONE);
7674                             activeTrack->clearSyncStartEvent();
7675                         }
7676                     }
7677                 }
7678 
7679                 if (framesOut == 0) {
7680                     break;
7681                 }
7682             }
7683 
7684             switch (overrun) {
7685             case OVERRUN_TRUE:
7686                 // client isn't retrieving buffers fast enough
7687                 if (!activeTrack->setOverflow()) {
7688                     nsecs_t now = systemTime();
7689                     // FIXME should lastWarning per track?
7690                     if ((now - lastWarning) > kWarningThrottleNs) {
7691                         ALOGW("RecordThread: buffer overflow");
7692                         lastWarning = now;
7693                     }
7694                 }
7695                 break;
7696             case OVERRUN_FALSE:
7697                 activeTrack->clearOverflow();
7698                 break;
7699             case OVERRUN_UNKNOWN:
7700                 break;
7701             }
7702 
7703             // update frame information and push timestamp out
7704             activeTrack->updateTrackFrameInfo(
7705                     activeTrack->mServerProxy->framesReleased(),
7706                     mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7707                     mSampleRate, mTimestamp);
7708         }
7709 
7710 unlock:
7711         // enable changes in effect chain
7712         unlockEffectChains(effectChains);
7713         // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
7714         if (audio_has_proportional_frames(mFormat)
7715             && loopCount == lastLoopCountRead + 1) {
7716             const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7717             const double jitterMs =
7718                 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7719                     {framesRead, readPeriodNs},
7720                     {0, 0} /* lastTimestamp */, mSampleRate);
7721             const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7722 
7723             Mutex::Autolock _l(mLock);
7724             mIoJitterMs.add(jitterMs);
7725             mProcessTimeMs.add(processMs);
7726         }
7727         // update timing info.
7728         mLastIoBeginNs = lastIoBeginNs;
7729         mLastIoEndNs = lastIoEndNs;
7730         lastLoopCountRead = loopCount;
7731     }
7732 
7733     standbyIfNotAlreadyInStandby();
7734 
7735     {
7736         Mutex::Autolock _l(mLock);
7737         for (size_t i = 0; i < mTracks.size(); i++) {
7738             sp<RecordTrack> track = mTracks[i];
7739             track->invalidate();
7740         }
7741         mActiveTracks.clear();
7742         mStartStopCond.broadcast();
7743     }
7744 
7745     releaseWakeLock();
7746 
7747     ALOGV("RecordThread %p exiting", this);
7748     return false;
7749 }
7750 
standbyIfNotAlreadyInStandby()7751 void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
7752 {
7753     if (!mStandby) {
7754         inputStandBy();
7755         mThreadMetrics.logEndInterval();
7756         mStandby = true;
7757     }
7758 }
7759 
inputStandBy()7760 void AudioFlinger::RecordThread::inputStandBy()
7761 {
7762     // Idle the fast capture if it's currently running
7763     if (mFastCapture != 0) {
7764         FastCaptureStateQueue *sq = mFastCapture->sq();
7765         FastCaptureState *state = sq->begin();
7766         if (!(state->mCommand & FastCaptureState::IDLE)) {
7767             state->mCommand = FastCaptureState::COLD_IDLE;
7768             state->mColdFutexAddr = &mFastCaptureFutex;
7769             state->mColdGen++;
7770             mFastCaptureFutex = 0;
7771             sq->end();
7772             // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7773             sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7774 #if 0
7775             if (kUseFastCapture == FastCapture_Dynamic) {
7776                 // FIXME
7777             }
7778 #endif
7779 #ifdef AUDIO_WATCHDOG
7780             // FIXME
7781 #endif
7782         } else {
7783             sq->end(false /*didModify*/);
7784         }
7785     }
7786     status_t result = mSource->standby();
7787     ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
7788 
7789     // If going into standby, flush the pipe source.
7790     if (mPipeSource.get() != nullptr) {
7791         const ssize_t flushed = mPipeSource->flush();
7792         if (flushed > 0) {
7793             ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7794             mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7795             mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7796         }
7797     }
7798 }
7799 
7800 // RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
createRecordTrack_l(const sp<AudioFlinger::Client> & client,const audio_attributes_t & attr,uint32_t * pSampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t * pFrameCount,audio_session_t sessionId,size_t * pNotificationFrameCount,pid_t creatorPid,const AttributionSourceState & attributionSource,audio_input_flags_t * flags,pid_t tid,status_t * status,audio_port_handle_t portId,int32_t maxSharedAudioHistoryMs)7801 sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
7802         const sp<AudioFlinger::Client>& client,
7803         const audio_attributes_t& attr,
7804         uint32_t *pSampleRate,
7805         audio_format_t format,
7806         audio_channel_mask_t channelMask,
7807         size_t *pFrameCount,
7808         audio_session_t sessionId,
7809         size_t *pNotificationFrameCount,
7810         pid_t creatorPid,
7811         const AttributionSourceState& attributionSource,
7812         audio_input_flags_t *flags,
7813         pid_t tid,
7814         status_t *status,
7815         audio_port_handle_t portId,
7816         int32_t maxSharedAudioHistoryMs)
7817 {
7818     size_t frameCount = *pFrameCount;
7819     size_t notificationFrameCount = *pNotificationFrameCount;
7820     sp<RecordTrack> track;
7821     status_t lStatus;
7822     audio_input_flags_t inputFlags = mInput->flags;
7823     audio_input_flags_t requestedFlags = *flags;
7824     uint32_t sampleRate;
7825     AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
7826             attributionSource);
7827 
7828     lStatus = initCheck();
7829     if (lStatus != NO_ERROR) {
7830         ALOGE("createRecordTrack_l() audio driver not initialized");
7831         goto Exit;
7832     }
7833 
7834     if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7835         ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7836         lStatus = BAD_VALUE;
7837         goto Exit;
7838     }
7839 
7840     if (maxSharedAudioHistoryMs != 0) {
7841         if (!captureHotwordAllowed(checkedAttributionSource)) {
7842             lStatus = PERMISSION_DENIED;
7843             goto Exit;
7844         }
7845         if (maxSharedAudioHistoryMs < 0
7846                 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
7847             lStatus = BAD_VALUE;
7848             goto Exit;
7849         }
7850     }
7851     if (*pSampleRate == 0) {
7852         *pSampleRate = mSampleRate;
7853     }
7854     sampleRate = *pSampleRate;
7855 
7856     // special case for FAST flag considered OK if fast capture is present and access to
7857     // audio history is not required
7858     if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
7859         inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7860     }
7861 
7862     // Check if requested flags are compatible with input stream flags
7863     if ((*flags & inputFlags) != *flags) {
7864         ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7865                 " input flags (%08x)",
7866               *flags, inputFlags);
7867         *flags = (audio_input_flags_t)(*flags & inputFlags);
7868     }
7869 
7870     // client expresses a preference for FAST and no access to audio history,
7871     // but we get the final say
7872     if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
7873       if (
7874             // we formerly checked for a callback handler (non-0 tid),
7875             // but that is no longer required for TRANSFER_OBTAIN mode
7876             //
7877             // Frame count is not specified (0), or is less than or equal the pipe depth.
7878             // It is OK to provide a higher capacity than requested.
7879             // We will force it to mPipeFramesP2 below.
7880             (frameCount <= mPipeFramesP2) &&
7881             // PCM data
7882             audio_is_linear_pcm(format) &&
7883             // hardware format
7884             (format == mFormat) &&
7885             // hardware channel mask
7886             (channelMask == mChannelMask) &&
7887             // hardware sample rate
7888             (sampleRate == mSampleRate) &&
7889             // record thread has an associated fast capture
7890             hasFastCapture() &&
7891             // there are sufficient fast track slots available
7892             mFastTrackAvail
7893         ) {
7894           // check compatibility with audio effects.
7895           Mutex::Autolock _l(mLock);
7896           // Do not accept FAST flag if the session has software effects
7897           sp<EffectChain> chain = getEffectChain_l(sessionId);
7898           if (chain != 0) {
7899               audio_input_flags_t old = *flags;
7900               chain->checkInputFlagCompatibility(flags);
7901               if (old != *flags) {
7902                   ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7903                           this, (int)old, (int)*flags);
7904               }
7905           }
7906           ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
7907                    "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7908                    this, frameCount, mFrameCount);
7909       } else {
7910         ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7911                 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
7912                 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
7913                 this, frameCount, mFrameCount, mPipeFramesP2,
7914                 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
7915                 hasFastCapture(), tid, mFastTrackAvail);
7916         *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
7917       }
7918     }
7919 
7920     // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7921     if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7922             (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7923         *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7924         lStatus = BAD_TYPE;
7925         goto Exit;
7926     }
7927 
7928     // compute track buffer size in frames, and suggest the notification frame count
7929     if (*flags & AUDIO_INPUT_FLAG_FAST) {
7930         // fast track: frame count is exactly the pipe depth
7931         frameCount = mPipeFramesP2;
7932         // ignore requested notificationFrames, and always notify exactly once every HAL buffer
7933         notificationFrameCount = mFrameCount;
7934     } else {
7935         // not fast track: max notification period is resampled equivalent of one HAL buffer time
7936         //                 or 20 ms if there is a fast capture
7937         // TODO This could be a roundupRatio inline, and const
7938         size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7939                 * sampleRate + mSampleRate - 1) / mSampleRate;
7940         // minimum number of notification periods is at least kMinNotifications,
7941         // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7942         static const size_t kMinNotifications = 3;
7943         static const uint32_t kMinMs = 30;
7944         // TODO This could be a roundupRatio inline
7945         const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7946         // TODO This could be a roundupRatio inline
7947         const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7948                 maxNotificationFrames;
7949         const size_t minFrameCount = maxNotificationFrames *
7950                 max(kMinNotifications, minNotificationsByMs);
7951         frameCount = max(frameCount, minFrameCount);
7952         if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7953             notificationFrameCount = maxNotificationFrames;
7954         }
7955     }
7956     *pFrameCount = frameCount;
7957     *pNotificationFrameCount = notificationFrameCount;
7958 
7959     { // scope for mLock
7960         Mutex::Autolock _l(mLock);
7961         int32_t startFrames = -1;
7962         if (!mSharedAudioPackageName.empty()
7963                 && mSharedAudioPackageName == checkedAttributionSource.packageName
7964                 && mSharedAudioSessionId == sessionId
7965                 && captureHotwordAllowed(checkedAttributionSource)) {
7966             startFrames = mSharedAudioStartFrames;
7967         }
7968 
7969         track = new RecordTrack(this, client, attr, sampleRate,
7970                       format, channelMask, frameCount,
7971                       nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
7972                       checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
7973                       startFrames);
7974 
7975         lStatus = track->initCheck();
7976         if (lStatus != NO_ERROR) {
7977             ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
7978             // track must be cleared from the caller as the caller has the AF lock
7979             goto Exit;
7980         }
7981         mTracks.add(track);
7982 
7983         if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
7984             pid_t callingPid = IPCThreadState::self()->getCallingPid();
7985             // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7986             // so ask activity manager to do this on our behalf
7987             sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
7988         }
7989 
7990         if (maxSharedAudioHistoryMs != 0) {
7991             sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
7992         }
7993     }
7994 
7995     lStatus = NO_ERROR;
7996 
7997 Exit:
7998     *status = lStatus;
7999     return track;
8000 }
8001 
start(RecordThread::RecordTrack * recordTrack,AudioSystem::sync_event_t event,audio_session_t triggerSession)8002 status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8003                                            AudioSystem::sync_event_t event,
8004                                            audio_session_t triggerSession)
8005 {
8006     ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8007     sp<ThreadBase> strongMe = this;
8008     status_t status = NO_ERROR;
8009 
8010     if (event == AudioSystem::SYNC_EVENT_NONE) {
8011         recordTrack->clearSyncStartEvent();
8012     } else if (event != AudioSystem::SYNC_EVENT_SAME) {
8013         recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
8014                                        triggerSession,
8015                                        recordTrack->sessionId(),
8016                                        syncStartEventCallback,
8017                                        recordTrack);
8018         // Sync event can be cancelled by the trigger session if the track is not in a
8019         // compatible state in which case we start record immediately
8020         if (recordTrack->mSyncStartEvent->isCancelled()) {
8021             recordTrack->clearSyncStartEvent();
8022         } else {
8023             // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
8024             recordTrack->mFramesToDrop = -(ssize_t)
8025                     ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
8026         }
8027     }
8028 
8029     {
8030         // This section is a rendezvous between binder thread executing start() and RecordThread
8031         AutoMutex lock(mLock);
8032         if (recordTrack->isInvalid()) {
8033             recordTrack->clearSyncStartEvent();
8034             ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8035             return DEAD_OBJECT;
8036         }
8037         if (mActiveTracks.indexOf(recordTrack) >= 0) {
8038             if (recordTrack->mState == TrackBase::PAUSING) {
8039                 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8040                 // so no need to startInput().
8041                 ALOGV("active record track PAUSING -> ACTIVE");
8042                 recordTrack->mState = TrackBase::ACTIVE;
8043             } else {
8044                 ALOGV("active record track state %d", recordTrack->mState);
8045             }
8046             return status;
8047         }
8048 
8049         // TODO consider other ways of handling this, such as changing the state to :STARTING and
8050         //      adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8051         //      or using a separate command thread
8052         recordTrack->mState = TrackBase::STARTING_1;
8053         mActiveTracks.add(recordTrack);
8054         status_t status = NO_ERROR;
8055         if (recordTrack->isExternalTrack()) {
8056             mLock.unlock();
8057             status = AudioSystem::startInput(recordTrack->portId());
8058             mLock.lock();
8059             if (recordTrack->isInvalid()) {
8060                 recordTrack->clearSyncStartEvent();
8061                 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8062                     recordTrack->mState = TrackBase::STARTING_2;
8063                     // STARTING_2 forces destroy to call stopInput.
8064                 }
8065                 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8066                 return DEAD_OBJECT;
8067             }
8068             if (recordTrack->mState != TrackBase::STARTING_1) {
8069                 ALOGW("%s(%d): unsynchronized mState:%d change",
8070                     __func__, recordTrack->id(), recordTrack->mState);
8071                 // Someone else has changed state, let them take over,
8072                 // leave mState in the new state.
8073                 recordTrack->clearSyncStartEvent();
8074                 return INVALID_OPERATION;
8075             }
8076             // we're ok, but perhaps startInput has failed
8077             if (status != NO_ERROR) {
8078                 ALOGW("%s(%d): startInput failed, status %d",
8079                     __func__, recordTrack->id(), status);
8080                 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8081                 // leave in STARTING_1, so destroy() will not call stopInput.
8082                 mActiveTracks.remove(recordTrack);
8083                 recordTrack->clearSyncStartEvent();
8084                 return status;
8085             }
8086             sendIoConfigEvent_l(
8087                 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
8088         }
8089 
8090         recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8091 
8092         // Catch up with current buffer indices if thread is already running.
8093         // This is what makes a new client discard all buffered data.  If the track's mRsmpInFront
8094         // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8095         // see previously buffered data before it called start(), but with greater risk of overrun.
8096 
8097         recordTrack->mResamplerBufferProvider->reset();
8098         if (!recordTrack->isDirect()) {
8099             // clear any converter state as new data will be discontinuous
8100             recordTrack->mRecordBufferConverter->reset();
8101         }
8102         recordTrack->mState = TrackBase::STARTING_2;
8103         // signal thread to start
8104         mWaitWorkCV.broadcast();
8105         return status;
8106     }
8107 }
8108 
syncStartEventCallback(const wp<SyncEvent> & event)8109 void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8110 {
8111     sp<SyncEvent> strongEvent = event.promote();
8112 
8113     if (strongEvent != 0) {
8114         sp<RefBase> ptr = strongEvent->cookie().promote();
8115         if (ptr != 0) {
8116             RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8117             recordTrack->handleSyncStartEvent(strongEvent);
8118         }
8119     }
8120 }
8121 
stop(RecordThread::RecordTrack * recordTrack)8122 bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
8123     ALOGV("RecordThread::stop");
8124     AutoMutex _l(mLock);
8125     // if we're invalid, we can't be on the ActiveTracks.
8126     if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
8127         return false;
8128     }
8129     // note that threadLoop may still be processing the track at this point [without lock]
8130     recordTrack->mState = TrackBase::PAUSING;
8131 
8132     // NOTE: Waiting here is important to keep stop synchronous.
8133     // This is needed for proper patchRecord peer release.
8134     while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8135         mWaitWorkCV.broadcast(); // signal thread to stop
8136         mStartStopCond.wait(mLock);
8137     }
8138 
8139     if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
8140         ALOGV("Record stopped OK");
8141         return true;
8142     }
8143 
8144     // don't handle anything - we've been invalidated or restarted and in a different state
8145     ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8146             __func__, recordTrack->id(), recordTrack->mState);
8147     return false;
8148 }
8149 
isValidSyncEvent(const sp<SyncEvent> & event __unused) const8150 bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8151 {
8152     return false;
8153 }
8154 
setSyncEvent(const sp<SyncEvent> & event __unused)8155 status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8156 {
8157 #if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
8158     if (!isValidSyncEvent(event)) {
8159         return BAD_VALUE;
8160     }
8161 
8162     audio_session_t eventSession = event->triggerSession();
8163     status_t ret = NAME_NOT_FOUND;
8164 
8165     Mutex::Autolock _l(mLock);
8166 
8167     for (size_t i = 0; i < mTracks.size(); i++) {
8168         sp<RecordTrack> track = mTracks[i];
8169         if (eventSession == track->sessionId()) {
8170             (void) track->setSyncEvent(event);
8171             ret = NO_ERROR;
8172         }
8173     }
8174     return ret;
8175 #else
8176     return BAD_VALUE;
8177 #endif
8178 }
8179 
getActiveMicrophones(std::vector<media::MicrophoneInfo> * activeMicrophones)8180 status_t AudioFlinger::RecordThread::getActiveMicrophones(
8181         std::vector<media::MicrophoneInfo>* activeMicrophones)
8182 {
8183     ALOGV("RecordThread::getActiveMicrophones");
8184     AutoMutex _l(mLock);
8185     if (!isStreamInitialized()) {
8186         return NO_INIT;
8187     }
8188     status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8189     return status;
8190 }
8191 
setPreferredMicrophoneDirection(audio_microphone_direction_t direction)8192 status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8193             audio_microphone_direction_t direction)
8194 {
8195     ALOGV("setPreferredMicrophoneDirection(%d)", direction);
8196     AutoMutex _l(mLock);
8197     if (!isStreamInitialized()) {
8198         return NO_INIT;
8199     }
8200     return mInput->stream->setPreferredMicrophoneDirection(direction);
8201 }
8202 
setPreferredMicrophoneFieldDimension(float zoom)8203 status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
8204 {
8205     ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
8206     AutoMutex _l(mLock);
8207     if (!isStreamInitialized()) {
8208         return NO_INIT;
8209     }
8210     return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
8211 }
8212 
shareAudioHistory(const std::string & sharedAudioPackageName,audio_session_t sharedSessionId,int64_t sharedAudioStartMs)8213 status_t AudioFlinger::RecordThread::shareAudioHistory(
8214         const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8215         int64_t sharedAudioStartMs) {
8216     AutoMutex _l(mLock);
8217     return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8218 }
8219 
shareAudioHistory_l(const std::string & sharedAudioPackageName,audio_session_t sharedSessionId,int64_t sharedAudioStartMs)8220 status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8221         const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8222         int64_t sharedAudioStartMs) {
8223 
8224     if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8225         return BAD_VALUE;
8226     }
8227 
8228     if (sharedAudioStartMs < 0
8229         || sharedAudioStartMs > INT64_MAX / mSampleRate) {
8230         return BAD_VALUE;
8231     }
8232 
8233     // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8234     // As we cannot detect more than one wraparound, only accept values up current write position
8235     // after one wraparound
8236     // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8237     // app waits several hours after the start time was computed.
8238     int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
8239     const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8240           (int32_t)sharedAudioStartFrames);
8241     // Bring the start frame position within the input buffer to match the documented
8242     // "best effort" behavior of the API.
8243     if (sharedOffset < 0) {
8244         sharedAudioStartFrames = mRsmpInRear;
8245     } else if (sharedOffset > mRsmpInFrames) {
8246         sharedAudioStartFrames =
8247                 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
8248     }
8249 
8250     mSharedAudioPackageName = sharedAudioPackageName;
8251     if (mSharedAudioPackageName.empty()) {
8252         resetAudioHistory_l();
8253     } else {
8254         mSharedAudioSessionId = sharedSessionId;
8255         mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
8256     }
8257     return NO_ERROR;
8258 }
8259 
resetAudioHistory_l()8260 void AudioFlinger::RecordThread::resetAudioHistory_l() {
8261     mSharedAudioSessionId = AUDIO_SESSION_NONE;
8262     mSharedAudioStartFrames = -1;
8263     mSharedAudioPackageName = "";
8264 }
8265 
updateMetadata_l()8266 void AudioFlinger::RecordThread::updateMetadata_l()
8267 {
8268     if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8269         return; // nothing to do
8270     }
8271     StreamInHalInterface::SinkMetadata metadata;
8272     for (const sp<RecordTrack> &track : mActiveTracks) {
8273         // Do not forward PatchRecord metadata to audio HAL
8274         if (track->isPatchTrack()) {
8275             continue;
8276         }
8277         // No track is invalid as this is called after prepareTrack_l in the same critical section
8278         record_track_metadata_v7_t trackMetadata;
8279         trackMetadata.base = {
8280                 .source = track->attributes().source,
8281                 .gain = 1, // capture tracks do not have volumes
8282         };
8283         trackMetadata.channel_mask = track->channelMask(),
8284         strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8285 
8286         metadata.tracks.push_back(trackMetadata);
8287     }
8288     mInput->stream->updateSinkMetadata(metadata);
8289 }
8290 
8291 // destroyTrack_l() must be called with ThreadBase::mLock held
destroyTrack_l(const sp<RecordTrack> & track)8292 void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8293 {
8294     track->terminate();
8295     track->mState = TrackBase::STOPPED;
8296 
8297     // active tracks are removed by threadLoop()
8298     if (mActiveTracks.indexOf(track) < 0) {
8299         removeTrack_l(track);
8300     }
8301 }
8302 
removeTrack_l(const sp<RecordTrack> & track)8303 void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8304 {
8305     String8 result;
8306     track->appendDump(result, false /* active */);
8307     mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8308 
8309     mTracks.remove(track);
8310     // need anything related to effects here?
8311     if (track->isFastTrack()) {
8312         ALOG_ASSERT(!mFastTrackAvail);
8313         mFastTrackAvail = true;
8314     }
8315 }
8316 
dumpInternals_l(int fd,const Vector<String16> & args __unused)8317 void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
8318 {
8319     AudioStreamIn *input = mInput;
8320     audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8321     dprintf(fd, "  AudioStreamIn: %p flags %#x (%s)\n",
8322             input, flags, toString(flags).c_str());
8323     dprintf(fd, "  Frames read: %lld\n", (long long)mFramesRead);
8324     if (mActiveTracks.isEmpty()) {
8325         dprintf(fd, "  No active record clients\n");
8326     }
8327 
8328     if (input != nullptr) {
8329         dprintf(fd, "  Hal stream dump:\n");
8330         (void)input->stream->dump(fd);
8331     }
8332 
8333     dprintf(fd, "  Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
8334     dprintf(fd, "  Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
8335 
8336     // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8337     // while we are dumping it.  It may be inconsistent, but it won't mutate!
8338     // This is a large object so we place it on the heap.
8339     // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
8340     const std::unique_ptr<FastCaptureDumpState> copy =
8341             std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
8342     copy->dump(fd);
8343 }
8344 
dumpTracks_l(int fd,const Vector<String16> & args __unused)8345 void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
8346 {
8347     String8 result;
8348     size_t numtracks = mTracks.size();
8349     size_t numactive = mActiveTracks.size();
8350     size_t numactiveseen = 0;
8351     dprintf(fd, "  %zu Tracks", numtracks);
8352     const char *prefix = "    ";
8353     if (numtracks) {
8354         dprintf(fd, " of which %zu are active\n", numactive);
8355         result.append(prefix);
8356         mTracks[0]->appendDumpHeader(result);
8357         for (size_t i = 0; i < numtracks ; ++i) {
8358             sp<RecordTrack> track = mTracks[i];
8359             if (track != 0) {
8360                 bool active = mActiveTracks.indexOf(track) >= 0;
8361                 if (active) {
8362                     numactiveseen++;
8363                 }
8364                 result.append(prefix);
8365                 track->appendDump(result, active);
8366             }
8367         }
8368     } else {
8369         dprintf(fd, "\n");
8370     }
8371 
8372     if (numactiveseen != numactive) {
8373         result.append("  The following tracks are in the active list but"
8374                 " not in the track list\n");
8375         result.append(prefix);
8376         mActiveTracks[0]->appendDumpHeader(result);
8377         for (size_t i = 0; i < numactive; ++i) {
8378             sp<RecordTrack> track = mActiveTracks[i];
8379             if (mTracks.indexOf(track) < 0) {
8380                 result.append(prefix);
8381                 track->appendDump(result, true /* active */);
8382             }
8383         }
8384 
8385     }
8386     write(fd, result.string(), result.size());
8387 }
8388 
setRecordSilenced(audio_port_handle_t portId,bool silenced)8389 void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
8390 {
8391     Mutex::Autolock _l(mLock);
8392     for (size_t i = 0; i < mTracks.size() ; i++) {
8393         sp<RecordTrack> track = mTracks[i];
8394         if (track != 0 && track->portId() == portId) {
8395             track->setSilenced(silenced);
8396         }
8397     }
8398 }
8399 
reset()8400 void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8401 {
8402     sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8403     RecordThread *recordThread = (RecordThread *) threadBase.get();
8404     mRsmpInUnrel = 0;
8405     const int32_t rear = recordThread->mRsmpInRear;
8406     ssize_t deltaFrames = 0;
8407     if (mRecordTrack->startFrames() >= 0) {
8408         int32_t startFrames = mRecordTrack->startFrames();
8409         // Accept a recent wraparound of mRsmpInRear
8410         if (startFrames <= rear) {
8411             deltaFrames = rear - startFrames;
8412         } else {
8413             deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
8414         }
8415         // start frame cannot be further in the past than start of resampling buffer
8416         if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8417             deltaFrames = recordThread->mRsmpInFrames;
8418         }
8419     }
8420     mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
8421 }
8422 
sync(size_t * framesAvailable,bool * hasOverrun)8423 void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8424         size_t *framesAvailable, bool *hasOverrun)
8425 {
8426     sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8427     RecordThread *recordThread = (RecordThread *) threadBase.get();
8428     const int32_t rear = recordThread->mRsmpInRear;
8429     const int32_t front = mRsmpInFront;
8430     const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
8431 
8432     size_t framesIn;
8433     bool overrun = false;
8434     if (filled < 0) {
8435         // should not happen, but treat like a massive overrun and re-sync
8436         framesIn = 0;
8437         mRsmpInFront = rear;
8438         overrun = true;
8439     } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8440         framesIn = (size_t) filled;
8441     } else {
8442         // client is not keeping up with server, but give it latest data
8443         framesIn = recordThread->mRsmpInFrames;
8444         mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8445                 rear, static_cast<int32_t>(framesIn));
8446         overrun = true;
8447     }
8448     if (framesAvailable != NULL) {
8449         *framesAvailable = framesIn;
8450     }
8451     if (hasOverrun != NULL) {
8452         *hasOverrun = overrun;
8453     }
8454 }
8455 
8456 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer)8457 status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
8458         AudioBufferProvider::Buffer* buffer)
8459 {
8460     sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8461     if (threadBase == 0) {
8462         buffer->frameCount = 0;
8463         buffer->raw = NULL;
8464         return NOT_ENOUGH_DATA;
8465     }
8466     RecordThread *recordThread = (RecordThread *) threadBase.get();
8467     int32_t rear = recordThread->mRsmpInRear;
8468     int32_t front = mRsmpInFront;
8469     ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
8470     // FIXME should not be P2 (don't want to increase latency)
8471     // FIXME if client not keeping up, discard
8472     LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
8473     // 'filled' may be non-contiguous, so return only the first contiguous chunk
8474 
8475     front &= recordThread->mRsmpInFramesP2 - 1;
8476     size_t part1 = recordThread->mRsmpInFramesP2 - front;
8477     if (part1 > (size_t) filled) {
8478         part1 = filled;
8479     }
8480     size_t ask = buffer->frameCount;
8481     ALOG_ASSERT(ask > 0);
8482     if (part1 > ask) {
8483         part1 = ask;
8484     }
8485     if (part1 == 0) {
8486         // out of data is fine since the resampler will return a short-count.
8487         buffer->raw = NULL;
8488         buffer->frameCount = 0;
8489         mRsmpInUnrel = 0;
8490         return NOT_ENOUGH_DATA;
8491     }
8492 
8493     buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
8494     buffer->frameCount = part1;
8495     mRsmpInUnrel = part1;
8496     return NO_ERROR;
8497 }
8498 
8499 // AudioBufferProvider interface
releaseBuffer(AudioBufferProvider::Buffer * buffer)8500 void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8501         AudioBufferProvider::Buffer* buffer)
8502 {
8503     int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
8504     if (stepCount == 0) {
8505         return;
8506     }
8507     ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8508     mRsmpInUnrel -= stepCount;
8509     mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
8510     buffer->raw = NULL;
8511     buffer->frameCount = 0;
8512 }
8513 
checkBtNrec()8514 void AudioFlinger::RecordThread::checkBtNrec()
8515 {
8516     Mutex::Autolock _l(mLock);
8517     checkBtNrec_l();
8518 }
8519 
checkBtNrec_l()8520 void AudioFlinger::RecordThread::checkBtNrec_l()
8521 {
8522     // disable AEC and NS if the device is a BT SCO headset supporting those
8523     // pre processings
8524     bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
8525                         mAudioFlinger->btNrecIsOff();
8526     if (mBtNrecSuspended.exchange(suspend) != suspend) {
8527         for (size_t i = 0; i < mEffectChains.size(); i++) {
8528             setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8529             setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8530         }
8531     }
8532 }
8533 
8534 
checkForNewParameter_l(const String8 & keyValuePair,status_t & status)8535 bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8536                                                         status_t& status)
8537 {
8538     bool reconfig = false;
8539 
8540     status = NO_ERROR;
8541 
8542     audio_format_t reqFormat = mFormat;
8543     uint32_t samplingRate = mSampleRate;
8544     // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
8545     audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8546 
8547     AudioParameter param = AudioParameter(keyValuePair);
8548     int value;
8549 
8550     // scope for AutoPark extends to end of method
8551     AutoPark<FastCapture> park(mFastCapture);
8552 
8553     // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8554     //      channel count change can be requested. Do we mandate the first client defines the
8555     //      HAL sampling rate and channel count or do we allow changes on the fly?
8556     if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8557         samplingRate = value;
8558         reconfig = true;
8559     }
8560     if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
8561         if (!audio_is_linear_pcm((audio_format_t) value)) {
8562             status = BAD_VALUE;
8563         } else {
8564             reqFormat = (audio_format_t) value;
8565             reconfig = true;
8566         }
8567     }
8568     if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8569         audio_channel_mask_t mask = (audio_channel_mask_t) value;
8570         if (!audio_is_input_channel(mask) ||
8571                 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
8572             status = BAD_VALUE;
8573         } else {
8574             channelMask = mask;
8575             reconfig = true;
8576         }
8577     }
8578     if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8579         // do not accept frame count changes if tracks are open as the track buffer
8580         // size depends on frame count and correct behavior would not be guaranteed
8581         // if frame count is changed after track creation
8582         if (mActiveTracks.size() > 0) {
8583             status = INVALID_OPERATION;
8584         } else {
8585             reconfig = true;
8586         }
8587     }
8588     if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
8589         LOG_FATAL("Should not set routing device in RecordThread");
8590     }
8591     if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8592             mAudioSource != (audio_source_t)value) {
8593         LOG_FATAL("Should not set audio source in RecordThread");
8594     }
8595 
8596     if (status == NO_ERROR) {
8597         status = mInput->stream->setParameters(keyValuePair);
8598         if (status == INVALID_OPERATION) {
8599             inputStandBy();
8600             status = mInput->stream->setParameters(keyValuePair);
8601         }
8602         if (reconfig) {
8603             if (status == BAD_VALUE) {
8604                 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8605                 if (mInput->stream->getAudioProperties(&config) == OK &&
8606                         audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8607                         config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8608                         audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
8609                     status = NO_ERROR;
8610                 }
8611             }
8612             if (status == NO_ERROR) {
8613                 readInputParameters_l();
8614                 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8615             }
8616         }
8617     }
8618 
8619     return reconfig;
8620 }
8621 
getParameters(const String8 & keys)8622 String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8623 {
8624     Mutex::Autolock _l(mLock);
8625     if (initCheck() == NO_ERROR) {
8626         String8 out_s8;
8627         if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8628             return out_s8;
8629         }
8630     }
8631     return String8();
8632 }
8633 
ioConfigChanged(audio_io_config_event event,pid_t pid,audio_port_handle_t portId)8634 void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8635                                                  audio_port_handle_t portId) {
8636     sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8637 
8638     desc->mIoHandle = mId;
8639 
8640     switch (event) {
8641     case AUDIO_INPUT_OPENED:
8642     case AUDIO_INPUT_REGISTERED:
8643     case AUDIO_INPUT_CONFIG_CHANGED:
8644         desc->mPatch = mPatch;
8645         desc->mChannelMask = mChannelMask;
8646         desc->mSamplingRate = mSampleRate;
8647         desc->mFormat = mFormat;
8648         desc->mFrameCount = mFrameCount;
8649         desc->mFrameCountHAL = mFrameCount;
8650         desc->mLatency = 0;
8651         break;
8652     case AUDIO_CLIENT_STARTED:
8653         desc->mPatch = mPatch;
8654         desc->mPortId = portId;
8655         break;
8656     case AUDIO_INPUT_CLOSED:
8657     default:
8658         break;
8659     }
8660     mAudioFlinger->ioConfigChanged(event, desc, pid);
8661 }
8662 
readInputParameters_l()8663 void AudioFlinger::RecordThread::readInputParameters_l()
8664 {
8665     status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8666     LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8667     mFormat = mHALFormat;
8668     mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8669     if (audio_is_linear_pcm(mFormat)) {
8670         LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
8671                 mChannelCount, FCC_LIMIT);
8672     } else {
8673         // Can have more that FCC_LIMIT channels in encoded streams.
8674         ALOGI("HAL format %#x is not linear pcm", mFormat);
8675     }
8676     result = mInput->stream->getFrameSize(&mFrameSize);
8677     LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8678     LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8679             mFrameSize);
8680     result = mInput->stream->getBufferSize(&mBufferSize);
8681     LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8682     mFrameCount = mBufferSize / mFrameSize;
8683     ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8684             "mBufferSize=%zu, mFrameCount=%zu",
8685             this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
8686 
8687     // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8688     mRsmpInFrames = 0;
8689     resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
8690 
8691     // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8692     // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
8693 
8694     audio_input_flags_t flags = mInput->flags;
8695     mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8696     item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8697         .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8698         .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8699         .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8700         .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8701         .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8702         .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8703         .record();
8704 }
8705 
getInputFramesLost()8706 uint32_t AudioFlinger::RecordThread::getInputFramesLost()
8707 {
8708     Mutex::Autolock _l(mLock);
8709     uint32_t result;
8710     if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8711         return result;
8712     }
8713     return 0;
8714 }
8715 
sessionIds() const8716 KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
8717 {
8718     KeyedVector<audio_session_t, bool> ids;
8719     Mutex::Autolock _l(mLock);
8720     for (size_t j = 0; j < mTracks.size(); ++j) {
8721         sp<RecordThread::RecordTrack> track = mTracks[j];
8722         audio_session_t sessionId = track->sessionId();
8723         if (ids.indexOfKey(sessionId) < 0) {
8724             ids.add(sessionId, true);
8725         }
8726     }
8727     return ids;
8728 }
8729 
clearInput()8730 AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8731 {
8732     Mutex::Autolock _l(mLock);
8733     AudioStreamIn *input = mInput;
8734     mInput = NULL;
8735     return input;
8736 }
8737 
8738 // this method must always be called either with ThreadBase mLock held or inside the thread loop
stream() const8739 sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
8740 {
8741     if (mInput == NULL) {
8742         return NULL;
8743     }
8744     return mInput->stream;
8745 }
8746 
addEffectChain_l(const sp<EffectChain> & chain)8747 status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8748 {
8749     ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
8750     chain->setThread(this);
8751     chain->setInBuffer(NULL);
8752     chain->setOutBuffer(NULL);
8753 
8754     checkSuspendOnAddEffectChain_l(chain);
8755 
8756     // make sure enabled pre processing effects state is communicated to the HAL as we
8757     // just moved them to a new input stream.
8758     chain->syncHalEffectsState();
8759 
8760     mEffectChains.add(chain);
8761 
8762     return NO_ERROR;
8763 }
8764 
removeEffectChain_l(const sp<EffectChain> & chain)8765 size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8766 {
8767     ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
8768 
8769     for (size_t i = 0; i < mEffectChains.size(); i++) {
8770         if (chain == mEffectChains[i]) {
8771             mEffectChains.removeAt(i);
8772             break;
8773         }
8774     }
8775     return mEffectChains.size();
8776 }
8777 
createAudioPatch_l(const struct audio_patch * patch,audio_patch_handle_t * handle)8778 status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8779                                                           audio_patch_handle_t *handle)
8780 {
8781     status_t status = NO_ERROR;
8782 
8783     // store new device and send to effects
8784     mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8785     mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
8786     audio_port_handle_t deviceId = patch->sources[0].id;
8787     for (size_t i = 0; i < mEffectChains.size(); i++) {
8788         mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
8789     }
8790 
8791     checkBtNrec_l();
8792 
8793     // store new source and send to effects
8794     if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8795         mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8796         for (size_t i = 0; i < mEffectChains.size(); i++) {
8797             mEffectChains[i]->setAudioSource_l(mAudioSource);
8798         }
8799     }
8800 
8801     if (mInput->audioHwDev->supportsAudioPatches()) {
8802         sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8803         status = hwDevice->createAudioPatch(patch->num_sources,
8804                                             patch->sources,
8805                                             patch->num_sinks,
8806                                             patch->sinks,
8807                                             handle);
8808     } else {
8809         char *address;
8810         if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8811             address = audio_device_address_to_parameter(
8812                                                 patch->sources[0].ext.device.type,
8813                                                 patch->sources[0].ext.device.address);
8814         } else {
8815             address = (char *)calloc(1, 1);
8816         }
8817         AudioParameter param = AudioParameter(String8(address));
8818         free(address);
8819         param.addInt(String8(AudioParameter::keyRouting),
8820                      (int)patch->sources[0].ext.device.type);
8821         param.addInt(String8(AudioParameter::keyInputSource),
8822                                          (int)patch->sinks[0].ext.mix.usecase.source);
8823         status = mInput->stream->setParameters(param.toString());
8824         *handle = AUDIO_PATCH_HANDLE_NONE;
8825     }
8826 
8827     if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
8828         sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8829         mPatch = *patch;
8830     }
8831 
8832     const std::string pathSourcesAsString = patchSourcesToString(patch);
8833     mThreadMetrics.logEndInterval();
8834     mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
8835     mThreadMetrics.logBeginInterval();
8836     // also dispatch to active AudioRecords
8837     for (const auto &track : mActiveTracks) {
8838         track->logEndInterval();
8839         track->logBeginInterval(pathSourcesAsString);
8840     }
8841     return status;
8842 }
8843 
releaseAudioPatch_l(const audio_patch_handle_t handle)8844 status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8845 {
8846     status_t status = NO_ERROR;
8847 
8848     mPatch = audio_patch{};
8849     mInDeviceTypeAddr.reset();
8850 
8851     if (mInput->audioHwDev->supportsAudioPatches()) {
8852         sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8853         status = hwDevice->releaseAudioPatch(handle);
8854     } else {
8855         AudioParameter param;
8856         param.addInt(String8(AudioParameter::keyRouting), 0);
8857         status = mInput->stream->setParameters(param.toString());
8858     }
8859     return status;
8860 }
8861 
updateOutDevices(const DeviceDescriptorBaseVector & outDevices)8862 void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8863 {
8864     Mutex::Autolock _l(mLock);
8865     mOutDevices = outDevices;
8866     mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8867     for (size_t i = 0; i < mEffectChains.size(); i++) {
8868         mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
8869     }
8870 }
8871 
getOldestFront_l()8872 int32_t AudioFlinger::RecordThread::getOldestFront_l()
8873 {
8874     if (mTracks.size() == 0) {
8875         return mRsmpInRear;
8876     }
8877     int32_t oldestFront = mRsmpInRear;
8878     int32_t maxFilled = 0;
8879     for (size_t i = 0; i < mTracks.size(); i++) {
8880         int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8881         int32_t filled;
8882         (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
8883         if (filled > maxFilled) {
8884             oldestFront = front;
8885             maxFilled = filled;
8886         }
8887     }
8888     if (maxFilled > mRsmpInFrames) {
8889         (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
8890     }
8891     return oldestFront;
8892 }
8893 
updateFronts_l(int32_t offset)8894 void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
8895 {
8896     if (offset == 0) {
8897         return;
8898     }
8899     for (size_t i = 0; i < mTracks.size(); i++) {
8900         int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
8901         front = audio_utils::safe_sub_overflow(front, offset);
8902         mTracks[i]->mResamplerBufferProvider->setFront(front);
8903     }
8904 }
8905 
resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)8906 void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
8907 {
8908     // This is the formula for calculating the temporary buffer size.
8909     // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
8910     // 1 full output buffer, regardless of the alignment of the available input.
8911     // The value is somewhat arbitrary, and could probably be even larger.
8912     // A larger value should allow more old data to be read after a track calls start(),
8913     // without increasing latency.
8914     //
8915     // Note this is independent of the maximum downsampling ratio permitted for capture.
8916     size_t minRsmpInFrames = mFrameCount * 7;
8917 
8918     // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
8919     // capture history available to another client using the same session ID:
8920     // dimension the resampler input buffer accordingly.
8921 
8922     // Get oldest client read position:  getOldestFront_l() must be called before altering
8923     // mRsmpInRear, or mRsmpInFrames
8924     int32_t previousFront = getOldestFront_l();
8925     size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
8926     int32_t previousRear = mRsmpInRear;
8927     mRsmpInRear = 0;
8928 
8929     ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
8930             && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
8931             "resizeInputBuffer_l() called with invalid max shared history %d",
8932             maxSharedAudioHistoryMs);
8933     if (maxSharedAudioHistoryMs != 0) {
8934         // resizeInputBuffer_l should never be called with a non zero shared history if the
8935         // buffer was not already allocated
8936         ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
8937                 "resizeInputBuffer_l() called with shared history and unallocated buffer");
8938         size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
8939         // never reduce resampler input buffer size
8940         if (rsmpInFrames <= mRsmpInFrames) {
8941             return;
8942         }
8943         mRsmpInFrames = rsmpInFrames;
8944     }
8945     mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
8946     // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
8947     // initialized
8948     if (mRsmpInFrames < minRsmpInFrames) {
8949         mRsmpInFrames = minRsmpInFrames;
8950     }
8951     mRsmpInFramesP2 = roundup(mRsmpInFrames);
8952 
8953     // TODO optimize audio capture buffer sizes ...
8954     // Here we calculate the size of the sliding buffer used as a source
8955     // for resampling.  mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8956     // For current HAL frame counts, this is usually 2048 = 40 ms.  It would
8957     // be better to have it derived from the pipe depth in the long term.
8958     // The current value is higher than necessary.  However it should not add to latency.
8959 
8960     // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
8961     mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8962 
8963     void *rsmpInBuffer;
8964     (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
8965     // if posix_memalign fails, will segv here.
8966     memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
8967 
8968     // Copy audio history if any from old buffer before freeing it
8969     if (previousRear != 0) {
8970         ALOG_ASSERT(mRsmpInBuffer != nullptr,
8971                 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
8972 
8973         ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
8974         previousFront &= previousRsmpInFramesP2 - 1;
8975         size_t part1 = previousRsmpInFramesP2 - previousFront;
8976         if (part1 > (size_t) unread) {
8977             part1 = unread;
8978         }
8979         if (part1 != 0) {
8980             memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
8981                    part1 * mFrameSize);
8982             mRsmpInRear = part1;
8983             part1 = unread - part1;
8984             if (part1 != 0) {
8985                 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
8986                        (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
8987                 mRsmpInRear += part1;
8988             }
8989         }
8990         // Update front for all clients according to new rear
8991         updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
8992     } else {
8993         mRsmpInRear = 0;
8994     }
8995     free(mRsmpInBuffer);
8996     mRsmpInBuffer = rsmpInBuffer;
8997 }
8998 
addPatchTrack(const sp<PatchRecord> & record)8999 void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
9000 {
9001     Mutex::Autolock _l(mLock);
9002     mTracks.add(record);
9003     if (record->getSource()) {
9004         mSource = record->getSource();
9005     }
9006 }
9007 
deletePatchTrack(const sp<PatchRecord> & record)9008 void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
9009 {
9010     Mutex::Autolock _l(mLock);
9011     if (mSource == record->getSource()) {
9012         mSource = mInput;
9013     }
9014     destroyTrack_l(record);
9015 }
9016 
toAudioPortConfig(struct audio_port_config * config)9017 void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
9018 {
9019     ThreadBase::toAudioPortConfig(config);
9020     config->role = AUDIO_PORT_ROLE_SINK;
9021     config->ext.mix.hw_module = mInput->audioHwDev->handle();
9022     config->ext.mix.usecase.source = mAudioSource;
9023     if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9024         config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9025         config->flags.input = mInput->flags;
9026     }
9027 }
9028 
9029 // ----------------------------------------------------------------------------
9030 //      Mmap
9031 // ----------------------------------------------------------------------------
9032 
MmapThreadHandle(const sp<MmapThread> & thread)9033 AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9034     : mThread(thread)
9035 {
9036     assert(thread != 0); // thread must start non-null and stay non-null
9037 }
9038 
~MmapThreadHandle()9039 AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9040 {
9041     mThread->disconnect();
9042 }
9043 
createMmapBuffer(int32_t minSizeFrames,struct audio_mmap_buffer_info * info)9044 status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9045                                   struct audio_mmap_buffer_info *info)
9046 {
9047     return mThread->createMmapBuffer(minSizeFrames, info);
9048 }
9049 
getMmapPosition(struct audio_mmap_position * position)9050 status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9051 {
9052     return mThread->getMmapPosition(position);
9053 }
9054 
getExternalPosition(uint64_t * position,int64_t * timeNanos)9055 status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9056                                                              int64_t *timeNanos) {
9057     return mThread->getExternalPosition(position, timeNanos);
9058 }
9059 
start(const AudioClient & client,const audio_attributes_t * attr,audio_port_handle_t * handle)9060 status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
9061         const audio_attributes_t *attr, audio_port_handle_t *handle)
9062 
9063 {
9064     return mThread->start(client, attr, handle);
9065 }
9066 
stop(audio_port_handle_t handle)9067 status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9068 {
9069     return mThread->stop(handle);
9070 }
9071 
standby()9072 status_t AudioFlinger::MmapThreadHandle::standby()
9073 {
9074     return mThread->standby();
9075 }
9076 
9077 
MmapThread(const sp<AudioFlinger> & audioFlinger,audio_io_handle_t id,AudioHwDevice * hwDev,sp<StreamHalInterface> stream,bool systemReady,bool isOut)9078 AudioFlinger::MmapThread::MmapThread(
9079         const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9080         AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
9081     : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
9082       mSessionId(AUDIO_SESSION_NONE),
9083       mPortId(AUDIO_PORT_HANDLE_NONE),
9084       mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
9085       mActiveTracks(&this->mLocalLog),
9086       mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9087       mNoCallbackWarningCount(0)
9088 {
9089     mStandby = true;
9090     readHalParameters_l();
9091 }
9092 
~MmapThread()9093 AudioFlinger::MmapThread::~MmapThread()
9094 {
9095 }
9096 
onFirstRef()9097 void AudioFlinger::MmapThread::onFirstRef()
9098 {
9099     run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9100 }
9101 
disconnect()9102 void AudioFlinger::MmapThread::disconnect()
9103 {
9104     ActiveTracks<MmapTrack> activeTracks;
9105     {
9106         Mutex::Autolock _l(mLock);
9107         for (const sp<MmapTrack> &t : mActiveTracks) {
9108             activeTracks.add(t);
9109         }
9110     }
9111     for (const sp<MmapTrack> &t : activeTracks) {
9112         stop(t->portId());
9113     }
9114     // This will decrement references and may cause the destruction of this thread.
9115     if (isOutput()) {
9116         AudioSystem::releaseOutput(mPortId);
9117     } else {
9118         AudioSystem::releaseInput(mPortId);
9119     }
9120 }
9121 
9122 
configure(const audio_attributes_t * attr,audio_stream_type_t streamType __unused,audio_session_t sessionId,const sp<MmapStreamCallback> & callback,audio_port_handle_t deviceId,audio_port_handle_t portId)9123 void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9124                                                 audio_stream_type_t streamType __unused,
9125                                                 audio_session_t sessionId,
9126                                                 const sp<MmapStreamCallback>& callback,
9127                                                 audio_port_handle_t deviceId,
9128                                                 audio_port_handle_t portId)
9129 {
9130     mAttr = *attr;
9131     mSessionId = sessionId;
9132     mCallback = callback;
9133     mDeviceId = deviceId;
9134     mPortId = portId;
9135 }
9136 
createMmapBuffer(int32_t minSizeFrames,struct audio_mmap_buffer_info * info)9137 status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9138                                   struct audio_mmap_buffer_info *info)
9139 {
9140     if (mHalStream == 0) {
9141         return NO_INIT;
9142     }
9143     mStandby = true;
9144     return mHalStream->createMmapBuffer(minSizeFrames, info);
9145 }
9146 
getMmapPosition(struct audio_mmap_position * position)9147 status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9148 {
9149     if (mHalStream == 0) {
9150         return NO_INIT;
9151     }
9152     return mHalStream->getMmapPosition(position);
9153 }
9154 
exitStandby()9155 status_t AudioFlinger::MmapThread::exitStandby()
9156 {
9157     status_t ret = mHalStream->start();
9158     if (ret != NO_ERROR) {
9159         ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9160         return ret;
9161     }
9162     if (mStandby) {
9163         mThreadMetrics.logBeginInterval();
9164         mStandby = false;
9165     }
9166     return NO_ERROR;
9167 }
9168 
start(const AudioClient & client,const audio_attributes_t * attr,audio_port_handle_t * handle)9169 status_t AudioFlinger::MmapThread::start(const AudioClient& client,
9170                                          const audio_attributes_t *attr,
9171                                          audio_port_handle_t *handle)
9172 {
9173     ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
9174           client.attributionSource.uid, mStandby, mPortId, *handle);
9175     if (mHalStream == 0) {
9176         return NO_INIT;
9177     }
9178 
9179     status_t ret;
9180 
9181     if (*handle == mPortId) {
9182         // For the first track, reuse portId and session allocated when the stream was opened.
9183         ret = exitStandby();
9184         if (ret == NO_ERROR) {
9185             acquireWakeLock();
9186         }
9187         return ret;
9188     }
9189 
9190     audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9191 
9192     audio_io_handle_t io = mId;
9193     if (isOutput()) {
9194         audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9195         config.sample_rate = mSampleRate;
9196         config.channel_mask = mChannelMask;
9197         config.format = mFormat;
9198         audio_stream_type_t stream = streamType();
9199         audio_output_flags_t flags =
9200                 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
9201         audio_port_handle_t deviceId = mDeviceId;
9202         std::vector<audio_io_handle_t> secondaryOutputs;
9203         ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9204                                             mSessionId,
9205                                             &stream,
9206                                             client.attributionSource,
9207                                             &config,
9208                                             flags,
9209                                             &deviceId,
9210                                             &portId,
9211                                             &secondaryOutputs);
9212         ALOGD_IF(!secondaryOutputs.empty(),
9213                  "MmapThread::start does not support secondary outputs, ignoring them");
9214     } else {
9215         audio_config_base_t config;
9216         config.sample_rate = mSampleRate;
9217         config.channel_mask = mChannelMask;
9218         config.format = mFormat;
9219         audio_port_handle_t deviceId = mDeviceId;
9220         ret = AudioSystem::getInputForAttr(&mAttr, &io,
9221                                               RECORD_RIID_INVALID,
9222                                               mSessionId,
9223                                               client.attributionSource,
9224                                               &config,
9225                                               AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9226                                               &deviceId,
9227                                               &portId);
9228     }
9229     // APM should not chose a different input or output stream for the same set of attributes
9230     // and audo configuration
9231     if (ret != NO_ERROR || io != mId) {
9232         ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9233               __FUNCTION__, ret, io, mId);
9234         return BAD_VALUE;
9235     }
9236 
9237     if (isOutput()) {
9238         ret = AudioSystem::startOutput(portId);
9239     } else {
9240         ret = AudioSystem::startInput(portId);
9241     }
9242 
9243     Mutex::Autolock _l(mLock);
9244     // abort if start is rejected by audio policy manager
9245     if (ret != NO_ERROR) {
9246         ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
9247         if (!mActiveTracks.isEmpty()) {
9248             mLock.unlock();
9249             if (isOutput()) {
9250                 AudioSystem::releaseOutput(portId);
9251             } else {
9252                 AudioSystem::releaseInput(portId);
9253             }
9254             mLock.lock();
9255         } else {
9256             mHalStream->stop();
9257         }
9258         return PERMISSION_DENIED;
9259     }
9260 
9261     // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
9262     sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
9263                                         mChannelMask, mSessionId, isOutput(),
9264                                         client.attributionSource,
9265                                         IPCThreadState::self()->getCallingPid(), portId);
9266 
9267     if (isOutput()) {
9268         // force volume update when a new track is added
9269         mHalVolFloat = -1.0f;
9270     } else if (!track->isSilenced_l()) {
9271         for (const sp<MmapTrack> &t : mActiveTracks) {
9272             if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
9273                 t->invalidate();
9274         }
9275     }
9276 
9277 
9278     mActiveTracks.add(track);
9279     sp<EffectChain> chain = getEffectChain_l(mSessionId);
9280     if (chain != 0) {
9281         chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
9282         chain->incTrackCnt();
9283         chain->incActiveTrackCnt();
9284     }
9285 
9286     track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
9287     *handle = portId;
9288     broadcast_l();
9289 
9290     ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
9291 
9292     return NO_ERROR;
9293 }
9294 
stop(audio_port_handle_t handle)9295 status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9296 {
9297     ALOGV("%s handle %d", __FUNCTION__, handle);
9298 
9299     if (mHalStream == 0) {
9300         return NO_INIT;
9301     }
9302 
9303     if (handle == mPortId) {
9304         mHalStream->stop();
9305         releaseWakeLock();
9306         return NO_ERROR;
9307     }
9308 
9309     Mutex::Autolock _l(mLock);
9310 
9311     sp<MmapTrack> track;
9312     for (const sp<MmapTrack> &t : mActiveTracks) {
9313         if (handle == t->portId()) {
9314             track = t;
9315             break;
9316         }
9317     }
9318     if (track == 0) {
9319         return BAD_VALUE;
9320     }
9321 
9322     mActiveTracks.remove(track);
9323 
9324     mLock.unlock();
9325     if (isOutput()) {
9326         AudioSystem::stopOutput(track->portId());
9327         AudioSystem::releaseOutput(track->portId());
9328     } else {
9329         AudioSystem::stopInput(track->portId());
9330         AudioSystem::releaseInput(track->portId());
9331     }
9332     mLock.lock();
9333 
9334     sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9335     if (chain != 0) {
9336         chain->decActiveTrackCnt();
9337         chain->decTrackCnt();
9338     }
9339 
9340     broadcast_l();
9341 
9342     return NO_ERROR;
9343 }
9344 
standby()9345 status_t AudioFlinger::MmapThread::standby()
9346 {
9347     ALOGV("%s", __FUNCTION__);
9348 
9349     if (mHalStream == 0) {
9350         return NO_INIT;
9351     }
9352     if (!mActiveTracks.isEmpty()) {
9353         return INVALID_OPERATION;
9354     }
9355     mHalStream->standby();
9356     if (!mStandby) {
9357         mThreadMetrics.logEndInterval();
9358         mStandby = true;
9359     }
9360     releaseWakeLock();
9361     return NO_ERROR;
9362 }
9363 
9364 
readHalParameters_l()9365 void AudioFlinger::MmapThread::readHalParameters_l()
9366 {
9367     status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9368     LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9369     mFormat = mHALFormat;
9370     LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9371     result = mHalStream->getFrameSize(&mFrameSize);
9372     LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
9373     LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9374             mFrameSize);
9375     result = mHalStream->getBufferSize(&mBufferSize);
9376     LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9377     mFrameCount = mBufferSize / mFrameSize;
9378 
9379     // TODO: make a readHalParameters call?
9380     mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9381     item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9382         .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9383         .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9384         .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9385         .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9386         .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9387         /*
9388         .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9389         .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9390                 (int32_t)mHapticChannelMask)
9391         .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9392                 (int32_t)mHapticChannelCount)
9393         */
9394         .set(AMEDIAMETRICS_PROP_PREFIX_HAL    AMEDIAMETRICS_PROP_ENCODING,
9395                 formatToString(mHALFormat).c_str())
9396         .set(AMEDIAMETRICS_PROP_PREFIX_HAL    AMEDIAMETRICS_PROP_FRAMECOUNT,
9397                 (int32_t)mFrameCount) // sic - added HAL
9398         .record();
9399 }
9400 
threadLoop()9401 bool AudioFlinger::MmapThread::threadLoop()
9402 {
9403     checkSilentMode_l();
9404 
9405     const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9406 
9407     while (!exitPending())
9408     {
9409         Vector< sp<EffectChain> > effectChains;
9410 
9411         { // under Thread lock
9412         Mutex::Autolock _l(mLock);
9413 
9414         if (mSignalPending) {
9415             // A signal was raised while we were unlocked
9416             mSignalPending = false;
9417         } else {
9418             if (mConfigEvents.isEmpty()) {
9419                 // we're about to wait, flush the binder command buffer
9420                 IPCThreadState::self()->flushCommands();
9421 
9422                 if (exitPending()) {
9423                     break;
9424                 }
9425 
9426                 // wait until we have something to do...
9427                 ALOGV("%s going to sleep", myName.string());
9428                 mWaitWorkCV.wait(mLock);
9429                 ALOGV("%s waking up", myName.string());
9430 
9431                 checkSilentMode_l();
9432 
9433                 continue;
9434             }
9435         }
9436 
9437         processConfigEvents_l();
9438 
9439         processVolume_l();
9440 
9441         checkInvalidTracks_l();
9442 
9443         mActiveTracks.updatePowerState(this);
9444 
9445         updateMetadata_l();
9446 
9447         lockEffectChains_l(effectChains);
9448         } // release Thread lock
9449 
9450         for (size_t i = 0; i < effectChains.size(); i ++) {
9451             effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
9452         }
9453 
9454         // enable changes in effect chain, including moving to another thread.
9455         unlockEffectChains(effectChains);
9456         // Effect chains will be actually deleted here if they were removed from
9457         // mEffectChains list during mixing or effects processing
9458     }
9459 
9460     threadLoop_exit();
9461 
9462     if (!mStandby) {
9463         threadLoop_standby();
9464         mStandby = true;
9465     }
9466 
9467     ALOGV("Thread %p type %d exiting", this, mType);
9468     return false;
9469 }
9470 
9471 // checkForNewParameter_l() must be called with ThreadBase::mLock held
checkForNewParameter_l(const String8 & keyValuePair,status_t & status)9472 bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9473                                                               status_t& status)
9474 {
9475     AudioParameter param = AudioParameter(keyValuePair);
9476     int value;
9477     bool sendToHal = true;
9478     if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
9479         LOG_FATAL("Should not happen set routing device in MmapThread");
9480     }
9481     if (sendToHal) {
9482         status = mHalStream->setParameters(keyValuePair);
9483     } else {
9484         status = NO_ERROR;
9485     }
9486 
9487     return false;
9488 }
9489 
getParameters(const String8 & keys)9490 String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9491 {
9492     Mutex::Autolock _l(mLock);
9493     String8 out_s8;
9494     if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9495         return out_s8;
9496     }
9497     return String8();
9498 }
9499 
ioConfigChanged(audio_io_config_event event,pid_t pid,audio_port_handle_t portId __unused)9500 void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9501                                                audio_port_handle_t portId __unused) {
9502     sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9503 
9504     desc->mIoHandle = mId;
9505 
9506     switch (event) {
9507     case AUDIO_INPUT_OPENED:
9508     case AUDIO_INPUT_REGISTERED:
9509     case AUDIO_INPUT_CONFIG_CHANGED:
9510     case AUDIO_OUTPUT_OPENED:
9511     case AUDIO_OUTPUT_REGISTERED:
9512     case AUDIO_OUTPUT_CONFIG_CHANGED:
9513         desc->mPatch = mPatch;
9514         desc->mChannelMask = mChannelMask;
9515         desc->mSamplingRate = mSampleRate;
9516         desc->mFormat = mFormat;
9517         desc->mFrameCount = mFrameCount;
9518         desc->mFrameCountHAL = mFrameCount;
9519         desc->mLatency = 0;
9520         break;
9521 
9522     case AUDIO_INPUT_CLOSED:
9523     case AUDIO_OUTPUT_CLOSED:
9524     default:
9525         break;
9526     }
9527     mAudioFlinger->ioConfigChanged(event, desc, pid);
9528 }
9529 
createAudioPatch_l(const struct audio_patch * patch,audio_patch_handle_t * handle)9530 status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9531                                                           audio_patch_handle_t *handle)
9532 {
9533     status_t status = NO_ERROR;
9534 
9535     // store new device and send to effects
9536     audio_devices_t type = AUDIO_DEVICE_NONE;
9537     audio_port_handle_t deviceId;
9538     AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9539     AudioDeviceTypeAddr sourceDeviceTypeAddr;
9540     uint32_t numDevices = 0;
9541     if (isOutput()) {
9542         for (unsigned int i = 0; i < patch->num_sinks; i++) {
9543             LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9544                                 && !mAudioHwDev->supportsAudioPatches(),
9545                                 "Enumerated device type(%#x) must not be used "
9546                                 "as it does not support audio patches",
9547                                 patch->sinks[i].ext.device.type);
9548             type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
9549             sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9550                     patch->sinks[i].ext.device.address));
9551         }
9552         deviceId = patch->sinks[0].id;
9553         numDevices = mPatch.num_sinks;
9554     } else {
9555         type = patch->sources[0].ext.device.type;
9556         deviceId = patch->sources[0].id;
9557         numDevices = mPatch.num_sources;
9558         sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
9559         sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
9560     }
9561 
9562     for (size_t i = 0; i < mEffectChains.size(); i++) {
9563         if (isOutput()) {
9564             mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9565         } else {
9566             mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9567         }
9568     }
9569 
9570     if (!isOutput()) {
9571         // store new source and send to effects
9572         if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9573             mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9574             for (size_t i = 0; i < mEffectChains.size(); i++) {
9575                 mEffectChains[i]->setAudioSource_l(mAudioSource);
9576             }
9577         }
9578     }
9579 
9580     if (mAudioHwDev->supportsAudioPatches()) {
9581         status = mHalDevice->createAudioPatch(patch->num_sources,
9582                                             patch->sources,
9583                                             patch->num_sinks,
9584                                             patch->sinks,
9585                                             handle);
9586     } else {
9587         char *address;
9588         if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9589             //FIXME: we only support address on first sink with HAL version < 3.0
9590             address = audio_device_address_to_parameter(
9591                                                         patch->sinks[0].ext.device.type,
9592                                                         patch->sinks[0].ext.device.address);
9593         } else {
9594             address = (char *)calloc(1, 1);
9595         }
9596         AudioParameter param = AudioParameter(String8(address));
9597         free(address);
9598         param.addInt(String8(AudioParameter::keyRouting), (int)type);
9599         if (!isOutput()) {
9600             param.addInt(String8(AudioParameter::keyInputSource),
9601                                          (int)patch->sinks[0].ext.mix.usecase.source);
9602         }
9603         status = mHalStream->setParameters(param.toString());
9604         *handle = AUDIO_PATCH_HANDLE_NONE;
9605     }
9606 
9607     if (numDevices == 0 || mDeviceId != deviceId) {
9608         if (isOutput()) {
9609             sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9610             mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
9611             checkSilentMode_l();
9612         } else {
9613             sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9614             mInDeviceTypeAddr = sourceDeviceTypeAddr;
9615         }
9616         sp<MmapStreamCallback> callback = mCallback.promote();
9617         if (mDeviceId != deviceId && callback != 0) {
9618             mLock.unlock();
9619             callback->onRoutingChanged(deviceId);
9620             mLock.lock();
9621         }
9622         mPatch = *patch;
9623         mDeviceId = deviceId;
9624     }
9625     return status;
9626 }
9627 
releaseAudioPatch_l(const audio_patch_handle_t handle)9628 status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9629 {
9630     status_t status = NO_ERROR;
9631 
9632     mPatch = audio_patch{};
9633     mOutDeviceTypeAddrs.clear();
9634     mInDeviceTypeAddr.reset();
9635 
9636     bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9637                                         supportsAudioPatches : false;
9638 
9639     if (supportsAudioPatches) {
9640         status = mHalDevice->releaseAudioPatch(handle);
9641     } else {
9642         AudioParameter param;
9643         param.addInt(String8(AudioParameter::keyRouting), 0);
9644         status = mHalStream->setParameters(param.toString());
9645     }
9646     return status;
9647 }
9648 
toAudioPortConfig(struct audio_port_config * config)9649 void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
9650 {
9651     ThreadBase::toAudioPortConfig(config);
9652     if (isOutput()) {
9653         config->role = AUDIO_PORT_ROLE_SOURCE;
9654         config->ext.mix.hw_module = mAudioHwDev->handle();
9655         config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9656     } else {
9657         config->role = AUDIO_PORT_ROLE_SINK;
9658         config->ext.mix.hw_module = mAudioHwDev->handle();
9659         config->ext.mix.usecase.source = mAudioSource;
9660     }
9661 }
9662 
addEffectChain_l(const sp<EffectChain> & chain)9663 status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9664 {
9665     audio_session_t session = chain->sessionId();
9666 
9667     ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9668     // Attach all tracks with same session ID to this chain.
9669     // indicate all active tracks in the chain
9670     for (const sp<MmapTrack> &track : mActiveTracks) {
9671         if (session == track->sessionId()) {
9672             chain->incTrackCnt();
9673             chain->incActiveTrackCnt();
9674         }
9675     }
9676 
9677     chain->setThread(this);
9678     chain->setInBuffer(nullptr);
9679     chain->setOutBuffer(nullptr);
9680     chain->syncHalEffectsState();
9681 
9682     mEffectChains.add(chain);
9683     checkSuspendOnAddEffectChain_l(chain);
9684     return NO_ERROR;
9685 }
9686 
removeEffectChain_l(const sp<EffectChain> & chain)9687 size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9688 {
9689     audio_session_t session = chain->sessionId();
9690 
9691     ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9692 
9693     for (size_t i = 0; i < mEffectChains.size(); i++) {
9694         if (chain == mEffectChains[i]) {
9695             mEffectChains.removeAt(i);
9696             // detach all active tracks from the chain
9697             // detach all tracks with same session ID from this chain
9698             for (const sp<MmapTrack> &track : mActiveTracks) {
9699                 if (session == track->sessionId()) {
9700                     chain->decActiveTrackCnt();
9701                     chain->decTrackCnt();
9702                 }
9703             }
9704             break;
9705         }
9706     }
9707     return mEffectChains.size();
9708 }
9709 
threadLoop_standby()9710 void AudioFlinger::MmapThread::threadLoop_standby()
9711 {
9712     mHalStream->standby();
9713 }
9714 
threadLoop_exit()9715 void AudioFlinger::MmapThread::threadLoop_exit()
9716 {
9717     // Do not call callback->onTearDown() because it is redundant for thread exit
9718     // and because it can cause a recursive mutex lock on stop().
9719 }
9720 
setSyncEvent(const sp<SyncEvent> & event __unused)9721 status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9722 {
9723     return BAD_VALUE;
9724 }
9725 
isValidSyncEvent(const sp<SyncEvent> & event __unused) const9726 bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9727 {
9728     return false;
9729 }
9730 
checkEffectCompatibility_l(const effect_descriptor_t * desc,audio_session_t sessionId)9731 status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9732         const effect_descriptor_t *desc, audio_session_t sessionId)
9733 {
9734     // No global effect sessions on mmap threads
9735     if (audio_is_global_session(sessionId)) {
9736         ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
9737                 desc->name, mThreadName);
9738         return BAD_VALUE;
9739     }
9740 
9741     if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9742         ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9743                 desc->name);
9744         return BAD_VALUE;
9745     }
9746     if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
9747         ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9748               "thread", desc->name);
9749         return BAD_VALUE;
9750     }
9751 
9752     // Only allow effects without processing load or latency
9753     if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9754         return BAD_VALUE;
9755     }
9756 
9757     if (EffectModule::isHapticGenerator(&desc->type)) {
9758         ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9759         return BAD_VALUE;
9760     }
9761 
9762     return NO_ERROR;
9763 }
9764 
checkInvalidTracks_l()9765 void AudioFlinger::MmapThread::checkInvalidTracks_l()
9766 {
9767     for (const sp<MmapTrack> &track : mActiveTracks) {
9768         if (track->isInvalid()) {
9769             sp<MmapStreamCallback> callback = mCallback.promote();
9770             if (callback != 0) {
9771                 mLock.unlock();
9772                 callback->onTearDown(track->portId());
9773                 mLock.lock();
9774             } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9775                 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9776                 mNoCallbackWarningCount++;
9777             }
9778         }
9779     }
9780 }
9781 
dumpInternals_l(int fd,const Vector<String16> & args __unused)9782 void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
9783 {
9784     dprintf(fd, "  Attributes: content type %d usage %d source %d\n",
9785             mAttr.content_type, mAttr.usage, mAttr.source);
9786     dprintf(fd, "  Session: %d port Id: %d\n", mSessionId, mPortId);
9787     if (mActiveTracks.isEmpty()) {
9788         dprintf(fd, "  No active clients\n");
9789     }
9790 }
9791 
dumpTracks_l(int fd,const Vector<String16> & args __unused)9792 void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
9793 {
9794     String8 result;
9795     size_t numtracks = mActiveTracks.size();
9796     dprintf(fd, "  %zu Tracks\n", numtracks);
9797     const char *prefix = "    ";
9798     if (numtracks) {
9799         result.append(prefix);
9800         mActiveTracks[0]->appendDumpHeader(result);
9801         for (size_t i = 0; i < numtracks ; ++i) {
9802             sp<MmapTrack> track = mActiveTracks[i];
9803             result.append(prefix);
9804             track->appendDump(result, true /* active */);
9805         }
9806     } else {
9807         dprintf(fd, "\n");
9808     }
9809     write(fd, result.string(), result.size());
9810 }
9811 
MmapPlaybackThread(const sp<AudioFlinger> & audioFlinger,audio_io_handle_t id,AudioHwDevice * hwDev,AudioStreamOut * output,bool systemReady)9812 AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9813         const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9814         AudioHwDevice *hwDev,  AudioStreamOut *output, bool systemReady)
9815     : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
9816       mStreamType(AUDIO_STREAM_MUSIC),
9817       mStreamVolume(1.0),
9818       mStreamMute(false),
9819       mOutput(output)
9820 {
9821     snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9822     mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9823     mMasterVolume = audioFlinger->masterVolume_l();
9824     mMasterMute = audioFlinger->masterMute_l();
9825     if (mAudioHwDev) {
9826         if (mAudioHwDev->canSetMasterVolume()) {
9827             mMasterVolume = 1.0;
9828         }
9829 
9830         if (mAudioHwDev->canSetMasterMute()) {
9831             mMasterMute = false;
9832         }
9833     }
9834 }
9835 
configure(const audio_attributes_t * attr,audio_stream_type_t streamType,audio_session_t sessionId,const sp<MmapStreamCallback> & callback,audio_port_handle_t deviceId,audio_port_handle_t portId)9836 void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9837                                                 audio_stream_type_t streamType,
9838                                                 audio_session_t sessionId,
9839                                                 const sp<MmapStreamCallback>& callback,
9840                                                 audio_port_handle_t deviceId,
9841                                                 audio_port_handle_t portId)
9842 {
9843     MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
9844     mStreamType = streamType;
9845 }
9846 
clearOutput()9847 AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9848 {
9849     Mutex::Autolock _l(mLock);
9850     AudioStreamOut *output = mOutput;
9851     mOutput = NULL;
9852     return output;
9853 }
9854 
setMasterVolume(float value)9855 void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9856 {
9857     Mutex::Autolock _l(mLock);
9858     // Don't apply master volume in SW if our HAL can do it for us.
9859     if (mAudioHwDev &&
9860             mAudioHwDev->canSetMasterVolume()) {
9861         mMasterVolume = 1.0;
9862     } else {
9863         mMasterVolume = value;
9864     }
9865 }
9866 
setMasterMute(bool muted)9867 void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9868 {
9869     Mutex::Autolock _l(mLock);
9870     // Don't apply master mute in SW if our HAL can do it for us.
9871     if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9872         mMasterMute = false;
9873     } else {
9874         mMasterMute = muted;
9875     }
9876 }
9877 
setStreamVolume(audio_stream_type_t stream,float value)9878 void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9879 {
9880     Mutex::Autolock _l(mLock);
9881     if (stream == mStreamType) {
9882         mStreamVolume = value;
9883         broadcast_l();
9884     }
9885 }
9886 
streamVolume(audio_stream_type_t stream) const9887 float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9888 {
9889     Mutex::Autolock _l(mLock);
9890     if (stream == mStreamType) {
9891         return mStreamVolume;
9892     }
9893     return 0.0f;
9894 }
9895 
setStreamMute(audio_stream_type_t stream,bool muted)9896 void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9897 {
9898     Mutex::Autolock _l(mLock);
9899     if (stream == mStreamType) {
9900         mStreamMute= muted;
9901         broadcast_l();
9902     }
9903 }
9904 
invalidateTracks(audio_stream_type_t streamType)9905 void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9906 {
9907     Mutex::Autolock _l(mLock);
9908     if (streamType == mStreamType) {
9909         for (const sp<MmapTrack> &track : mActiveTracks) {
9910             track->invalidate();
9911         }
9912         broadcast_l();
9913     }
9914 }
9915 
processVolume_l()9916 void AudioFlinger::MmapPlaybackThread::processVolume_l()
9917 {
9918     float volume;
9919 
9920     if (mMasterMute || mStreamMute) {
9921         volume = 0;
9922     } else {
9923         volume = mMasterVolume * mStreamVolume;
9924     }
9925 
9926     if (volume != mHalVolFloat) {
9927 
9928         // Convert volumes from float to 8.24
9929         uint32_t vol = (uint32_t)(volume * (1 << 24));
9930 
9931         // Delegate volume control to effect in track effect chain if needed
9932         // only one effect chain can be present on DirectOutputThread, so if
9933         // there is one, the track is connected to it
9934         if (!mEffectChains.isEmpty()) {
9935             mEffectChains[0]->setVolume_l(&vol, &vol);
9936             volume = (float)vol / (1 << 24);
9937         }
9938         // Try to use HW volume control and fall back to SW control if not implemented
9939         if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9940             mHalVolFloat = volume; // HW volume control worked, so update value.
9941             mNoCallbackWarningCount = 0;
9942         } else {
9943             sp<MmapStreamCallback> callback = mCallback.promote();
9944             if (callback != 0) {
9945                 int channelCount;
9946                 if (isOutput()) {
9947                     channelCount = audio_channel_count_from_out_mask(mChannelMask);
9948                 } else {
9949                     channelCount = audio_channel_count_from_in_mask(mChannelMask);
9950                 }
9951                 Vector<float> values;
9952                 for (int i = 0; i < channelCount; i++) {
9953                     values.add(volume);
9954                 }
9955                 mHalVolFloat = volume; // SW volume control worked, so update value.
9956                 mNoCallbackWarningCount = 0;
9957                 mLock.unlock();
9958                 callback->onVolumeChanged(mChannelMask, values);
9959                 mLock.lock();
9960             } else {
9961                 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9962                     ALOGW("Could not set MMAP stream volume: no volume callback!");
9963                     mNoCallbackWarningCount++;
9964                 }
9965             }
9966         }
9967         for (const sp<MmapTrack> &track : mActiveTracks) {
9968             track->setMetadataHasChanged();
9969         }
9970     }
9971 }
9972 
updateMetadata_l()9973 void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9974 {
9975     if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
9976         return; // nothing to do
9977     }
9978     StreamOutHalInterface::SourceMetadata metadata;
9979     for (const sp<MmapTrack> &track : mActiveTracks) {
9980         // No track is invalid as this is called after prepareTrack_l in the same critical section
9981         playback_track_metadata_v7_t trackMetadata;
9982         trackMetadata.base = {
9983                 .usage = track->attributes().usage,
9984                 .content_type = track->attributes().content_type,
9985                 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9986         };
9987         trackMetadata.channel_mask = track->channelMask(),
9988         strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
9989         metadata.tracks.push_back(trackMetadata);
9990     }
9991     mOutput->stream->updateSourceMetadata(metadata);
9992 }
9993 
checkSilentMode_l()9994 void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9995 {
9996     if (!mMasterMute) {
9997         char value[PROPERTY_VALUE_MAX];
9998         if (property_get("ro.audio.silent", value, "0") > 0) {
9999             char *endptr;
10000             unsigned long ul = strtoul(value, &endptr, 0);
10001             if (*endptr == '\0' && ul != 0) {
10002                 ALOGD("Silence is golden");
10003                 // The setprop command will not allow a property to be changed after
10004                 // the first time it is set, so we don't have to worry about un-muting.
10005                 setMasterMute_l(true);
10006             }
10007         }
10008     }
10009 }
10010 
toAudioPortConfig(struct audio_port_config * config)10011 void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10012 {
10013     MmapThread::toAudioPortConfig(config);
10014     if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10015         config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10016         config->flags.output = mOutput->flags;
10017     }
10018 }
10019 
getExternalPosition(uint64_t * position,int64_t * timeNanos)10020 status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10021                                                                int64_t *timeNanos)
10022 {
10023     if (mOutput == nullptr) {
10024         return NO_INIT;
10025     }
10026     struct timespec timestamp;
10027     status_t status = mOutput->getPresentationPosition(position, &timestamp);
10028     if (status == NO_ERROR) {
10029         *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10030     }
10031     return status;
10032 }
10033 
dumpInternals_l(int fd,const Vector<String16> & args)10034 void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
10035 {
10036     MmapThread::dumpInternals_l(fd, args);
10037 
10038     dprintf(fd, "  Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10039             mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
10040     dprintf(fd, "  Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10041 }
10042 
MmapCaptureThread(const sp<AudioFlinger> & audioFlinger,audio_io_handle_t id,AudioHwDevice * hwDev,AudioStreamIn * input,bool systemReady)10043 AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10044         const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
10045         AudioHwDevice *hwDev,  AudioStreamIn *input, bool systemReady)
10046     : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
10047       mInput(input)
10048 {
10049     snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10050     mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10051 }
10052 
exitStandby()10053 status_t AudioFlinger::MmapCaptureThread::exitStandby()
10054 {
10055     {
10056         // mInput might have been cleared by clearInput()
10057         Mutex::Autolock _l(mLock);
10058         if (mInput != nullptr && mInput->stream != nullptr) {
10059             mInput->stream->setGain(1.0f);
10060         }
10061     }
10062     return MmapThread::exitStandby();
10063 }
10064 
clearInput()10065 AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10066 {
10067     Mutex::Autolock _l(mLock);
10068     AudioStreamIn *input = mInput;
10069     mInput = NULL;
10070     return input;
10071 }
10072 
10073 
processVolume_l()10074 void AudioFlinger::MmapCaptureThread::processVolume_l()
10075 {
10076     bool changed = false;
10077     bool silenced = false;
10078 
10079     sp<MmapStreamCallback> callback = mCallback.promote();
10080     if (callback == 0) {
10081         if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10082             ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10083             mNoCallbackWarningCount++;
10084         }
10085     }
10086 
10087     // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10088     // track is silenced and unmute otherwise
10089     for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10090         if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10091             changed = true;
10092             silenced = mActiveTracks[i]->isSilenced_l();
10093         }
10094     }
10095 
10096     if (changed) {
10097         mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10098     }
10099 }
10100 
updateMetadata_l()10101 void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10102 {
10103     if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10104         return; // nothing to do
10105     }
10106     StreamInHalInterface::SinkMetadata metadata;
10107     for (const sp<MmapTrack> &track : mActiveTracks) {
10108         // No track is invalid as this is called after prepareTrack_l in the same critical section
10109         record_track_metadata_v7_t trackMetadata;
10110         trackMetadata.base = {
10111                 .source = track->attributes().source,
10112                 .gain = 1, // capture tracks do not have volumes
10113         };
10114         trackMetadata.channel_mask = track->channelMask(),
10115         strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10116         metadata.tracks.push_back(trackMetadata);
10117     }
10118     mInput->stream->updateSinkMetadata(metadata);
10119 }
10120 
setRecordSilenced(audio_port_handle_t portId,bool silenced)10121 void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
10122 {
10123     Mutex::Autolock _l(mLock);
10124     for (size_t i = 0; i < mActiveTracks.size() ; i++) {
10125         if (mActiveTracks[i]->portId() == portId) {
10126             mActiveTracks[i]->setSilenced_l(silenced);
10127             broadcast_l();
10128         }
10129     }
10130 }
10131 
toAudioPortConfig(struct audio_port_config * config)10132 void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10133 {
10134     MmapThread::toAudioPortConfig(config);
10135     if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10136         config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10137         config->flags.input = mInput->flags;
10138     }
10139 }
10140 
getExternalPosition(uint64_t * position,int64_t * timeNanos)10141 status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10142         uint64_t *position, int64_t *timeNanos)
10143 {
10144     if (mInput == nullptr) {
10145         return NO_INIT;
10146     }
10147     return mInput->getCapturePosition((int64_t*)position, timeNanos);
10148 }
10149 
10150 } // namespace android
10151