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