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