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