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