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