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