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