• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 **
3 ** Copyright 2012, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 
19 #define LOG_TAG "AudioFlinger"
20 //#define LOG_NDEBUG 0
21 #define ATRACE_TAG ATRACE_TAG_AUDIO
22 
23 #include "Configuration.h"
24 #include <math.h>
25 #include <fcntl.h>
26 #include <linux/futex.h>
27 #include <sys/stat.h>
28 #include <sys/syscall.h>
29 #include <cutils/properties.h>
30 #include <media/AudioParameter.h>
31 #include <media/AudioResamplerPublic.h>
32 #include <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::__anon7d4e85f80308230     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::__anon7d4e85f80308244     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::__anon7d4e85f80308257     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::__anon7d4e85f80308273     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 // checkEffectCompatibility_l() must be called with ThreadBase::mLock held
checkEffectCompatibility_l(const effect_descriptor_t * desc,audio_session_t sessionId)1260 status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1261         const effect_descriptor_t *desc, audio_session_t sessionId)
1262 {
1263     // No global effect sessions on record threads
1264     if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1265         ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1266                 desc->name, mThreadName);
1267         return BAD_VALUE;
1268     }
1269     // only pre processing effects on record thread
1270     if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1271         ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1272                 desc->name, mThreadName);
1273         return BAD_VALUE;
1274     }
1275     audio_input_flags_t flags = mInput->flags;
1276     if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1277         if (flags & AUDIO_INPUT_FLAG_RAW) {
1278             ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1279                   desc->name, mThreadName);
1280             return BAD_VALUE;
1281         }
1282         if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1283             ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1284                   desc->name, mThreadName);
1285             return BAD_VALUE;
1286         }
1287     }
1288     return NO_ERROR;
1289 }
1290 
1291 // checkEffectCompatibility_l() must be called with ThreadBase::mLock held
checkEffectCompatibility_l(const effect_descriptor_t * desc,audio_session_t sessionId)1292 status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1293         const effect_descriptor_t *desc, audio_session_t sessionId)
1294 {
1295     // no preprocessing on playback threads
1296     if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1297         ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1298                 " thread %s", desc->name, mThreadName);
1299         return BAD_VALUE;
1300     }
1301 
1302     switch (mType) {
1303     case MIXER: {
1304         // Reject any effect on mixer multichannel sinks.
1305         // TODO: fix both format and multichannel issues with effects.
1306         if (mChannelCount != FCC_2) {
1307             ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1308                     " thread %s", desc->name, mChannelCount, mThreadName);
1309             return BAD_VALUE;
1310         }
1311         audio_output_flags_t flags = mOutput->flags;
1312         if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1313             if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1314                 // global effects are applied only to non fast tracks if they are SW
1315                 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1316                     break;
1317                 }
1318             } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1319                 // only post processing on output stage session
1320                 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1321                     ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1322                             " on output stage session", desc->name);
1323                     return BAD_VALUE;
1324                 }
1325             } else {
1326                 // no restriction on effects applied on non fast tracks
1327                 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1328                     break;
1329                 }
1330             }
1331             if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1332                 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1333                       desc->name);
1334                 return BAD_VALUE;
1335             }
1336             if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1337                 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1338                         " in fast mode", desc->name);
1339                 return BAD_VALUE;
1340             }
1341         }
1342     } break;
1343     case OFFLOAD:
1344         // nothing actionable on offload threads, if the effect:
1345         //   - is offloadable: the effect can be created
1346         //   - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1347         //     will take care of invalidating the tracks of the thread
1348         break;
1349     case DIRECT:
1350         // Reject any effect on Direct output threads for now, since the format of
1351         // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1352         ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1353                 desc->name, mThreadName);
1354         return BAD_VALUE;
1355     case DUPLICATING:
1356         // Reject any effect on mixer multichannel sinks.
1357         // TODO: fix both format and multichannel issues with effects.
1358         if (mChannelCount != FCC_2) {
1359             ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1360                     " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1361             return BAD_VALUE;
1362         }
1363         if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1364             ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1365                     " thread %s", desc->name, mThreadName);
1366             return BAD_VALUE;
1367         }
1368         if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1369             ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1370                     " DUPLICATING thread %s", desc->name, mThreadName);
1371             return BAD_VALUE;
1372         }
1373         if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1374             ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1375                     " DUPLICATING thread %s", desc->name, mThreadName);
1376             return BAD_VALUE;
1377         }
1378         break;
1379     default:
1380         LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1381     }
1382 
1383     return NO_ERROR;
1384 }
1385 
1386 // 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)1387 sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1388         const sp<AudioFlinger::Client>& client,
1389         const sp<IEffectClient>& effectClient,
1390         int32_t priority,
1391         audio_session_t sessionId,
1392         effect_descriptor_t *desc,
1393         int *enabled,
1394         status_t *status)
1395 {
1396     sp<EffectModule> effect;
1397     sp<EffectHandle> handle;
1398     status_t lStatus;
1399     sp<EffectChain> chain;
1400     bool chainCreated = false;
1401     bool effectCreated = false;
1402     bool effectRegistered = false;
1403 
1404     lStatus = initCheck();
1405     if (lStatus != NO_ERROR) {
1406         ALOGW("createEffect_l() Audio driver not initialized.");
1407         goto Exit;
1408     }
1409 
1410     ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1411 
1412     { // scope for mLock
1413         Mutex::Autolock _l(mLock);
1414 
1415         lStatus = checkEffectCompatibility_l(desc, sessionId);
1416         if (lStatus != NO_ERROR) {
1417             goto Exit;
1418         }
1419 
1420         // check for existing effect chain with the requested audio session
1421         chain = getEffectChain_l(sessionId);
1422         if (chain == 0) {
1423             // create a new chain for this session
1424             ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1425             chain = new EffectChain(this, sessionId);
1426             addEffectChain_l(chain);
1427             chain->setStrategy(getStrategyForSession_l(sessionId));
1428             chainCreated = true;
1429         } else {
1430             effect = chain->getEffectFromDesc_l(desc);
1431         }
1432 
1433         ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1434 
1435         if (effect == 0) {
1436             audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
1437             // Check CPU and memory usage
1438             lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1439             if (lStatus != NO_ERROR) {
1440                 goto Exit;
1441             }
1442             effectRegistered = true;
1443             // create a new effect module if none present in the chain
1444             effect = new EffectModule(this, chain, desc, id, sessionId);
1445             lStatus = effect->status();
1446             if (lStatus != NO_ERROR) {
1447                 goto Exit;
1448             }
1449             effect->setOffloaded(mType == OFFLOAD, mId);
1450 
1451             lStatus = chain->addEffect_l(effect);
1452             if (lStatus != NO_ERROR) {
1453                 goto Exit;
1454             }
1455             effectCreated = true;
1456 
1457             effect->setDevice(mOutDevice);
1458             effect->setDevice(mInDevice);
1459             effect->setMode(mAudioFlinger->getMode());
1460             effect->setAudioSource(mAudioSource);
1461         }
1462         // create effect handle and connect it to effect module
1463         handle = new EffectHandle(effect, client, effectClient, priority);
1464         lStatus = handle->initCheck();
1465         if (lStatus == OK) {
1466             lStatus = effect->addHandle(handle.get());
1467         }
1468         if (enabled != NULL) {
1469             *enabled = (int)effect->isEnabled();
1470         }
1471     }
1472 
1473 Exit:
1474     if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1475         Mutex::Autolock _l(mLock);
1476         if (effectCreated) {
1477             chain->removeEffect_l(effect);
1478         }
1479         if (effectRegistered) {
1480             AudioSystem::unregisterEffect(effect->id());
1481         }
1482         if (chainCreated) {
1483             removeEffectChain_l(chain);
1484         }
1485         handle.clear();
1486     }
1487 
1488     *status = lStatus;
1489     return handle;
1490 }
1491 
getEffect(audio_session_t sessionId,int effectId)1492 sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1493         int effectId)
1494 {
1495     Mutex::Autolock _l(mLock);
1496     return getEffect_l(sessionId, effectId);
1497 }
1498 
getEffect_l(audio_session_t sessionId,int effectId)1499 sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1500         int effectId)
1501 {
1502     sp<EffectChain> chain = getEffectChain_l(sessionId);
1503     return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1504 }
1505 
1506 // PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1507 // PlaybackThread::mLock held
addEffect_l(const sp<EffectModule> & effect)1508 status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1509 {
1510     // check for existing effect chain with the requested audio session
1511     audio_session_t sessionId = effect->sessionId();
1512     sp<EffectChain> chain = getEffectChain_l(sessionId);
1513     bool chainCreated = false;
1514 
1515     ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1516              "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1517                     this, effect->desc().name, effect->desc().flags);
1518 
1519     if (chain == 0) {
1520         // create a new chain for this session
1521         ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1522         chain = new EffectChain(this, sessionId);
1523         addEffectChain_l(chain);
1524         chain->setStrategy(getStrategyForSession_l(sessionId));
1525         chainCreated = true;
1526     }
1527     ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1528 
1529     if (chain->getEffectFromId_l(effect->id()) != 0) {
1530         ALOGW("addEffect_l() %p effect %s already present in chain %p",
1531                 this, effect->desc().name, chain.get());
1532         return BAD_VALUE;
1533     }
1534 
1535     effect->setOffloaded(mType == OFFLOAD, mId);
1536 
1537     status_t status = chain->addEffect_l(effect);
1538     if (status != NO_ERROR) {
1539         if (chainCreated) {
1540             removeEffectChain_l(chain);
1541         }
1542         return status;
1543     }
1544 
1545     effect->setDevice(mOutDevice);
1546     effect->setDevice(mInDevice);
1547     effect->setMode(mAudioFlinger->getMode());
1548     effect->setAudioSource(mAudioSource);
1549     return NO_ERROR;
1550 }
1551 
removeEffect_l(const sp<EffectModule> & effect)1552 void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1553 
1554     ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1555     effect_descriptor_t desc = effect->desc();
1556     if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1557         detachAuxEffect_l(effect->id());
1558     }
1559 
1560     sp<EffectChain> chain = effect->chain().promote();
1561     if (chain != 0) {
1562         // remove effect chain if removing last effect
1563         if (chain->removeEffect_l(effect) == 0) {
1564             removeEffectChain_l(chain);
1565         }
1566     } else {
1567         ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1568     }
1569 }
1570 
lockEffectChains_l(Vector<sp<AudioFlinger::EffectChain>> & effectChains)1571 void AudioFlinger::ThreadBase::lockEffectChains_l(
1572         Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1573 {
1574     effectChains = mEffectChains;
1575     for (size_t i = 0; i < mEffectChains.size(); i++) {
1576         mEffectChains[i]->lock();
1577     }
1578 }
1579 
unlockEffectChains(const Vector<sp<AudioFlinger::EffectChain>> & effectChains)1580 void AudioFlinger::ThreadBase::unlockEffectChains(
1581         const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1582 {
1583     for (size_t i = 0; i < effectChains.size(); i++) {
1584         effectChains[i]->unlock();
1585     }
1586 }
1587 
getEffectChain(audio_session_t sessionId)1588 sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
1589 {
1590     Mutex::Autolock _l(mLock);
1591     return getEffectChain_l(sessionId);
1592 }
1593 
getEffectChain_l(audio_session_t sessionId) const1594 sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1595         const
1596 {
1597     size_t size = mEffectChains.size();
1598     for (size_t i = 0; i < size; i++) {
1599         if (mEffectChains[i]->sessionId() == sessionId) {
1600             return mEffectChains[i];
1601         }
1602     }
1603     return 0;
1604 }
1605 
setMode(audio_mode_t mode)1606 void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1607 {
1608     Mutex::Autolock _l(mLock);
1609     size_t size = mEffectChains.size();
1610     for (size_t i = 0; i < size; i++) {
1611         mEffectChains[i]->setMode_l(mode);
1612     }
1613 }
1614 
getAudioPortConfig(struct audio_port_config * config)1615 void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1616 {
1617     config->type = AUDIO_PORT_TYPE_MIX;
1618     config->ext.mix.handle = mId;
1619     config->sample_rate = mSampleRate;
1620     config->format = mFormat;
1621     config->channel_mask = mChannelMask;
1622     config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1623                             AUDIO_PORT_CONFIG_FORMAT;
1624 }
1625 
systemReady()1626 void AudioFlinger::ThreadBase::systemReady()
1627 {
1628     Mutex::Autolock _l(mLock);
1629     if (mSystemReady) {
1630         return;
1631     }
1632     mSystemReady = true;
1633 
1634     for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1635         sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1636     }
1637     mPendingConfigEvents.clear();
1638 }
1639 
1640 
1641 // ----------------------------------------------------------------------------
1642 //      Playback
1643 // ----------------------------------------------------------------------------
1644 
PlaybackThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,audio_devices_t device,type_t type,bool systemReady)1645 AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1646                                              AudioStreamOut* output,
1647                                              audio_io_handle_t id,
1648                                              audio_devices_t device,
1649                                              type_t type,
1650                                              bool systemReady)
1651     :   ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
1652         mNormalFrameCount(0), mSinkBuffer(NULL),
1653         mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
1654         mMixerBuffer(NULL),
1655         mMixerBufferSize(0),
1656         mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1657         mMixerBufferValid(false),
1658         mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
1659         mEffectBuffer(NULL),
1660         mEffectBufferSize(0),
1661         mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1662         mEffectBufferValid(false),
1663         mSuspended(0), mBytesWritten(0),
1664         mFramesWritten(0),
1665         mSuspendedFrames(0),
1666         mActiveTracksGeneration(0),
1667         // mStreamTypes[] initialized in constructor body
1668         mOutput(output),
1669         mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1670         mMixerStatus(MIXER_IDLE),
1671         mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1672         mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
1673         mBytesRemaining(0),
1674         mCurrentWriteLength(0),
1675         mUseAsyncWrite(false),
1676         mWriteAckSequence(0),
1677         mDrainSequence(0),
1678         mSignalPending(false),
1679         mScreenState(AudioFlinger::mScreenState),
1680         // index 0 is reserved for normal mixer's submix
1681         mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
1682         mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
1683 {
1684     snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1685     mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
1686 
1687     // Assumes constructor is called by AudioFlinger with it's mLock held, but
1688     // it would be safer to explicitly pass initial masterVolume/masterMute as
1689     // parameter.
1690     //
1691     // If the HAL we are using has support for master volume or master mute,
1692     // then do not attenuate or mute during mixing (just leave the volume at 1.0
1693     // and the mute set to false).
1694     mMasterVolume = audioFlinger->masterVolume_l();
1695     mMasterMute = audioFlinger->masterMute_l();
1696     if (mOutput && mOutput->audioHwDev) {
1697         if (mOutput->audioHwDev->canSetMasterVolume()) {
1698             mMasterVolume = 1.0;
1699         }
1700 
1701         if (mOutput->audioHwDev->canSetMasterMute()) {
1702             mMasterMute = false;
1703         }
1704     }
1705 
1706     readOutputParameters_l();
1707 
1708     // ++ operator does not compile
1709     for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
1710             stream = (audio_stream_type_t) (stream + 1)) {
1711         mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1712         mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1713     }
1714 }
1715 
~PlaybackThread()1716 AudioFlinger::PlaybackThread::~PlaybackThread()
1717 {
1718     mAudioFlinger->unregisterWriter(mNBLogWriter);
1719     free(mSinkBuffer);
1720     free(mMixerBuffer);
1721     free(mEffectBuffer);
1722 }
1723 
dump(int fd,const Vector<String16> & args)1724 void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1725 {
1726     dumpInternals(fd, args);
1727     dumpTracks(fd, args);
1728     dumpEffectChains(fd, args);
1729 }
1730 
dumpTracks(int fd,const Vector<String16> & args __unused)1731 void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
1732 {
1733     const size_t SIZE = 256;
1734     char buffer[SIZE];
1735     String8 result;
1736 
1737     result.appendFormat("  Stream volumes in dB: ");
1738     for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1739         const stream_type_t *st = &mStreamTypes[i];
1740         if (i > 0) {
1741             result.appendFormat(", ");
1742         }
1743         result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1744         if (st->mute) {
1745             result.append("M");
1746         }
1747     }
1748     result.append("\n");
1749     write(fd, result.string(), result.length());
1750     result.clear();
1751 
1752     // These values are "raw"; they will wrap around.  See prepareTracks_l() for a better way.
1753     FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1754     dprintf(fd, "  Normal mixer raw underrun counters: partial=%u empty=%u\n",
1755             underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1756 
1757     size_t numtracks = mTracks.size();
1758     size_t numactive = mActiveTracks.size();
1759     dprintf(fd, "  %zu Tracks", numtracks);
1760     size_t numactiveseen = 0;
1761     if (numtracks) {
1762         dprintf(fd, " of which %zu are active\n", numactive);
1763         Track::appendDumpHeader(result);
1764         for (size_t i = 0; i < numtracks; ++i) {
1765             sp<Track> track = mTracks[i];
1766             if (track != 0) {
1767                 bool active = mActiveTracks.indexOf(track) >= 0;
1768                 if (active) {
1769                     numactiveseen++;
1770                 }
1771                 track->dump(buffer, SIZE, active);
1772                 result.append(buffer);
1773             }
1774         }
1775     } else {
1776         result.append("\n");
1777     }
1778     if (numactiveseen != numactive) {
1779         // some tracks in the active list were not in the tracks list
1780         snprintf(buffer, SIZE, "  The following tracks are in the active list but"
1781                 " not in the track list\n");
1782         result.append(buffer);
1783         Track::appendDumpHeader(result);
1784         for (size_t i = 0; i < numactive; ++i) {
1785             sp<Track> track = mActiveTracks[i].promote();
1786             if (track != 0 && mTracks.indexOf(track) < 0) {
1787                 track->dump(buffer, SIZE, true);
1788                 result.append(buffer);
1789             }
1790         }
1791     }
1792 
1793     write(fd, result.string(), result.size());
1794 }
1795 
dumpInternals(int fd,const Vector<String16> & args)1796 void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1797 {
1798     dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
1799 
1800     dumpBase(fd, args);
1801 
1802     dprintf(fd, "  Normal frame count: %zu\n", mNormalFrameCount);
1803     dprintf(fd, "  Last write occurred (msecs): %llu\n",
1804             (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
1805     dprintf(fd, "  Total writes: %d\n", mNumWrites);
1806     dprintf(fd, "  Delayed writes: %d\n", mNumDelayedWrites);
1807     dprintf(fd, "  Blocked in write: %s\n", mInWrite ? "yes" : "no");
1808     dprintf(fd, "  Suspend count: %d\n", mSuspended);
1809     dprintf(fd, "  Sink buffer : %p\n", mSinkBuffer);
1810     dprintf(fd, "  Mixer buffer: %p\n", mMixerBuffer);
1811     dprintf(fd, "  Effect buffer: %p\n", mEffectBuffer);
1812     dprintf(fd, "  Fast track availMask=%#x\n", mFastTrackAvailMask);
1813     dprintf(fd, "  Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
1814     AudioStreamOut *output = mOutput;
1815     audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1816     String8 flagsAsString = outputFlagsToString(flags);
1817     dprintf(fd, "  AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
1818 }
1819 
1820 // Thread virtuals
1821 
onFirstRef()1822 void AudioFlinger::PlaybackThread::onFirstRef()
1823 {
1824     run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
1825 }
1826 
1827 // ThreadBase virtuals
preExit()1828 void AudioFlinger::PlaybackThread::preExit()
1829 {
1830     ALOGV("  preExit()");
1831     // FIXME this is using hard-coded strings but in the future, this functionality will be
1832     //       converted to use audio HAL extensions required to support tunneling
1833     mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1834 }
1835 
1836 // PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
createTrack_l(const sp<AudioFlinger::Client> & client,audio_stream_type_t streamType,uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask,size_t * pFrameCount,const sp<IMemory> & sharedBuffer,audio_session_t sessionId,audio_output_flags_t * flags,pid_t tid,int uid,status_t * status)1837 sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1838         const sp<AudioFlinger::Client>& client,
1839         audio_stream_type_t streamType,
1840         uint32_t sampleRate,
1841         audio_format_t format,
1842         audio_channel_mask_t channelMask,
1843         size_t *pFrameCount,
1844         const sp<IMemory>& sharedBuffer,
1845         audio_session_t sessionId,
1846         audio_output_flags_t *flags,
1847         pid_t tid,
1848         int uid,
1849         status_t *status)
1850 {
1851     size_t frameCount = *pFrameCount;
1852     sp<Track> track;
1853     status_t lStatus;
1854     audio_output_flags_t outputFlags = mOutput->flags;
1855 
1856     // special case for FAST flag considered OK if fast mixer is present
1857     if (hasFastMixer()) {
1858         outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1859     }
1860 
1861     // Check if requested flags are compatible with output stream flags
1862     if ((*flags & outputFlags) != *flags) {
1863         ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1864               *flags, outputFlags);
1865         *flags = (audio_output_flags_t)(*flags & outputFlags);
1866     }
1867 
1868     // client expresses a preference for FAST, but we get the final say
1869     if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
1870       if (
1871             // PCM data
1872             audio_is_linear_pcm(format) &&
1873             // TODO: extract as a data library function that checks that a computationally
1874             // expensive downmixer is not required: isFastOutputChannelConversion()
1875             (channelMask == mChannelMask ||
1876                     mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1877                     (channelMask == AUDIO_CHANNEL_OUT_MONO
1878                             /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
1879             // hardware sample rate
1880             (sampleRate == mSampleRate) &&
1881             // normal mixer has an associated fast mixer
1882             hasFastMixer() &&
1883             // there are sufficient fast track slots available
1884             (mFastTrackAvailMask != 0)
1885             // FIXME test that MixerThread for this fast track has a capable output HAL
1886             // FIXME add a permission test also?
1887         ) {
1888         // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1889         if (sharedBuffer == 0) {
1890             // read the fast track multiplier property the first time it is needed
1891             int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1892             if (ok != 0) {
1893                 ALOGE("%s pthread_once failed: %d", __func__, ok);
1894             }
1895             frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
1896         }
1897 
1898         // check compatibility with audio effects.
1899         { // scope for mLock
1900             Mutex::Autolock _l(mLock);
1901             // do not accept RAW flag if post processing are present. Note that post processing on
1902             // a fast mixer are necessarily hardware
1903             sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
1904             if (chain != 0) {
1905                 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
1906                         "AUDIO_OUTPUT_FLAG_RAW denied: post processing effect present");
1907                 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1908             }
1909             // Do not accept FAST flag if software global effects are present
1910             chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
1911             if (chain != 0) {
1912                 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
1913                         "AUDIO_OUTPUT_FLAG_RAW denied: global effect present");
1914                 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1915                 if (chain->hasSoftwareEffect()) {
1916                     ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software global effect present");
1917                     *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1918                 }
1919             }
1920             // Do not accept FAST flag if the session has software effects
1921             chain = getEffectChain_l(sessionId);
1922             if (chain != 0) {
1923                 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0,
1924                         "AUDIO_OUTPUT_FLAG_RAW denied: effect present on session");
1925                 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
1926                 if (chain->hasSoftwareEffect()) {
1927                     ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: software effect present on session");
1928                     *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1929                 }
1930             }
1931         }
1932         ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
1933                  "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1934                  frameCount, mFrameCount);
1935       } else {
1936         ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1937                 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1938                 "sampleRate=%u mSampleRate=%u "
1939                 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1940                 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
1941                 audio_is_linear_pcm(format),
1942                 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1943         *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
1944       }
1945     }
1946     // For normal PCM streaming tracks, update minimum frame count.
1947     // For compatibility with AudioTrack calculation, buffer depth is forced
1948     // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1949     // This is probably too conservative, but legacy application code may depend on it.
1950     // If you change this calculation, also review the start threshold which is related.
1951     if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
1952             && audio_has_proportional_frames(format) && sharedBuffer == 0) {
1953         // this must match AudioTrack.cpp calculateMinFrameCount().
1954         // TODO: Move to a common library
1955         uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1956         uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1957         if (minBufCount < 2) {
1958             minBufCount = 2;
1959         }
1960         // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1961         // or the client should compute and pass in a larger buffer request.
1962         size_t minFrameCount =
1963                 minBufCount * sourceFramesNeededWithTimestretch(
1964                         sampleRate, mNormalFrameCount,
1965                         mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
1966         if (frameCount < minFrameCount) { // including frameCount == 0
1967             frameCount = minFrameCount;
1968         }
1969     }
1970     *pFrameCount = frameCount;
1971 
1972     switch (mType) {
1973 
1974     case DIRECT:
1975         if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
1976             if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1977                 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1978                         "for output %p with format %#x",
1979                         sampleRate, format, channelMask, mOutput, mFormat);
1980                 lStatus = BAD_VALUE;
1981                 goto Exit;
1982             }
1983         }
1984         break;
1985 
1986     case OFFLOAD:
1987         if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1988             ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1989                     "for output %p with format %#x",
1990                     sampleRate, format, channelMask, mOutput, mFormat);
1991             lStatus = BAD_VALUE;
1992             goto Exit;
1993         }
1994         break;
1995 
1996     default:
1997         if (!audio_is_linear_pcm(format)) {
1998                 ALOGE("createTrack_l() Bad parameter: format %#x \""
1999                         "for output %p with format %#x",
2000                         format, mOutput, mFormat);
2001                 lStatus = BAD_VALUE;
2002                 goto Exit;
2003         }
2004         if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
2005             ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2006             lStatus = BAD_VALUE;
2007             goto Exit;
2008         }
2009         break;
2010 
2011     }
2012 
2013     lStatus = initCheck();
2014     if (lStatus != NO_ERROR) {
2015         ALOGE("createTrack_l() audio driver not initialized");
2016         goto Exit;
2017     }
2018 
2019     { // scope for mLock
2020         Mutex::Autolock _l(mLock);
2021 
2022         // all tracks in same audio session must share the same routing strategy otherwise
2023         // conflicts will happen when tracks are moved from one output to another by audio policy
2024         // manager
2025         uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2026         for (size_t i = 0; i < mTracks.size(); ++i) {
2027             sp<Track> t = mTracks[i];
2028             if (t != 0 && t->isExternalTrack()) {
2029                 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2030                 if (sessionId == t->sessionId() && strategy != actual) {
2031                     ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2032                             strategy, actual);
2033                     lStatus = BAD_VALUE;
2034                     goto Exit;
2035                 }
2036             }
2037         }
2038 
2039         track = new Track(this, client, streamType, sampleRate, format,
2040                           channelMask, frameCount, NULL, sharedBuffer,
2041                           sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
2042 
2043         lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2044         if (lStatus != NO_ERROR) {
2045             ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
2046             // track must be cleared from the caller as the caller has the AF lock
2047             goto Exit;
2048         }
2049         mTracks.add(track);
2050 
2051         sp<EffectChain> chain = getEffectChain_l(sessionId);
2052         if (chain != 0) {
2053             ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2054             track->setMainBuffer(chain->inBuffer());
2055             chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2056             chain->incTrackCnt();
2057         }
2058 
2059         if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
2060             pid_t callingPid = IPCThreadState::self()->getCallingPid();
2061             // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2062             // so ask activity manager to do this on our behalf
2063             sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2064         }
2065     }
2066 
2067     lStatus = NO_ERROR;
2068 
2069 Exit:
2070     *status = lStatus;
2071     return track;
2072 }
2073 
correctLatency_l(uint32_t latency) const2074 uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2075 {
2076     return latency;
2077 }
2078 
latency() const2079 uint32_t AudioFlinger::PlaybackThread::latency() const
2080 {
2081     Mutex::Autolock _l(mLock);
2082     return latency_l();
2083 }
latency_l() const2084 uint32_t AudioFlinger::PlaybackThread::latency_l() const
2085 {
2086     if (initCheck() == NO_ERROR) {
2087         return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
2088     } else {
2089         return 0;
2090     }
2091 }
2092 
setMasterVolume(float value)2093 void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2094 {
2095     Mutex::Autolock _l(mLock);
2096     // Don't apply master volume in SW if our HAL can do it for us.
2097     if (mOutput && mOutput->audioHwDev &&
2098         mOutput->audioHwDev->canSetMasterVolume()) {
2099         mMasterVolume = 1.0;
2100     } else {
2101         mMasterVolume = value;
2102     }
2103 }
2104 
setMasterMute(bool muted)2105 void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2106 {
2107     Mutex::Autolock _l(mLock);
2108     // Don't apply master mute in SW if our HAL can do it for us.
2109     if (mOutput && mOutput->audioHwDev &&
2110         mOutput->audioHwDev->canSetMasterMute()) {
2111         mMasterMute = false;
2112     } else {
2113         mMasterMute = muted;
2114     }
2115 }
2116 
setStreamVolume(audio_stream_type_t stream,float value)2117 void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2118 {
2119     Mutex::Autolock _l(mLock);
2120     mStreamTypes[stream].volume = value;
2121     broadcast_l();
2122 }
2123 
setStreamMute(audio_stream_type_t stream,bool muted)2124 void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2125 {
2126     Mutex::Autolock _l(mLock);
2127     mStreamTypes[stream].mute = muted;
2128     broadcast_l();
2129 }
2130 
streamVolume(audio_stream_type_t stream) const2131 float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2132 {
2133     Mutex::Autolock _l(mLock);
2134     return mStreamTypes[stream].volume;
2135 }
2136 
2137 // addTrack_l() must be called with ThreadBase::mLock held
addTrack_l(const sp<Track> & track)2138 status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2139 {
2140     status_t status = ALREADY_EXISTS;
2141 
2142     if (mActiveTracks.indexOf(track) < 0) {
2143         // the track is newly added, make sure it fills up all its
2144         // buffers before playing. This is to ensure the client will
2145         // effectively get the latency it requested.
2146         if (track->isExternalTrack()) {
2147             TrackBase::track_state state = track->mState;
2148             mLock.unlock();
2149             status = AudioSystem::startOutput(mId, track->streamType(),
2150                                               track->sessionId());
2151             mLock.lock();
2152             // abort track was stopped/paused while we released the lock
2153             if (state != track->mState) {
2154                 if (status == NO_ERROR) {
2155                     mLock.unlock();
2156                     AudioSystem::stopOutput(mId, track->streamType(),
2157                                             track->sessionId());
2158                     mLock.lock();
2159                 }
2160                 return INVALID_OPERATION;
2161             }
2162             // abort if start is rejected by audio policy manager
2163             if (status != NO_ERROR) {
2164                 return PERMISSION_DENIED;
2165             }
2166 #ifdef ADD_BATTERY_DATA
2167             // to track the speaker usage
2168             addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2169 #endif
2170         }
2171 
2172         // set retry count for buffer fill
2173         if (track->isOffloaded()) {
2174             if (track->isStopping_1()) {
2175                 track->mRetryCount = kMaxTrackStopRetriesOffload;
2176             } else {
2177                 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2178             }
2179             track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
2180         } else {
2181             track->mRetryCount = kMaxTrackStartupRetries;
2182             track->mFillingUpStatus =
2183                     track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
2184         }
2185 
2186         track->mResetDone = false;
2187         track->mPresentationCompleteFrames = 0;
2188         mActiveTracks.add(track);
2189         mWakeLockUids.add(track->uid());
2190         mActiveTracksGeneration++;
2191         mLatestActiveTrack = track;
2192         sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2193         if (chain != 0) {
2194             ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2195                     track->sessionId());
2196             chain->incActiveTrackCnt();
2197         }
2198 
2199         status = NO_ERROR;
2200     }
2201 
2202     onAddNewTrack_l();
2203     return status;
2204 }
2205 
destroyTrack_l(const sp<Track> & track)2206 bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
2207 {
2208     track->terminate();
2209     // active tracks are removed by threadLoop()
2210     bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2211     track->mState = TrackBase::STOPPED;
2212     if (!trackActive) {
2213         removeTrack_l(track);
2214     } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
2215         track->mState = TrackBase::STOPPING_1;
2216     }
2217 
2218     return trackActive;
2219 }
2220 
removeTrack_l(const sp<Track> & track)2221 void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2222 {
2223     track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2224     mTracks.remove(track);
2225     deleteTrackName_l(track->name());
2226     // redundant as track is about to be destroyed, for dumpsys only
2227     track->mName = -1;
2228     if (track->isFastTrack()) {
2229         int index = track->mFastIndex;
2230         ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
2231         ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2232         mFastTrackAvailMask |= 1 << index;
2233         // redundant as track is about to be destroyed, for dumpsys only
2234         track->mFastIndex = -1;
2235     }
2236     sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2237     if (chain != 0) {
2238         chain->decTrackCnt();
2239     }
2240 }
2241 
broadcast_l()2242 void AudioFlinger::PlaybackThread::broadcast_l()
2243 {
2244     // Thread could be blocked waiting for async
2245     // so signal it to handle state changes immediately
2246     // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2247     // be lost so we also flag to prevent it blocking on mWaitWorkCV
2248     mSignalPending = true;
2249     mWaitWorkCV.broadcast();
2250 }
2251 
getParameters(const String8 & keys)2252 String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2253 {
2254     Mutex::Autolock _l(mLock);
2255     if (initCheck() != NO_ERROR) {
2256         return String8();
2257     }
2258 
2259     char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2260     const String8 out_s8(s);
2261     free(s);
2262     return out_s8;
2263 }
2264 
ioConfigChanged(audio_io_config_event event,pid_t pid)2265 void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
2266     sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2267     ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
2268 
2269     desc->mIoHandle = mId;
2270 
2271     switch (event) {
2272     case AUDIO_OUTPUT_OPENED:
2273     case AUDIO_OUTPUT_CONFIG_CHANGED:
2274         desc->mPatch = mPatch;
2275         desc->mChannelMask = mChannelMask;
2276         desc->mSamplingRate = mSampleRate;
2277         desc->mFormat = mFormat;
2278         desc->mFrameCount = mNormalFrameCount; // FIXME see
2279                                              // AudioFlinger::frameCount(audio_io_handle_t)
2280         desc->mFrameCountHAL = mFrameCount;
2281         desc->mLatency = latency_l();
2282         break;
2283 
2284     case AUDIO_OUTPUT_CLOSED:
2285     default:
2286         break;
2287     }
2288     mAudioFlinger->ioConfigChanged(event, desc, pid);
2289 }
2290 
writeCallback()2291 void AudioFlinger::PlaybackThread::writeCallback()
2292 {
2293     ALOG_ASSERT(mCallbackThread != 0);
2294     mCallbackThread->resetWriteBlocked();
2295 }
2296 
drainCallback()2297 void AudioFlinger::PlaybackThread::drainCallback()
2298 {
2299     ALOG_ASSERT(mCallbackThread != 0);
2300     mCallbackThread->resetDraining();
2301 }
2302 
errorCallback()2303 void AudioFlinger::PlaybackThread::errorCallback()
2304 {
2305     ALOG_ASSERT(mCallbackThread != 0);
2306     mCallbackThread->setAsyncError();
2307 }
2308 
resetWriteBlocked(uint32_t sequence)2309 void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
2310 {
2311     Mutex::Autolock _l(mLock);
2312     // reject out of sequence requests
2313     if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2314         mWriteAckSequence &= ~1;
2315         mWaitWorkCV.signal();
2316     }
2317 }
2318 
resetDraining(uint32_t sequence)2319 void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
2320 {
2321     Mutex::Autolock _l(mLock);
2322     // reject out of sequence requests
2323     if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2324         mDrainSequence &= ~1;
2325         mWaitWorkCV.signal();
2326     }
2327 }
2328 
2329 // static
asyncCallback(stream_callback_event_t event,void * param __unused,void * cookie)2330 int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
2331                                                 void *param __unused,
2332                                                 void *cookie)
2333 {
2334     AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2335     ALOGV("asyncCallback() event %d", event);
2336     switch (event) {
2337     case STREAM_CBK_EVENT_WRITE_READY:
2338         me->writeCallback();
2339         break;
2340     case STREAM_CBK_EVENT_DRAIN_READY:
2341         me->drainCallback();
2342         break;
2343     case STREAM_CBK_EVENT_ERROR:
2344         me->errorCallback();
2345         break;
2346     default:
2347         ALOGW("asyncCallback() unknown event %d", event);
2348         break;
2349     }
2350     return 0;
2351 }
2352 
readOutputParameters_l()2353 void AudioFlinger::PlaybackThread::readOutputParameters_l()
2354 {
2355     // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
2356     mSampleRate = mOutput->getSampleRate();
2357     mChannelMask = mOutput->getChannelMask();
2358     if (!audio_is_output_channel(mChannelMask)) {
2359         LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
2360     }
2361     if ((mType == MIXER || mType == DUPLICATING)
2362             && !isValidPcmSinkChannelMask(mChannelMask)) {
2363         LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2364                 mChannelMask);
2365     }
2366     mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
2367 
2368     // Get actual HAL format.
2369     mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2370     // Get format from the shim, which will be different than the HAL format
2371     // if playing compressed audio over HDMI passthrough.
2372     mFormat = mOutput->getFormat();
2373     if (!audio_is_valid_format(mFormat)) {
2374         LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
2375     }
2376     if ((mType == MIXER || mType == DUPLICATING)
2377             && !isValidPcmSinkFormat(mFormat)) {
2378         LOG_FATAL("HAL format %#x not supported for mixed output",
2379                 mFormat);
2380     }
2381     mFrameSize = mOutput->getFrameSize();
2382     mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2383     mFrameCount = mBufferSize / mFrameSize;
2384     if (mFrameCount & 15) {
2385         ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
2386                 mFrameCount);
2387     }
2388 
2389     if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2390             (mOutput->stream->set_callback != NULL)) {
2391         if (mOutput->stream->set_callback(mOutput->stream,
2392                                       AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2393             mUseAsyncWrite = true;
2394             mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
2395         }
2396     }
2397 
2398     mHwSupportsPause = false;
2399     if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2400         if (mOutput->stream->pause != NULL) {
2401             if (mOutput->stream->resume != NULL) {
2402                 mHwSupportsPause = true;
2403             } else {
2404                 ALOGW("direct output implements pause but not resume");
2405             }
2406         } else if (mOutput->stream->resume != NULL) {
2407             ALOGW("direct output implements resume but not pause");
2408         }
2409     }
2410     if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2411         LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2412     }
2413 
2414     if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2415         // For best precision, we use float instead of the associated output
2416         // device format (typically PCM 16 bit).
2417 
2418         mFormat = AUDIO_FORMAT_PCM_FLOAT;
2419         mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2420         mBufferSize = mFrameSize * mFrameCount;
2421 
2422         // TODO: We currently use the associated output device channel mask and sample rate.
2423         // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2424         // (if a valid mask) to avoid premature downmix.
2425         // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2426         // instead of the output device sample rate to avoid loss of high frequency information.
2427         // This may need to be updated as MixerThread/OutputTracks are added and not here.
2428     }
2429 
2430     // Calculate size of normal sink buffer relative to the HAL output buffer size
2431     double multiplier = 1.0;
2432     if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2433             kUseFastMixer == FastMixer_Dynamic)) {
2434         size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2435         size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
2436 
2437         // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2438         minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2439         maxNormalFrameCount = maxNormalFrameCount & ~15;
2440         if (maxNormalFrameCount < minNormalFrameCount) {
2441             maxNormalFrameCount = minNormalFrameCount;
2442         }
2443         multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2444         if (multiplier <= 1.0) {
2445             multiplier = 1.0;
2446         } else if (multiplier <= 2.0) {
2447             if (2 * mFrameCount <= maxNormalFrameCount) {
2448                 multiplier = 2.0;
2449             } else {
2450                 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2451             }
2452         } else {
2453             multiplier = floor(multiplier);
2454         }
2455     }
2456     mNormalFrameCount = multiplier * mFrameCount;
2457     // round up to nearest 16 frames to satisfy AudioMixer
2458     if (mType == MIXER || mType == DUPLICATING) {
2459         mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2460     }
2461     ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
2462             mNormalFrameCount);
2463 
2464     // Check if we want to throttle the processing to no more than 2x normal rate
2465     mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
2466     mThreadThrottleTimeMs = 0;
2467     mThreadThrottleEndMs = 0;
2468     mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2469 
2470     // mSinkBuffer is the sink buffer.  Size is always multiple-of-16 frames.
2471     // Originally this was int16_t[] array, need to remove legacy implications.
2472     free(mSinkBuffer);
2473     mSinkBuffer = NULL;
2474     // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2475     // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2476     const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2477     (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2478 
2479     // We resize the mMixerBuffer according to the requirements of the sink buffer which
2480     // drives the output.
2481     free(mMixerBuffer);
2482     mMixerBuffer = NULL;
2483     if (mMixerBufferEnabled) {
2484         mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2485         mMixerBufferSize = mNormalFrameCount * mChannelCount
2486                 * audio_bytes_per_sample(mMixerBufferFormat);
2487         (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2488     }
2489     free(mEffectBuffer);
2490     mEffectBuffer = NULL;
2491     if (mEffectBufferEnabled) {
2492         mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2493         mEffectBufferSize = mNormalFrameCount * mChannelCount
2494                 * audio_bytes_per_sample(mEffectBufferFormat);
2495         (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2496     }
2497 
2498     // force reconfiguration of effect chains and engines to take new buffer size and audio
2499     // parameters into account
2500     // Note that mLock is not held when readOutputParameters_l() is called from the constructor
2501     // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2502     // matter.
2503     // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2504     Vector< sp<EffectChain> > effectChains = mEffectChains;
2505     for (size_t i = 0; i < effectChains.size(); i ++) {
2506         mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2507     }
2508 }
2509 
2510 
getRenderPosition(uint32_t * halFrames,uint32_t * dspFrames)2511 status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2512 {
2513     if (halFrames == NULL || dspFrames == NULL) {
2514         return BAD_VALUE;
2515     }
2516     Mutex::Autolock _l(mLock);
2517     if (initCheck() != NO_ERROR) {
2518         return INVALID_OPERATION;
2519     }
2520     int64_t framesWritten = mBytesWritten / mFrameSize;
2521     *halFrames = framesWritten;
2522 
2523     if (isSuspended()) {
2524         // return an estimation of rendered frames when the output is suspended
2525         size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2526         *dspFrames = (uint32_t)
2527                 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
2528         return NO_ERROR;
2529     } else {
2530         status_t status;
2531         uint32_t frames;
2532         status = mOutput->getRenderPosition(&frames);
2533         *dspFrames = (size_t)frames;
2534         return status;
2535     }
2536 }
2537 
2538 // hasAudioSession_l() must be called with ThreadBase::mLock held
hasAudioSession_l(audio_session_t sessionId) const2539 uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
2540 {
2541     uint32_t result = 0;
2542     if (getEffectChain_l(sessionId) != 0) {
2543         result = EFFECT_SESSION;
2544     }
2545 
2546     for (size_t i = 0; i < mTracks.size(); ++i) {
2547         sp<Track> track = mTracks[i];
2548         if (sessionId == track->sessionId() && !track->isInvalid()) {
2549             result |= TRACK_SESSION;
2550             if (track->isFastTrack()) {
2551                 result |= FAST_SESSION;
2552             }
2553             break;
2554         }
2555     }
2556 
2557     return result;
2558 }
2559 
getStrategyForSession_l(audio_session_t sessionId)2560 uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
2561 {
2562     // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2563     // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2564     if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2565         return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2566     }
2567     for (size_t i = 0; i < mTracks.size(); i++) {
2568         sp<Track> track = mTracks[i];
2569         if (sessionId == track->sessionId() && !track->isInvalid()) {
2570             return AudioSystem::getStrategyForStream(track->streamType());
2571         }
2572     }
2573     return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2574 }
2575 
2576 
getOutput() const2577 AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2578 {
2579     Mutex::Autolock _l(mLock);
2580     return mOutput;
2581 }
2582 
clearOutput()2583 AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2584 {
2585     Mutex::Autolock _l(mLock);
2586     AudioStreamOut *output = mOutput;
2587     mOutput = NULL;
2588     // FIXME FastMixer might also have a raw ptr to mOutputSink;
2589     //       must push a NULL and wait for ack
2590     mOutputSink.clear();
2591     mPipeSink.clear();
2592     mNormalSink.clear();
2593     return output;
2594 }
2595 
2596 // this method must always be called either with ThreadBase mLock held or inside the thread loop
stream() const2597 audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2598 {
2599     if (mOutput == NULL) {
2600         return NULL;
2601     }
2602     return &mOutput->stream->common;
2603 }
2604 
activeSleepTimeUs() const2605 uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2606 {
2607     return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2608 }
2609 
setSyncEvent(const sp<SyncEvent> & event)2610 status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2611 {
2612     if (!isValidSyncEvent(event)) {
2613         return BAD_VALUE;
2614     }
2615 
2616     Mutex::Autolock _l(mLock);
2617 
2618     for (size_t i = 0; i < mTracks.size(); ++i) {
2619         sp<Track> track = mTracks[i];
2620         if (event->triggerSession() == track->sessionId()) {
2621             (void) track->setSyncEvent(event);
2622             return NO_ERROR;
2623         }
2624     }
2625 
2626     return NAME_NOT_FOUND;
2627 }
2628 
isValidSyncEvent(const sp<SyncEvent> & event) const2629 bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2630 {
2631     return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2632 }
2633 
threadLoop_removeTracks(const Vector<sp<Track>> & tracksToRemove)2634 void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2635         const Vector< sp<Track> >& tracksToRemove)
2636 {
2637     size_t count = tracksToRemove.size();
2638     if (count > 0) {
2639         for (size_t i = 0 ; i < count ; i++) {
2640             const sp<Track>& track = tracksToRemove.itemAt(i);
2641             if (track->isExternalTrack()) {
2642                 AudioSystem::stopOutput(mId, track->streamType(),
2643                                         track->sessionId());
2644 #ifdef ADD_BATTERY_DATA
2645                 // to track the speaker usage
2646                 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2647 #endif
2648                 if (track->isTerminated()) {
2649                     AudioSystem::releaseOutput(mId, track->streamType(),
2650                                                track->sessionId());
2651                 }
2652             }
2653         }
2654     }
2655 }
2656 
checkSilentMode_l()2657 void AudioFlinger::PlaybackThread::checkSilentMode_l()
2658 {
2659     if (!mMasterMute) {
2660         char value[PROPERTY_VALUE_MAX];
2661         if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2662             ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2663             return;
2664         }
2665         if (property_get("ro.audio.silent", value, "0") > 0) {
2666             char *endptr;
2667             unsigned long ul = strtoul(value, &endptr, 0);
2668             if (*endptr == '\0' && ul != 0) {
2669                 ALOGD("Silence is golden");
2670                 // The setprop command will not allow a property to be changed after
2671                 // the first time it is set, so we don't have to worry about un-muting.
2672                 setMasterMute_l(true);
2673             }
2674         }
2675     }
2676 }
2677 
2678 // shared by MIXER and DIRECT, overridden by DUPLICATING
threadLoop_write()2679 ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
2680 {
2681     mInWrite = true;
2682     ssize_t bytesWritten;
2683     const size_t offset = mCurrentWriteLength - mBytesRemaining;
2684 
2685     // If an NBAIO sink is present, use it to write the normal mixer's submix
2686     if (mNormalSink != 0) {
2687 
2688         const size_t count = mBytesRemaining / mFrameSize;
2689 
2690         ATRACE_BEGIN("write");
2691         // update the setpoint when AudioFlinger::mScreenState changes
2692         uint32_t screenState = AudioFlinger::mScreenState;
2693         if (screenState != mScreenState) {
2694             mScreenState = screenState;
2695             MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2696             if (pipe != NULL) {
2697                 pipe->setAvgFrames((mScreenState & 1) ?
2698                         (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2699             }
2700         }
2701         ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
2702         ATRACE_END();
2703         if (framesWritten > 0) {
2704             bytesWritten = framesWritten * mFrameSize;
2705         } else {
2706             bytesWritten = framesWritten;
2707         }
2708     // otherwise use the HAL / AudioStreamOut directly
2709     } else {
2710         // Direct output and offload threads
2711 
2712         if (mUseAsyncWrite) {
2713             ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2714             mWriteAckSequence += 2;
2715             mWriteAckSequence |= 1;
2716             ALOG_ASSERT(mCallbackThread != 0);
2717             mCallbackThread->setWriteBlocked(mWriteAckSequence);
2718         }
2719         // FIXME We should have an implementation of timestamps for direct output threads.
2720         // They are used e.g for multichannel PCM playback over HDMI.
2721         bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
2722 
2723         if (mUseAsyncWrite &&
2724                 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2725             // do not wait for async callback in case of error of full write
2726             mWriteAckSequence &= ~1;
2727             ALOG_ASSERT(mCallbackThread != 0);
2728             mCallbackThread->setWriteBlocked(mWriteAckSequence);
2729         }
2730     }
2731 
2732     mNumWrites++;
2733     mInWrite = false;
2734     mStandby = false;
2735     return bytesWritten;
2736 }
2737 
threadLoop_drain()2738 void AudioFlinger::PlaybackThread::threadLoop_drain()
2739 {
2740     if (mOutput->stream->drain) {
2741         ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2742         if (mUseAsyncWrite) {
2743             ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2744             mDrainSequence |= 1;
2745             ALOG_ASSERT(mCallbackThread != 0);
2746             mCallbackThread->setDraining(mDrainSequence);
2747         }
2748         mOutput->stream->drain(mOutput->stream,
2749             (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2750                                                 : AUDIO_DRAIN_ALL);
2751     }
2752 }
2753 
threadLoop_exit()2754 void AudioFlinger::PlaybackThread::threadLoop_exit()
2755 {
2756     {
2757         Mutex::Autolock _l(mLock);
2758         for (size_t i = 0; i < mTracks.size(); i++) {
2759             sp<Track> track = mTracks[i];
2760             track->invalidate();
2761         }
2762     }
2763 }
2764 
2765 /*
2766 The derived values that are cached:
2767  - mSinkBufferSize from frame count * frame size
2768  - mActiveSleepTimeUs from activeSleepTimeUs()
2769  - mIdleSleepTimeUs from idleSleepTimeUs()
2770  - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2771    kDefaultStandbyTimeInNsecs when connected to an A2DP device.
2772  - maxPeriod from frame count and sample rate (MIXER only)
2773 
2774 The parameters that affect these derived values are:
2775  - frame count
2776  - frame size
2777  - sample rate
2778  - device type: A2DP or not
2779  - device latency
2780  - format: PCM or not
2781  - active sleep time
2782  - idle sleep time
2783 */
2784 
cacheParameters_l()2785 void AudioFlinger::PlaybackThread::cacheParameters_l()
2786 {
2787     mSinkBufferSize = mNormalFrameCount * mFrameSize;
2788     mActiveSleepTimeUs = activeSleepTimeUs();
2789     mIdleSleepTimeUs = idleSleepTimeUs();
2790 
2791     // make sure standby delay is not too short when connected to an A2DP sink to avoid
2792     // truncating audio when going to standby.
2793     mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2794     if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2795         if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2796             mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2797         }
2798     }
2799 }
2800 
invalidateTracks_l(audio_stream_type_t streamType)2801 bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
2802 {
2803     ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
2804             this,  streamType, mTracks.size());
2805     bool trackMatch = false;
2806     size_t size = mTracks.size();
2807     for (size_t i = 0; i < size; i++) {
2808         sp<Track> t = mTracks[i];
2809         if (t->streamType() == streamType && t->isExternalTrack()) {
2810             t->invalidate();
2811             trackMatch = true;
2812         }
2813     }
2814     return trackMatch;
2815 }
2816 
invalidateTracks(audio_stream_type_t streamType)2817 void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2818 {
2819     Mutex::Autolock _l(mLock);
2820     invalidateTracks_l(streamType);
2821 }
2822 
addEffectChain_l(const sp<EffectChain> & chain)2823 status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2824 {
2825     audio_session_t session = chain->sessionId();
2826     int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2827             ? mEffectBuffer : mSinkBuffer);
2828     bool ownsBuffer = false;
2829 
2830     ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2831     if (session > AUDIO_SESSION_OUTPUT_MIX) {
2832         // Only one effect chain can be present in direct output thread and it uses
2833         // the sink buffer as input
2834         if (mType != DIRECT) {
2835             size_t numSamples = mNormalFrameCount * mChannelCount;
2836             buffer = new int16_t[numSamples];
2837             memset(buffer, 0, numSamples * sizeof(int16_t));
2838             ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2839             ownsBuffer = true;
2840         }
2841 
2842         // Attach all tracks with same session ID to this chain.
2843         for (size_t i = 0; i < mTracks.size(); ++i) {
2844             sp<Track> track = mTracks[i];
2845             if (session == track->sessionId()) {
2846                 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2847                         buffer);
2848                 track->setMainBuffer(buffer);
2849                 chain->incTrackCnt();
2850             }
2851         }
2852 
2853         // indicate all active tracks in the chain
2854         for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2855             sp<Track> track = mActiveTracks[i].promote();
2856             if (track == 0) {
2857                 continue;
2858             }
2859             if (session == track->sessionId()) {
2860                 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2861                 chain->incActiveTrackCnt();
2862             }
2863         }
2864     }
2865     chain->setThread(this);
2866     chain->setInBuffer(buffer, ownsBuffer);
2867     chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2868             ? mEffectBuffer : mSinkBuffer));
2869     // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2870     // chains list in order to be processed last as it contains output stage effects.
2871     // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2872     // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2873     // after track specific effects and before output stage.
2874     // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2875     // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
2876     // Effect chain for other sessions are inserted at beginning of effect
2877     // chains list to be processed before output mix effects. Relative order between other
2878     // sessions is not important.
2879     static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2880             AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2881             "audio_session_t constants misdefined");
2882     size_t size = mEffectChains.size();
2883     size_t i = 0;
2884     for (i = 0; i < size; i++) {
2885         if (mEffectChains[i]->sessionId() < session) {
2886             break;
2887         }
2888     }
2889     mEffectChains.insertAt(chain, i);
2890     checkSuspendOnAddEffectChain_l(chain);
2891 
2892     return NO_ERROR;
2893 }
2894 
removeEffectChain_l(const sp<EffectChain> & chain)2895 size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2896 {
2897     audio_session_t session = chain->sessionId();
2898 
2899     ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2900 
2901     for (size_t i = 0; i < mEffectChains.size(); i++) {
2902         if (chain == mEffectChains[i]) {
2903             mEffectChains.removeAt(i);
2904             // detach all active tracks from the chain
2905             for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2906                 sp<Track> track = mActiveTracks[i].promote();
2907                 if (track == 0) {
2908                     continue;
2909                 }
2910                 if (session == track->sessionId()) {
2911                     ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2912                             chain.get(), session);
2913                     chain->decActiveTrackCnt();
2914                 }
2915             }
2916 
2917             // detach all tracks with same session ID from this chain
2918             for (size_t i = 0; i < mTracks.size(); ++i) {
2919                 sp<Track> track = mTracks[i];
2920                 if (session == track->sessionId()) {
2921                     track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
2922                     chain->decTrackCnt();
2923                 }
2924             }
2925             break;
2926         }
2927     }
2928     return mEffectChains.size();
2929 }
2930 
attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,int EffectId)2931 status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2932         const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2933 {
2934     Mutex::Autolock _l(mLock);
2935     return attachAuxEffect_l(track, EffectId);
2936 }
2937 
attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,int EffectId)2938 status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2939         const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2940 {
2941     status_t status = NO_ERROR;
2942 
2943     if (EffectId == 0) {
2944         track->setAuxBuffer(0, NULL);
2945     } else {
2946         // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2947         sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2948         if (effect != 0) {
2949             if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2950                 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2951             } else {
2952                 status = INVALID_OPERATION;
2953             }
2954         } else {
2955             status = BAD_VALUE;
2956         }
2957     }
2958     return status;
2959 }
2960 
detachAuxEffect_l(int effectId)2961 void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2962 {
2963     for (size_t i = 0; i < mTracks.size(); ++i) {
2964         sp<Track> track = mTracks[i];
2965         if (track->auxEffectId() == effectId) {
2966             attachAuxEffect_l(track, 0);
2967         }
2968     }
2969 }
2970 
threadLoop()2971 bool AudioFlinger::PlaybackThread::threadLoop()
2972 {
2973     Vector< sp<Track> > tracksToRemove;
2974 
2975     mStandbyTimeNs = systemTime();
2976     nsecs_t lastWriteFinished = -1; // time last server write completed
2977     int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
2978 
2979     // MIXER
2980     nsecs_t lastWarning = 0;
2981 
2982     // DUPLICATING
2983     // FIXME could this be made local to while loop?
2984     writeFrames = 0;
2985 
2986     int lastGeneration = 0;
2987 
2988     cacheParameters_l();
2989     mSleepTimeUs = mIdleSleepTimeUs;
2990 
2991     if (mType == MIXER) {
2992         sleepTimeShift = 0;
2993     }
2994 
2995     CpuStats cpuStats;
2996     const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2997 
2998     acquireWakeLock();
2999 
3000     // mNBLogWriter->log can only be called while thread mutex mLock is held.
3001     // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3002     // and then that string will be logged at the next convenient opportunity.
3003     const char *logString = NULL;
3004 
3005     checkSilentMode_l();
3006 
3007     while (!exitPending())
3008     {
3009         cpuStats.sample(myName);
3010 
3011         Vector< sp<EffectChain> > effectChains;
3012 
3013         { // scope for mLock
3014 
3015             Mutex::Autolock _l(mLock);
3016 
3017             processConfigEvents_l();
3018 
3019             if (logString != NULL) {
3020                 mNBLogWriter->logTimestamp();
3021                 mNBLogWriter->log(logString);
3022                 logString = NULL;
3023             }
3024 
3025             // Gather the framesReleased counters for all active tracks,
3026             // and associate with the sink frames written out.  We need
3027             // this to convert the sink timestamp to the track timestamp.
3028             bool kernelLocationUpdate = false;
3029             if (mNormalSink != 0) {
3030                 // Note: The DuplicatingThread may not have a mNormalSink.
3031                 // We always fetch the timestamp here because often the downstream
3032                 // sink will block while writing.
3033                 ExtendedTimestamp timestamp; // use private copy to fetch
3034                 (void) mNormalSink->getTimestamp(timestamp);
3035 
3036                 // We keep track of the last valid kernel position in case we are in underrun
3037                 // and the normal mixer period is the same as the fast mixer period, or there
3038                 // is some error from the HAL.
3039                 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3040                     mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3041                             mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3042                     mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3043                             mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3044 
3045                     mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3046                             mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3047                     mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3048                             mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
3049                 }
3050 
3051                 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3052                     kernelLocationUpdate = true;
3053                 } else {
3054                     ALOGVV("getTimestamp error - no valid kernel position");
3055                 }
3056 
3057                 // copy over kernel info
3058                 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
3059                         timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3060                         + mSuspendedFrames; // add frames discarded when suspended
3061                 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3062                         timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3063             }
3064             // mFramesWritten for non-offloaded tracks are contiguous
3065             // even after standby() is called. This is useful for the track frame
3066             // to sink frame mapping.
3067             bool serverLocationUpdate = false;
3068             if (mFramesWritten != lastFramesWritten) {
3069                 serverLocationUpdate = true;
3070                 lastFramesWritten = mFramesWritten;
3071             }
3072             // Only update timestamps if there is a meaningful change.
3073             // Either the kernel timestamp must be valid or we have written something.
3074             if (kernelLocationUpdate || serverLocationUpdate) {
3075                 if (serverLocationUpdate) {
3076                     // use the time before we called the HAL write - it is a bit more accurate
3077                     // to when the server last read data than the current time here.
3078                     //
3079                     // If we haven't written anything, mLastWriteTime will be -1
3080                     // and we use systemTime().
3081                     mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3082                     mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3083                             ? systemTime() : mLastWriteTime;
3084                 }
3085                 const size_t size = mActiveTracks.size();
3086                 for (size_t i = 0; i < size; ++i) {
3087                     sp<Track> t = mActiveTracks[i].promote();
3088                     if (t != 0 && !t->isFastTrack()) {
3089                         t->updateTrackFrameInfo(
3090                                 t->mAudioTrackServerProxy->framesReleased(),
3091                                 mFramesWritten,
3092                                 mTimestamp);
3093                     }
3094                 }
3095             }
3096 
3097             saveOutputTracks();
3098             if (mSignalPending) {
3099                 // A signal was raised while we were unlocked
3100                 mSignalPending = false;
3101             } else if (waitingAsyncCallback_l()) {
3102                 if (exitPending()) {
3103                     break;
3104                 }
3105                 bool released = false;
3106                 if (!keepWakeLock()) {
3107                     releaseWakeLock_l();
3108                     released = true;
3109                 }
3110                 mWakeLockUids.clear();
3111                 mActiveTracksGeneration++;
3112                 ALOGV("wait async completion");
3113                 mWaitWorkCV.wait(mLock);
3114                 ALOGV("async completion/wake");
3115                 if (released) {
3116                     acquireWakeLock_l();
3117                 }
3118                 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3119                 mSleepTimeUs = 0;
3120 
3121                 continue;
3122             }
3123             if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
3124                                    isSuspended()) {
3125                 // put audio hardware into standby after short delay
3126                 if (shouldStandby_l()) {
3127 
3128                     threadLoop_standby();
3129 
3130                     mStandby = true;
3131                 }
3132 
3133                 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3134                     // we're about to wait, flush the binder command buffer
3135                     IPCThreadState::self()->flushCommands();
3136 
3137                     clearOutputTracks();
3138 
3139                     if (exitPending()) {
3140                         break;
3141                     }
3142 
3143                     releaseWakeLock_l();
3144                     mWakeLockUids.clear();
3145                     mActiveTracksGeneration++;
3146                     // wait until we have something to do...
3147                     ALOGV("%s going to sleep", myName.string());
3148                     mWaitWorkCV.wait(mLock);
3149                     ALOGV("%s waking up", myName.string());
3150                     acquireWakeLock_l();
3151 
3152                     mMixerStatus = MIXER_IDLE;
3153                     mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3154                     mBytesWritten = 0;
3155                     mBytesRemaining = 0;
3156                     checkSilentMode_l();
3157 
3158                     mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3159                     mSleepTimeUs = mIdleSleepTimeUs;
3160                     if (mType == MIXER) {
3161                         sleepTimeShift = 0;
3162                     }
3163 
3164                     continue;
3165                 }
3166             }
3167             // mMixerStatusIgnoringFastTracks is also updated internally
3168             mMixerStatus = prepareTracks_l(&tracksToRemove);
3169 
3170             // compare with previously applied list
3171             if (lastGeneration != mActiveTracksGeneration) {
3172                 // update wakelock
3173                 updateWakeLockUids_l(mWakeLockUids);
3174                 lastGeneration = mActiveTracksGeneration;
3175             }
3176 
3177             // prevent any changes in effect chain list and in each effect chain
3178             // during mixing and effect process as the audio buffers could be deleted
3179             // or modified if an effect is created or deleted
3180             lockEffectChains_l(effectChains);
3181         } // mLock scope ends
3182 
3183         if (mBytesRemaining == 0) {
3184             mCurrentWriteLength = 0;
3185             if (mMixerStatus == MIXER_TRACKS_READY) {
3186                 // threadLoop_mix() sets mCurrentWriteLength
3187                 threadLoop_mix();
3188             } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3189                         && (mMixerStatus != MIXER_DRAIN_ALL)) {
3190                 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
3191                 // must be written to HAL
3192                 threadLoop_sleepTime();
3193                 if (mSleepTimeUs == 0) {
3194                     mCurrentWriteLength = mSinkBufferSize;
3195                 }
3196             }
3197             // Either threadLoop_mix() or threadLoop_sleepTime() should have set
3198             // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
3199             // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3200             // or mSinkBuffer (if there are no effects).
3201             //
3202             // This is done pre-effects computation; if effects change to
3203             // support higher precision, this needs to move.
3204             //
3205             // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
3206             // TODO use mSleepTimeUs == 0 as an additional condition.
3207             if (mMixerBufferValid) {
3208                 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3209                 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3210 
3211                 // mono blend occurs for mixer threads only (not direct or offloaded)
3212                 // and is handled here if we're going directly to the sink.
3213                 if (requireMonoBlend() && !mEffectBufferValid) {
3214                     mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3215                                true /*limit*/);
3216                 }
3217 
3218                 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3219                         mNormalFrameCount * mChannelCount);
3220             }
3221 
3222             mBytesRemaining = mCurrentWriteLength;
3223             if (isSuspended()) {
3224                 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3225                 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3226                 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3227                 mBytesWritten += mBytesRemaining;
3228                 mFramesWritten += framesRemaining;
3229                 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
3230                 mBytesRemaining = 0;
3231             }
3232 
3233             // only process effects if we're going to write
3234             if (mSleepTimeUs == 0 && mType != OFFLOAD) {
3235                 for (size_t i = 0; i < effectChains.size(); i ++) {
3236                     effectChains[i]->process_l();
3237                 }
3238             }
3239         }
3240         // Process effect chains for offloaded thread even if no audio
3241         // was read from audio track: process only updates effect state
3242         // and thus does have to be synchronized with audio writes but may have
3243         // to be called while waiting for async write callback
3244         if (mType == OFFLOAD) {
3245             for (size_t i = 0; i < effectChains.size(); i ++) {
3246                 effectChains[i]->process_l();
3247             }
3248         }
3249 
3250         // Only if the Effects buffer is enabled and there is data in the
3251         // Effects buffer (buffer valid), we need to
3252         // copy into the sink buffer.
3253         // TODO use mSleepTimeUs == 0 as an additional condition.
3254         if (mEffectBufferValid) {
3255             //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
3256 
3257             if (requireMonoBlend()) {
3258                 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3259                            true /*limit*/);
3260             }
3261 
3262             memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3263                     mNormalFrameCount * mChannelCount);
3264         }
3265 
3266         // enable changes in effect chain
3267         unlockEffectChains(effectChains);
3268 
3269         if (!waitingAsyncCallback()) {
3270             // mSleepTimeUs == 0 means we must write to audio hardware
3271             if (mSleepTimeUs == 0) {
3272                 ssize_t ret = 0;
3273                 // We save lastWriteFinished here, as previousLastWriteFinished,
3274                 // for throttling. On thread start, previousLastWriteFinished will be
3275                 // set to -1, which properly results in no throttling after the first write.
3276                 nsecs_t previousLastWriteFinished = lastWriteFinished;
3277                 nsecs_t delta = 0;
3278                 if (mBytesRemaining) {
3279                     // FIXME rewrite to reduce number of system calls
3280                     mLastWriteTime = systemTime();  // also used for dumpsys
3281                     ret = threadLoop_write();
3282                     lastWriteFinished = systemTime();
3283                     delta = lastWriteFinished - mLastWriteTime;
3284                     if (ret < 0) {
3285                         mBytesRemaining = 0;
3286                     } else {
3287                         mBytesWritten += ret;
3288                         mBytesRemaining -= ret;
3289                         mFramesWritten += ret / mFrameSize;
3290                     }
3291                 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3292                         (mMixerStatus == MIXER_DRAIN_ALL)) {
3293                     threadLoop_drain();
3294                 }
3295                 if (mType == MIXER && !mStandby) {
3296                     // write blocked detection
3297                     if (delta > maxPeriod) {
3298                         mNumDelayedWrites++;
3299                         if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
3300                             ATRACE_NAME("underrun");
3301                             ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3302                                     (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
3303                             lastWarning = lastWriteFinished;
3304                         }
3305                     }
3306 
3307                     if (mThreadThrottle
3308                             && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3309                             && ret > 0) {                         // we wrote something
3310                         // Limit MixerThread data processing to no more than twice the
3311                         // expected processing rate.
3312                         //
3313                         // This helps prevent underruns with NuPlayer and other applications
3314                         // which may set up buffers that are close to the minimum size, or use
3315                         // deep buffers, and rely on a double-buffering sleep strategy to fill.
3316                         //
3317                         // The throttle smooths out sudden large data drains from the device,
3318                         // e.g. when it comes out of standby, which often causes problems with
3319                         // (1) mixer threads without a fast mixer (which has its own warm-up)
3320                         // (2) minimum buffer sized tracks (even if the track is full,
3321                         //     the app won't fill fast enough to handle the sudden draw).
3322                         //
3323                         // Total time spent in last processing cycle equals time spent in
3324                         // 1. threadLoop_write, as well as time spent in
3325                         // 2. threadLoop_mix (significant for heavy mixing, especially
3326                         //                    on low tier processors)
3327 
3328                         // it's OK if deltaMs is an overestimate.
3329                         const int32_t deltaMs =
3330                                 (lastWriteFinished - previousLastWriteFinished) / 1000000;
3331                         const int32_t throttleMs = mHalfBufferMs - deltaMs;
3332                         if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3333                             usleep(throttleMs * 1000);
3334                             // notify of throttle start on verbose log
3335                             ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3336                                     "mixer(%p) throttle begin:"
3337                                     " ret(%zd) deltaMs(%d) requires sleep %d ms",
3338                                     this, ret, deltaMs, throttleMs);
3339                             mThreadThrottleTimeMs += throttleMs;
3340                             // Throttle must be attributed to the previous mixer loop's write time
3341                             // to allow back-to-back throttling.
3342                             lastWriteFinished += throttleMs * 1000000;
3343                         } else {
3344                             uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3345                             if (diff > 0) {
3346                                 // notify of throttle end on debug log
3347                                 // but prevent spamming for bluetooth
3348                                 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3349                                         "mixer(%p) throttle end: throttle time(%u)", this, diff);
3350                                 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3351                             }
3352                         }
3353                     }
3354                 }
3355 
3356             } else {
3357                 ATRACE_BEGIN("sleep");
3358                 Mutex::Autolock _l(mLock);
3359                 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3360                     mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
3361                 }
3362                 ATRACE_END();
3363             }
3364         }
3365 
3366         // Finally let go of removed track(s), without the lock held
3367         // since we can't guarantee the destructors won't acquire that
3368         // same lock.  This will also mutate and push a new fast mixer state.
3369         threadLoop_removeTracks(tracksToRemove);
3370         tracksToRemove.clear();
3371 
3372         // FIXME I don't understand the need for this here;
3373         //       it was in the original code but maybe the
3374         //       assignment in saveOutputTracks() makes this unnecessary?
3375         clearOutputTracks();
3376 
3377         // Effect chains will be actually deleted here if they were removed from
3378         // mEffectChains list during mixing or effects processing
3379         effectChains.clear();
3380 
3381         // FIXME Note that the above .clear() is no longer necessary since effectChains
3382         // is now local to this block, but will keep it for now (at least until merge done).
3383     }
3384 
3385     threadLoop_exit();
3386 
3387     if (!mStandby) {
3388         threadLoop_standby();
3389         mStandby = true;
3390     }
3391 
3392     releaseWakeLock();
3393     mWakeLockUids.clear();
3394     mActiveTracksGeneration++;
3395 
3396     ALOGV("Thread %p type %d exiting", this, mType);
3397     return false;
3398 }
3399 
3400 // removeTracks_l() must be called with ThreadBase::mLock held
removeTracks_l(const Vector<sp<Track>> & tracksToRemove)3401 void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3402 {
3403     size_t count = tracksToRemove.size();
3404     if (count > 0) {
3405         for (size_t i=0 ; i<count ; i++) {
3406             const sp<Track>& track = tracksToRemove.itemAt(i);
3407             mActiveTracks.remove(track);
3408             mWakeLockUids.remove(track->uid());
3409             mActiveTracksGeneration++;
3410             ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3411             sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3412             if (chain != 0) {
3413                 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3414                         track->sessionId());
3415                 chain->decActiveTrackCnt();
3416             }
3417             if (track->isTerminated()) {
3418                 removeTrack_l(track);
3419             }
3420         }
3421     }
3422 
3423 }
3424 
getTimestamp_l(AudioTimestamp & timestamp)3425 status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3426 {
3427     if (mNormalSink != 0) {
3428         ExtendedTimestamp ets;
3429         status_t status = mNormalSink->getTimestamp(ets);
3430         if (status == NO_ERROR) {
3431             status = ets.getBestTimestamp(&timestamp);
3432         }
3433         return status;
3434     }
3435     if ((mType == OFFLOAD || mType == DIRECT)
3436             && mOutput != NULL && mOutput->stream->get_presentation_position) {
3437         uint64_t position64;
3438         int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
3439         if (ret == 0) {
3440             timestamp.mPosition = (uint32_t)position64;
3441             return NO_ERROR;
3442         }
3443     }
3444     return INVALID_OPERATION;
3445 }
3446 
createAudioPatch_l(const struct audio_patch * patch,audio_patch_handle_t * handle)3447 status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3448                                                           audio_patch_handle_t *handle)
3449 {
3450     status_t status;
3451     if (property_get_bool("af.patch_park", false /* default_value */)) {
3452         // Park FastMixer to avoid potential DOS issues with writing to the HAL
3453         // or if HAL does not properly lock against access.
3454         AutoPark<FastMixer> park(mFastMixer);
3455         status = PlaybackThread::createAudioPatch_l(patch, handle);
3456     } else {
3457         status = PlaybackThread::createAudioPatch_l(patch, handle);
3458     }
3459     return status;
3460 }
3461 
createAudioPatch_l(const struct audio_patch * patch,audio_patch_handle_t * handle)3462 status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3463                                                           audio_patch_handle_t *handle)
3464 {
3465     status_t status = NO_ERROR;
3466 
3467     // store new device and send to effects
3468     audio_devices_t type = AUDIO_DEVICE_NONE;
3469     for (unsigned int i = 0; i < patch->num_sinks; i++) {
3470         type |= patch->sinks[i].ext.device.type;
3471     }
3472 
3473 #ifdef ADD_BATTERY_DATA
3474     // when changing the audio output device, call addBatteryData to notify
3475     // the change
3476     if (mOutDevice != type) {
3477         uint32_t params = 0;
3478         // check whether speaker is on
3479         if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3480             params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3481         }
3482 
3483         audio_devices_t deviceWithoutSpeaker
3484             = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3485         // check if any other device (except speaker) is on
3486         if (type & deviceWithoutSpeaker) {
3487             params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3488         }
3489 
3490         if (params != 0) {
3491             addBatteryData(params);
3492         }
3493     }
3494 #endif
3495 
3496     for (size_t i = 0; i < mEffectChains.size(); i++) {
3497         mEffectChains[i]->setDevice_l(type);
3498     }
3499 
3500     // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3501     // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3502     bool configChanged = mPrevOutDevice != type;
3503     mOutDevice = type;
3504     mPatch = *patch;
3505 
3506     if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3507         audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3508         status = hwDevice->create_audio_patch(hwDevice,
3509                                                patch->num_sources,
3510                                                patch->sources,
3511                                                patch->num_sinks,
3512                                                patch->sinks,
3513                                                handle);
3514     } else {
3515         char *address;
3516         if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3517             //FIXME: we only support address on first sink with HAL version < 3.0
3518             address = audio_device_address_to_parameter(
3519                                                         patch->sinks[0].ext.device.type,
3520                                                         patch->sinks[0].ext.device.address);
3521         } else {
3522             address = (char *)calloc(1, 1);
3523         }
3524         AudioParameter param = AudioParameter(String8(address));
3525         free(address);
3526         param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3527         status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3528                 param.toString().string());
3529         *handle = AUDIO_PATCH_HANDLE_NONE;
3530     }
3531     if (configChanged) {
3532         mPrevOutDevice = type;
3533         sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3534     }
3535     return status;
3536 }
3537 
releaseAudioPatch_l(const audio_patch_handle_t handle)3538 status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3539 {
3540     status_t status;
3541     if (property_get_bool("af.patch_park", false /* default_value */)) {
3542         // Park FastMixer to avoid potential DOS issues with writing to the HAL
3543         // or if HAL does not properly lock against access.
3544         AutoPark<FastMixer> park(mFastMixer);
3545         status = PlaybackThread::releaseAudioPatch_l(handle);
3546     } else {
3547         status = PlaybackThread::releaseAudioPatch_l(handle);
3548     }
3549     return status;
3550 }
3551 
releaseAudioPatch_l(const audio_patch_handle_t handle)3552 status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3553 {
3554     status_t status = NO_ERROR;
3555 
3556     mOutDevice = AUDIO_DEVICE_NONE;
3557 
3558     if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3559         audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3560         status = hwDevice->release_audio_patch(hwDevice, handle);
3561     } else {
3562         AudioParameter param;
3563         param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3564         status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3565                 param.toString().string());
3566     }
3567     return status;
3568 }
3569 
addPatchTrack(const sp<PatchTrack> & track)3570 void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3571 {
3572     Mutex::Autolock _l(mLock);
3573     mTracks.add(track);
3574 }
3575 
deletePatchTrack(const sp<PatchTrack> & track)3576 void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3577 {
3578     Mutex::Autolock _l(mLock);
3579     destroyTrack_l(track);
3580 }
3581 
getAudioPortConfig(struct audio_port_config * config)3582 void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3583 {
3584     ThreadBase::getAudioPortConfig(config);
3585     config->role = AUDIO_PORT_ROLE_SOURCE;
3586     config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3587     config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3588 }
3589 
3590 // ----------------------------------------------------------------------------
3591 
MixerThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,audio_devices_t device,bool systemReady,type_t type)3592 AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
3593         audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3594     :   PlaybackThread(audioFlinger, output, id, device, type, systemReady),
3595         // mAudioMixer below
3596         // mFastMixer below
3597         mFastMixerFutex(0),
3598         mMasterMono(false)
3599         // mOutputSink below
3600         // mPipeSink below
3601         // mNormalSink below
3602 {
3603     ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
3604     ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3605             "mFrameCount=%zu, mNormalFrameCount=%zu",
3606             mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3607             mNormalFrameCount);
3608     mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3609 
3610     if (type == DUPLICATING) {
3611         // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3612         // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3613         // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3614         return;
3615     }
3616     // create an NBAIO sink for the HAL output stream, and negotiate
3617     mOutputSink = new AudioStreamOutSink(output->stream);
3618     size_t numCounterOffers = 0;
3619     const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
3620 #if !LOG_NDEBUG
3621     ssize_t index =
3622 #else
3623     (void)
3624 #endif
3625             mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3626     ALOG_ASSERT(index == 0);
3627 
3628     // initialize fast mixer depending on configuration
3629     bool initFastMixer;
3630     switch (kUseFastMixer) {
3631     case FastMixer_Never:
3632         initFastMixer = false;
3633         break;
3634     case FastMixer_Always:
3635         initFastMixer = true;
3636         break;
3637     case FastMixer_Static:
3638     case FastMixer_Dynamic:
3639         initFastMixer = mFrameCount < mNormalFrameCount;
3640         break;
3641     }
3642     if (initFastMixer) {
3643         audio_format_t fastMixerFormat;
3644         if (mMixerBufferEnabled && mEffectBufferEnabled) {
3645             fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3646         } else {
3647             fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3648         }
3649         if (mFormat != fastMixerFormat) {
3650             // change our Sink format to accept our intermediate precision
3651             mFormat = fastMixerFormat;
3652             free(mSinkBuffer);
3653             mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3654             const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3655             (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3656         }
3657 
3658         // create a MonoPipe to connect our submix to FastMixer
3659         NBAIO_Format format = mOutputSink->format();
3660 #ifdef TEE_SINK
3661         NBAIO_Format origformat = format;
3662 #endif
3663         // adjust format to match that of the Fast Mixer
3664         ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
3665         format.mFormat = fastMixerFormat;
3666         format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3667 
3668         // This pipe depth compensates for scheduling latency of the normal mixer thread.
3669         // When it wakes up after a maximum latency, it runs a few cycles quickly before
3670         // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
3671         MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3672         const NBAIO_Format offers[1] = {format};
3673         size_t numCounterOffers = 0;
3674 #if !LOG_NDEBUG || defined(TEE_SINK)
3675         ssize_t index =
3676 #else
3677         (void)
3678 #endif
3679                 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3680         ALOG_ASSERT(index == 0);
3681         monoPipe->setAvgFrames((mScreenState & 1) ?
3682                 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3683         mPipeSink = monoPipe;
3684 
3685 #ifdef TEE_SINK
3686         if (mTeeSinkOutputEnabled) {
3687             // create a Pipe to archive a copy of FastMixer's output for dumpsys
3688             Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3689             const NBAIO_Format offers2[1] = {origformat};
3690             numCounterOffers = 0;
3691             index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
3692             ALOG_ASSERT(index == 0);
3693             mTeeSink = teeSink;
3694             PipeReader *teeSource = new PipeReader(*teeSink);
3695             numCounterOffers = 0;
3696             index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
3697             ALOG_ASSERT(index == 0);
3698             mTeeSource = teeSource;
3699         }
3700 #endif
3701 
3702         // create fast mixer and configure it initially with just one fast track for our submix
3703         mFastMixer = new FastMixer();
3704         FastMixerStateQueue *sq = mFastMixer->sq();
3705 #ifdef STATE_QUEUE_DUMP
3706         sq->setObserverDump(&mStateQueueObserverDump);
3707         sq->setMutatorDump(&mStateQueueMutatorDump);
3708 #endif
3709         FastMixerState *state = sq->begin();
3710         FastTrack *fastTrack = &state->mFastTracks[0];
3711         // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3712         fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3713         fastTrack->mVolumeProvider = NULL;
3714         fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3715         fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
3716         fastTrack->mGeneration++;
3717         state->mFastTracksGen++;
3718         state->mTrackMask = 1;
3719         // fast mixer will use the HAL output sink
3720         state->mOutputSink = mOutputSink.get();
3721         state->mOutputSinkGen++;
3722         state->mFrameCount = mFrameCount;
3723         state->mCommand = FastMixerState::COLD_IDLE;
3724         // already done in constructor initialization list
3725         //mFastMixerFutex = 0;
3726         state->mColdFutexAddr = &mFastMixerFutex;
3727         state->mColdGen++;
3728         state->mDumpState = &mFastMixerDumpState;
3729 #ifdef TEE_SINK
3730         state->mTeeSink = mTeeSink.get();
3731 #endif
3732         mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3733         state->mNBLogWriter = mFastMixerNBLogWriter.get();
3734         sq->end();
3735         sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3736 
3737         // start the fast mixer
3738         mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3739         pid_t tid = mFastMixer->getTid();
3740         sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
3741 
3742 #ifdef AUDIO_WATCHDOG
3743         // create and start the watchdog
3744         mAudioWatchdog = new AudioWatchdog();
3745         mAudioWatchdog->setDump(&mAudioWatchdogDump);
3746         mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3747         tid = mAudioWatchdog->getTid();
3748         sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
3749 #endif
3750 
3751     }
3752 
3753     switch (kUseFastMixer) {
3754     case FastMixer_Never:
3755     case FastMixer_Dynamic:
3756         mNormalSink = mOutputSink;
3757         break;
3758     case FastMixer_Always:
3759         mNormalSink = mPipeSink;
3760         break;
3761     case FastMixer_Static:
3762         mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3763         break;
3764     }
3765 }
3766 
~MixerThread()3767 AudioFlinger::MixerThread::~MixerThread()
3768 {
3769     if (mFastMixer != 0) {
3770         FastMixerStateQueue *sq = mFastMixer->sq();
3771         FastMixerState *state = sq->begin();
3772         if (state->mCommand == FastMixerState::COLD_IDLE) {
3773             int32_t old = android_atomic_inc(&mFastMixerFutex);
3774             if (old == -1) {
3775                 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3776             }
3777         }
3778         state->mCommand = FastMixerState::EXIT;
3779         sq->end();
3780         sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3781         mFastMixer->join();
3782         // Though the fast mixer thread has exited, it's state queue is still valid.
3783         // We'll use that extract the final state which contains one remaining fast track
3784         // corresponding to our sub-mix.
3785         state = sq->begin();
3786         ALOG_ASSERT(state->mTrackMask == 1);
3787         FastTrack *fastTrack = &state->mFastTracks[0];
3788         ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3789         delete fastTrack->mBufferProvider;
3790         sq->end(false /*didModify*/);
3791         mFastMixer.clear();
3792 #ifdef AUDIO_WATCHDOG
3793         if (mAudioWatchdog != 0) {
3794             mAudioWatchdog->requestExit();
3795             mAudioWatchdog->requestExitAndWait();
3796             mAudioWatchdog.clear();
3797         }
3798 #endif
3799     }
3800     mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
3801     delete mAudioMixer;
3802 }
3803 
3804 
correctLatency_l(uint32_t latency) const3805 uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3806 {
3807     if (mFastMixer != 0) {
3808         MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3809         latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3810     }
3811     return latency;
3812 }
3813 
3814 
threadLoop_removeTracks(const Vector<sp<Track>> & tracksToRemove)3815 void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3816 {
3817     PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3818 }
3819 
threadLoop_write()3820 ssize_t AudioFlinger::MixerThread::threadLoop_write()
3821 {
3822     // FIXME we should only do one push per cycle; confirm this is true
3823     // Start the fast mixer if it's not already running
3824     if (mFastMixer != 0) {
3825         FastMixerStateQueue *sq = mFastMixer->sq();
3826         FastMixerState *state = sq->begin();
3827         if (state->mCommand != FastMixerState::MIX_WRITE &&
3828                 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3829             if (state->mCommand == FastMixerState::COLD_IDLE) {
3830 
3831                 // FIXME workaround for first HAL write being CPU bound on some devices
3832                 ATRACE_BEGIN("write");
3833                 mOutput->write((char *)mSinkBuffer, 0);
3834                 ATRACE_END();
3835 
3836                 int32_t old = android_atomic_inc(&mFastMixerFutex);
3837                 if (old == -1) {
3838                     (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3839                 }
3840 #ifdef AUDIO_WATCHDOG
3841                 if (mAudioWatchdog != 0) {
3842                     mAudioWatchdog->resume();
3843                 }
3844 #endif
3845             }
3846             state->mCommand = FastMixerState::MIX_WRITE;
3847 #ifdef FAST_THREAD_STATISTICS
3848             mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3849                 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
3850 #endif
3851             sq->end();
3852             sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3853             if (kUseFastMixer == FastMixer_Dynamic) {
3854                 mNormalSink = mPipeSink;
3855             }
3856         } else {
3857             sq->end(false /*didModify*/);
3858         }
3859     }
3860     return PlaybackThread::threadLoop_write();
3861 }
3862 
threadLoop_standby()3863 void AudioFlinger::MixerThread::threadLoop_standby()
3864 {
3865     // Idle the fast mixer if it's currently running
3866     if (mFastMixer != 0) {
3867         FastMixerStateQueue *sq = mFastMixer->sq();
3868         FastMixerState *state = sq->begin();
3869         if (!(state->mCommand & FastMixerState::IDLE)) {
3870             state->mCommand = FastMixerState::COLD_IDLE;
3871             state->mColdFutexAddr = &mFastMixerFutex;
3872             state->mColdGen++;
3873             mFastMixerFutex = 0;
3874             sq->end();
3875             // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3876             sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3877             if (kUseFastMixer == FastMixer_Dynamic) {
3878                 mNormalSink = mOutputSink;
3879             }
3880 #ifdef AUDIO_WATCHDOG
3881             if (mAudioWatchdog != 0) {
3882                 mAudioWatchdog->pause();
3883             }
3884 #endif
3885         } else {
3886             sq->end(false /*didModify*/);
3887         }
3888     }
3889     PlaybackThread::threadLoop_standby();
3890 }
3891 
waitingAsyncCallback_l()3892 bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3893 {
3894     return false;
3895 }
3896 
shouldStandby_l()3897 bool AudioFlinger::PlaybackThread::shouldStandby_l()
3898 {
3899     return !mStandby;
3900 }
3901 
waitingAsyncCallback()3902 bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3903 {
3904     Mutex::Autolock _l(mLock);
3905     return waitingAsyncCallback_l();
3906 }
3907 
3908 // shared by MIXER and DIRECT, overridden by DUPLICATING
threadLoop_standby()3909 void AudioFlinger::PlaybackThread::threadLoop_standby()
3910 {
3911     ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3912     mOutput->standby();
3913     if (mUseAsyncWrite != 0) {
3914         // discard any pending drain or write ack by incrementing sequence
3915         mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3916         mDrainSequence = (mDrainSequence + 2) & ~1;
3917         ALOG_ASSERT(mCallbackThread != 0);
3918         mCallbackThread->setWriteBlocked(mWriteAckSequence);
3919         mCallbackThread->setDraining(mDrainSequence);
3920     }
3921     mHwPaused = false;
3922 }
3923 
onAddNewTrack_l()3924 void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3925 {
3926     ALOGV("signal playback thread");
3927     broadcast_l();
3928 }
3929 
onAsyncError()3930 void AudioFlinger::PlaybackThread::onAsyncError()
3931 {
3932     for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3933         invalidateTracks((audio_stream_type_t)i);
3934     }
3935 }
3936 
threadLoop_mix()3937 void AudioFlinger::MixerThread::threadLoop_mix()
3938 {
3939     // mix buffers...
3940     mAudioMixer->process();
3941     mCurrentWriteLength = mSinkBufferSize;
3942     // increase sleep time progressively when application underrun condition clears.
3943     // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3944     // that a steady state of alternating ready/not ready conditions keeps the sleep time
3945     // such that we would underrun the audio HAL.
3946     if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
3947         sleepTimeShift--;
3948     }
3949     mSleepTimeUs = 0;
3950     mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3951     //TODO: delay standby when effects have a tail
3952 
3953 }
3954 
threadLoop_sleepTime()3955 void AudioFlinger::MixerThread::threadLoop_sleepTime()
3956 {
3957     // If no tracks are ready, sleep once for the duration of an output
3958     // buffer size, then write 0s to the output
3959     if (mSleepTimeUs == 0) {
3960         if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3961             mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3962             if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3963                 mSleepTimeUs = kMinThreadSleepTimeUs;
3964             }
3965             // reduce sleep time in case of consecutive application underruns to avoid
3966             // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3967             // duration we would end up writing less data than needed by the audio HAL if
3968             // the condition persists.
3969             if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3970                 sleepTimeShift++;
3971             }
3972         } else {
3973             mSleepTimeUs = mIdleSleepTimeUs;
3974         }
3975     } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
3976         // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3977         // before effects processing or output.
3978         if (mMixerBufferValid) {
3979             memset(mMixerBuffer, 0, mMixerBufferSize);
3980         } else {
3981             memset(mSinkBuffer, 0, mSinkBufferSize);
3982         }
3983         mSleepTimeUs = 0;
3984         ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3985                 "anticipated start");
3986     }
3987     // TODO add standby time extension fct of effect tail
3988 }
3989 
3990 // prepareTracks_l() must be called with ThreadBase::mLock held
prepareTracks_l(Vector<sp<Track>> * tracksToRemove)3991 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3992         Vector< sp<Track> > *tracksToRemove)
3993 {
3994 
3995     mixer_state mixerStatus = MIXER_IDLE;
3996     // find out which tracks need to be processed
3997     size_t count = mActiveTracks.size();
3998     size_t mixedTracks = 0;
3999     size_t tracksWithEffect = 0;
4000     // counts only _active_ fast tracks
4001     size_t fastTracks = 0;
4002     uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4003 
4004     float masterVolume = mMasterVolume;
4005     bool masterMute = mMasterMute;
4006 
4007     if (masterMute) {
4008         masterVolume = 0;
4009     }
4010     // Delegate master volume control to effect in output mix effect chain if needed
4011     sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4012     if (chain != 0) {
4013         uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4014         chain->setVolume_l(&v, &v);
4015         masterVolume = (float)((v + (1 << 23)) >> 24);
4016         chain.clear();
4017     }
4018 
4019     // prepare a new state to push
4020     FastMixerStateQueue *sq = NULL;
4021     FastMixerState *state = NULL;
4022     bool didModify = false;
4023     FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
4024     if (mFastMixer != 0) {
4025         sq = mFastMixer->sq();
4026         state = sq->begin();
4027     }
4028 
4029     mMixerBufferValid = false;  // mMixerBuffer has no valid data until appropriate tracks found.
4030     mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
4031 
4032     for (size_t i=0 ; i<count ; i++) {
4033         const sp<Track> t = mActiveTracks[i].promote();
4034         if (t == 0) {
4035             continue;
4036         }
4037 
4038         // this const just means the local variable doesn't change
4039         Track* const track = t.get();
4040 
4041         // process fast tracks
4042         if (track->isFastTrack()) {
4043 
4044             // It's theoretically possible (though unlikely) for a fast track to be created
4045             // and then removed within the same normal mix cycle.  This is not a problem, as
4046             // the track never becomes active so it's fast mixer slot is never touched.
4047             // The converse, of removing an (active) track and then creating a new track
4048             // at the identical fast mixer slot within the same normal mix cycle,
4049             // is impossible because the slot isn't marked available until the end of each cycle.
4050             int j = track->mFastIndex;
4051             ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
4052             ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4053             FastTrack *fastTrack = &state->mFastTracks[j];
4054 
4055             // Determine whether the track is currently in underrun condition,
4056             // and whether it had a recent underrun.
4057             FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4058             FastTrackUnderruns underruns = ftDump->mUnderruns;
4059             uint32_t recentFull = (underruns.mBitFields.mFull -
4060                     track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4061             uint32_t recentPartial = (underruns.mBitFields.mPartial -
4062                     track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4063             uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4064                     track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4065             uint32_t recentUnderruns = recentPartial + recentEmpty;
4066             track->mObservedUnderruns = underruns;
4067             // don't count underruns that occur while stopping or pausing
4068             // or stopped which can occur when flush() is called while active
4069             if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4070                     recentUnderruns > 0) {
4071                 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4072                 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
4073             } else {
4074                 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
4075             }
4076 
4077             // This is similar to the state machine for normal tracks,
4078             // with a few modifications for fast tracks.
4079             bool isActive = true;
4080             switch (track->mState) {
4081             case TrackBase::STOPPING_1:
4082                 // track stays active in STOPPING_1 state until first underrun
4083                 if (recentUnderruns > 0 || track->isTerminated()) {
4084                     track->mState = TrackBase::STOPPING_2;
4085                 }
4086                 break;
4087             case TrackBase::PAUSING:
4088                 // ramp down is not yet implemented
4089                 track->setPaused();
4090                 break;
4091             case TrackBase::RESUMING:
4092                 // ramp up is not yet implemented
4093                 track->mState = TrackBase::ACTIVE;
4094                 break;
4095             case TrackBase::ACTIVE:
4096                 if (recentFull > 0 || recentPartial > 0) {
4097                     // track has provided at least some frames recently: reset retry count
4098                     track->mRetryCount = kMaxTrackRetries;
4099                 }
4100                 if (recentUnderruns == 0) {
4101                     // no recent underruns: stay active
4102                     break;
4103                 }
4104                 // there has recently been an underrun of some kind
4105                 if (track->sharedBuffer() == 0) {
4106                     // were any of the recent underruns "empty" (no frames available)?
4107                     if (recentEmpty == 0) {
4108                         // no, then ignore the partial underruns as they are allowed indefinitely
4109                         break;
4110                     }
4111                     // there has recently been an "empty" underrun: decrement the retry counter
4112                     if (--(track->mRetryCount) > 0) {
4113                         break;
4114                     }
4115                     // indicate to client process that the track was disabled because of underrun;
4116                     // it will then automatically call start() when data is available
4117                     track->disable();
4118                     // remove from active list, but state remains ACTIVE [confusing but true]
4119                     isActive = false;
4120                     break;
4121                 }
4122                 // fall through
4123             case TrackBase::STOPPING_2:
4124             case TrackBase::PAUSED:
4125             case TrackBase::STOPPED:
4126             case TrackBase::FLUSHED:   // flush() while active
4127                 // Check for presentation complete if track is inactive
4128                 // We have consumed all the buffers of this track.
4129                 // This would be incomplete if we auto-paused on underrun
4130                 {
4131                     size_t audioHALFrames =
4132                             (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4133                     int64_t framesWritten = mBytesWritten / mFrameSize;
4134                     if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4135                         // track stays in active list until presentation is complete
4136                         break;
4137                     }
4138                 }
4139                 if (track->isStopping_2()) {
4140                     track->mState = TrackBase::STOPPED;
4141                 }
4142                 if (track->isStopped()) {
4143                     // Can't reset directly, as fast mixer is still polling this track
4144                     //   track->reset();
4145                     // So instead mark this track as needing to be reset after push with ack
4146                     resetMask |= 1 << i;
4147                 }
4148                 isActive = false;
4149                 break;
4150             case TrackBase::IDLE:
4151             default:
4152                 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
4153             }
4154 
4155             if (isActive) {
4156                 // was it previously inactive?
4157                 if (!(state->mTrackMask & (1 << j))) {
4158                     ExtendedAudioBufferProvider *eabp = track;
4159                     VolumeProvider *vp = track;
4160                     fastTrack->mBufferProvider = eabp;
4161                     fastTrack->mVolumeProvider = vp;
4162                     fastTrack->mChannelMask = track->mChannelMask;
4163                     fastTrack->mFormat = track->mFormat;
4164                     fastTrack->mGeneration++;
4165                     state->mTrackMask |= 1 << j;
4166                     didModify = true;
4167                     // no acknowledgement required for newly active tracks
4168                 }
4169                 // cache the combined master volume and stream type volume for fast mixer; this
4170                 // lacks any synchronization or barrier so VolumeProvider may read a stale value
4171                 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
4172                 ++fastTracks;
4173             } else {
4174                 // was it previously active?
4175                 if (state->mTrackMask & (1 << j)) {
4176                     fastTrack->mBufferProvider = NULL;
4177                     fastTrack->mGeneration++;
4178                     state->mTrackMask &= ~(1 << j);
4179                     didModify = true;
4180                     // If any fast tracks were removed, we must wait for acknowledgement
4181                     // because we're about to decrement the last sp<> on those tracks.
4182                     block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4183                 } else {
4184                     LOG_ALWAYS_FATAL("fast track %d should have been active; "
4185                             "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4186                             j, track->mState, state->mTrackMask, recentUnderruns,
4187                             track->sharedBuffer() != 0);
4188                 }
4189                 tracksToRemove->add(track);
4190                 // Avoids a misleading display in dumpsys
4191                 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4192             }
4193             continue;
4194         }
4195 
4196         {   // local variable scope to avoid goto warning
4197 
4198         audio_track_cblk_t* cblk = track->cblk();
4199 
4200         // The first time a track is added we wait
4201         // for all its buffers to be filled before processing it
4202         int name = track->name();
4203         // make sure that we have enough frames to mix one full buffer.
4204         // enforce this condition only once to enable draining the buffer in case the client
4205         // app does not call stop() and relies on underrun to stop:
4206         // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4207         // during last round
4208         size_t desiredFrames;
4209         const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
4210         AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
4211 
4212         desiredFrames = sourceFramesNeededWithTimestretch(
4213                 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
4214         // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4215         // add frames already consumed but not yet released by the resampler
4216         // because mAudioTrackServerProxy->framesReady() will include these frames
4217         desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4218 
4219         uint32_t minFrames = 1;
4220         if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4221                 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
4222             minFrames = desiredFrames;
4223         }
4224 
4225         size_t framesReady = track->framesReady();
4226         if (ATRACE_ENABLED()) {
4227             // I wish we had formatted trace names
4228             char traceName[16];
4229             strcpy(traceName, "nRdy");
4230             int name = track->name();
4231             if (AudioMixer::TRACK0 <= name &&
4232                     name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4233                 name -= AudioMixer::TRACK0;
4234                 traceName[4] = (name / 10) + '0';
4235                 traceName[5] = (name % 10) + '0';
4236             } else {
4237                 traceName[4] = '?';
4238                 traceName[5] = '?';
4239             }
4240             traceName[6] = '\0';
4241             ATRACE_INT(traceName, framesReady);
4242         }
4243         if ((framesReady >= minFrames) && track->isReady() &&
4244                 !track->isPaused() && !track->isTerminated())
4245         {
4246             ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
4247 
4248             mixedTracks++;
4249 
4250             // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4251             // there is an effect chain connected to the track
4252             chain.clear();
4253             if (track->mainBuffer() != mSinkBuffer &&
4254                     track->mainBuffer() != mMixerBuffer) {
4255                 if (mEffectBufferEnabled) {
4256                     mEffectBufferValid = true; // Later can set directly.
4257                 }
4258                 chain = getEffectChain_l(track->sessionId());
4259                 // Delegate volume control to effect in track effect chain if needed
4260                 if (chain != 0) {
4261                     tracksWithEffect++;
4262                 } else {
4263                     ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4264                             "session %d",
4265                             name, track->sessionId());
4266                 }
4267             }
4268 
4269 
4270             int param = AudioMixer::VOLUME;
4271             if (track->mFillingUpStatus == Track::FS_FILLED) {
4272                 // no ramp for the first volume setting
4273                 track->mFillingUpStatus = Track::FS_ACTIVE;
4274                 if (track->mState == TrackBase::RESUMING) {
4275                     track->mState = TrackBase::ACTIVE;
4276                     param = AudioMixer::RAMP_VOLUME;
4277                 }
4278                 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
4279             // FIXME should not make a decision based on mServer
4280             } else if (cblk->mServer != 0) {
4281                 // If the track is stopped before the first frame was mixed,
4282                 // do not apply ramp
4283                 param = AudioMixer::RAMP_VOLUME;
4284             }
4285 
4286             // compute volume for this track
4287             uint32_t vl, vr;       // in U8.24 integer format
4288             float vlf, vrf, vaf;   // in [0.0, 1.0] float format
4289             if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
4290                 vl = vr = 0;
4291                 vlf = vrf = vaf = 0.;
4292                 if (track->isPausing()) {
4293                     track->setPaused();
4294                 }
4295             } else {
4296 
4297                 // read original volumes with volume control
4298                 float typeVolume = mStreamTypes[track->streamType()].volume;
4299                 float v = masterVolume * typeVolume;
4300                 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
4301                 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4302                 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4303                 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
4304                 // track volumes come from shared memory, so can't be trusted and must be clamped
4305                 if (vlf > GAIN_FLOAT_UNITY) {
4306                     ALOGV("Track left volume out of range: %.3g", vlf);
4307                     vlf = GAIN_FLOAT_UNITY;
4308                 }
4309                 if (vrf > GAIN_FLOAT_UNITY) {
4310                     ALOGV("Track right volume out of range: %.3g", vrf);
4311                     vrf = GAIN_FLOAT_UNITY;
4312                 }
4313                 // now apply the master volume and stream type volume
4314                 vlf *= v;
4315                 vrf *= v;
4316                 // assuming master volume and stream type volume each go up to 1.0,
4317                 // then derive vl and vr as U8.24 versions for the effect chain
4318                 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4319                 vl = (uint32_t) (scaleto8_24 * vlf);
4320                 vr = (uint32_t) (scaleto8_24 * vrf);
4321                 // vl and vr are now in U8.24 format
4322                 uint16_t sendLevel = proxy->getSendLevel_U4_12();
4323                 // send level comes from shared memory and so may be corrupt
4324                 if (sendLevel > MAX_GAIN_INT) {
4325                     ALOGV("Track send level out of range: %04X", sendLevel);
4326                     sendLevel = MAX_GAIN_INT;
4327                 }
4328                 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4329                 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
4330             }
4331 
4332             // Delegate volume control to effect in track effect chain if needed
4333             if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4334                 // Do not ramp volume if volume is controlled by effect
4335                 param = AudioMixer::VOLUME;
4336                 // Update remaining floating point volume levels
4337                 vlf = (float)vl / (1 << 24);
4338                 vrf = (float)vr / (1 << 24);
4339                 track->mHasVolumeController = true;
4340             } else {
4341                 // force no volume ramp when volume controller was just disabled or removed
4342                 // from effect chain to avoid volume spike
4343                 if (track->mHasVolumeController) {
4344                     param = AudioMixer::VOLUME;
4345                 }
4346                 track->mHasVolumeController = false;
4347             }
4348 
4349             // XXX: these things DON'T need to be done each time
4350             mAudioMixer->setBufferProvider(name, track);
4351             mAudioMixer->enable(name);
4352 
4353             mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4354             mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4355             mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
4356             mAudioMixer->setParameter(
4357                 name,
4358                 AudioMixer::TRACK,
4359                 AudioMixer::FORMAT, (void *)track->format());
4360             mAudioMixer->setParameter(
4361                 name,
4362                 AudioMixer::TRACK,
4363                 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
4364             mAudioMixer->setParameter(
4365                 name,
4366                 AudioMixer::TRACK,
4367                 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
4368             // limit track sample rate to 2 x output sample rate, which changes at re-configuration
4369             uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
4370             uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
4371             if (reqSampleRate == 0) {
4372                 reqSampleRate = mSampleRate;
4373             } else if (reqSampleRate > maxSampleRate) {
4374                 reqSampleRate = maxSampleRate;
4375             }
4376             mAudioMixer->setParameter(
4377                 name,
4378                 AudioMixer::RESAMPLE,
4379                 AudioMixer::SAMPLE_RATE,
4380                 (void *)(uintptr_t)reqSampleRate);
4381 
4382             AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
4383             mAudioMixer->setParameter(
4384                 name,
4385                 AudioMixer::TIMESTRETCH,
4386                 AudioMixer::PLAYBACK_RATE,
4387                 &playbackRate);
4388 
4389             /*
4390              * Select the appropriate output buffer for the track.
4391              *
4392              * Tracks with effects go into their own effects chain buffer
4393              * and from there into either mEffectBuffer or mSinkBuffer.
4394              *
4395              * Other tracks can use mMixerBuffer for higher precision
4396              * channel accumulation.  If this buffer is enabled
4397              * (mMixerBufferEnabled true), then selected tracks will accumulate
4398              * into it.
4399              *
4400              */
4401             if (mMixerBufferEnabled
4402                     && (track->mainBuffer() == mSinkBuffer
4403                             || track->mainBuffer() == mMixerBuffer)) {
4404                 mAudioMixer->setParameter(
4405                         name,
4406                         AudioMixer::TRACK,
4407                         AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
4408                 mAudioMixer->setParameter(
4409                         name,
4410                         AudioMixer::TRACK,
4411                         AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4412                 // TODO: override track->mainBuffer()?
4413                 mMixerBufferValid = true;
4414             } else {
4415                 mAudioMixer->setParameter(
4416                         name,
4417                         AudioMixer::TRACK,
4418                         AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
4419                 mAudioMixer->setParameter(
4420                         name,
4421                         AudioMixer::TRACK,
4422                         AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4423             }
4424             mAudioMixer->setParameter(
4425                 name,
4426                 AudioMixer::TRACK,
4427                 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4428 
4429             // reset retry count
4430             track->mRetryCount = kMaxTrackRetries;
4431 
4432             // If one track is ready, set the mixer ready if:
4433             //  - the mixer was not ready during previous round OR
4434             //  - no other track is not ready
4435             if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4436                     mixerStatus != MIXER_TRACKS_ENABLED) {
4437                 mixerStatus = MIXER_TRACKS_READY;
4438             }
4439         } else {
4440             if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
4441                 ALOGV("track(%p) underrun,  framesReady(%zu) < framesDesired(%zd)",
4442                         track, framesReady, desiredFrames);
4443                 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
4444             } else {
4445                 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
4446             }
4447 
4448             // clear effect chain input buffer if an active track underruns to avoid sending
4449             // previous audio buffer again to effects
4450             chain = getEffectChain_l(track->sessionId());
4451             if (chain != 0) {
4452                 chain->clearInputBuffer();
4453             }
4454 
4455             ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
4456             if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4457                     track->isStopped() || track->isPaused()) {
4458                 // We have consumed all the buffers of this track.
4459                 // Remove it from the list of active tracks.
4460                 // TODO: use actual buffer filling status instead of latency when available from
4461                 // audio HAL
4462                 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
4463                 int64_t framesWritten = mBytesWritten / mFrameSize;
4464                 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4465                     if (track->isStopped()) {
4466                         track->reset();
4467                     }
4468                     tracksToRemove->add(track);
4469                 }
4470             } else {
4471                 // No buffers for this track. Give it a few chances to
4472                 // fill a buffer, then remove it from active list.
4473                 if (--(track->mRetryCount) <= 0) {
4474                     ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
4475                     tracksToRemove->add(track);
4476                     // indicate to client process that the track was disabled because of underrun;
4477                     // it will then automatically call start() when data is available
4478                     track->disable();
4479                 // If one track is not ready, mark the mixer also not ready if:
4480                 //  - the mixer was ready during previous round OR
4481                 //  - no other track is ready
4482                 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4483                                 mixerStatus != MIXER_TRACKS_READY) {
4484                     mixerStatus = MIXER_TRACKS_ENABLED;
4485                 }
4486             }
4487             mAudioMixer->disable(name);
4488         }
4489 
4490         }   // local variable scope to avoid goto warning
4491 
4492     }
4493 
4494     // Push the new FastMixer state if necessary
4495     bool pauseAudioWatchdog = false;
4496     if (didModify) {
4497         state->mFastTracksGen++;
4498         // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4499         if (kUseFastMixer == FastMixer_Dynamic &&
4500                 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4501             state->mCommand = FastMixerState::COLD_IDLE;
4502             state->mColdFutexAddr = &mFastMixerFutex;
4503             state->mColdGen++;
4504             mFastMixerFutex = 0;
4505             if (kUseFastMixer == FastMixer_Dynamic) {
4506                 mNormalSink = mOutputSink;
4507             }
4508             // If we go into cold idle, need to wait for acknowledgement
4509             // so that fast mixer stops doing I/O.
4510             block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4511             pauseAudioWatchdog = true;
4512         }
4513     }
4514     if (sq != NULL) {
4515         sq->end(didModify);
4516         sq->push(block);
4517     }
4518 #ifdef AUDIO_WATCHDOG
4519     if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4520         mAudioWatchdog->pause();
4521     }
4522 #endif
4523 
4524     // Now perform the deferred reset on fast tracks that have stopped
4525     while (resetMask != 0) {
4526         size_t i = __builtin_ctz(resetMask);
4527         ALOG_ASSERT(i < count);
4528         resetMask &= ~(1 << i);
4529         sp<Track> t = mActiveTracks[i].promote();
4530         if (t == 0) {
4531             continue;
4532         }
4533         Track* track = t.get();
4534         ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4535         track->reset();
4536     }
4537 
4538     // remove all the tracks that need to be...
4539     removeTracks_l(*tracksToRemove);
4540 
4541     if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4542         mEffectBufferValid = true;
4543     }
4544 
4545     if (mEffectBufferValid) {
4546         // as long as there are effects we should clear the effects buffer, to avoid
4547         // passing a non-clean buffer to the effect chain
4548         memset(mEffectBuffer, 0, mEffectBufferSize);
4549     }
4550     // sink or mix buffer must be cleared if all tracks are connected to an
4551     // effect chain as in this case the mixer will not write to the sink or mix buffer
4552     // and track effects will accumulate into it
4553     if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4554             (mixedTracks == 0 && fastTracks > 0))) {
4555         // FIXME as a performance optimization, should remember previous zero status
4556         if (mMixerBufferValid) {
4557             memset(mMixerBuffer, 0, mMixerBufferSize);
4558             // TODO: In testing, mSinkBuffer below need not be cleared because
4559             // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4560             // after mixing.
4561             //
4562             // To enforce this guarantee:
4563             // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4564             // (mixedTracks == 0 && fastTracks > 0))
4565             // must imply MIXER_TRACKS_READY.
4566             // Later, we may clear buffers regardless, and skip much of this logic.
4567         }
4568         // FIXME as a performance optimization, should remember previous zero status
4569         memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
4570     }
4571 
4572     // if any fast tracks, then status is ready
4573     mMixerStatusIgnoringFastTracks = mixerStatus;
4574     if (fastTracks > 0) {
4575         mixerStatus = MIXER_TRACKS_READY;
4576     }
4577     return mixerStatus;
4578 }
4579 
4580 // getTrackName_l() must be called with ThreadBase::mLock held
getTrackName_l(audio_channel_mask_t channelMask,audio_format_t format,audio_session_t sessionId)4581 int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4582         audio_format_t format, audio_session_t sessionId)
4583 {
4584     return mAudioMixer->getTrackName(channelMask, format, sessionId);
4585 }
4586 
4587 // deleteTrackName_l() must be called with ThreadBase::mLock held
deleteTrackName_l(int name)4588 void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4589 {
4590     ALOGV("remove track (%d) and delete from mixer", name);
4591     mAudioMixer->deleteTrackName(name);
4592 }
4593 
4594 // checkForNewParameter_l() must be called with ThreadBase::mLock held
checkForNewParameter_l(const String8 & keyValuePair,status_t & status)4595 bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4596                                                        status_t& status)
4597 {
4598     bool reconfig = false;
4599     bool a2dpDeviceChanged = false;
4600 
4601     status = NO_ERROR;
4602 
4603     AutoPark<FastMixer> park(mFastMixer);
4604 
4605     AudioParameter param = AudioParameter(keyValuePair);
4606     int value;
4607     if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4608         reconfig = true;
4609     }
4610     if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4611         if (!isValidPcmSinkFormat((audio_format_t) value)) {
4612             status = BAD_VALUE;
4613         } else {
4614             // no need to save value, since it's constant
4615             reconfig = true;
4616         }
4617     }
4618     if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4619         if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
4620             status = BAD_VALUE;
4621         } else {
4622             // no need to save value, since it's constant
4623             reconfig = true;
4624         }
4625     }
4626     if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4627         // do not accept frame count changes if tracks are open as the track buffer
4628         // size depends on frame count and correct behavior would not be guaranteed
4629         // if frame count is changed after track creation
4630         if (!mTracks.isEmpty()) {
4631             status = INVALID_OPERATION;
4632         } else {
4633             reconfig = true;
4634         }
4635     }
4636     if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4637 #ifdef ADD_BATTERY_DATA
4638         // when changing the audio output device, call addBatteryData to notify
4639         // the change
4640         if (mOutDevice != value) {
4641             uint32_t params = 0;
4642             // check whether speaker is on
4643             if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4644                 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
4645             }
4646 
4647             audio_devices_t deviceWithoutSpeaker
4648                 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4649             // check if any other device (except speaker) is on
4650             if (value & deviceWithoutSpeaker) {
4651                 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4652             }
4653 
4654             if (params != 0) {
4655                 addBatteryData(params);
4656             }
4657         }
4658 #endif
4659 
4660         // forward device change to effects that have requested to be
4661         // aware of attached audio device.
4662         if (value != AUDIO_DEVICE_NONE) {
4663             a2dpDeviceChanged =
4664                     (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
4665             mOutDevice = value;
4666             for (size_t i = 0; i < mEffectChains.size(); i++) {
4667                 mEffectChains[i]->setDevice_l(mOutDevice);
4668             }
4669         }
4670     }
4671 
4672     if (status == NO_ERROR) {
4673         status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4674                                                 keyValuePair.string());
4675         if (!mStandby && status == INVALID_OPERATION) {
4676             mOutput->standby();
4677             mStandby = true;
4678             mBytesWritten = 0;
4679             status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4680                                                    keyValuePair.string());
4681         }
4682         if (status == NO_ERROR && reconfig) {
4683             readOutputParameters_l();
4684             delete mAudioMixer;
4685             mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4686             for (size_t i = 0; i < mTracks.size() ; i++) {
4687                 int name = getTrackName_l(mTracks[i]->mChannelMask,
4688                         mTracks[i]->mFormat, mTracks[i]->mSessionId);
4689                 if (name < 0) {
4690                     break;
4691                 }
4692                 mTracks[i]->mName = name;
4693             }
4694             sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4695         }
4696     }
4697 
4698     return reconfig || a2dpDeviceChanged;
4699 }
4700 
4701 
dumpInternals(int fd,const Vector<String16> & args)4702 void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4703 {
4704     PlaybackThread::dumpInternals(fd, args);
4705     dprintf(fd, "  Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
4706     dprintf(fd, "  AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
4707     dprintf(fd, "  Master mono: %s\n", mMasterMono ? "on" : "off");
4708 
4709     // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4710     // while we are dumping it.  It may be inconsistent, but it won't mutate!
4711     // This is a large object so we place it on the heap.
4712     // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4713     const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4714     copy->dump(fd);
4715     delete copy;
4716 
4717 #ifdef STATE_QUEUE_DUMP
4718     // Similar for state queue
4719     StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4720     observerCopy.dump(fd);
4721     StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4722     mutatorCopy.dump(fd);
4723 #endif
4724 
4725 #ifdef TEE_SINK
4726     // Write the tee output to a .wav file
4727     dumpTee(fd, mTeeSource, mId);
4728 #endif
4729 
4730 #ifdef AUDIO_WATCHDOG
4731     if (mAudioWatchdog != 0) {
4732         // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4733         AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4734         wdCopy.dump(fd);
4735     }
4736 #endif
4737 }
4738 
idleSleepTimeUs() const4739 uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4740 {
4741     return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4742 }
4743 
suspendSleepTimeUs() const4744 uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4745 {
4746     return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4747 }
4748 
cacheParameters_l()4749 void AudioFlinger::MixerThread::cacheParameters_l()
4750 {
4751     PlaybackThread::cacheParameters_l();
4752 
4753     // FIXME: Relaxed timing because of a certain device that can't meet latency
4754     // Should be reduced to 2x after the vendor fixes the driver issue
4755     // increase threshold again due to low power audio mode. The way this warning
4756     // threshold is calculated and its usefulness should be reconsidered anyway.
4757     maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4758 }
4759 
4760 // ----------------------------------------------------------------------------
4761 
DirectOutputThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,audio_devices_t device,bool systemReady)4762 AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4763         AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4764     :   PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
4765         // mLeftVolFloat, mRightVolFloat
4766 {
4767 }
4768 
DirectOutputThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,uint32_t device,ThreadBase::type_t type,bool systemReady)4769 AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4770         AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4771         ThreadBase::type_t type, bool systemReady)
4772     :   PlaybackThread(audioFlinger, output, id, device, type, systemReady)
4773         // mLeftVolFloat, mRightVolFloat
4774 {
4775 }
4776 
~DirectOutputThread()4777 AudioFlinger::DirectOutputThread::~DirectOutputThread()
4778 {
4779 }
4780 
processVolume_l(Track * track,bool lastTrack)4781 void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4782 {
4783     float left, right;
4784 
4785     if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4786         left = right = 0;
4787     } else {
4788         float typeVolume = mStreamTypes[track->streamType()].volume;
4789         float v = mMasterVolume * typeVolume;
4790         AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
4791         gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4792         left = float_from_gain(gain_minifloat_unpack_left(vlr));
4793         if (left > GAIN_FLOAT_UNITY) {
4794             left = GAIN_FLOAT_UNITY;
4795         }
4796         left *= v;
4797         right = float_from_gain(gain_minifloat_unpack_right(vlr));
4798         if (right > GAIN_FLOAT_UNITY) {
4799             right = GAIN_FLOAT_UNITY;
4800         }
4801         right *= v;
4802     }
4803 
4804     if (lastTrack) {
4805         if (left != mLeftVolFloat || right != mRightVolFloat) {
4806             mLeftVolFloat = left;
4807             mRightVolFloat = right;
4808 
4809             // Convert volumes from float to 8.24
4810             uint32_t vl = (uint32_t)(left * (1 << 24));
4811             uint32_t vr = (uint32_t)(right * (1 << 24));
4812 
4813             // Delegate volume control to effect in track effect chain if needed
4814             // only one effect chain can be present on DirectOutputThread, so if
4815             // there is one, the track is connected to it
4816             if (!mEffectChains.isEmpty()) {
4817                 mEffectChains[0]->setVolume_l(&vl, &vr);
4818                 left = (float)vl / (1 << 24);
4819                 right = (float)vr / (1 << 24);
4820             }
4821             if (mOutput->stream->set_volume) {
4822                 mOutput->stream->set_volume(mOutput->stream, left, right);
4823             }
4824         }
4825     }
4826 }
4827 
onAddNewTrack_l()4828 void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4829 {
4830     sp<Track> previousTrack = mPreviousTrack.promote();
4831     sp<Track> latestTrack = mLatestActiveTrack.promote();
4832 
4833     if (previousTrack != 0 && latestTrack != 0) {
4834         if (mType == DIRECT) {
4835             if (previousTrack.get() != latestTrack.get()) {
4836                 mFlushPending = true;
4837             }
4838         } else /* mType == OFFLOAD */ {
4839             if (previousTrack->sessionId() != latestTrack->sessionId()) {
4840                 mFlushPending = true;
4841             }
4842         }
4843     }
4844     PlaybackThread::onAddNewTrack_l();
4845 }
4846 
prepareTracks_l(Vector<sp<Track>> * tracksToRemove)4847 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4848     Vector< sp<Track> > *tracksToRemove
4849 )
4850 {
4851     size_t count = mActiveTracks.size();
4852     mixer_state mixerStatus = MIXER_IDLE;
4853     bool doHwPause = false;
4854     bool doHwResume = false;
4855 
4856     // find out which tracks need to be processed
4857     for (size_t i = 0; i < count; i++) {
4858         sp<Track> t = mActiveTracks[i].promote();
4859         // The track died recently
4860         if (t == 0) {
4861             continue;
4862         }
4863 
4864         if (t->isInvalid()) {
4865             ALOGW("An invalidated track shouldn't be in active list");
4866             tracksToRemove->add(t);
4867             continue;
4868         }
4869 
4870         Track* const track = t.get();
4871 #ifdef VERY_VERY_VERBOSE_LOGGING
4872         audio_track_cblk_t* cblk = track->cblk();
4873 #endif
4874         // Only consider last track started for volume and mixer state control.
4875         // In theory an older track could underrun and restart after the new one starts
4876         // but as we only care about the transition phase between two tracks on a
4877         // direct output, it is not a problem to ignore the underrun case.
4878         sp<Track> l = mLatestActiveTrack.promote();
4879         bool last = l.get() == track;
4880 
4881         if (track->isPausing()) {
4882             track->setPaused();
4883             if (mHwSupportsPause && last && !mHwPaused) {
4884                 doHwPause = true;
4885                 mHwPaused = true;
4886             }
4887             tracksToRemove->add(track);
4888         } else if (track->isFlushPending()) {
4889             track->flushAck();
4890             if (last) {
4891                 mFlushPending = true;
4892             }
4893         } else if (track->isResumePending()) {
4894             track->resumeAck();
4895             if (last) {
4896                 mLeftVolFloat = mRightVolFloat = -1.0;
4897                 if (mHwPaused) {
4898                     doHwResume = true;
4899                     mHwPaused = false;
4900                 }
4901             }
4902         }
4903 
4904         // The first time a track is added we wait
4905         // for all its buffers to be filled before processing it.
4906         // Allow draining the buffer in case the client
4907         // app does not call stop() and relies on underrun to stop:
4908         // hence the test on (track->mRetryCount > 1).
4909         // If retryCount<=1 then track is about to underrun and be removed.
4910         // Do not use a high threshold for compressed audio.
4911         uint32_t minFrames;
4912         if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4913             && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
4914             minFrames = mNormalFrameCount;
4915         } else {
4916             minFrames = 1;
4917         }
4918 
4919         if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4920                 !track->isStopping_2() && !track->isStopped())
4921         {
4922             ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
4923 
4924             if (track->mFillingUpStatus == Track::FS_FILLED) {
4925                 track->mFillingUpStatus = Track::FS_ACTIVE;
4926                 if (last) {
4927                     // make sure processVolume_l() will apply new volume even if 0
4928                     mLeftVolFloat = mRightVolFloat = -1.0;
4929                 }
4930                 if (!mHwSupportsPause) {
4931                     track->resumeAck();
4932                 }
4933             }
4934 
4935             // compute volume for this track
4936             processVolume_l(track, last);
4937             if (last) {
4938                 sp<Track> previousTrack = mPreviousTrack.promote();
4939                 if (previousTrack != 0) {
4940                     if (track != previousTrack.get()) {
4941                         // Flush any data still being written from last track
4942                         mBytesRemaining = 0;
4943                         // Invalidate previous track to force a seek when resuming.
4944                         previousTrack->invalidate();
4945                     }
4946                 }
4947                 mPreviousTrack = track;
4948 
4949                 // reset retry count
4950                 track->mRetryCount = kMaxTrackRetriesDirect;
4951                 mActiveTrack = t;
4952                 mixerStatus = MIXER_TRACKS_READY;
4953                 if (mHwPaused) {
4954                     doHwResume = true;
4955                     mHwPaused = false;
4956                 }
4957             }
4958         } else {
4959             // clear effect chain input buffer if the last active track started underruns
4960             // to avoid sending previous audio buffer again to effects
4961             if (!mEffectChains.isEmpty() && last) {
4962                 mEffectChains[0]->clearInputBuffer();
4963             }
4964             if (track->isStopping_1()) {
4965                 track->mState = TrackBase::STOPPING_2;
4966                 if (last && mHwPaused) {
4967                      doHwResume = true;
4968                      mHwPaused = false;
4969                  }
4970             }
4971             if ((track->sharedBuffer() != 0) || track->isStopped() ||
4972                     track->isStopping_2() || track->isPaused()) {
4973                 // We have consumed all the buffers of this track.
4974                 // Remove it from the list of active tracks.
4975                 size_t audioHALFrames;
4976                 if (audio_has_proportional_frames(mFormat)) {
4977                     audioHALFrames = (latency_l() * mSampleRate) / 1000;
4978                 } else {
4979                     audioHALFrames = 0;
4980                 }
4981 
4982                 int64_t framesWritten = mBytesWritten / mFrameSize;
4983                 if (mStandby || !last ||
4984                         track->presentationComplete(framesWritten, audioHALFrames)) {
4985                     if (track->isStopping_2()) {
4986                         track->mState = TrackBase::STOPPED;
4987                     }
4988                     if (track->isStopped()) {
4989                         track->reset();
4990                     }
4991                     tracksToRemove->add(track);
4992                 }
4993             } else {
4994                 // No buffers for this track. Give it a few chances to
4995                 // fill a buffer, then remove it from active list.
4996                 // Only consider last track started for mixer state control
4997                 if (--(track->mRetryCount) <= 0) {
4998                     ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
4999                     tracksToRemove->add(track);
5000                     // indicate to client process that the track was disabled because of underrun;
5001                     // it will then automatically call start() when data is available
5002                     track->disable();
5003                 } else if (last) {
5004                     ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5005                             "minFrames = %u, mFormat = %#x",
5006                             track->framesReady(), minFrames, mFormat);
5007                     mixerStatus = MIXER_TRACKS_ENABLED;
5008                     if (mHwSupportsPause && !mHwPaused && !mStandby) {
5009                         doHwPause = true;
5010                         mHwPaused = true;
5011                     }
5012                 }
5013             }
5014         }
5015     }
5016 
5017     // if an active track did not command a flush, check for pending flush on stopped tracks
5018     if (!mFlushPending) {
5019         for (size_t i = 0; i < mTracks.size(); i++) {
5020             if (mTracks[i]->isFlushPending()) {
5021                 mTracks[i]->flushAck();
5022                 mFlushPending = true;
5023             }
5024         }
5025     }
5026 
5027     // make sure the pause/flush/resume sequence is executed in the right order.
5028     // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5029     // before flush and then resume HW. This can happen in case of pause/flush/resume
5030     // if resume is received before pause is executed.
5031     if (mHwSupportsPause && !mStandby &&
5032             (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
5033         mOutput->stream->pause(mOutput->stream);
5034     }
5035     if (mFlushPending) {
5036         flushHw_l();
5037     }
5038     if (mHwSupportsPause && !mStandby && doHwResume) {
5039         mOutput->stream->resume(mOutput->stream);
5040     }
5041     // remove all the tracks that need to be...
5042     removeTracks_l(*tracksToRemove);
5043 
5044     return mixerStatus;
5045 }
5046 
threadLoop_mix()5047 void AudioFlinger::DirectOutputThread::threadLoop_mix()
5048 {
5049     size_t frameCount = mFrameCount;
5050     int8_t *curBuf = (int8_t *)mSinkBuffer;
5051     // output audio to hardware
5052     while (frameCount) {
5053         AudioBufferProvider::Buffer buffer;
5054         buffer.frameCount = frameCount;
5055         status_t status = mActiveTrack->getNextBuffer(&buffer);
5056         if (status != NO_ERROR || buffer.raw == NULL) {
5057             // no need to pad with 0 for compressed audio
5058             if (audio_has_proportional_frames(mFormat)) {
5059                 memset(curBuf, 0, frameCount * mFrameSize);
5060             }
5061             break;
5062         }
5063         memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5064         frameCount -= buffer.frameCount;
5065         curBuf += buffer.frameCount * mFrameSize;
5066         mActiveTrack->releaseBuffer(&buffer);
5067     }
5068     mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
5069     mSleepTimeUs = 0;
5070     mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5071     mActiveTrack.clear();
5072 }
5073 
threadLoop_sleepTime()5074 void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5075 {
5076     // do not write to HAL when paused
5077     if (mHwPaused || (usesHwAvSync() && mStandby)) {
5078         mSleepTimeUs = mIdleSleepTimeUs;
5079         return;
5080     }
5081     if (mSleepTimeUs == 0) {
5082         if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5083             mSleepTimeUs = mActiveSleepTimeUs;
5084         } else {
5085             mSleepTimeUs = mIdleSleepTimeUs;
5086         }
5087     } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
5088         memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
5089         mSleepTimeUs = 0;
5090     }
5091 }
5092 
threadLoop_exit()5093 void AudioFlinger::DirectOutputThread::threadLoop_exit()
5094 {
5095     {
5096         Mutex::Autolock _l(mLock);
5097         for (size_t i = 0; i < mTracks.size(); i++) {
5098             if (mTracks[i]->isFlushPending()) {
5099                 mTracks[i]->flushAck();
5100                 mFlushPending = true;
5101             }
5102         }
5103         if (mFlushPending) {
5104             flushHw_l();
5105         }
5106     }
5107     PlaybackThread::threadLoop_exit();
5108 }
5109 
5110 // must be called with thread mutex locked
shouldStandby_l()5111 bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5112 {
5113     bool trackPaused = false;
5114     bool trackStopped = false;
5115 
5116     if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5117         return !mStandby;
5118     }
5119 
5120     // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5121     // after a timeout and we will enter standby then.
5122     if (mTracks.size() > 0) {
5123         trackPaused = mTracks[mTracks.size() - 1]->isPaused();
5124         trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5125                            mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
5126     }
5127 
5128     return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
5129 }
5130 
5131 // 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)5132 int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
5133         audio_format_t format __unused, audio_session_t sessionId __unused)
5134 {
5135     return 0;
5136 }
5137 
5138 // deleteTrackName_l() must be called with ThreadBase::mLock held
deleteTrackName_l(int name __unused)5139 void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
5140 {
5141 }
5142 
5143 // checkForNewParameter_l() must be called with ThreadBase::mLock held
checkForNewParameter_l(const String8 & keyValuePair,status_t & status)5144 bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5145                                                               status_t& status)
5146 {
5147     bool reconfig = false;
5148     bool a2dpDeviceChanged = false;
5149 
5150     status = NO_ERROR;
5151 
5152     AudioParameter param = AudioParameter(keyValuePair);
5153     int value;
5154     if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5155         // forward device change to effects that have requested to be
5156         // aware of attached audio device.
5157         if (value != AUDIO_DEVICE_NONE) {
5158             a2dpDeviceChanged =
5159                     (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
5160             mOutDevice = value;
5161             for (size_t i = 0; i < mEffectChains.size(); i++) {
5162                 mEffectChains[i]->setDevice_l(mOutDevice);
5163             }
5164         }
5165     }
5166     if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5167         // do not accept frame count changes if tracks are open as the track buffer
5168         // size depends on frame count and correct behavior would not be garantied
5169         // if frame count is changed after track creation
5170         if (!mTracks.isEmpty()) {
5171             status = INVALID_OPERATION;
5172         } else {
5173             reconfig = true;
5174         }
5175     }
5176     if (status == NO_ERROR) {
5177         status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5178                                                 keyValuePair.string());
5179         if (!mStandby && status == INVALID_OPERATION) {
5180             mOutput->standby();
5181             mStandby = true;
5182             mBytesWritten = 0;
5183             status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5184                                                    keyValuePair.string());
5185         }
5186         if (status == NO_ERROR && reconfig) {
5187             readOutputParameters_l();
5188             sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5189         }
5190     }
5191 
5192     return reconfig || a2dpDeviceChanged;
5193 }
5194 
activeSleepTimeUs() const5195 uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5196 {
5197     uint32_t time;
5198     if (audio_has_proportional_frames(mFormat)) {
5199         time = PlaybackThread::activeSleepTimeUs();
5200     } else {
5201         time = kDirectMinSleepTimeUs;
5202     }
5203     return time;
5204 }
5205 
idleSleepTimeUs() const5206 uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5207 {
5208     uint32_t time;
5209     if (audio_has_proportional_frames(mFormat)) {
5210         time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5211     } else {
5212         time = kDirectMinSleepTimeUs;
5213     }
5214     return time;
5215 }
5216 
suspendSleepTimeUs() const5217 uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5218 {
5219     uint32_t time;
5220     if (audio_has_proportional_frames(mFormat)) {
5221         time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5222     } else {
5223         time = kDirectMinSleepTimeUs;
5224     }
5225     return time;
5226 }
5227 
cacheParameters_l()5228 void AudioFlinger::DirectOutputThread::cacheParameters_l()
5229 {
5230     PlaybackThread::cacheParameters_l();
5231 
5232     // use shorter standby delay as on normal output to release
5233     // hardware resources as soon as possible
5234     // no delay on outputs with HW A/V sync
5235     if (usesHwAvSync()) {
5236         mStandbyDelayNs = 0;
5237     } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
5238         mStandbyDelayNs = kOffloadStandbyDelayNs;
5239     } else {
5240         mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
5241     }
5242 }
5243 
flushHw_l()5244 void AudioFlinger::DirectOutputThread::flushHw_l()
5245 {
5246     mOutput->flush();
5247     mHwPaused = false;
5248     mFlushPending = false;
5249 }
5250 
5251 // ----------------------------------------------------------------------------
5252 
AsyncCallbackThread(const wp<AudioFlinger::PlaybackThread> & playbackThread)5253 AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
5254         const wp<AudioFlinger::PlaybackThread>& playbackThread)
5255     :   Thread(false /*canCallJava*/),
5256         mPlaybackThread(playbackThread),
5257         mWriteAckSequence(0),
5258         mDrainSequence(0),
5259         mAsyncError(false)
5260 {
5261 }
5262 
~AsyncCallbackThread()5263 AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5264 {
5265 }
5266 
onFirstRef()5267 void AudioFlinger::AsyncCallbackThread::onFirstRef()
5268 {
5269     run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5270 }
5271 
threadLoop()5272 bool AudioFlinger::AsyncCallbackThread::threadLoop()
5273 {
5274     while (!exitPending()) {
5275         uint32_t writeAckSequence;
5276         uint32_t drainSequence;
5277         bool asyncError;
5278 
5279         {
5280             Mutex::Autolock _l(mLock);
5281             while (!((mWriteAckSequence & 1) ||
5282                      (mDrainSequence & 1) ||
5283                      mAsyncError ||
5284                      exitPending())) {
5285                 mWaitWorkCV.wait(mLock);
5286             }
5287 
5288             if (exitPending()) {
5289                 break;
5290             }
5291             ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5292                   mWriteAckSequence, mDrainSequence);
5293             writeAckSequence = mWriteAckSequence;
5294             mWriteAckSequence &= ~1;
5295             drainSequence = mDrainSequence;
5296             mDrainSequence &= ~1;
5297             asyncError = mAsyncError;
5298             mAsyncError = false;
5299         }
5300         {
5301             sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5302             if (playbackThread != 0) {
5303                 if (writeAckSequence & 1) {
5304                     playbackThread->resetWriteBlocked(writeAckSequence >> 1);
5305                 }
5306                 if (drainSequence & 1) {
5307                     playbackThread->resetDraining(drainSequence >> 1);
5308                 }
5309                 if (asyncError) {
5310                     playbackThread->onAsyncError();
5311                 }
5312             }
5313         }
5314     }
5315     return false;
5316 }
5317 
exit()5318 void AudioFlinger::AsyncCallbackThread::exit()
5319 {
5320     ALOGV("AsyncCallbackThread::exit");
5321     Mutex::Autolock _l(mLock);
5322     requestExit();
5323     mWaitWorkCV.broadcast();
5324 }
5325 
setWriteBlocked(uint32_t sequence)5326 void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
5327 {
5328     Mutex::Autolock _l(mLock);
5329     // bit 0 is cleared
5330     mWriteAckSequence = sequence << 1;
5331 }
5332 
resetWriteBlocked()5333 void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5334 {
5335     Mutex::Autolock _l(mLock);
5336     // ignore unexpected callbacks
5337     if (mWriteAckSequence & 2) {
5338         mWriteAckSequence |= 1;
5339         mWaitWorkCV.signal();
5340     }
5341 }
5342 
setDraining(uint32_t sequence)5343 void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
5344 {
5345     Mutex::Autolock _l(mLock);
5346     // bit 0 is cleared
5347     mDrainSequence = sequence << 1;
5348 }
5349 
resetDraining()5350 void AudioFlinger::AsyncCallbackThread::resetDraining()
5351 {
5352     Mutex::Autolock _l(mLock);
5353     // ignore unexpected callbacks
5354     if (mDrainSequence & 2) {
5355         mDrainSequence |= 1;
5356         mWaitWorkCV.signal();
5357     }
5358 }
5359 
setAsyncError()5360 void AudioFlinger::AsyncCallbackThread::setAsyncError()
5361 {
5362     Mutex::Autolock _l(mLock);
5363     mAsyncError = true;
5364     mWaitWorkCV.signal();
5365 }
5366 
5367 
5368 // ----------------------------------------------------------------------------
OffloadThread(const sp<AudioFlinger> & audioFlinger,AudioStreamOut * output,audio_io_handle_t id,uint32_t device,bool systemReady)5369 AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
5370         AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5371     :   DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
5372         mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5373         mOffloadUnderrunPosition(~0LL)
5374 {
5375     //FIXME: mStandby should be set to true by ThreadBase constructor
5376     mStandby = true;
5377     mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
5378 }
5379 
threadLoop_exit()5380 void AudioFlinger::OffloadThread::threadLoop_exit()
5381 {
5382     if (mFlushPending || mHwPaused) {
5383         // If a flush is pending or track was paused, just discard buffered data
5384         flushHw_l();
5385     } else {
5386         mMixerStatus = MIXER_DRAIN_ALL;
5387         threadLoop_drain();
5388     }
5389     if (mUseAsyncWrite) {
5390         ALOG_ASSERT(mCallbackThread != 0);
5391         mCallbackThread->exit();
5392     }
5393     PlaybackThread::threadLoop_exit();
5394 }
5395 
prepareTracks_l(Vector<sp<Track>> * tracksToRemove)5396 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5397     Vector< sp<Track> > *tracksToRemove
5398 )
5399 {
5400     size_t count = mActiveTracks.size();
5401 
5402     mixer_state mixerStatus = MIXER_IDLE;
5403     bool doHwPause = false;
5404     bool doHwResume = false;
5405 
5406     ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
5407 
5408     // find out which tracks need to be processed
5409     for (size_t i = 0; i < count; i++) {
5410         sp<Track> t = mActiveTracks[i].promote();
5411         // The track died recently
5412         if (t == 0) {
5413             continue;
5414         }
5415         Track* const track = t.get();
5416 #ifdef VERY_VERY_VERBOSE_LOGGING
5417         audio_track_cblk_t* cblk = track->cblk();
5418 #endif
5419         // Only consider last track started for volume and mixer state control.
5420         // In theory an older track could underrun and restart after the new one starts
5421         // but as we only care about the transition phase between two tracks on a
5422         // direct output, it is not a problem to ignore the underrun case.
5423         sp<Track> l = mLatestActiveTrack.promote();
5424         bool last = l.get() == track;
5425 
5426         if (track->isInvalid()) {
5427             ALOGW("An invalidated track shouldn't be in active list");
5428             tracksToRemove->add(track);
5429             continue;
5430         }
5431 
5432         if (track->mState == TrackBase::IDLE) {
5433             ALOGW("An idle track shouldn't be in active list");
5434             continue;
5435         }
5436 
5437         if (track->isPausing()) {
5438             track->setPaused();
5439             if (last) {
5440                 if (mHwSupportsPause && !mHwPaused) {
5441                     doHwPause = true;
5442                     mHwPaused = true;
5443                 }
5444                 // If we were part way through writing the mixbuffer to
5445                 // the HAL we must save this until we resume
5446                 // BUG - this will be wrong if a different track is made active,
5447                 // in that case we want to discard the pending data in the
5448                 // mixbuffer and tell the client to present it again when the
5449                 // track is resumed
5450                 mPausedWriteLength = mCurrentWriteLength;
5451                 mPausedBytesRemaining = mBytesRemaining;
5452                 mBytesRemaining = 0;    // stop writing
5453             }
5454             tracksToRemove->add(track);
5455         } else if (track->isFlushPending()) {
5456             if (track->isStopping_1()) {
5457                 track->mRetryCount = kMaxTrackStopRetriesOffload;
5458             } else {
5459                 track->mRetryCount = kMaxTrackRetriesOffload;
5460             }
5461             track->flushAck();
5462             if (last) {
5463                 mFlushPending = true;
5464             }
5465         } else if (track->isResumePending()){
5466             track->resumeAck();
5467             if (last) {
5468                 if (mPausedBytesRemaining) {
5469                     // Need to continue write that was interrupted
5470                     mCurrentWriteLength = mPausedWriteLength;
5471                     mBytesRemaining = mPausedBytesRemaining;
5472                     mPausedBytesRemaining = 0;
5473                 }
5474                 if (mHwPaused) {
5475                     doHwResume = true;
5476                     mHwPaused = false;
5477                     // threadLoop_mix() will handle the case that we need to
5478                     // resume an interrupted write
5479                 }
5480                 // enable write to audio HAL
5481                 mSleepTimeUs = 0;
5482 
5483                 mLeftVolFloat = mRightVolFloat = -1.0;
5484 
5485                 // Do not handle new data in this iteration even if track->framesReady()
5486                 mixerStatus = MIXER_TRACKS_ENABLED;
5487             }
5488         }  else if (track->framesReady() && track->isReady() &&
5489                 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
5490             ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
5491             if (track->mFillingUpStatus == Track::FS_FILLED) {
5492                 track->mFillingUpStatus = Track::FS_ACTIVE;
5493                 if (last) {
5494                     // make sure processVolume_l() will apply new volume even if 0
5495                     mLeftVolFloat = mRightVolFloat = -1.0;
5496                 }
5497             }
5498 
5499             if (last) {
5500                 sp<Track> previousTrack = mPreviousTrack.promote();
5501                 if (previousTrack != 0) {
5502                     if (track != previousTrack.get()) {
5503                         // Flush any data still being written from last track
5504                         mBytesRemaining = 0;
5505                         if (mPausedBytesRemaining) {
5506                             // Last track was paused so we also need to flush saved
5507                             // mixbuffer state and invalidate track so that it will
5508                             // re-submit that unwritten data when it is next resumed
5509                             mPausedBytesRemaining = 0;
5510                             // Invalidate is a bit drastic - would be more efficient
5511                             // to have a flag to tell client that some of the
5512                             // previously written data was lost
5513                             previousTrack->invalidate();
5514                         }
5515                         // flush data already sent to the DSP if changing audio session as audio
5516                         // comes from a different source. Also invalidate previous track to force a
5517                         // seek when resuming.
5518                         if (previousTrack->sessionId() != track->sessionId()) {
5519                             previousTrack->invalidate();
5520                         }
5521                     }
5522                 }
5523                 mPreviousTrack = track;
5524                 // reset retry count
5525                 if (track->isStopping_1()) {
5526                     track->mRetryCount = kMaxTrackStopRetriesOffload;
5527                 } else {
5528                     track->mRetryCount = kMaxTrackRetriesOffload;
5529                 }
5530                 mActiveTrack = t;
5531                 mixerStatus = MIXER_TRACKS_READY;
5532             }
5533         } else {
5534             ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
5535             if (track->isStopping_1()) {
5536                 if (--(track->mRetryCount) <= 0) {
5537                     // Hardware buffer can hold a large amount of audio so we must
5538                     // wait for all current track's data to drain before we say
5539                     // that the track is stopped.
5540                     if (mBytesRemaining == 0) {
5541                         // Only start draining when all data in mixbuffer
5542                         // has been written
5543                         ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5544                         track->mState = TrackBase::STOPPING_2; // so presentation completes after
5545                         // drain do not drain if no data was ever sent to HAL (mStandby == true)
5546                         if (last && !mStandby) {
5547                             // do not modify drain sequence if we are already draining. This happens
5548                             // when resuming from pause after drain.
5549                             if ((mDrainSequence & 1) == 0) {
5550                                 mSleepTimeUs = 0;
5551                                 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5552                                 mixerStatus = MIXER_DRAIN_TRACK;
5553                                 mDrainSequence += 2;
5554                             }
5555                             if (mHwPaused) {
5556                                 // It is possible to move from PAUSED to STOPPING_1 without
5557                                 // a resume so we must ensure hardware is running
5558                                 doHwResume = true;
5559                                 mHwPaused = false;
5560                             }
5561                         }
5562                     }
5563                 } else if (last) {
5564                     ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5565                     mixerStatus = MIXER_TRACKS_ENABLED;
5566                 }
5567             } else if (track->isStopping_2()) {
5568                 // Drain has completed or we are in standby, signal presentation complete
5569                 if (!(mDrainSequence & 1) || !last || mStandby) {
5570                     track->mState = TrackBase::STOPPED;
5571                     size_t audioHALFrames =
5572                             (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5573                     int64_t framesWritten =
5574                             mBytesWritten / mOutput->getFrameSize();
5575                     track->presentationComplete(framesWritten, audioHALFrames);
5576                     track->reset();
5577                     tracksToRemove->add(track);
5578                 }
5579             } else {
5580                 // No buffers for this track. Give it a few chances to
5581                 // fill a buffer, then remove it from active list.
5582                 if (--(track->mRetryCount) <= 0) {
5583                     bool running = false;
5584                     if (mOutput->stream->get_presentation_position != nullptr) {
5585                         uint64_t position = 0;
5586                         struct timespec unused;
5587                         // The running check restarts the retry counter at least once.
5588                         int ret = mOutput->stream->get_presentation_position(
5589                                 mOutput->stream, &position, &unused);
5590                         if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5591                             running = true;
5592                             mOffloadUnderrunPosition = position;
5593                         }
5594                         ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5595                                 (long long)position, (long long)mOffloadUnderrunPosition);
5596                     }
5597                     if (running) { // still running, give us more time.
5598                         track->mRetryCount = kMaxTrackRetriesOffload;
5599                     } else {
5600                         ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5601                                 track->name());
5602                         tracksToRemove->add(track);
5603                         // indicate to client process that the track was disabled because of underrun;
5604                         // it will then automatically call start() when data is available
5605                         track->disable();
5606                     }
5607                 } else if (last){
5608                     mixerStatus = MIXER_TRACKS_ENABLED;
5609                 }
5610             }
5611         }
5612         // compute volume for this track
5613         processVolume_l(track, last);
5614     }
5615 
5616     // make sure the pause/flush/resume sequence is executed in the right order.
5617     // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5618     // before flush and then resume HW. This can happen in case of pause/flush/resume
5619     // if resume is received before pause is executed.
5620     if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
5621         mOutput->stream->pause(mOutput->stream);
5622     }
5623     if (mFlushPending) {
5624         flushHw_l();
5625     }
5626     if (!mStandby && doHwResume) {
5627         mOutput->stream->resume(mOutput->stream);
5628     }
5629 
5630     // remove all the tracks that need to be...
5631     removeTracks_l(*tracksToRemove);
5632 
5633     return mixerStatus;
5634 }
5635 
5636 // must be called with thread mutex locked
waitingAsyncCallback_l()5637 bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5638 {
5639     ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5640           mWriteAckSequence, mDrainSequence);
5641     if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
5642         return true;
5643     }
5644     return false;
5645 }
5646 
waitingAsyncCallback()5647 bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5648 {
5649     Mutex::Autolock _l(mLock);
5650     return waitingAsyncCallback_l();
5651 }
5652 
flushHw_l()5653 void AudioFlinger::OffloadThread::flushHw_l()
5654 {
5655     DirectOutputThread::flushHw_l();
5656     // Flush anything still waiting in the mixbuffer
5657     mCurrentWriteLength = 0;
5658     mBytesRemaining = 0;
5659     mPausedWriteLength = 0;
5660     mPausedBytesRemaining = 0;
5661     // reset bytes written count to reflect that DSP buffers are empty after flush.
5662     mBytesWritten = 0;
5663     mOffloadUnderrunPosition = ~0LL;
5664 
5665     if (mUseAsyncWrite) {
5666         // discard any pending drain or write ack by incrementing sequence
5667         mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5668         mDrainSequence = (mDrainSequence + 2) & ~1;
5669         ALOG_ASSERT(mCallbackThread != 0);
5670         mCallbackThread->setWriteBlocked(mWriteAckSequence);
5671         mCallbackThread->setDraining(mDrainSequence);
5672     }
5673 }
5674 
invalidateTracks(audio_stream_type_t streamType)5675 void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5676 {
5677     Mutex::Autolock _l(mLock);
5678     if (PlaybackThread::invalidateTracks_l(streamType)) {
5679         mFlushPending = true;
5680     }
5681 }
5682 
5683 // ----------------------------------------------------------------------------
5684 
DuplicatingThread(const sp<AudioFlinger> & audioFlinger,AudioFlinger::MixerThread * mainThread,audio_io_handle_t id,bool systemReady)5685 AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
5686         AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
5687     :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
5688                     systemReady, DUPLICATING),
5689         mWaitTimeMs(UINT_MAX)
5690 {
5691     addOutputTrack(mainThread);
5692 }
5693 
~DuplicatingThread()5694 AudioFlinger::DuplicatingThread::~DuplicatingThread()
5695 {
5696     for (size_t i = 0; i < mOutputTracks.size(); i++) {
5697         mOutputTracks[i]->destroy();
5698     }
5699 }
5700 
threadLoop_mix()5701 void AudioFlinger::DuplicatingThread::threadLoop_mix()
5702 {
5703     // mix buffers...
5704     if (outputsReady(outputTracks)) {
5705         mAudioMixer->process();
5706     } else {
5707         if (mMixerBufferValid) {
5708             memset(mMixerBuffer, 0, mMixerBufferSize);
5709         } else {
5710             memset(mSinkBuffer, 0, mSinkBufferSize);
5711         }
5712     }
5713     mSleepTimeUs = 0;
5714     writeFrames = mNormalFrameCount;
5715     mCurrentWriteLength = mSinkBufferSize;
5716     mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5717 }
5718 
threadLoop_sleepTime()5719 void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5720 {
5721     if (mSleepTimeUs == 0) {
5722         if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5723             mSleepTimeUs = mActiveSleepTimeUs;
5724         } else {
5725             mSleepTimeUs = mIdleSleepTimeUs;
5726         }
5727     } else if (mBytesWritten != 0) {
5728         if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5729             writeFrames = mNormalFrameCount;
5730             memset(mSinkBuffer, 0, mSinkBufferSize);
5731         } else {
5732             // flush remaining overflow buffers in output tracks
5733             writeFrames = 0;
5734         }
5735         mSleepTimeUs = 0;
5736     }
5737 }
5738 
threadLoop_write()5739 ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
5740 {
5741     for (size_t i = 0; i < outputTracks.size(); i++) {
5742         outputTracks[i]->write(mSinkBuffer, writeFrames);
5743     }
5744     mStandby = false;
5745     return (ssize_t)mSinkBufferSize;
5746 }
5747 
threadLoop_standby()5748 void AudioFlinger::DuplicatingThread::threadLoop_standby()
5749 {
5750     // DuplicatingThread implements standby by stopping all tracks
5751     for (size_t i = 0; i < outputTracks.size(); i++) {
5752         outputTracks[i]->stop();
5753     }
5754 }
5755 
saveOutputTracks()5756 void AudioFlinger::DuplicatingThread::saveOutputTracks()
5757 {
5758     outputTracks = mOutputTracks;
5759 }
5760 
clearOutputTracks()5761 void AudioFlinger::DuplicatingThread::clearOutputTracks()
5762 {
5763     outputTracks.clear();
5764 }
5765 
addOutputTrack(MixerThread * thread)5766 void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5767 {
5768     Mutex::Autolock _l(mLock);
5769     // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5770     // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5771     // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5772     const size_t frameCount =
5773             3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5774     // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5775     // from different OutputTracks and their associated MixerThreads (e.g. one may
5776     // nearly empty and the other may be dropping data).
5777 
5778     sp<OutputTrack> outputTrack = new OutputTrack(thread,
5779                                             this,
5780                                             mSampleRate,
5781                                             mFormat,
5782                                             mChannelMask,
5783                                             frameCount,
5784                                             IPCThreadState::self()->getCallingUid());
5785     status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5786     if (status != NO_ERROR) {
5787         ALOGE("addOutputTrack() initCheck failed %d", status);
5788         return;
5789     }
5790     thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5791     mOutputTracks.add(outputTrack);
5792     ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5793     updateWaitTime_l();
5794 }
5795 
removeOutputTrack(MixerThread * thread)5796 void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5797 {
5798     Mutex::Autolock _l(mLock);
5799     for (size_t i = 0; i < mOutputTracks.size(); i++) {
5800         if (mOutputTracks[i]->thread() == thread) {
5801             mOutputTracks[i]->destroy();
5802             mOutputTracks.removeAt(i);
5803             updateWaitTime_l();
5804             if (thread->getOutput() == mOutput) {
5805                 mOutput = NULL;
5806             }
5807             return;
5808         }
5809     }
5810     ALOGV("removeOutputTrack(): unknown thread: %p", thread);
5811 }
5812 
5813 // caller must hold mLock
updateWaitTime_l()5814 void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5815 {
5816     mWaitTimeMs = UINT_MAX;
5817     for (size_t i = 0; i < mOutputTracks.size(); i++) {
5818         sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5819         if (strong != 0) {
5820             uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5821             if (waitTimeMs < mWaitTimeMs) {
5822                 mWaitTimeMs = waitTimeMs;
5823             }
5824         }
5825     }
5826 }
5827 
5828 
outputsReady(const SortedVector<sp<OutputTrack>> & outputTracks)5829 bool AudioFlinger::DuplicatingThread::outputsReady(
5830         const SortedVector< sp<OutputTrack> > &outputTracks)
5831 {
5832     for (size_t i = 0; i < outputTracks.size(); i++) {
5833         sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5834         if (thread == 0) {
5835             ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5836                     outputTracks[i].get());
5837             return false;
5838         }
5839         PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5840         // see note at standby() declaration
5841         if (playbackThread->standby() && !playbackThread->isSuspended()) {
5842             ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5843                     thread.get());
5844             return false;
5845         }
5846     }
5847     return true;
5848 }
5849 
activeSleepTimeUs() const5850 uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5851 {
5852     return (mWaitTimeMs * 1000) / 2;
5853 }
5854 
cacheParameters_l()5855 void AudioFlinger::DuplicatingThread::cacheParameters_l()
5856 {
5857     // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5858     updateWaitTime_l();
5859 
5860     MixerThread::cacheParameters_l();
5861 }
5862 
5863 // ----------------------------------------------------------------------------
5864 //      Record
5865 // ----------------------------------------------------------------------------
5866 
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)5867 AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5868                                          AudioStreamIn *input,
5869                                          audio_io_handle_t id,
5870                                          audio_devices_t outDevice,
5871                                          audio_devices_t inDevice,
5872                                          bool systemReady
5873 #ifdef TEE_SINK
5874                                          , const sp<NBAIO_Sink>& teeSink
5875 #endif
5876                                          ) :
5877     ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
5878     mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
5879     // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
5880     mRsmpInRear(0)
5881 #ifdef TEE_SINK
5882     , mTeeSink(teeSink)
5883 #endif
5884     , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5885             "RecordThreadRO", MemoryHeapBase::READ_ONLY))
5886     // mFastCapture below
5887     , mFastCaptureFutex(0)
5888     // mInputSource
5889     // mPipeSink
5890     // mPipeSource
5891     , mPipeFramesP2(0)
5892     // mPipeMemory
5893     // mFastCaptureNBLogWriter
5894     , mFastTrackAvail(false)
5895 {
5896     snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5897     mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
5898 
5899     readInputParameters_l();
5900 
5901     // create an NBAIO source for the HAL input stream, and negotiate
5902     mInputSource = new AudioStreamInSource(input->stream);
5903     size_t numCounterOffers = 0;
5904     const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5905 #if !LOG_NDEBUG
5906     ssize_t index =
5907 #else
5908     (void)
5909 #endif
5910             mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5911     ALOG_ASSERT(index == 0);
5912 
5913     // initialize fast capture depending on configuration
5914     bool initFastCapture;
5915     switch (kUseFastCapture) {
5916     case FastCapture_Never:
5917         initFastCapture = false;
5918         break;
5919     case FastCapture_Always:
5920         initFastCapture = true;
5921         break;
5922     case FastCapture_Static:
5923         initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
5924         break;
5925     // case FastCapture_Dynamic:
5926     }
5927 
5928     if (initFastCapture) {
5929         // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
5930         NBAIO_Format format = mInputSource->format();
5931         size_t pipeFramesP2 = roundup(mSampleRate / 25);    // double-buffering of 20 ms each
5932         size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5933         void *pipeBuffer;
5934         const sp<MemoryDealer> roHeap(readOnlyHeap());
5935         sp<IMemory> pipeMemory;
5936         if ((roHeap == 0) ||
5937                 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5938                 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5939             ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5940             goto failed;
5941         }
5942         // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5943         memset(pipeBuffer, 0, pipeSize);
5944         Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5945         const NBAIO_Format offers[1] = {format};
5946         size_t numCounterOffers = 0;
5947         ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5948         ALOG_ASSERT(index == 0);
5949         mPipeSink = pipe;
5950         PipeReader *pipeReader = new PipeReader(*pipe);
5951         numCounterOffers = 0;
5952         index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5953         ALOG_ASSERT(index == 0);
5954         mPipeSource = pipeReader;
5955         mPipeFramesP2 = pipeFramesP2;
5956         mPipeMemory = pipeMemory;
5957 
5958         // create fast capture
5959         mFastCapture = new FastCapture();
5960         FastCaptureStateQueue *sq = mFastCapture->sq();
5961 #ifdef STATE_QUEUE_DUMP
5962         // FIXME
5963 #endif
5964         FastCaptureState *state = sq->begin();
5965         state->mCblk = NULL;
5966         state->mInputSource = mInputSource.get();
5967         state->mInputSourceGen++;
5968         state->mPipeSink = pipe;
5969         state->mPipeSinkGen++;
5970         state->mFrameCount = mFrameCount;
5971         state->mCommand = FastCaptureState::COLD_IDLE;
5972         // already done in constructor initialization list
5973         //mFastCaptureFutex = 0;
5974         state->mColdFutexAddr = &mFastCaptureFutex;
5975         state->mColdGen++;
5976         state->mDumpState = &mFastCaptureDumpState;
5977 #ifdef TEE_SINK
5978         // FIXME
5979 #endif
5980         mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5981         state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5982         sq->end();
5983         sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5984 
5985         // start the fast capture
5986         mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5987         pid_t tid = mFastCapture->getTid();
5988         sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
5989 #ifdef AUDIO_WATCHDOG
5990         // FIXME
5991 #endif
5992 
5993         mFastTrackAvail = true;
5994     }
5995 failed: ;
5996 
5997     // FIXME mNormalSource
5998 }
5999 
~RecordThread()6000 AudioFlinger::RecordThread::~RecordThread()
6001 {
6002     if (mFastCapture != 0) {
6003         FastCaptureStateQueue *sq = mFastCapture->sq();
6004         FastCaptureState *state = sq->begin();
6005         if (state->mCommand == FastCaptureState::COLD_IDLE) {
6006             int32_t old = android_atomic_inc(&mFastCaptureFutex);
6007             if (old == -1) {
6008                 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6009             }
6010         }
6011         state->mCommand = FastCaptureState::EXIT;
6012         sq->end();
6013         sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6014         mFastCapture->join();
6015         mFastCapture.clear();
6016     }
6017     mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
6018     mAudioFlinger->unregisterWriter(mNBLogWriter);
6019     free(mRsmpInBuffer);
6020 }
6021 
onFirstRef()6022 void AudioFlinger::RecordThread::onFirstRef()
6023 {
6024     run(mThreadName, PRIORITY_URGENT_AUDIO);
6025 }
6026 
threadLoop()6027 bool AudioFlinger::RecordThread::threadLoop()
6028 {
6029     nsecs_t lastWarning = 0;
6030 
6031     inputStandBy();
6032 
6033 reacquire_wakelock:
6034     sp<RecordTrack> activeTrack;
6035     int activeTracksGen;
6036     {
6037         Mutex::Autolock _l(mLock);
6038         size_t size = mActiveTracks.size();
6039         activeTracksGen = mActiveTracksGen;
6040         if (size > 0) {
6041             // FIXME an arbitrary choice
6042             activeTrack = mActiveTracks[0];
6043             acquireWakeLock_l(activeTrack->uid());
6044             if (size > 1) {
6045                 SortedVector<int> tmp;
6046                 for (size_t i = 0; i < size; i++) {
6047                     tmp.add(mActiveTracks[i]->uid());
6048                 }
6049                 updateWakeLockUids_l(tmp);
6050             }
6051         } else {
6052             acquireWakeLock_l(-1);
6053         }
6054     }
6055 
6056     // used to request a deferred sleep, to be executed later while mutex is unlocked
6057     uint32_t sleepUs = 0;
6058 
6059     // loop while there is work to do
6060     for (;;) {
6061         Vector< sp<EffectChain> > effectChains;
6062 
6063         // activeTracks accumulates a copy of a subset of mActiveTracks
6064         Vector< sp<RecordTrack> > activeTracks;
6065 
6066         // reference to the (first and only) active fast track
6067         sp<RecordTrack> fastTrack;
6068 
6069         // reference to a fast track which is about to be removed
6070         sp<RecordTrack> fastTrackToRemove;
6071 
6072         { // scope for mLock
6073             Mutex::Autolock _l(mLock);
6074 
6075             processConfigEvents_l();
6076 
6077             // check exitPending here because checkForNewParameters_l() and
6078             // checkForNewParameters_l() can temporarily release mLock
6079             if (exitPending()) {
6080                 break;
6081             }
6082 
6083             // sleep with mutex unlocked
6084             if (sleepUs > 0) {
6085                 ATRACE_BEGIN("sleepC");
6086                 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6087                 ATRACE_END();
6088                 sleepUs = 0;
6089                 continue;
6090             }
6091 
6092             // if no active track(s), then standby and release wakelock
6093             size_t size = mActiveTracks.size();
6094             if (size == 0) {
6095                 standbyIfNotAlreadyInStandby();
6096                 // exitPending() can't become true here
6097                 releaseWakeLock_l();
6098                 ALOGV("RecordThread: loop stopping");
6099                 // go to sleep
6100                 mWaitWorkCV.wait(mLock);
6101                 ALOGV("RecordThread: loop starting");
6102                 goto reacquire_wakelock;
6103             }
6104 
6105             if (mActiveTracksGen != activeTracksGen) {
6106                 activeTracksGen = mActiveTracksGen;
6107                 SortedVector<int> tmp;
6108                 for (size_t i = 0; i < size; i++) {
6109                     tmp.add(mActiveTracks[i]->uid());
6110                 }
6111                 updateWakeLockUids_l(tmp);
6112             }
6113 
6114             bool doBroadcast = false;
6115             bool allStopped = true;
6116             for (size_t i = 0; i < size; ) {
6117 
6118                 activeTrack = mActiveTracks[i];
6119                 if (activeTrack->isTerminated()) {
6120                     if (activeTrack->isFastTrack()) {
6121                         ALOG_ASSERT(fastTrackToRemove == 0);
6122                         fastTrackToRemove = activeTrack;
6123                     }
6124                     removeTrack_l(activeTrack);
6125                     mActiveTracks.remove(activeTrack);
6126                     mActiveTracksGen++;
6127                     size--;
6128                     continue;
6129                 }
6130 
6131                 TrackBase::track_state activeTrackState = activeTrack->mState;
6132                 switch (activeTrackState) {
6133 
6134                 case TrackBase::PAUSING:
6135                     mActiveTracks.remove(activeTrack);
6136                     mActiveTracksGen++;
6137                     doBroadcast = true;
6138                     size--;
6139                     continue;
6140 
6141                 case TrackBase::STARTING_1:
6142                     sleepUs = 10000;
6143                     i++;
6144                     allStopped = false;
6145                     continue;
6146 
6147                 case TrackBase::STARTING_2:
6148                     doBroadcast = true;
6149                     mStandby = false;
6150                     activeTrack->mState = TrackBase::ACTIVE;
6151                     allStopped = false;
6152                     break;
6153 
6154                 case TrackBase::ACTIVE:
6155                     allStopped = false;
6156                     break;
6157 
6158                 case TrackBase::IDLE:
6159                     i++;
6160                     continue;
6161 
6162                 default:
6163                     LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
6164                 }
6165 
6166                 activeTracks.add(activeTrack);
6167                 i++;
6168 
6169                 if (activeTrack->isFastTrack()) {
6170                     ALOG_ASSERT(!mFastTrackAvail);
6171                     ALOG_ASSERT(fastTrack == 0);
6172                     fastTrack = activeTrack;
6173                 }
6174             }
6175 
6176             if (allStopped) {
6177                 standbyIfNotAlreadyInStandby();
6178             }
6179             if (doBroadcast) {
6180                 mStartStopCond.broadcast();
6181             }
6182 
6183             // sleep if there are no active tracks to process
6184             if (activeTracks.size() == 0) {
6185                 if (sleepUs == 0) {
6186                     sleepUs = kRecordThreadSleepUs;
6187                 }
6188                 continue;
6189             }
6190             sleepUs = 0;
6191 
6192             lockEffectChains_l(effectChains);
6193         }
6194 
6195         // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
6196 
6197         size_t size = effectChains.size();
6198         for (size_t i = 0; i < size; i++) {
6199             // thread mutex is not locked, but effect chain is locked
6200             effectChains[i]->process_l();
6201         }
6202 
6203         // Push a new fast capture state if fast capture is not already running, or cblk change
6204         if (mFastCapture != 0) {
6205             FastCaptureStateQueue *sq = mFastCapture->sq();
6206             FastCaptureState *state = sq->begin();
6207             bool didModify = false;
6208             FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
6209             if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6210                     (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6211                 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6212                     int32_t old = android_atomic_inc(&mFastCaptureFutex);
6213                     if (old == -1) {
6214                         (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6215                     }
6216                 }
6217                 state->mCommand = FastCaptureState::READ_WRITE;
6218 #if 0   // FIXME
6219                 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
6220                         FastThreadDumpState::kSamplingNforLowRamDevice :
6221                         FastThreadDumpState::kSamplingN);
6222 #endif
6223                 didModify = true;
6224             }
6225             audio_track_cblk_t *cblkOld = state->mCblk;
6226             audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6227             if (cblkNew != cblkOld) {
6228                 state->mCblk = cblkNew;
6229                 // block until acked if removing a fast track
6230                 if (cblkOld != NULL) {
6231                     block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6232                 }
6233                 didModify = true;
6234             }
6235             sq->end(didModify);
6236             if (didModify) {
6237                 sq->push(block);
6238 #if 0
6239                 if (kUseFastCapture == FastCapture_Dynamic) {
6240                     mNormalSource = mPipeSource;
6241                 }
6242 #endif
6243             }
6244         }
6245 
6246         // now run the fast track destructor with thread mutex unlocked
6247         fastTrackToRemove.clear();
6248 
6249         // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6250         // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6251         // slow, then this RecordThread will overrun by not calling HAL read often enough.
6252         // If destination is non-contiguous, first read past the nominal end of buffer, then
6253         // copy to the right place.  Permitted because mRsmpInBuffer was over-allocated.
6254 
6255         int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
6256         ssize_t framesRead;
6257 
6258         // If an NBAIO source is present, use it to read the normal capture's data
6259         if (mPipeSource != 0) {
6260             size_t framesToRead = mBufferSize / mFrameSize;
6261             framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6262                     framesToRead);
6263             if (framesRead == 0) {
6264                 // since pipe is non-blocking, simulate blocking input
6265                 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6266             }
6267         // otherwise use the HAL / AudioStreamIn directly
6268         } else {
6269             ATRACE_BEGIN("read");
6270             ssize_t bytesRead = mInput->stream->read(mInput->stream,
6271                     (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
6272             ATRACE_END();
6273             if (bytesRead < 0) {
6274                 framesRead = bytesRead;
6275             } else {
6276                 framesRead = bytesRead / mFrameSize;
6277             }
6278         }
6279 
6280         // Update server timestamp with server stats
6281         // systemTime() is optional if the hardware supports timestamps.
6282         mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6283         mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6284 
6285         // Update server timestamp with kernel stats
6286         if (mInput->stream->get_capture_position != nullptr
6287                 && mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
6288             int64_t position, time;
6289             int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6290             if (ret == NO_ERROR) {
6291                 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6292                 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6293                 // Note: In general record buffers should tend to be empty in
6294                 // a properly running pipeline.
6295                 //
6296                 // Also, it is not advantageous to call get_presentation_position during the read
6297                 // as the read obtains a lock, preventing the timestamp call from executing.
6298             }
6299         }
6300         // Use this to track timestamp information
6301         // ALOGD("%s", mTimestamp.toString().c_str());
6302 
6303         if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
6304             ALOGE("read failed: framesRead=%zd", framesRead);
6305             // Force input into standby so that it tries to recover at next read attempt
6306             inputStandBy();
6307             sleepUs = kRecordThreadSleepUs;
6308         }
6309         if (framesRead <= 0) {
6310             goto unlock;
6311         }
6312         ALOG_ASSERT(framesRead > 0);
6313 
6314         if (mTeeSink != 0) {
6315             (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6316         }
6317         // If destination is non-contiguous, we now correct for reading past end of buffer.
6318         {
6319             size_t part1 = mRsmpInFramesP2 - rear;
6320             if ((size_t) framesRead > part1) {
6321                 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
6322                         (framesRead - part1) * mFrameSize);
6323             }
6324         }
6325         rear = mRsmpInRear += framesRead;
6326 
6327         size = activeTracks.size();
6328         // loop over each active track
6329         for (size_t i = 0; i < size; i++) {
6330             activeTrack = activeTracks[i];
6331 
6332             // skip fast tracks, as those are handled directly by FastCapture
6333             if (activeTrack->isFastTrack()) {
6334                 continue;
6335             }
6336 
6337             // TODO: This code probably should be moved to RecordTrack.
6338             // TODO: Update the activeTrack buffer converter in case of reconfigure.
6339 
6340             enum {
6341                 OVERRUN_UNKNOWN,
6342                 OVERRUN_TRUE,
6343                 OVERRUN_FALSE
6344             } overrun = OVERRUN_UNKNOWN;
6345 
6346             // loop over getNextBuffer to handle circular sink
6347             for (;;) {
6348 
6349                 activeTrack->mSink.frameCount = ~0;
6350                 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6351                 size_t framesOut = activeTrack->mSink.frameCount;
6352                 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6353 
6354                 // check available frames and handle overrun conditions
6355                 // if the record track isn't draining fast enough.
6356                 bool hasOverrun;
6357                 size_t framesIn;
6358                 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6359                 if (hasOverrun) {
6360                     overrun = OVERRUN_TRUE;
6361                 }
6362                 if (framesOut == 0 || framesIn == 0) {
6363                     break;
6364                 }
6365 
6366                 // Don't allow framesOut to be larger than what is possible with resampling
6367                 // from framesIn.
6368                 // This isn't strictly necessary but helps limit buffer resizing in
6369                 // RecordBufferConverter.  TODO: remove when no longer needed.
6370                 framesOut = min(framesOut,
6371                         destinationFramesPossible(
6372                                 framesIn, mSampleRate, activeTrack->mSampleRate));
6373                 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6374                 framesOut = activeTrack->mRecordBufferConverter->convert(
6375                         activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
6376 
6377                 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6378                     overrun = OVERRUN_FALSE;
6379                 }
6380 
6381                 if (activeTrack->mFramesToDrop == 0) {
6382                     if (framesOut > 0) {
6383                         activeTrack->mSink.frameCount = framesOut;
6384                         activeTrack->releaseBuffer(&activeTrack->mSink);
6385                     }
6386                 } else {
6387                     // FIXME could do a partial drop of framesOut
6388                     if (activeTrack->mFramesToDrop > 0) {
6389                         activeTrack->mFramesToDrop -= framesOut;
6390                         if (activeTrack->mFramesToDrop <= 0) {
6391                             activeTrack->clearSyncStartEvent();
6392                         }
6393                     } else {
6394                         activeTrack->mFramesToDrop += framesOut;
6395                         if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6396                                 activeTrack->mSyncStartEvent->isCancelled()) {
6397                             ALOGW("Synced record %s, session %d, trigger session %d",
6398                                   (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6399                                   activeTrack->sessionId(),
6400                                   (activeTrack->mSyncStartEvent != 0) ?
6401                                           activeTrack->mSyncStartEvent->triggerSession() :
6402                                           AUDIO_SESSION_NONE);
6403                             activeTrack->clearSyncStartEvent();
6404                         }
6405                     }
6406                 }
6407 
6408                 if (framesOut == 0) {
6409                     break;
6410                 }
6411             }
6412 
6413             switch (overrun) {
6414             case OVERRUN_TRUE:
6415                 // client isn't retrieving buffers fast enough
6416                 if (!activeTrack->setOverflow()) {
6417                     nsecs_t now = systemTime();
6418                     // FIXME should lastWarning per track?
6419                     if ((now - lastWarning) > kWarningThrottleNs) {
6420                         ALOGW("RecordThread: buffer overflow");
6421                         lastWarning = now;
6422                     }
6423                 }
6424                 break;
6425             case OVERRUN_FALSE:
6426                 activeTrack->clearOverflow();
6427                 break;
6428             case OVERRUN_UNKNOWN:
6429                 break;
6430             }
6431 
6432             // update frame information and push timestamp out
6433             activeTrack->updateTrackFrameInfo(
6434                     activeTrack->mServerProxy->framesReleased(),
6435                     mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6436                     mSampleRate, mTimestamp);
6437         }
6438 
6439 unlock:
6440         // enable changes in effect chain
6441         unlockEffectChains(effectChains);
6442         // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
6443     }
6444 
6445     standbyIfNotAlreadyInStandby();
6446 
6447     {
6448         Mutex::Autolock _l(mLock);
6449         for (size_t i = 0; i < mTracks.size(); i++) {
6450             sp<RecordTrack> track = mTracks[i];
6451             track->invalidate();
6452         }
6453         mActiveTracks.clear();
6454         mActiveTracksGen++;
6455         mStartStopCond.broadcast();
6456     }
6457 
6458     releaseWakeLock();
6459 
6460     ALOGV("RecordThread %p exiting", this);
6461     return false;
6462 }
6463 
standbyIfNotAlreadyInStandby()6464 void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
6465 {
6466     if (!mStandby) {
6467         inputStandBy();
6468         mStandby = true;
6469     }
6470 }
6471 
inputStandBy()6472 void AudioFlinger::RecordThread::inputStandBy()
6473 {
6474     // Idle the fast capture if it's currently running
6475     if (mFastCapture != 0) {
6476         FastCaptureStateQueue *sq = mFastCapture->sq();
6477         FastCaptureState *state = sq->begin();
6478         if (!(state->mCommand & FastCaptureState::IDLE)) {
6479             state->mCommand = FastCaptureState::COLD_IDLE;
6480             state->mColdFutexAddr = &mFastCaptureFutex;
6481             state->mColdGen++;
6482             mFastCaptureFutex = 0;
6483             sq->end();
6484             // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6485             sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6486 #if 0
6487             if (kUseFastCapture == FastCapture_Dynamic) {
6488                 // FIXME
6489             }
6490 #endif
6491 #ifdef AUDIO_WATCHDOG
6492             // FIXME
6493 #endif
6494         } else {
6495             sq->end(false /*didModify*/);
6496         }
6497     }
6498     mInput->stream->common.standby(&mInput->stream->common);
6499 }
6500 
6501 // 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,audio_input_flags_t * flags,pid_t tid,status_t * status)6502 sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6503         const sp<AudioFlinger::Client>& client,
6504         uint32_t sampleRate,
6505         audio_format_t format,
6506         audio_channel_mask_t channelMask,
6507         size_t *pFrameCount,
6508         audio_session_t sessionId,
6509         size_t *notificationFrames,
6510         int uid,
6511         audio_input_flags_t *flags,
6512         pid_t tid,
6513         status_t *status)
6514 {
6515     size_t frameCount = *pFrameCount;
6516     sp<RecordTrack> track;
6517     status_t lStatus;
6518     audio_input_flags_t inputFlags = mInput->flags;
6519 
6520     // special case for FAST flag considered OK if fast capture is present
6521     if (hasFastCapture()) {
6522         inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6523     }
6524 
6525     // Check if requested flags are compatible with output stream flags
6526     if ((*flags & inputFlags) != *flags) {
6527         ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6528                 " input flags (%08x)",
6529               *flags, inputFlags);
6530         *flags = (audio_input_flags_t)(*flags & inputFlags);
6531     }
6532 
6533     // client expresses a preference for FAST, but we get the final say
6534     if (*flags & AUDIO_INPUT_FLAG_FAST) {
6535       if (
6536             // we formerly checked for a callback handler (non-0 tid),
6537             // but that is no longer required for TRANSFER_OBTAIN mode
6538             //
6539             // frame count is not specified, or is exactly the pipe depth
6540             ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
6541             // PCM data
6542             audio_is_linear_pcm(format) &&
6543             // hardware format
6544             (format == mFormat) &&
6545             // hardware channel mask
6546             (channelMask == mChannelMask) &&
6547             // hardware sample rate
6548             (sampleRate == mSampleRate) &&
6549             // record thread has an associated fast capture
6550             hasFastCapture() &&
6551             // there are sufficient fast track slots available
6552             mFastTrackAvail
6553         ) {
6554           // check compatibility with audio effects.
6555           Mutex::Autolock _l(mLock);
6556           // Do not accept FAST flag if the session has software effects
6557           sp<EffectChain> chain = getEffectChain_l(sessionId);
6558           if (chain != 0) {
6559               ALOGV_IF((*flags & AUDIO_INPUT_FLAG_RAW) != 0,
6560                       "AUDIO_INPUT_FLAG_RAW denied: effect present on session");
6561               *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
6562               if (chain->hasSoftwareEffect()) {
6563                   ALOGV("AUDIO_INPUT_FLAG_FAST denied: software effect present on session");
6564                   *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
6565               }
6566           }
6567           ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
6568                    "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6569                    frameCount, mFrameCount);
6570       } else {
6571         ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6572                 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
6573                 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
6574                 frameCount, mFrameCount, mPipeFramesP2,
6575                 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6576                 hasFastCapture(), tid, mFastTrackAvail);
6577         *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
6578       }
6579     }
6580 
6581     // compute track buffer size in frames, and suggest the notification frame count
6582     if (*flags & AUDIO_INPUT_FLAG_FAST) {
6583         // fast track: frame count is exactly the pipe depth
6584         frameCount = mPipeFramesP2;
6585         // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6586         *notificationFrames = mFrameCount;
6587     } else {
6588         // not fast track: max notification period is resampled equivalent of one HAL buffer time
6589         //                 or 20 ms if there is a fast capture
6590         // TODO This could be a roundupRatio inline, and const
6591         size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6592                 * sampleRate + mSampleRate - 1) / mSampleRate;
6593         // minimum number of notification periods is at least kMinNotifications,
6594         // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6595         static const size_t kMinNotifications = 3;
6596         static const uint32_t kMinMs = 30;
6597         // TODO This could be a roundupRatio inline
6598         const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6599         // TODO This could be a roundupRatio inline
6600         const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6601                 maxNotificationFrames;
6602         const size_t minFrameCount = maxNotificationFrames *
6603                 max(kMinNotifications, minNotificationsByMs);
6604         frameCount = max(frameCount, minFrameCount);
6605         if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6606             *notificationFrames = maxNotificationFrames;
6607         }
6608     }
6609     *pFrameCount = frameCount;
6610 
6611     lStatus = initCheck();
6612     if (lStatus != NO_ERROR) {
6613         ALOGE("createRecordTrack_l() audio driver not initialized");
6614         goto Exit;
6615     }
6616 
6617     { // scope for mLock
6618         Mutex::Autolock _l(mLock);
6619 
6620         track = new RecordTrack(this, client, sampleRate,
6621                       format, channelMask, frameCount, NULL, sessionId, uid,
6622                       *flags, TrackBase::TYPE_DEFAULT);
6623 
6624         lStatus = track->initCheck();
6625         if (lStatus != NO_ERROR) {
6626             ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
6627             // track must be cleared from the caller as the caller has the AF lock
6628             goto Exit;
6629         }
6630         mTracks.add(track);
6631 
6632         // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6633         bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6634                         mAudioFlinger->btNrecIsOff();
6635         setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6636         setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
6637 
6638         if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
6639             pid_t callingPid = IPCThreadState::self()->getCallingPid();
6640             // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6641             // so ask activity manager to do this on our behalf
6642             sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6643         }
6644     }
6645 
6646     lStatus = NO_ERROR;
6647 
6648 Exit:
6649     *status = lStatus;
6650     return track;
6651 }
6652 
start(RecordThread::RecordTrack * recordTrack,AudioSystem::sync_event_t event,audio_session_t triggerSession)6653 status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6654                                            AudioSystem::sync_event_t event,
6655                                            audio_session_t triggerSession)
6656 {
6657     ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6658     sp<ThreadBase> strongMe = this;
6659     status_t status = NO_ERROR;
6660 
6661     if (event == AudioSystem::SYNC_EVENT_NONE) {
6662         recordTrack->clearSyncStartEvent();
6663     } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6664         recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6665                                        triggerSession,
6666                                        recordTrack->sessionId(),
6667                                        syncStartEventCallback,
6668                                        recordTrack);
6669         // Sync event can be cancelled by the trigger session if the track is not in a
6670         // compatible state in which case we start record immediately
6671         if (recordTrack->mSyncStartEvent->isCancelled()) {
6672             recordTrack->clearSyncStartEvent();
6673         } else {
6674             // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6675             recordTrack->mFramesToDrop = -
6676                     ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
6677         }
6678     }
6679 
6680     {
6681         // This section is a rendezvous between binder thread executing start() and RecordThread
6682         AutoMutex lock(mLock);
6683         if (mActiveTracks.indexOf(recordTrack) >= 0) {
6684             if (recordTrack->mState == TrackBase::PAUSING) {
6685                 ALOGV("active record track PAUSING -> ACTIVE");
6686                 recordTrack->mState = TrackBase::ACTIVE;
6687             } else {
6688                 ALOGV("active record track state %d", recordTrack->mState);
6689             }
6690             return status;
6691         }
6692 
6693         // TODO consider other ways of handling this, such as changing the state to :STARTING and
6694         //      adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6695         //      or using a separate command thread
6696         recordTrack->mState = TrackBase::STARTING_1;
6697         mActiveTracks.add(recordTrack);
6698         mActiveTracksGen++;
6699         status_t status = NO_ERROR;
6700         if (recordTrack->isExternalTrack()) {
6701             mLock.unlock();
6702             status = AudioSystem::startInput(mId, recordTrack->sessionId());
6703             mLock.lock();
6704             // FIXME should verify that recordTrack is still in mActiveTracks
6705             if (status != NO_ERROR) {
6706                 mActiveTracks.remove(recordTrack);
6707                 mActiveTracksGen++;
6708                 recordTrack->clearSyncStartEvent();
6709                 ALOGV("RecordThread::start error %d", status);
6710                 return status;
6711             }
6712         }
6713         // Catch up with current buffer indices if thread is already running.
6714         // This is what makes a new client discard all buffered data.  If the track's mRsmpInFront
6715         // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6716         // see previously buffered data before it called start(), but with greater risk of overrun.
6717 
6718         recordTrack->mResamplerBufferProvider->reset();
6719         // clear any converter state as new data will be discontinuous
6720         recordTrack->mRecordBufferConverter->reset();
6721         recordTrack->mState = TrackBase::STARTING_2;
6722         // signal thread to start
6723         mWaitWorkCV.broadcast();
6724         if (mActiveTracks.indexOf(recordTrack) < 0) {
6725             ALOGV("Record failed to start");
6726             status = BAD_VALUE;
6727             goto startError;
6728         }
6729         return status;
6730     }
6731 
6732 startError:
6733     if (recordTrack->isExternalTrack()) {
6734         AudioSystem::stopInput(mId, recordTrack->sessionId());
6735     }
6736     recordTrack->clearSyncStartEvent();
6737     // FIXME I wonder why we do not reset the state here?
6738     return status;
6739 }
6740 
syncStartEventCallback(const wp<SyncEvent> & event)6741 void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6742 {
6743     sp<SyncEvent> strongEvent = event.promote();
6744 
6745     if (strongEvent != 0) {
6746         sp<RefBase> ptr = strongEvent->cookie().promote();
6747         if (ptr != 0) {
6748             RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6749             recordTrack->handleSyncStartEvent(strongEvent);
6750         }
6751     }
6752 }
6753 
stop(RecordThread::RecordTrack * recordTrack)6754 bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
6755     ALOGV("RecordThread::stop");
6756     AutoMutex _l(mLock);
6757     if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
6758         return false;
6759     }
6760     // note that threadLoop may still be processing the track at this point [without lock]
6761     recordTrack->mState = TrackBase::PAUSING;
6762     // signal thread to stop
6763     mWaitWorkCV.broadcast();
6764     // do not wait for mStartStopCond if exiting
6765     if (exitPending()) {
6766         return true;
6767     }
6768     // FIXME incorrect usage of wait: no explicit predicate or loop
6769     mStartStopCond.wait(mLock);
6770     // if we have been restarted, recordTrack is in mActiveTracks here
6771     if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
6772         ALOGV("Record stopped OK");
6773         return true;
6774     }
6775     return false;
6776 }
6777 
isValidSyncEvent(const sp<SyncEvent> & event __unused) const6778 bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
6779 {
6780     return false;
6781 }
6782 
setSyncEvent(const sp<SyncEvent> & event __unused)6783 status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
6784 {
6785 #if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
6786     if (!isValidSyncEvent(event)) {
6787         return BAD_VALUE;
6788     }
6789 
6790     audio_session_t eventSession = event->triggerSession();
6791     status_t ret = NAME_NOT_FOUND;
6792 
6793     Mutex::Autolock _l(mLock);
6794 
6795     for (size_t i = 0; i < mTracks.size(); i++) {
6796         sp<RecordTrack> track = mTracks[i];
6797         if (eventSession == track->sessionId()) {
6798             (void) track->setSyncEvent(event);
6799             ret = NO_ERROR;
6800         }
6801     }
6802     return ret;
6803 #else
6804     return BAD_VALUE;
6805 #endif
6806 }
6807 
6808 // destroyTrack_l() must be called with ThreadBase::mLock held
destroyTrack_l(const sp<RecordTrack> & track)6809 void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6810 {
6811     track->terminate();
6812     track->mState = TrackBase::STOPPED;
6813     // active tracks are removed by threadLoop()
6814     if (mActiveTracks.indexOf(track) < 0) {
6815         removeTrack_l(track);
6816     }
6817 }
6818 
removeTrack_l(const sp<RecordTrack> & track)6819 void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6820 {
6821     mTracks.remove(track);
6822     // need anything related to effects here?
6823     if (track->isFastTrack()) {
6824         ALOG_ASSERT(!mFastTrackAvail);
6825         mFastTrackAvail = true;
6826     }
6827 }
6828 
dump(int fd,const Vector<String16> & args)6829 void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6830 {
6831     dumpInternals(fd, args);
6832     dumpTracks(fd, args);
6833     dumpEffectChains(fd, args);
6834 }
6835 
dumpInternals(int fd,const Vector<String16> & args)6836 void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6837 {
6838     dprintf(fd, "\nInput thread %p:\n", this);
6839 
6840     dumpBase(fd, args);
6841 
6842     if (mActiveTracks.size() == 0) {
6843         dprintf(fd, "  No active record clients\n");
6844     }
6845     dprintf(fd, "  Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
6846     dprintf(fd, "  Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
6847 
6848     // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6849     // while we are dumping it.  It may be inconsistent, but it won't mutate!
6850     // This is a large object so we place it on the heap.
6851     // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6852     const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6853     copy->dump(fd);
6854     delete copy;
6855 }
6856 
dumpTracks(int fd,const Vector<String16> & args __unused)6857 void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
6858 {
6859     const size_t SIZE = 256;
6860     char buffer[SIZE];
6861     String8 result;
6862 
6863     size_t numtracks = mTracks.size();
6864     size_t numactive = mActiveTracks.size();
6865     size_t numactiveseen = 0;
6866     dprintf(fd, "  %zu Tracks", numtracks);
6867     if (numtracks) {
6868         dprintf(fd, " of which %zu are active\n", numactive);
6869         RecordTrack::appendDumpHeader(result);
6870         for (size_t i = 0; i < numtracks ; ++i) {
6871             sp<RecordTrack> track = mTracks[i];
6872             if (track != 0) {
6873                 bool active = mActiveTracks.indexOf(track) >= 0;
6874                 if (active) {
6875                     numactiveseen++;
6876                 }
6877                 track->dump(buffer, SIZE, active);
6878                 result.append(buffer);
6879             }
6880         }
6881     } else {
6882         dprintf(fd, "\n");
6883     }
6884 
6885     if (numactiveseen != numactive) {
6886         snprintf(buffer, SIZE, "  The following tracks are in the active list but"
6887                 " not in the track list\n");
6888         result.append(buffer);
6889         RecordTrack::appendDumpHeader(result);
6890         for (size_t i = 0; i < numactive; ++i) {
6891             sp<RecordTrack> track = mActiveTracks[i];
6892             if (mTracks.indexOf(track) < 0) {
6893                 track->dump(buffer, SIZE, true);
6894                 result.append(buffer);
6895             }
6896         }
6897 
6898     }
6899     write(fd, result.string(), result.size());
6900 }
6901 
6902 
reset()6903 void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6904 {
6905     sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6906     RecordThread *recordThread = (RecordThread *) threadBase.get();
6907     mRsmpInFront = recordThread->mRsmpInRear;
6908     mRsmpInUnrel = 0;
6909 }
6910 
sync(size_t * framesAvailable,bool * hasOverrun)6911 void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6912         size_t *framesAvailable, bool *hasOverrun)
6913 {
6914     sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6915     RecordThread *recordThread = (RecordThread *) threadBase.get();
6916     const int32_t rear = recordThread->mRsmpInRear;
6917     const int32_t front = mRsmpInFront;
6918     const ssize_t filled = rear - front;
6919 
6920     size_t framesIn;
6921     bool overrun = false;
6922     if (filled < 0) {
6923         // should not happen, but treat like a massive overrun and re-sync
6924         framesIn = 0;
6925         mRsmpInFront = rear;
6926         overrun = true;
6927     } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6928         framesIn = (size_t) filled;
6929     } else {
6930         // client is not keeping up with server, but give it latest data
6931         framesIn = recordThread->mRsmpInFrames;
6932         mRsmpInFront = /* front = */ rear - framesIn;
6933         overrun = true;
6934     }
6935     if (framesAvailable != NULL) {
6936         *framesAvailable = framesIn;
6937     }
6938     if (hasOverrun != NULL) {
6939         *hasOverrun = overrun;
6940     }
6941 }
6942 
6943 // AudioBufferProvider interface
getNextBuffer(AudioBufferProvider::Buffer * buffer)6944 status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6945         AudioBufferProvider::Buffer* buffer)
6946 {
6947     sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6948     if (threadBase == 0) {
6949         buffer->frameCount = 0;
6950         buffer->raw = NULL;
6951         return NOT_ENOUGH_DATA;
6952     }
6953     RecordThread *recordThread = (RecordThread *) threadBase.get();
6954     int32_t rear = recordThread->mRsmpInRear;
6955     int32_t front = mRsmpInFront;
6956     ssize_t filled = rear - front;
6957     // FIXME should not be P2 (don't want to increase latency)
6958     // FIXME if client not keeping up, discard
6959     LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
6960     // 'filled' may be non-contiguous, so return only the first contiguous chunk
6961     front &= recordThread->mRsmpInFramesP2 - 1;
6962     size_t part1 = recordThread->mRsmpInFramesP2 - front;
6963     if (part1 > (size_t) filled) {
6964         part1 = filled;
6965     }
6966     size_t ask = buffer->frameCount;
6967     ALOG_ASSERT(ask > 0);
6968     if (part1 > ask) {
6969         part1 = ask;
6970     }
6971     if (part1 == 0) {
6972         // out of data is fine since the resampler will return a short-count.
6973         buffer->raw = NULL;
6974         buffer->frameCount = 0;
6975         mRsmpInUnrel = 0;
6976         return NOT_ENOUGH_DATA;
6977     }
6978 
6979     buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
6980     buffer->frameCount = part1;
6981     mRsmpInUnrel = part1;
6982     return NO_ERROR;
6983 }
6984 
6985 // AudioBufferProvider interface
releaseBuffer(AudioBufferProvider::Buffer * buffer)6986 void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6987         AudioBufferProvider::Buffer* buffer)
6988 {
6989     size_t stepCount = buffer->frameCount;
6990     if (stepCount == 0) {
6991         return;
6992     }
6993     ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6994     mRsmpInUnrel -= stepCount;
6995     mRsmpInFront += stepCount;
6996     buffer->raw = NULL;
6997     buffer->frameCount = 0;
6998 }
6999 
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)7000 AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
7001         audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7002         uint32_t srcSampleRate,
7003         audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7004         uint32_t dstSampleRate) :
7005             mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
7006             // mSrcFormat
7007             // mSrcSampleRate
7008             // mDstChannelMask
7009             // mDstFormat
7010             // mDstSampleRate
7011             // mSrcChannelCount
7012             // mDstChannelCount
7013             // mDstFrameSize
7014             mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
7015             mResampler(NULL),
7016             mIsLegacyDownmix(false),
7017             mIsLegacyUpmix(false),
7018             mRequiresFloat(false),
7019             mInputConverterProvider(NULL)
7020 {
7021     (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
7022             dstChannelMask, dstFormat, dstSampleRate);
7023 }
7024 
~RecordBufferConverter()7025 AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
7026     free(mBuf);
7027     delete mResampler;
7028     delete mInputConverterProvider;
7029 }
7030 
convert(void * dst,AudioBufferProvider * provider,size_t frames)7031 size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
7032         AudioBufferProvider *provider, size_t frames)
7033 {
7034     if (mInputConverterProvider != NULL) {
7035         mInputConverterProvider->setBufferProvider(provider);
7036         provider = mInputConverterProvider;
7037     }
7038 
7039     if (mResampler == NULL) {
7040         ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7041                 mSrcSampleRate, mSrcFormat, mDstFormat);
7042 
7043         AudioBufferProvider::Buffer buffer;
7044         for (size_t i = frames; i > 0; ) {
7045             buffer.frameCount = i;
7046             status_t status = provider->getNextBuffer(&buffer);
7047             if (status != OK || buffer.frameCount == 0) {
7048                 frames -= i; // cannot fill request.
7049                 break;
7050             }
7051             // format convert to destination buffer
7052             convertNoResampler(dst, buffer.raw, buffer.frameCount);
7053 
7054             dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
7055             i -= buffer.frameCount;
7056             provider->releaseBuffer(&buffer);
7057         }
7058     } else {
7059          ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
7060                  mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7061 
7062          // reallocate buffer if needed
7063          if (mBufFrameSize != 0 && mBufFrames < frames) {
7064              free(mBuf);
7065              mBufFrames = frames;
7066              (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7067          }
7068         // resampler accumulates, but we only have one source track
7069         memset(mBuf, 0, frames * mBufFrameSize);
7070         frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7071         // format convert to destination buffer
7072         convertResampler(dst, mBuf, frames);
7073     }
7074     return frames;
7075 }
7076 
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)7077 status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7078         audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7079         uint32_t srcSampleRate,
7080         audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7081         uint32_t dstSampleRate)
7082 {
7083     // quick evaluation if there is any change.
7084     if (mSrcFormat == srcFormat
7085             && mSrcChannelMask == srcChannelMask
7086             && mSrcSampleRate == srcSampleRate
7087             && mDstFormat == dstFormat
7088             && mDstChannelMask == dstChannelMask
7089             && mDstSampleRate == dstSampleRate) {
7090         return NO_ERROR;
7091     }
7092 
7093     ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7094             "  srcFormat:%#x dstFormat:%#x  srcRate:%u dstRate:%u",
7095             srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
7096     const bool valid =
7097             audio_is_input_channel(srcChannelMask)
7098             && audio_is_input_channel(dstChannelMask)
7099             && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7100             && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7101             && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7102             ; // no upsampling checks for now
7103     if (!valid) {
7104         return BAD_VALUE;
7105     }
7106 
7107     mSrcFormat = srcFormat;
7108     mSrcChannelMask = srcChannelMask;
7109     mSrcSampleRate = srcSampleRate;
7110     mDstFormat = dstFormat;
7111     mDstChannelMask = dstChannelMask;
7112     mDstSampleRate = dstSampleRate;
7113 
7114     // compute derived parameters
7115     mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7116     mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7117     mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7118 
7119     // do we need to resample?
7120     delete mResampler;
7121     mResampler = NULL;
7122     if (mSrcSampleRate != mDstSampleRate) {
7123         mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7124                 mSrcChannelCount, mDstSampleRate);
7125         mResampler->setSampleRate(mSrcSampleRate);
7126         mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7127     }
7128 
7129     // are we running legacy channel conversion modes?
7130     mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7131                             || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7132                    && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7133     mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7134                    && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7135                             || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7136 
7137     // do we need to process in float?
7138     mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7139 
7140     // do we need a staging buffer to convert for destination (we can still optimize this)?
7141     // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7142     if (mResampler != NULL) {
7143         mBufFrameSize = max(mSrcChannelCount, FCC_2)
7144                 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7145     } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
7146         mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7147     } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
7148         mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7149     } else {
7150         mBufFrameSize = 0;
7151     }
7152     mBufFrames = 0; // force the buffer to be resized.
7153 
7154     // do we need an input converter buffer provider to give us float?
7155     delete mInputConverterProvider;
7156     mInputConverterProvider = NULL;
7157     if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7158         mInputConverterProvider = new ReformatBufferProvider(
7159                 audio_channel_count_from_in_mask(mSrcChannelMask),
7160                 mSrcFormat,
7161                 AUDIO_FORMAT_PCM_FLOAT,
7162                 256 /* provider buffer frame count */);
7163     }
7164 
7165     // do we need a remixer to do channel mask conversion
7166     if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7167         (void) memcpy_by_index_array_initialization_from_channel_mask(
7168                 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
7169     }
7170     return NO_ERROR;
7171 }
7172 
convertNoResampler(void * dst,const void * src,size_t frames)7173 void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7174         void *dst, const void *src, size_t frames)
7175 {
7176     // src is native type unless there is legacy upmix or downmix, whereupon it is float.
7177     if (mBufFrameSize != 0 && mBufFrames < frames) {
7178         free(mBuf);
7179         mBufFrames = frames;
7180         (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7181     }
7182     // do we need to do legacy upmix and downmix?
7183     if (mIsLegacyUpmix || mIsLegacyDownmix) {
7184         void *dstBuf = mBuf != NULL ? mBuf : dst;
7185         if (mIsLegacyUpmix) {
7186             upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7187                     (const float *)src, frames);
7188         } else /*mIsLegacyDownmix */ {
7189             downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7190                     (const float *)src, frames);
7191         }
7192         if (mBuf != NULL) {
7193             memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7194                     frames * mDstChannelCount);
7195         }
7196         return;
7197     }
7198     // do we need to do channel mask conversion?
7199     if (mSrcChannelMask != mDstChannelMask) {
7200         void *dstBuf = mBuf != NULL ? mBuf : dst;
7201         memcpy_by_index_array(dstBuf, mDstChannelCount,
7202                 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7203         if (dstBuf == dst) {
7204             return; // format is the same
7205         }
7206     }
7207     // convert to destination buffer
7208     const void *convertBuf = mBuf != NULL ? mBuf : src;
7209     memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7210             frames * mDstChannelCount);
7211 }
7212 
convertResampler(void * dst,void * src,size_t frames)7213 void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7214         void *dst, /*not-a-const*/ void *src, size_t frames)
7215 {
7216     // src buffer format is ALWAYS float when entering this routine
7217     if (mIsLegacyUpmix) {
7218         ; // mono to stereo already handled by resampler
7219     } else if (mIsLegacyDownmix
7220             || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7221         // the resampler outputs stereo for mono input channel (a feature?)
7222         // must convert to mono
7223         downmix_to_mono_float_from_stereo_float((float *)src,
7224                 (const float *)src, frames);
7225     } else if (mSrcChannelMask != mDstChannelMask) {
7226         // convert to mono channel again for channel mask conversion (could be skipped
7227         // with further optimization).
7228         if (mSrcChannelCount == 1) {
7229             downmix_to_mono_float_from_stereo_float((float *)src,
7230                 (const float *)src, frames);
7231         }
7232         // convert to destination format (in place, OK as float is larger than other types)
7233         if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7234             memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7235                     frames * mSrcChannelCount);
7236         }
7237         // channel convert and save to dst
7238         memcpy_by_index_array(dst, mDstChannelCount,
7239                 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7240         return;
7241     }
7242     // convert to destination format and save to dst
7243     memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7244             frames * mDstChannelCount);
7245 }
7246 
checkForNewParameter_l(const String8 & keyValuePair,status_t & status)7247 bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7248                                                         status_t& status)
7249 {
7250     bool reconfig = false;
7251 
7252     status = NO_ERROR;
7253 
7254     audio_format_t reqFormat = mFormat;
7255     uint32_t samplingRate = mSampleRate;
7256     // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
7257     audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7258 
7259     AudioParameter param = AudioParameter(keyValuePair);
7260     int value;
7261 
7262     // scope for AutoPark extends to end of method
7263     AutoPark<FastCapture> park(mFastCapture);
7264 
7265     // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7266     //      channel count change can be requested. Do we mandate the first client defines the
7267     //      HAL sampling rate and channel count or do we allow changes on the fly?
7268     if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7269         samplingRate = value;
7270         reconfig = true;
7271     }
7272     if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
7273         if (!audio_is_linear_pcm((audio_format_t) value)) {
7274             status = BAD_VALUE;
7275         } else {
7276             reqFormat = (audio_format_t) value;
7277             reconfig = true;
7278         }
7279     }
7280     if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7281         audio_channel_mask_t mask = (audio_channel_mask_t) value;
7282         if (!audio_is_input_channel(mask) ||
7283                 audio_channel_count_from_in_mask(mask) > FCC_8) {
7284             status = BAD_VALUE;
7285         } else {
7286             channelMask = mask;
7287             reconfig = true;
7288         }
7289     }
7290     if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7291         // do not accept frame count changes if tracks are open as the track buffer
7292         // size depends on frame count and correct behavior would not be guaranteed
7293         // if frame count is changed after track creation
7294         if (mActiveTracks.size() > 0) {
7295             status = INVALID_OPERATION;
7296         } else {
7297             reconfig = true;
7298         }
7299     }
7300     if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7301         // forward device change to effects that have requested to be
7302         // aware of attached audio device.
7303         for (size_t i = 0; i < mEffectChains.size(); i++) {
7304             mEffectChains[i]->setDevice_l(value);
7305         }
7306 
7307         // store input device and output device but do not forward output device to audio HAL.
7308         // Note that status is ignored by the caller for output device
7309         // (see AudioFlinger::setParameters()
7310         if (audio_is_output_devices(value)) {
7311             mOutDevice = value;
7312             status = BAD_VALUE;
7313         } else {
7314             mInDevice = value;
7315             if (value != AUDIO_DEVICE_NONE) {
7316                 mPrevInDevice = value;
7317             }
7318             // disable AEC and NS if the device is a BT SCO headset supporting those
7319             // pre processings
7320             if (mTracks.size() > 0) {
7321                 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7322                                     mAudioFlinger->btNrecIsOff();
7323                 for (size_t i = 0; i < mTracks.size(); i++) {
7324                     sp<RecordTrack> track = mTracks[i];
7325                     setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7326                     setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7327                 }
7328             }
7329         }
7330     }
7331     if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7332             mAudioSource != (audio_source_t)value) {
7333         // forward device change to effects that have requested to be
7334         // aware of attached audio device.
7335         for (size_t i = 0; i < mEffectChains.size(); i++) {
7336             mEffectChains[i]->setAudioSource_l((audio_source_t)value);
7337         }
7338         mAudioSource = (audio_source_t)value;
7339     }
7340 
7341     if (status == NO_ERROR) {
7342         status = mInput->stream->common.set_parameters(&mInput->stream->common,
7343                 keyValuePair.string());
7344         if (status == INVALID_OPERATION) {
7345             inputStandBy();
7346             status = mInput->stream->common.set_parameters(&mInput->stream->common,
7347                     keyValuePair.string());
7348         }
7349         if (reconfig) {
7350             if (status == BAD_VALUE &&
7351                 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7352                 audio_is_linear_pcm(reqFormat) &&
7353                 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
7354                         <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
7355                 audio_channel_count_from_in_mask(
7356                         mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
7357                 status = NO_ERROR;
7358             }
7359             if (status == NO_ERROR) {
7360                 readInputParameters_l();
7361                 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7362             }
7363         }
7364     }
7365 
7366     return reconfig;
7367 }
7368 
getParameters(const String8 & keys)7369 String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7370 {
7371     Mutex::Autolock _l(mLock);
7372     if (initCheck() != NO_ERROR) {
7373         return String8();
7374     }
7375 
7376     char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7377     const String8 out_s8(s);
7378     free(s);
7379     return out_s8;
7380 }
7381 
ioConfigChanged(audio_io_config_event event,pid_t pid)7382 void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7383     sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7384 
7385     desc->mIoHandle = mId;
7386 
7387     switch (event) {
7388     case AUDIO_INPUT_OPENED:
7389     case AUDIO_INPUT_CONFIG_CHANGED:
7390         desc->mPatch = mPatch;
7391         desc->mChannelMask = mChannelMask;
7392         desc->mSamplingRate = mSampleRate;
7393         desc->mFormat = mFormat;
7394         desc->mFrameCount = mFrameCount;
7395         desc->mFrameCountHAL = mFrameCount;
7396         desc->mLatency = 0;
7397         break;
7398 
7399     case AUDIO_INPUT_CLOSED:
7400     default:
7401         break;
7402     }
7403     mAudioFlinger->ioConfigChanged(event, desc, pid);
7404 }
7405 
readInputParameters_l()7406 void AudioFlinger::RecordThread::readInputParameters_l()
7407 {
7408     mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7409     mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
7410     mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
7411     if (mChannelCount > FCC_8) {
7412         ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7413     }
7414     mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7415     mFormat = mHALFormat;
7416     if (!audio_is_linear_pcm(mFormat)) {
7417         ALOGE("HAL format %#x is not linear pcm", mFormat);
7418     }
7419     mFrameSize = audio_stream_in_frame_size(mInput->stream);
7420     mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7421     mFrameCount = mBufferSize / mFrameSize;
7422     // This is the formula for calculating the temporary buffer size.
7423     // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
7424     // 1 full output buffer, regardless of the alignment of the available input.
7425     // The value is somewhat arbitrary, and could probably be even larger.
7426     // A larger value should allow more old data to be read after a track calls start(),
7427     // without increasing latency.
7428     //
7429     // Note this is independent of the maximum downsampling ratio permitted for capture.
7430     mRsmpInFrames = mFrameCount * 7;
7431     mRsmpInFramesP2 = roundup(mRsmpInFrames);
7432     free(mRsmpInBuffer);
7433     mRsmpInBuffer = NULL;
7434 
7435     // TODO optimize audio capture buffer sizes ...
7436     // Here we calculate the size of the sliding buffer used as a source
7437     // for resampling.  mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7438     // For current HAL frame counts, this is usually 2048 = 40 ms.  It would
7439     // be better to have it derived from the pipe depth in the long term.
7440     // The current value is higher than necessary.  However it should not add to latency.
7441 
7442     // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
7443     size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7444     (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7445     memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
7446 
7447     // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7448     // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
7449 }
7450 
getInputFramesLost()7451 uint32_t AudioFlinger::RecordThread::getInputFramesLost()
7452 {
7453     Mutex::Autolock _l(mLock);
7454     if (initCheck() != NO_ERROR) {
7455         return 0;
7456     }
7457 
7458     return mInput->stream->get_input_frames_lost(mInput->stream);
7459 }
7460 
7461 // hasAudioSession_l() must be called with ThreadBase::mLock held
hasAudioSession_l(audio_session_t sessionId) const7462 uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
7463 {
7464     uint32_t result = 0;
7465     if (getEffectChain_l(sessionId) != 0) {
7466         result = EFFECT_SESSION;
7467     }
7468 
7469     for (size_t i = 0; i < mTracks.size(); ++i) {
7470         if (sessionId == mTracks[i]->sessionId()) {
7471             result |= TRACK_SESSION;
7472             if (mTracks[i]->isFastTrack()) {
7473                 result |= FAST_SESSION;
7474             }
7475             break;
7476         }
7477     }
7478 
7479     return result;
7480 }
7481 
sessionIds() const7482 KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
7483 {
7484     KeyedVector<audio_session_t, bool> ids;
7485     Mutex::Autolock _l(mLock);
7486     for (size_t j = 0; j < mTracks.size(); ++j) {
7487         sp<RecordThread::RecordTrack> track = mTracks[j];
7488         audio_session_t sessionId = track->sessionId();
7489         if (ids.indexOfKey(sessionId) < 0) {
7490             ids.add(sessionId, true);
7491         }
7492     }
7493     return ids;
7494 }
7495 
clearInput()7496 AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7497 {
7498     Mutex::Autolock _l(mLock);
7499     AudioStreamIn *input = mInput;
7500     mInput = NULL;
7501     return input;
7502 }
7503 
7504 // this method must always be called either with ThreadBase mLock held or inside the thread loop
stream() const7505 audio_stream_t* AudioFlinger::RecordThread::stream() const
7506 {
7507     if (mInput == NULL) {
7508         return NULL;
7509     }
7510     return &mInput->stream->common;
7511 }
7512 
addEffectChain_l(const sp<EffectChain> & chain)7513 status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7514 {
7515     // only one chain per input thread
7516     if (mEffectChains.size() != 0) {
7517         ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
7518         return INVALID_OPERATION;
7519     }
7520     ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
7521     chain->setThread(this);
7522     chain->setInBuffer(NULL);
7523     chain->setOutBuffer(NULL);
7524 
7525     checkSuspendOnAddEffectChain_l(chain);
7526 
7527     // make sure enabled pre processing effects state is communicated to the HAL as we
7528     // just moved them to a new input stream.
7529     chain->syncHalEffectsState();
7530 
7531     mEffectChains.add(chain);
7532 
7533     return NO_ERROR;
7534 }
7535 
removeEffectChain_l(const sp<EffectChain> & chain)7536 size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7537 {
7538     ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7539     ALOGW_IF(mEffectChains.size() != 1,
7540             "removeEffectChain_l() %p invalid chain size %zu on thread %p",
7541             chain.get(), mEffectChains.size(), this);
7542     if (mEffectChains.size() == 1) {
7543         mEffectChains.removeAt(0);
7544     }
7545     return 0;
7546 }
7547 
createAudioPatch_l(const struct audio_patch * patch,audio_patch_handle_t * handle)7548 status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7549                                                           audio_patch_handle_t *handle)
7550 {
7551     status_t status = NO_ERROR;
7552 
7553     // store new device and send to effects
7554     mInDevice = patch->sources[0].ext.device.type;
7555     mPatch = *patch;
7556     for (size_t i = 0; i < mEffectChains.size(); i++) {
7557         mEffectChains[i]->setDevice_l(mInDevice);
7558     }
7559 
7560     // disable AEC and NS if the device is a BT SCO headset supporting those
7561     // pre processings
7562     if (mTracks.size() > 0) {
7563         bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7564                             mAudioFlinger->btNrecIsOff();
7565         for (size_t i = 0; i < mTracks.size(); i++) {
7566             sp<RecordTrack> track = mTracks[i];
7567             setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7568             setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7569         }
7570     }
7571 
7572     // store new source and send to effects
7573     if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7574         mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7575         for (size_t i = 0; i < mEffectChains.size(); i++) {
7576             mEffectChains[i]->setAudioSource_l(mAudioSource);
7577         }
7578     }
7579 
7580     if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7581         audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7582         status = hwDevice->create_audio_patch(hwDevice,
7583                                                patch->num_sources,
7584                                                patch->sources,
7585                                                patch->num_sinks,
7586                                                patch->sinks,
7587                                                handle);
7588     } else {
7589         char *address;
7590         if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7591             address = audio_device_address_to_parameter(
7592                                                 patch->sources[0].ext.device.type,
7593                                                 patch->sources[0].ext.device.address);
7594         } else {
7595             address = (char *)calloc(1, 1);
7596         }
7597         AudioParameter param = AudioParameter(String8(address));
7598         free(address);
7599         param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7600                      (int)patch->sources[0].ext.device.type);
7601         param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7602                                          (int)patch->sinks[0].ext.mix.usecase.source);
7603         status = mInput->stream->common.set_parameters(&mInput->stream->common,
7604                 param.toString().string());
7605         *handle = AUDIO_PATCH_HANDLE_NONE;
7606     }
7607 
7608     if (mInDevice != mPrevInDevice) {
7609         sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7610         mPrevInDevice = mInDevice;
7611     }
7612 
7613     return status;
7614 }
7615 
releaseAudioPatch_l(const audio_patch_handle_t handle)7616 status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7617 {
7618     status_t status = NO_ERROR;
7619 
7620     mInDevice = AUDIO_DEVICE_NONE;
7621 
7622     if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7623         audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7624         status = hwDevice->release_audio_patch(hwDevice, handle);
7625     } else {
7626         AudioParameter param;
7627         param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7628         status = mInput->stream->common.set_parameters(&mInput->stream->common,
7629                 param.toString().string());
7630     }
7631     return status;
7632 }
7633 
addPatchRecord(const sp<PatchRecord> & record)7634 void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7635 {
7636     Mutex::Autolock _l(mLock);
7637     mTracks.add(record);
7638 }
7639 
deletePatchRecord(const sp<PatchRecord> & record)7640 void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7641 {
7642     Mutex::Autolock _l(mLock);
7643     destroyTrack_l(record);
7644 }
7645 
getAudioPortConfig(struct audio_port_config * config)7646 void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7647 {
7648     ThreadBase::getAudioPortConfig(config);
7649     config->role = AUDIO_PORT_ROLE_SINK;
7650     config->ext.mix.hw_module = mInput->audioHwDev->handle();
7651     config->ext.mix.usecase.source = mAudioSource;
7652 }
7653 
7654 } // namespace android
7655