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