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