Threads.cpp revision 57c4e6f7464d458eb52d209c2a63524913d6406d
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    // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5006    // after a timeout and we will enter standby then.
5007    if (mTracks.size() > 0) {
5008        trackPaused = mTracks[mTracks.size() - 1]->isPaused();
5009        trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5010                           mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
5011    }
5012
5013    return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
5014}
5015
5016// getTrackName_l() must be called with ThreadBase::mLock held
5017int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
5018        audio_format_t format __unused, audio_session_t sessionId __unused)
5019{
5020    return 0;
5021}
5022
5023// deleteTrackName_l() must be called with ThreadBase::mLock held
5024void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
5025{
5026}
5027
5028// checkForNewParameter_l() must be called with ThreadBase::mLock held
5029bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5030                                                              status_t& status)
5031{
5032    bool reconfig = false;
5033    bool a2dpDeviceChanged = false;
5034
5035    status = NO_ERROR;
5036
5037    AudioParameter param = AudioParameter(keyValuePair);
5038    int value;
5039    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5040        // forward device change to effects that have requested to be
5041        // aware of attached audio device.
5042        if (value != AUDIO_DEVICE_NONE) {
5043            a2dpDeviceChanged =
5044                    (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
5045            mOutDevice = value;
5046            for (size_t i = 0; i < mEffectChains.size(); i++) {
5047                mEffectChains[i]->setDevice_l(mOutDevice);
5048            }
5049        }
5050    }
5051    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5052        // do not accept frame count changes if tracks are open as the track buffer
5053        // size depends on frame count and correct behavior would not be garantied
5054        // if frame count is changed after track creation
5055        if (!mTracks.isEmpty()) {
5056            status = INVALID_OPERATION;
5057        } else {
5058            reconfig = true;
5059        }
5060    }
5061    if (status == NO_ERROR) {
5062        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5063                                                keyValuePair.string());
5064        if (!mStandby && status == INVALID_OPERATION) {
5065            mOutput->standby();
5066            mStandby = true;
5067            mBytesWritten = 0;
5068            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5069                                                   keyValuePair.string());
5070        }
5071        if (status == NO_ERROR && reconfig) {
5072            readOutputParameters_l();
5073            sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5074        }
5075    }
5076
5077    return reconfig || a2dpDeviceChanged;
5078}
5079
5080uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5081{
5082    uint32_t time;
5083    if (audio_has_proportional_frames(mFormat)) {
5084        time = PlaybackThread::activeSleepTimeUs();
5085    } else {
5086        time = kDirectMinSleepTimeUs;
5087    }
5088    return time;
5089}
5090
5091uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5092{
5093    uint32_t time;
5094    if (audio_has_proportional_frames(mFormat)) {
5095        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5096    } else {
5097        time = kDirectMinSleepTimeUs;
5098    }
5099    return time;
5100}
5101
5102uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5103{
5104    uint32_t time;
5105    if (audio_has_proportional_frames(mFormat)) {
5106        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5107    } else {
5108        time = kDirectMinSleepTimeUs;
5109    }
5110    return time;
5111}
5112
5113void AudioFlinger::DirectOutputThread::cacheParameters_l()
5114{
5115    PlaybackThread::cacheParameters_l();
5116
5117    // use shorter standby delay as on normal output to release
5118    // hardware resources as soon as possible
5119    // no delay on outputs with HW A/V sync
5120    if (usesHwAvSync()) {
5121        mStandbyDelayNs = 0;
5122    } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
5123        mStandbyDelayNs = kOffloadStandbyDelayNs;
5124    } else {
5125        mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
5126    }
5127}
5128
5129void AudioFlinger::DirectOutputThread::flushHw_l()
5130{
5131    mOutput->flush();
5132    mHwPaused = false;
5133    mFlushPending = false;
5134}
5135
5136// ----------------------------------------------------------------------------
5137
5138AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
5139        const wp<AudioFlinger::PlaybackThread>& playbackThread)
5140    :   Thread(false /*canCallJava*/),
5141        mPlaybackThread(playbackThread),
5142        mWriteAckSequence(0),
5143        mDrainSequence(0)
5144{
5145}
5146
5147AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5148{
5149}
5150
5151void AudioFlinger::AsyncCallbackThread::onFirstRef()
5152{
5153    run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5154}
5155
5156bool AudioFlinger::AsyncCallbackThread::threadLoop()
5157{
5158    while (!exitPending()) {
5159        uint32_t writeAckSequence;
5160        uint32_t drainSequence;
5161
5162        {
5163            Mutex::Autolock _l(mLock);
5164            while (!((mWriteAckSequence & 1) ||
5165                     (mDrainSequence & 1) ||
5166                     exitPending())) {
5167                mWaitWorkCV.wait(mLock);
5168            }
5169
5170            if (exitPending()) {
5171                break;
5172            }
5173            ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5174                  mWriteAckSequence, mDrainSequence);
5175            writeAckSequence = mWriteAckSequence;
5176            mWriteAckSequence &= ~1;
5177            drainSequence = mDrainSequence;
5178            mDrainSequence &= ~1;
5179        }
5180        {
5181            sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5182            if (playbackThread != 0) {
5183                if (writeAckSequence & 1) {
5184                    playbackThread->resetWriteBlocked(writeAckSequence >> 1);
5185                }
5186                if (drainSequence & 1) {
5187                    playbackThread->resetDraining(drainSequence >> 1);
5188                }
5189            }
5190        }
5191    }
5192    return false;
5193}
5194
5195void AudioFlinger::AsyncCallbackThread::exit()
5196{
5197    ALOGV("AsyncCallbackThread::exit");
5198    Mutex::Autolock _l(mLock);
5199    requestExit();
5200    mWaitWorkCV.broadcast();
5201}
5202
5203void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
5204{
5205    Mutex::Autolock _l(mLock);
5206    // bit 0 is cleared
5207    mWriteAckSequence = sequence << 1;
5208}
5209
5210void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5211{
5212    Mutex::Autolock _l(mLock);
5213    // ignore unexpected callbacks
5214    if (mWriteAckSequence & 2) {
5215        mWriteAckSequence |= 1;
5216        mWaitWorkCV.signal();
5217    }
5218}
5219
5220void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
5221{
5222    Mutex::Autolock _l(mLock);
5223    // bit 0 is cleared
5224    mDrainSequence = sequence << 1;
5225}
5226
5227void AudioFlinger::AsyncCallbackThread::resetDraining()
5228{
5229    Mutex::Autolock _l(mLock);
5230    // ignore unexpected callbacks
5231    if (mDrainSequence & 2) {
5232        mDrainSequence |= 1;
5233        mWaitWorkCV.signal();
5234    }
5235}
5236
5237
5238// ----------------------------------------------------------------------------
5239AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
5240        AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady,
5241        uint32_t bitRate)
5242    :   DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate),
5243        mPausedBytesRemaining(0)
5244{
5245    //FIXME: mStandby should be set to true by ThreadBase constructor
5246    mStandby = true;
5247}
5248
5249void AudioFlinger::OffloadThread::threadLoop_exit()
5250{
5251    if (mFlushPending || mHwPaused) {
5252        // If a flush is pending or track was paused, just discard buffered data
5253        flushHw_l();
5254    } else {
5255        mMixerStatus = MIXER_DRAIN_ALL;
5256        threadLoop_drain();
5257    }
5258    if (mUseAsyncWrite) {
5259        ALOG_ASSERT(mCallbackThread != 0);
5260        mCallbackThread->exit();
5261    }
5262    PlaybackThread::threadLoop_exit();
5263}
5264
5265AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5266    Vector< sp<Track> > *tracksToRemove
5267)
5268{
5269    size_t count = mActiveTracks.size();
5270
5271    mixer_state mixerStatus = MIXER_IDLE;
5272    bool doHwPause = false;
5273    bool doHwResume = false;
5274
5275    ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5276
5277    // find out which tracks need to be processed
5278    for (size_t i = 0; i < count; i++) {
5279        sp<Track> t = mActiveTracks[i].promote();
5280        // The track died recently
5281        if (t == 0) {
5282            continue;
5283        }
5284        Track* const track = t.get();
5285#ifdef VERY_VERY_VERBOSE_LOGGING
5286        audio_track_cblk_t* cblk = track->cblk();
5287#endif
5288        // Only consider last track started for volume and mixer state control.
5289        // In theory an older track could underrun and restart after the new one starts
5290        // but as we only care about the transition phase between two tracks on a
5291        // direct output, it is not a problem to ignore the underrun case.
5292        sp<Track> l = mLatestActiveTrack.promote();
5293        bool last = l.get() == track;
5294
5295        if (track->isInvalid()) {
5296            ALOGW("An invalidated track shouldn't be in active list");
5297            tracksToRemove->add(track);
5298            continue;
5299        }
5300
5301        if (track->mState == TrackBase::IDLE) {
5302            ALOGW("An idle track shouldn't be in active list");
5303            continue;
5304        }
5305
5306        if (track->isPausing()) {
5307            track->setPaused();
5308            if (last) {
5309                if (mHwSupportsPause && !mHwPaused) {
5310                    doHwPause = true;
5311                    mHwPaused = true;
5312                }
5313                // If we were part way through writing the mixbuffer to
5314                // the HAL we must save this until we resume
5315                // BUG - this will be wrong if a different track is made active,
5316                // in that case we want to discard the pending data in the
5317                // mixbuffer and tell the client to present it again when the
5318                // track is resumed
5319                mPausedWriteLength = mCurrentWriteLength;
5320                mPausedBytesRemaining = mBytesRemaining;
5321                mBytesRemaining = 0;    // stop writing
5322            }
5323            tracksToRemove->add(track);
5324        } else if (track->isFlushPending()) {
5325            track->mRetryCount = kMaxTrackRetriesOffload;
5326            track->flushAck();
5327            if (last) {
5328                mFlushPending = true;
5329            }
5330        } else if (track->isResumePending()){
5331            track->resumeAck();
5332            if (last) {
5333                if (mPausedBytesRemaining) {
5334                    // Need to continue write that was interrupted
5335                    mCurrentWriteLength = mPausedWriteLength;
5336                    mBytesRemaining = mPausedBytesRemaining;
5337                    mPausedBytesRemaining = 0;
5338                }
5339                if (mHwPaused) {
5340                    doHwResume = true;
5341                    mHwPaused = false;
5342                    // threadLoop_mix() will handle the case that we need to
5343                    // resume an interrupted write
5344                }
5345                // enable write to audio HAL
5346                mSleepTimeUs = 0;
5347
5348                // Do not handle new data in this iteration even if track->framesReady()
5349                mixerStatus = MIXER_TRACKS_ENABLED;
5350            }
5351        }  else if (track->framesReady() && track->isReady() &&
5352                !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
5353            ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
5354            if (track->mFillingUpStatus == Track::FS_FILLED) {
5355                track->mFillingUpStatus = Track::FS_ACTIVE;
5356                // make sure processVolume_l() will apply new volume even if 0
5357                mLeftVolFloat = mRightVolFloat = -1.0;
5358            }
5359
5360            if (last) {
5361                sp<Track> previousTrack = mPreviousTrack.promote();
5362                if (previousTrack != 0) {
5363                    if (track != previousTrack.get()) {
5364                        // Flush any data still being written from last track
5365                        mBytesRemaining = 0;
5366                        if (mPausedBytesRemaining) {
5367                            // Last track was paused so we also need to flush saved
5368                            // mixbuffer state and invalidate track so that it will
5369                            // re-submit that unwritten data when it is next resumed
5370                            mPausedBytesRemaining = 0;
5371                            // Invalidate is a bit drastic - would be more efficient
5372                            // to have a flag to tell client that some of the
5373                            // previously written data was lost
5374                            previousTrack->invalidate();
5375                        }
5376                        // flush data already sent to the DSP if changing audio session as audio
5377                        // comes from a different source. Also invalidate previous track to force a
5378                        // seek when resuming.
5379                        if (previousTrack->sessionId() != track->sessionId()) {
5380                            previousTrack->invalidate();
5381                        }
5382                    }
5383                }
5384                mPreviousTrack = track;
5385                // reset retry count
5386                track->mRetryCount = kMaxTrackRetriesOffload;
5387                mActiveTrack = t;
5388                mixerStatus = MIXER_TRACKS_READY;
5389            }
5390        } else {
5391            ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
5392            if (track->isStopping_1()) {
5393                // Hardware buffer can hold a large amount of audio so we must
5394                // wait for all current track's data to drain before we say
5395                // that the track is stopped.
5396                if (mBytesRemaining == 0) {
5397                    // Only start draining when all data in mixbuffer
5398                    // has been written
5399                    ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5400                    track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
5401                    // do not drain if no data was ever sent to HAL (mStandby == true)
5402                    if (last && !mStandby) {
5403                        // do not modify drain sequence if we are already draining. This happens
5404                        // when resuming from pause after drain.
5405                        if ((mDrainSequence & 1) == 0) {
5406                            mSleepTimeUs = 0;
5407                            mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5408                            mixerStatus = MIXER_DRAIN_TRACK;
5409                            mDrainSequence += 2;
5410                        }
5411                        if (mHwPaused) {
5412                            // It is possible to move from PAUSED to STOPPING_1 without
5413                            // a resume so we must ensure hardware is running
5414                            doHwResume = true;
5415                            mHwPaused = false;
5416                        }
5417                    }
5418                }
5419            } else if (track->isStopping_2()) {
5420                // Drain has completed or we are in standby, signal presentation complete
5421                if (!(mDrainSequence & 1) || !last || mStandby) {
5422                    track->mState = TrackBase::STOPPED;
5423                    size_t audioHALFrames =
5424                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5425                    int64_t framesWritten =
5426                            mBytesWritten / mOutput->getFrameSize();
5427                    track->presentationComplete(framesWritten, audioHALFrames);
5428                    track->reset();
5429                    tracksToRemove->add(track);
5430                }
5431            } else {
5432                // No buffers for this track. Give it a few chances to
5433                // fill a buffer, then remove it from active list.
5434                if (--(track->mRetryCount) <= 0) {
5435                    ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5436                          track->name());
5437                    tracksToRemove->add(track);
5438                    // indicate to client process that the track was disabled because of underrun;
5439                    // it will then automatically call start() when data is available
5440                    track->disable();
5441                } else if (last){
5442                    mixerStatus = MIXER_TRACKS_ENABLED;
5443                }
5444            }
5445        }
5446        // compute volume for this track
5447        processVolume_l(track, last);
5448    }
5449
5450    // make sure the pause/flush/resume sequence is executed in the right order.
5451    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5452    // before flush and then resume HW. This can happen in case of pause/flush/resume
5453    // if resume is received before pause is executed.
5454    if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
5455        mOutput->stream->pause(mOutput->stream);
5456    }
5457    if (mFlushPending) {
5458        flushHw_l();
5459    }
5460    if (!mStandby && doHwResume) {
5461        mOutput->stream->resume(mOutput->stream);
5462    }
5463
5464    // remove all the tracks that need to be...
5465    removeTracks_l(*tracksToRemove);
5466
5467    return mixerStatus;
5468}
5469
5470// must be called with thread mutex locked
5471bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5472{
5473    ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5474          mWriteAckSequence, mDrainSequence);
5475    if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
5476        return true;
5477    }
5478    return false;
5479}
5480
5481bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5482{
5483    Mutex::Autolock _l(mLock);
5484    return waitingAsyncCallback_l();
5485}
5486
5487void AudioFlinger::OffloadThread::flushHw_l()
5488{
5489    DirectOutputThread::flushHw_l();
5490    // Flush anything still waiting in the mixbuffer
5491    mCurrentWriteLength = 0;
5492    mBytesRemaining = 0;
5493    mPausedWriteLength = 0;
5494    mPausedBytesRemaining = 0;
5495
5496    if (mUseAsyncWrite) {
5497        // discard any pending drain or write ack by incrementing sequence
5498        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5499        mDrainSequence = (mDrainSequence + 2) & ~1;
5500        ALOG_ASSERT(mCallbackThread != 0);
5501        mCallbackThread->setWriteBlocked(mWriteAckSequence);
5502        mCallbackThread->setDraining(mDrainSequence);
5503    }
5504}
5505
5506uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const
5507{
5508    uint32_t time;
5509    if (audio_has_proportional_frames(mFormat)) {
5510        time = PlaybackThread::activeSleepTimeUs();
5511    } else {
5512        // sleep time is half the duration of an audio HAL buffer.
5513        // Note: This can be problematic in case of underrun with variable bit rate and
5514        // current rate is much less than initial rate.
5515        time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2);
5516    }
5517    return time;
5518}
5519
5520// ----------------------------------------------------------------------------
5521
5522AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
5523        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
5524    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
5525                    systemReady, DUPLICATING),
5526        mWaitTimeMs(UINT_MAX)
5527{
5528    addOutputTrack(mainThread);
5529}
5530
5531AudioFlinger::DuplicatingThread::~DuplicatingThread()
5532{
5533    for (size_t i = 0; i < mOutputTracks.size(); i++) {
5534        mOutputTracks[i]->destroy();
5535    }
5536}
5537
5538void AudioFlinger::DuplicatingThread::threadLoop_mix()
5539{
5540    // mix buffers...
5541    if (outputsReady(outputTracks)) {
5542        mAudioMixer->process();
5543    } else {
5544        if (mMixerBufferValid) {
5545            memset(mMixerBuffer, 0, mMixerBufferSize);
5546        } else {
5547            memset(mSinkBuffer, 0, mSinkBufferSize);
5548        }
5549    }
5550    mSleepTimeUs = 0;
5551    writeFrames = mNormalFrameCount;
5552    mCurrentWriteLength = mSinkBufferSize;
5553    mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5554}
5555
5556void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5557{
5558    if (mSleepTimeUs == 0) {
5559        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5560            mSleepTimeUs = mActiveSleepTimeUs;
5561        } else {
5562            mSleepTimeUs = mIdleSleepTimeUs;
5563        }
5564    } else if (mBytesWritten != 0) {
5565        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5566            writeFrames = mNormalFrameCount;
5567            memset(mSinkBuffer, 0, mSinkBufferSize);
5568        } else {
5569            // flush remaining overflow buffers in output tracks
5570            writeFrames = 0;
5571        }
5572        mSleepTimeUs = 0;
5573    }
5574}
5575
5576ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
5577{
5578    for (size_t i = 0; i < outputTracks.size(); i++) {
5579        outputTracks[i]->write(mSinkBuffer, writeFrames);
5580    }
5581    mStandby = false;
5582    return (ssize_t)mSinkBufferSize;
5583}
5584
5585void AudioFlinger::DuplicatingThread::threadLoop_standby()
5586{
5587    // DuplicatingThread implements standby by stopping all tracks
5588    for (size_t i = 0; i < outputTracks.size(); i++) {
5589        outputTracks[i]->stop();
5590    }
5591}
5592
5593void AudioFlinger::DuplicatingThread::saveOutputTracks()
5594{
5595    outputTracks = mOutputTracks;
5596}
5597
5598void AudioFlinger::DuplicatingThread::clearOutputTracks()
5599{
5600    outputTracks.clear();
5601}
5602
5603void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5604{
5605    Mutex::Autolock _l(mLock);
5606    // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5607    // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5608    // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5609    const size_t frameCount =
5610            3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5611    // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5612    // from different OutputTracks and their associated MixerThreads (e.g. one may
5613    // nearly empty and the other may be dropping data).
5614
5615    sp<OutputTrack> outputTrack = new OutputTrack(thread,
5616                                            this,
5617                                            mSampleRate,
5618                                            mFormat,
5619                                            mChannelMask,
5620                                            frameCount,
5621                                            IPCThreadState::self()->getCallingUid());
5622    if (outputTrack->cblk() != NULL) {
5623        thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5624        mOutputTracks.add(outputTrack);
5625        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5626        updateWaitTime_l();
5627    }
5628}
5629
5630void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5631{
5632    Mutex::Autolock _l(mLock);
5633    for (size_t i = 0; i < mOutputTracks.size(); i++) {
5634        if (mOutputTracks[i]->thread() == thread) {
5635            mOutputTracks[i]->destroy();
5636            mOutputTracks.removeAt(i);
5637            updateWaitTime_l();
5638            if (thread->getOutput() == mOutput) {
5639                mOutput = NULL;
5640            }
5641            return;
5642        }
5643    }
5644    ALOGV("removeOutputTrack(): unknown thread: %p", thread);
5645}
5646
5647// caller must hold mLock
5648void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5649{
5650    mWaitTimeMs = UINT_MAX;
5651    for (size_t i = 0; i < mOutputTracks.size(); i++) {
5652        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5653        if (strong != 0) {
5654            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5655            if (waitTimeMs < mWaitTimeMs) {
5656                mWaitTimeMs = waitTimeMs;
5657            }
5658        }
5659    }
5660}
5661
5662
5663bool AudioFlinger::DuplicatingThread::outputsReady(
5664        const SortedVector< sp<OutputTrack> > &outputTracks)
5665{
5666    for (size_t i = 0; i < outputTracks.size(); i++) {
5667        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5668        if (thread == 0) {
5669            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5670                    outputTracks[i].get());
5671            return false;
5672        }
5673        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5674        // see note at standby() declaration
5675        if (playbackThread->standby() && !playbackThread->isSuspended()) {
5676            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5677                    thread.get());
5678            return false;
5679        }
5680    }
5681    return true;
5682}
5683
5684uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5685{
5686    return (mWaitTimeMs * 1000) / 2;
5687}
5688
5689void AudioFlinger::DuplicatingThread::cacheParameters_l()
5690{
5691    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5692    updateWaitTime_l();
5693
5694    MixerThread::cacheParameters_l();
5695}
5696
5697// ----------------------------------------------------------------------------
5698//      Record
5699// ----------------------------------------------------------------------------
5700
5701AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5702                                         AudioStreamIn *input,
5703                                         audio_io_handle_t id,
5704                                         audio_devices_t outDevice,
5705                                         audio_devices_t inDevice,
5706                                         bool systemReady
5707#ifdef TEE_SINK
5708                                         , const sp<NBAIO_Sink>& teeSink
5709#endif
5710                                         ) :
5711    ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
5712    mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
5713    // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
5714    mRsmpInRear(0)
5715#ifdef TEE_SINK
5716    , mTeeSink(teeSink)
5717#endif
5718    , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5719            "RecordThreadRO", MemoryHeapBase::READ_ONLY))
5720    // mFastCapture below
5721    , mFastCaptureFutex(0)
5722    // mInputSource
5723    // mPipeSink
5724    // mPipeSource
5725    , mPipeFramesP2(0)
5726    // mPipeMemory
5727    // mFastCaptureNBLogWriter
5728    , mFastTrackAvail(false)
5729{
5730    snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5731    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
5732
5733    readInputParameters_l();
5734
5735    // create an NBAIO source for the HAL input stream, and negotiate
5736    mInputSource = new AudioStreamInSource(input->stream);
5737    size_t numCounterOffers = 0;
5738    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5739#if !LOG_NDEBUG
5740    ssize_t index =
5741#else
5742    (void)
5743#endif
5744            mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5745    ALOG_ASSERT(index == 0);
5746
5747    // initialize fast capture depending on configuration
5748    bool initFastCapture;
5749    switch (kUseFastCapture) {
5750    case FastCapture_Never:
5751        initFastCapture = false;
5752        break;
5753    case FastCapture_Always:
5754        initFastCapture = true;
5755        break;
5756    case FastCapture_Static:
5757        initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
5758        break;
5759    // case FastCapture_Dynamic:
5760    }
5761
5762    if (initFastCapture) {
5763        // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
5764        NBAIO_Format format = mInputSource->format();
5765        size_t pipeFramesP2 = roundup(mSampleRate / 25);    // double-buffering of 20 ms each
5766        size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5767        void *pipeBuffer;
5768        const sp<MemoryDealer> roHeap(readOnlyHeap());
5769        sp<IMemory> pipeMemory;
5770        if ((roHeap == 0) ||
5771                (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5772                (pipeBuffer = pipeMemory->pointer()) == NULL) {
5773            ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5774            goto failed;
5775        }
5776        // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5777        memset(pipeBuffer, 0, pipeSize);
5778        Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5779        const NBAIO_Format offers[1] = {format};
5780        size_t numCounterOffers = 0;
5781        ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5782        ALOG_ASSERT(index == 0);
5783        mPipeSink = pipe;
5784        PipeReader *pipeReader = new PipeReader(*pipe);
5785        numCounterOffers = 0;
5786        index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5787        ALOG_ASSERT(index == 0);
5788        mPipeSource = pipeReader;
5789        mPipeFramesP2 = pipeFramesP2;
5790        mPipeMemory = pipeMemory;
5791
5792        // create fast capture
5793        mFastCapture = new FastCapture();
5794        FastCaptureStateQueue *sq = mFastCapture->sq();
5795#ifdef STATE_QUEUE_DUMP
5796        // FIXME
5797#endif
5798        FastCaptureState *state = sq->begin();
5799        state->mCblk = NULL;
5800        state->mInputSource = mInputSource.get();
5801        state->mInputSourceGen++;
5802        state->mPipeSink = pipe;
5803        state->mPipeSinkGen++;
5804        state->mFrameCount = mFrameCount;
5805        state->mCommand = FastCaptureState::COLD_IDLE;
5806        // already done in constructor initialization list
5807        //mFastCaptureFutex = 0;
5808        state->mColdFutexAddr = &mFastCaptureFutex;
5809        state->mColdGen++;
5810        state->mDumpState = &mFastCaptureDumpState;
5811#ifdef TEE_SINK
5812        // FIXME
5813#endif
5814        mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5815        state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5816        sq->end();
5817        sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5818
5819        // start the fast capture
5820        mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5821        pid_t tid = mFastCapture->getTid();
5822        sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
5823#ifdef AUDIO_WATCHDOG
5824        // FIXME
5825#endif
5826
5827        mFastTrackAvail = true;
5828    }
5829failed: ;
5830
5831    // FIXME mNormalSource
5832}
5833
5834AudioFlinger::RecordThread::~RecordThread()
5835{
5836    if (mFastCapture != 0) {
5837        FastCaptureStateQueue *sq = mFastCapture->sq();
5838        FastCaptureState *state = sq->begin();
5839        if (state->mCommand == FastCaptureState::COLD_IDLE) {
5840            int32_t old = android_atomic_inc(&mFastCaptureFutex);
5841            if (old == -1) {
5842                (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5843            }
5844        }
5845        state->mCommand = FastCaptureState::EXIT;
5846        sq->end();
5847        sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5848        mFastCapture->join();
5849        mFastCapture.clear();
5850    }
5851    mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
5852    mAudioFlinger->unregisterWriter(mNBLogWriter);
5853    free(mRsmpInBuffer);
5854}
5855
5856void AudioFlinger::RecordThread::onFirstRef()
5857{
5858    run(mThreadName, PRIORITY_URGENT_AUDIO);
5859}
5860
5861bool AudioFlinger::RecordThread::threadLoop()
5862{
5863    nsecs_t lastWarning = 0;
5864
5865    inputStandBy();
5866
5867reacquire_wakelock:
5868    sp<RecordTrack> activeTrack;
5869    int activeTracksGen;
5870    {
5871        Mutex::Autolock _l(mLock);
5872        size_t size = mActiveTracks.size();
5873        activeTracksGen = mActiveTracksGen;
5874        if (size > 0) {
5875            // FIXME an arbitrary choice
5876            activeTrack = mActiveTracks[0];
5877            acquireWakeLock_l(activeTrack->uid());
5878            if (size > 1) {
5879                SortedVector<int> tmp;
5880                for (size_t i = 0; i < size; i++) {
5881                    tmp.add(mActiveTracks[i]->uid());
5882                }
5883                updateWakeLockUids_l(tmp);
5884            }
5885        } else {
5886            acquireWakeLock_l(-1);
5887        }
5888    }
5889
5890    // used to request a deferred sleep, to be executed later while mutex is unlocked
5891    uint32_t sleepUs = 0;
5892
5893    // loop while there is work to do
5894    for (;;) {
5895        Vector< sp<EffectChain> > effectChains;
5896
5897        // sleep with mutex unlocked
5898        if (sleepUs > 0) {
5899            ATRACE_BEGIN("sleep");
5900            usleep(sleepUs);
5901            ATRACE_END();
5902            sleepUs = 0;
5903        }
5904
5905        // activeTracks accumulates a copy of a subset of mActiveTracks
5906        Vector< sp<RecordTrack> > activeTracks;
5907
5908        // reference to the (first and only) active fast track
5909        sp<RecordTrack> fastTrack;
5910
5911        // reference to a fast track which is about to be removed
5912        sp<RecordTrack> fastTrackToRemove;
5913
5914        { // scope for mLock
5915            Mutex::Autolock _l(mLock);
5916
5917            processConfigEvents_l();
5918
5919            // check exitPending here because checkForNewParameters_l() and
5920            // checkForNewParameters_l() can temporarily release mLock
5921            if (exitPending()) {
5922                break;
5923            }
5924
5925            // if no active track(s), then standby and release wakelock
5926            size_t size = mActiveTracks.size();
5927            if (size == 0) {
5928                standbyIfNotAlreadyInStandby();
5929                // exitPending() can't become true here
5930                releaseWakeLock_l();
5931                ALOGV("RecordThread: loop stopping");
5932                // go to sleep
5933                mWaitWorkCV.wait(mLock);
5934                ALOGV("RecordThread: loop starting");
5935                goto reacquire_wakelock;
5936            }
5937
5938            if (mActiveTracksGen != activeTracksGen) {
5939                activeTracksGen = mActiveTracksGen;
5940                SortedVector<int> tmp;
5941                for (size_t i = 0; i < size; i++) {
5942                    tmp.add(mActiveTracks[i]->uid());
5943                }
5944                updateWakeLockUids_l(tmp);
5945            }
5946
5947            bool doBroadcast = false;
5948            for (size_t i = 0; i < size; ) {
5949
5950                activeTrack = mActiveTracks[i];
5951                if (activeTrack->isTerminated()) {
5952                    if (activeTrack->isFastTrack()) {
5953                        ALOG_ASSERT(fastTrackToRemove == 0);
5954                        fastTrackToRemove = activeTrack;
5955                    }
5956                    removeTrack_l(activeTrack);
5957                    mActiveTracks.remove(activeTrack);
5958                    mActiveTracksGen++;
5959                    size--;
5960                    continue;
5961                }
5962
5963                TrackBase::track_state activeTrackState = activeTrack->mState;
5964                switch (activeTrackState) {
5965
5966                case TrackBase::PAUSING:
5967                    mActiveTracks.remove(activeTrack);
5968                    mActiveTracksGen++;
5969                    doBroadcast = true;
5970                    size--;
5971                    continue;
5972
5973                case TrackBase::STARTING_1:
5974                    sleepUs = 10000;
5975                    i++;
5976                    continue;
5977
5978                case TrackBase::STARTING_2:
5979                    doBroadcast = true;
5980                    mStandby = false;
5981                    activeTrack->mState = TrackBase::ACTIVE;
5982                    break;
5983
5984                case TrackBase::ACTIVE:
5985                    break;
5986
5987                case TrackBase::IDLE:
5988                    i++;
5989                    continue;
5990
5991                default:
5992                    LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
5993                }
5994
5995                activeTracks.add(activeTrack);
5996                i++;
5997
5998                if (activeTrack->isFastTrack()) {
5999                    ALOG_ASSERT(!mFastTrackAvail);
6000                    ALOG_ASSERT(fastTrack == 0);
6001                    fastTrack = activeTrack;
6002                }
6003            }
6004            if (doBroadcast) {
6005                mStartStopCond.broadcast();
6006            }
6007
6008            // sleep if there are no active tracks to process
6009            if (activeTracks.size() == 0) {
6010                if (sleepUs == 0) {
6011                    sleepUs = kRecordThreadSleepUs;
6012                }
6013                continue;
6014            }
6015            sleepUs = 0;
6016
6017            lockEffectChains_l(effectChains);
6018        }
6019
6020        // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
6021
6022        size_t size = effectChains.size();
6023        for (size_t i = 0; i < size; i++) {
6024            // thread mutex is not locked, but effect chain is locked
6025            effectChains[i]->process_l();
6026        }
6027
6028        // Push a new fast capture state if fast capture is not already running, or cblk change
6029        if (mFastCapture != 0) {
6030            FastCaptureStateQueue *sq = mFastCapture->sq();
6031            FastCaptureState *state = sq->begin();
6032            bool didModify = false;
6033            FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
6034            if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6035                    (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6036                if (state->mCommand == FastCaptureState::COLD_IDLE) {
6037                    int32_t old = android_atomic_inc(&mFastCaptureFutex);
6038                    if (old == -1) {
6039                        (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6040                    }
6041                }
6042                state->mCommand = FastCaptureState::READ_WRITE;
6043#if 0   // FIXME
6044                mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
6045                        FastThreadDumpState::kSamplingNforLowRamDevice :
6046                        FastThreadDumpState::kSamplingN);
6047#endif
6048                didModify = true;
6049            }
6050            audio_track_cblk_t *cblkOld = state->mCblk;
6051            audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6052            if (cblkNew != cblkOld) {
6053                state->mCblk = cblkNew;
6054                // block until acked if removing a fast track
6055                if (cblkOld != NULL) {
6056                    block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6057                }
6058                didModify = true;
6059            }
6060            sq->end(didModify);
6061            if (didModify) {
6062                sq->push(block);
6063#if 0
6064                if (kUseFastCapture == FastCapture_Dynamic) {
6065                    mNormalSource = mPipeSource;
6066                }
6067#endif
6068            }
6069        }
6070
6071        // now run the fast track destructor with thread mutex unlocked
6072        fastTrackToRemove.clear();
6073
6074        // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6075        // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6076        // slow, then this RecordThread will overrun by not calling HAL read often enough.
6077        // If destination is non-contiguous, first read past the nominal end of buffer, then
6078        // copy to the right place.  Permitted because mRsmpInBuffer was over-allocated.
6079
6080        int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
6081        ssize_t framesRead;
6082
6083        // If an NBAIO source is present, use it to read the normal capture's data
6084        if (mPipeSource != 0) {
6085            size_t framesToRead = mBufferSize / mFrameSize;
6086            framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6087                    framesToRead);
6088            if (framesRead == 0) {
6089                // since pipe is non-blocking, simulate blocking input
6090                sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6091            }
6092        // otherwise use the HAL / AudioStreamIn directly
6093        } else {
6094            ssize_t bytesRead = mInput->stream->read(mInput->stream,
6095                    (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
6096            if (bytesRead < 0) {
6097                framesRead = bytesRead;
6098            } else {
6099                framesRead = bytesRead / mFrameSize;
6100            }
6101        }
6102
6103        // Update server timestamp with server stats
6104        // systemTime() is optional if the hardware supports timestamps.
6105        mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6106        mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6107
6108        // Update server timestamp with kernel stats
6109        if (mInput->stream->get_capture_position != nullptr) {
6110            int64_t position, time;
6111            int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6112            if (ret == NO_ERROR) {
6113                mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6114                mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6115                // Note: In general record buffers should tend to be empty in
6116                // a properly running pipeline.
6117                //
6118                // Also, it is not advantageous to call get_presentation_position during the read
6119                // as the read obtains a lock, preventing the timestamp call from executing.
6120            }
6121        }
6122        // Use this to track timestamp information
6123        // ALOGD("%s", mTimestamp.toString().c_str());
6124
6125        if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
6126            ALOGE("read failed: framesRead=%d", framesRead);
6127            // Force input into standby so that it tries to recover at next read attempt
6128            inputStandBy();
6129            sleepUs = kRecordThreadSleepUs;
6130        }
6131        if (framesRead <= 0) {
6132            goto unlock;
6133        }
6134        ALOG_ASSERT(framesRead > 0);
6135
6136        if (mTeeSink != 0) {
6137            (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6138        }
6139        // If destination is non-contiguous, we now correct for reading past end of buffer.
6140        {
6141            size_t part1 = mRsmpInFramesP2 - rear;
6142            if ((size_t) framesRead > part1) {
6143                memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
6144                        (framesRead - part1) * mFrameSize);
6145            }
6146        }
6147        rear = mRsmpInRear += framesRead;
6148
6149        size = activeTracks.size();
6150        // loop over each active track
6151        for (size_t i = 0; i < size; i++) {
6152            activeTrack = activeTracks[i];
6153
6154            // skip fast tracks, as those are handled directly by FastCapture
6155            if (activeTrack->isFastTrack()) {
6156                continue;
6157            }
6158
6159            // TODO: This code probably should be moved to RecordTrack.
6160            // TODO: Update the activeTrack buffer converter in case of reconfigure.
6161
6162            enum {
6163                OVERRUN_UNKNOWN,
6164                OVERRUN_TRUE,
6165                OVERRUN_FALSE
6166            } overrun = OVERRUN_UNKNOWN;
6167
6168            // loop over getNextBuffer to handle circular sink
6169            for (;;) {
6170
6171                activeTrack->mSink.frameCount = ~0;
6172                status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6173                size_t framesOut = activeTrack->mSink.frameCount;
6174                LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6175
6176                // check available frames and handle overrun conditions
6177                // if the record track isn't draining fast enough.
6178                bool hasOverrun;
6179                size_t framesIn;
6180                activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6181                if (hasOverrun) {
6182                    overrun = OVERRUN_TRUE;
6183                }
6184                if (framesOut == 0 || framesIn == 0) {
6185                    break;
6186                }
6187
6188                // Don't allow framesOut to be larger than what is possible with resampling
6189                // from framesIn.
6190                // This isn't strictly necessary but helps limit buffer resizing in
6191                // RecordBufferConverter.  TODO: remove when no longer needed.
6192                framesOut = min(framesOut,
6193                        destinationFramesPossible(
6194                                framesIn, mSampleRate, activeTrack->mSampleRate));
6195                // process frames from the RecordThread buffer provider to the RecordTrack buffer
6196                framesOut = activeTrack->mRecordBufferConverter->convert(
6197                        activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
6198
6199                if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6200                    overrun = OVERRUN_FALSE;
6201                }
6202
6203                if (activeTrack->mFramesToDrop == 0) {
6204                    if (framesOut > 0) {
6205                        activeTrack->mSink.frameCount = framesOut;
6206                        activeTrack->releaseBuffer(&activeTrack->mSink);
6207                    }
6208                } else {
6209                    // FIXME could do a partial drop of framesOut
6210                    if (activeTrack->mFramesToDrop > 0) {
6211                        activeTrack->mFramesToDrop -= framesOut;
6212                        if (activeTrack->mFramesToDrop <= 0) {
6213                            activeTrack->clearSyncStartEvent();
6214                        }
6215                    } else {
6216                        activeTrack->mFramesToDrop += framesOut;
6217                        if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6218                                activeTrack->mSyncStartEvent->isCancelled()) {
6219                            ALOGW("Synced record %s, session %d, trigger session %d",
6220                                  (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6221                                  activeTrack->sessionId(),
6222                                  (activeTrack->mSyncStartEvent != 0) ?
6223                                          activeTrack->mSyncStartEvent->triggerSession() :
6224                                          AUDIO_SESSION_NONE);
6225                            activeTrack->clearSyncStartEvent();
6226                        }
6227                    }
6228                }
6229
6230                if (framesOut == 0) {
6231                    break;
6232                }
6233            }
6234
6235            switch (overrun) {
6236            case OVERRUN_TRUE:
6237                // client isn't retrieving buffers fast enough
6238                if (!activeTrack->setOverflow()) {
6239                    nsecs_t now = systemTime();
6240                    // FIXME should lastWarning per track?
6241                    if ((now - lastWarning) > kWarningThrottleNs) {
6242                        ALOGW("RecordThread: buffer overflow");
6243                        lastWarning = now;
6244                    }
6245                }
6246                break;
6247            case OVERRUN_FALSE:
6248                activeTrack->clearOverflow();
6249                break;
6250            case OVERRUN_UNKNOWN:
6251                break;
6252            }
6253
6254            // update frame information and push timestamp out
6255            activeTrack->updateTrackFrameInfo(
6256                    activeTrack->mServerProxy->framesReleased(),
6257                    mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6258                    mSampleRate, mTimestamp);
6259        }
6260
6261unlock:
6262        // enable changes in effect chain
6263        unlockEffectChains(effectChains);
6264        // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
6265    }
6266
6267    standbyIfNotAlreadyInStandby();
6268
6269    {
6270        Mutex::Autolock _l(mLock);
6271        for (size_t i = 0; i < mTracks.size(); i++) {
6272            sp<RecordTrack> track = mTracks[i];
6273            track->invalidate();
6274        }
6275        mActiveTracks.clear();
6276        mActiveTracksGen++;
6277        mStartStopCond.broadcast();
6278    }
6279
6280    releaseWakeLock();
6281
6282    ALOGV("RecordThread %p exiting", this);
6283    return false;
6284}
6285
6286void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
6287{
6288    if (!mStandby) {
6289        inputStandBy();
6290        mStandby = true;
6291    }
6292}
6293
6294void AudioFlinger::RecordThread::inputStandBy()
6295{
6296    // Idle the fast capture if it's currently running
6297    if (mFastCapture != 0) {
6298        FastCaptureStateQueue *sq = mFastCapture->sq();
6299        FastCaptureState *state = sq->begin();
6300        if (!(state->mCommand & FastCaptureState::IDLE)) {
6301            state->mCommand = FastCaptureState::COLD_IDLE;
6302            state->mColdFutexAddr = &mFastCaptureFutex;
6303            state->mColdGen++;
6304            mFastCaptureFutex = 0;
6305            sq->end();
6306            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6307            sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6308#if 0
6309            if (kUseFastCapture == FastCapture_Dynamic) {
6310                // FIXME
6311            }
6312#endif
6313#ifdef AUDIO_WATCHDOG
6314            // FIXME
6315#endif
6316        } else {
6317            sq->end(false /*didModify*/);
6318        }
6319    }
6320    mInput->stream->common.standby(&mInput->stream->common);
6321}
6322
6323// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
6324sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6325        const sp<AudioFlinger::Client>& client,
6326        uint32_t sampleRate,
6327        audio_format_t format,
6328        audio_channel_mask_t channelMask,
6329        size_t *pFrameCount,
6330        audio_session_t sessionId,
6331        size_t *notificationFrames,
6332        int uid,
6333        IAudioFlinger::track_flags_t *flags,
6334        pid_t tid,
6335        status_t *status)
6336{
6337    size_t frameCount = *pFrameCount;
6338    sp<RecordTrack> track;
6339    status_t lStatus;
6340
6341    // client expresses a preference for FAST, but we get the final say
6342    if (*flags & IAudioFlinger::TRACK_FAST) {
6343      if (
6344            // we formerly checked for a callback handler (non-0 tid),
6345            // but that is no longer required for TRANSFER_OBTAIN mode
6346            //
6347            // frame count is not specified, or is exactly the pipe depth
6348            ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
6349            // PCM data
6350            audio_is_linear_pcm(format) &&
6351            // hardware format
6352            (format == mFormat) &&
6353            // hardware channel mask
6354            (channelMask == mChannelMask) &&
6355            // hardware sample rate
6356            (sampleRate == mSampleRate) &&
6357            // record thread has an associated fast capture
6358            hasFastCapture() &&
6359            // there are sufficient fast track slots available
6360            mFastTrackAvail
6361        ) {
6362        ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
6363                frameCount, mFrameCount);
6364      } else {
6365        ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6366                "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
6367                "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
6368                frameCount, mFrameCount, mPipeFramesP2,
6369                format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6370                hasFastCapture(), tid, mFastTrackAvail);
6371        *flags &= ~IAudioFlinger::TRACK_FAST;
6372      }
6373    }
6374
6375    // compute track buffer size in frames, and suggest the notification frame count
6376    if (*flags & IAudioFlinger::TRACK_FAST) {
6377        // fast track: frame count is exactly the pipe depth
6378        frameCount = mPipeFramesP2;
6379        // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6380        *notificationFrames = mFrameCount;
6381    } else {
6382        // not fast track: max notification period is resampled equivalent of one HAL buffer time
6383        //                 or 20 ms if there is a fast capture
6384        // TODO This could be a roundupRatio inline, and const
6385        size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6386                * sampleRate + mSampleRate - 1) / mSampleRate;
6387        // minimum number of notification periods is at least kMinNotifications,
6388        // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6389        static const size_t kMinNotifications = 3;
6390        static const uint32_t kMinMs = 30;
6391        // TODO This could be a roundupRatio inline
6392        const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6393        // TODO This could be a roundupRatio inline
6394        const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6395                maxNotificationFrames;
6396        const size_t minFrameCount = maxNotificationFrames *
6397                max(kMinNotifications, minNotificationsByMs);
6398        frameCount = max(frameCount, minFrameCount);
6399        if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6400            *notificationFrames = maxNotificationFrames;
6401        }
6402    }
6403    *pFrameCount = frameCount;
6404
6405    lStatus = initCheck();
6406    if (lStatus != NO_ERROR) {
6407        ALOGE("createRecordTrack_l() audio driver not initialized");
6408        goto Exit;
6409    }
6410
6411    { // scope for mLock
6412        Mutex::Autolock _l(mLock);
6413
6414        track = new RecordTrack(this, client, sampleRate,
6415                      format, channelMask, frameCount, NULL, sessionId, uid,
6416                      *flags, TrackBase::TYPE_DEFAULT);
6417
6418        lStatus = track->initCheck();
6419        if (lStatus != NO_ERROR) {
6420            ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
6421            // track must be cleared from the caller as the caller has the AF lock
6422            goto Exit;
6423        }
6424        mTracks.add(track);
6425
6426        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6427        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6428                        mAudioFlinger->btNrecIsOff();
6429        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6430        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
6431
6432        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6433            pid_t callingPid = IPCThreadState::self()->getCallingPid();
6434            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6435            // so ask activity manager to do this on our behalf
6436            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6437        }
6438    }
6439
6440    lStatus = NO_ERROR;
6441
6442Exit:
6443    *status = lStatus;
6444    return track;
6445}
6446
6447status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6448                                           AudioSystem::sync_event_t event,
6449                                           audio_session_t triggerSession)
6450{
6451    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6452    sp<ThreadBase> strongMe = this;
6453    status_t status = NO_ERROR;
6454
6455    if (event == AudioSystem::SYNC_EVENT_NONE) {
6456        recordTrack->clearSyncStartEvent();
6457    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6458        recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6459                                       triggerSession,
6460                                       recordTrack->sessionId(),
6461                                       syncStartEventCallback,
6462                                       recordTrack);
6463        // Sync event can be cancelled by the trigger session if the track is not in a
6464        // compatible state in which case we start record immediately
6465        if (recordTrack->mSyncStartEvent->isCancelled()) {
6466            recordTrack->clearSyncStartEvent();
6467        } else {
6468            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6469            recordTrack->mFramesToDrop = -
6470                    ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
6471        }
6472    }
6473
6474    {
6475        // This section is a rendezvous between binder thread executing start() and RecordThread
6476        AutoMutex lock(mLock);
6477        if (mActiveTracks.indexOf(recordTrack) >= 0) {
6478            if (recordTrack->mState == TrackBase::PAUSING) {
6479                ALOGV("active record track PAUSING -> ACTIVE");
6480                recordTrack->mState = TrackBase::ACTIVE;
6481            } else {
6482                ALOGV("active record track state %d", recordTrack->mState);
6483            }
6484            return status;
6485        }
6486
6487        // TODO consider other ways of handling this, such as changing the state to :STARTING and
6488        //      adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6489        //      or using a separate command thread
6490        recordTrack->mState = TrackBase::STARTING_1;
6491        mActiveTracks.add(recordTrack);
6492        mActiveTracksGen++;
6493        status_t status = NO_ERROR;
6494        if (recordTrack->isExternalTrack()) {
6495            mLock.unlock();
6496            status = AudioSystem::startInput(mId, recordTrack->sessionId());
6497            mLock.lock();
6498            // FIXME should verify that recordTrack is still in mActiveTracks
6499            if (status != NO_ERROR) {
6500                mActiveTracks.remove(recordTrack);
6501                mActiveTracksGen++;
6502                recordTrack->clearSyncStartEvent();
6503                ALOGV("RecordThread::start error %d", status);
6504                return status;
6505            }
6506        }
6507        // Catch up with current buffer indices if thread is already running.
6508        // This is what makes a new client discard all buffered data.  If the track's mRsmpInFront
6509        // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6510        // see previously buffered data before it called start(), but with greater risk of overrun.
6511
6512        recordTrack->mResamplerBufferProvider->reset();
6513        // clear any converter state as new data will be discontinuous
6514        recordTrack->mRecordBufferConverter->reset();
6515        recordTrack->mState = TrackBase::STARTING_2;
6516        // signal thread to start
6517        mWaitWorkCV.broadcast();
6518        if (mActiveTracks.indexOf(recordTrack) < 0) {
6519            ALOGV("Record failed to start");
6520            status = BAD_VALUE;
6521            goto startError;
6522        }
6523        return status;
6524    }
6525
6526startError:
6527    if (recordTrack->isExternalTrack()) {
6528        AudioSystem::stopInput(mId, recordTrack->sessionId());
6529    }
6530    recordTrack->clearSyncStartEvent();
6531    // FIXME I wonder why we do not reset the state here?
6532    return status;
6533}
6534
6535void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6536{
6537    sp<SyncEvent> strongEvent = event.promote();
6538
6539    if (strongEvent != 0) {
6540        sp<RefBase> ptr = strongEvent->cookie().promote();
6541        if (ptr != 0) {
6542            RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6543            recordTrack->handleSyncStartEvent(strongEvent);
6544        }
6545    }
6546}
6547
6548bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
6549    ALOGV("RecordThread::stop");
6550    AutoMutex _l(mLock);
6551    if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
6552        return false;
6553    }
6554    // note that threadLoop may still be processing the track at this point [without lock]
6555    recordTrack->mState = TrackBase::PAUSING;
6556    // do not wait for mStartStopCond if exiting
6557    if (exitPending()) {
6558        return true;
6559    }
6560    // FIXME incorrect usage of wait: no explicit predicate or loop
6561    mStartStopCond.wait(mLock);
6562    // if we have been restarted, recordTrack is in mActiveTracks here
6563    if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
6564        ALOGV("Record stopped OK");
6565        return true;
6566    }
6567    return false;
6568}
6569
6570bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
6571{
6572    return false;
6573}
6574
6575status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
6576{
6577#if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
6578    if (!isValidSyncEvent(event)) {
6579        return BAD_VALUE;
6580    }
6581
6582    audio_session_t eventSession = event->triggerSession();
6583    status_t ret = NAME_NOT_FOUND;
6584
6585    Mutex::Autolock _l(mLock);
6586
6587    for (size_t i = 0; i < mTracks.size(); i++) {
6588        sp<RecordTrack> track = mTracks[i];
6589        if (eventSession == track->sessionId()) {
6590            (void) track->setSyncEvent(event);
6591            ret = NO_ERROR;
6592        }
6593    }
6594    return ret;
6595#else
6596    return BAD_VALUE;
6597#endif
6598}
6599
6600// destroyTrack_l() must be called with ThreadBase::mLock held
6601void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6602{
6603    track->terminate();
6604    track->mState = TrackBase::STOPPED;
6605    // active tracks are removed by threadLoop()
6606    if (mActiveTracks.indexOf(track) < 0) {
6607        removeTrack_l(track);
6608    }
6609}
6610
6611void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6612{
6613    mTracks.remove(track);
6614    // need anything related to effects here?
6615    if (track->isFastTrack()) {
6616        ALOG_ASSERT(!mFastTrackAvail);
6617        mFastTrackAvail = true;
6618    }
6619}
6620
6621void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6622{
6623    dumpInternals(fd, args);
6624    dumpTracks(fd, args);
6625    dumpEffectChains(fd, args);
6626}
6627
6628void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6629{
6630    dprintf(fd, "\nInput thread %p:\n", this);
6631
6632    dumpBase(fd, args);
6633
6634    if (mActiveTracks.size() == 0) {
6635        dprintf(fd, "  No active record clients\n");
6636    }
6637    dprintf(fd, "  Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
6638    dprintf(fd, "  Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
6639
6640    // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6641    // while we are dumping it.  It may be inconsistent, but it won't mutate!
6642    // This is a large object so we place it on the heap.
6643    // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6644    const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6645    copy->dump(fd);
6646    delete copy;
6647}
6648
6649void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
6650{
6651    const size_t SIZE = 256;
6652    char buffer[SIZE];
6653    String8 result;
6654
6655    size_t numtracks = mTracks.size();
6656    size_t numactive = mActiveTracks.size();
6657    size_t numactiveseen = 0;
6658    dprintf(fd, "  %d Tracks", numtracks);
6659    if (numtracks) {
6660        dprintf(fd, " of which %d are active\n", numactive);
6661        RecordTrack::appendDumpHeader(result);
6662        for (size_t i = 0; i < numtracks ; ++i) {
6663            sp<RecordTrack> track = mTracks[i];
6664            if (track != 0) {
6665                bool active = mActiveTracks.indexOf(track) >= 0;
6666                if (active) {
6667                    numactiveseen++;
6668                }
6669                track->dump(buffer, SIZE, active);
6670                result.append(buffer);
6671            }
6672        }
6673    } else {
6674        dprintf(fd, "\n");
6675    }
6676
6677    if (numactiveseen != numactive) {
6678        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
6679                " not in the track list\n");
6680        result.append(buffer);
6681        RecordTrack::appendDumpHeader(result);
6682        for (size_t i = 0; i < numactive; ++i) {
6683            sp<RecordTrack> track = mActiveTracks[i];
6684            if (mTracks.indexOf(track) < 0) {
6685                track->dump(buffer, SIZE, true);
6686                result.append(buffer);
6687            }
6688        }
6689
6690    }
6691    write(fd, result.string(), result.size());
6692}
6693
6694
6695void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6696{
6697    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6698    RecordThread *recordThread = (RecordThread *) threadBase.get();
6699    mRsmpInFront = recordThread->mRsmpInRear;
6700    mRsmpInUnrel = 0;
6701}
6702
6703void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6704        size_t *framesAvailable, bool *hasOverrun)
6705{
6706    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6707    RecordThread *recordThread = (RecordThread *) threadBase.get();
6708    const int32_t rear = recordThread->mRsmpInRear;
6709    const int32_t front = mRsmpInFront;
6710    const ssize_t filled = rear - front;
6711
6712    size_t framesIn;
6713    bool overrun = false;
6714    if (filled < 0) {
6715        // should not happen, but treat like a massive overrun and re-sync
6716        framesIn = 0;
6717        mRsmpInFront = rear;
6718        overrun = true;
6719    } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6720        framesIn = (size_t) filled;
6721    } else {
6722        // client is not keeping up with server, but give it latest data
6723        framesIn = recordThread->mRsmpInFrames;
6724        mRsmpInFront = /* front = */ rear - framesIn;
6725        overrun = true;
6726    }
6727    if (framesAvailable != NULL) {
6728        *framesAvailable = framesIn;
6729    }
6730    if (hasOverrun != NULL) {
6731        *hasOverrun = overrun;
6732    }
6733}
6734
6735// AudioBufferProvider interface
6736status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6737        AudioBufferProvider::Buffer* buffer)
6738{
6739    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6740    if (threadBase == 0) {
6741        buffer->frameCount = 0;
6742        buffer->raw = NULL;
6743        return NOT_ENOUGH_DATA;
6744    }
6745    RecordThread *recordThread = (RecordThread *) threadBase.get();
6746    int32_t rear = recordThread->mRsmpInRear;
6747    int32_t front = mRsmpInFront;
6748    ssize_t filled = rear - front;
6749    // FIXME should not be P2 (don't want to increase latency)
6750    // FIXME if client not keeping up, discard
6751    LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
6752    // 'filled' may be non-contiguous, so return only the first contiguous chunk
6753    front &= recordThread->mRsmpInFramesP2 - 1;
6754    size_t part1 = recordThread->mRsmpInFramesP2 - front;
6755    if (part1 > (size_t) filled) {
6756        part1 = filled;
6757    }
6758    size_t ask = buffer->frameCount;
6759    ALOG_ASSERT(ask > 0);
6760    if (part1 > ask) {
6761        part1 = ask;
6762    }
6763    if (part1 == 0) {
6764        // out of data is fine since the resampler will return a short-count.
6765        buffer->raw = NULL;
6766        buffer->frameCount = 0;
6767        mRsmpInUnrel = 0;
6768        return NOT_ENOUGH_DATA;
6769    }
6770
6771    buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
6772    buffer->frameCount = part1;
6773    mRsmpInUnrel = part1;
6774    return NO_ERROR;
6775}
6776
6777// AudioBufferProvider interface
6778void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6779        AudioBufferProvider::Buffer* buffer)
6780{
6781    size_t stepCount = buffer->frameCount;
6782    if (stepCount == 0) {
6783        return;
6784    }
6785    ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6786    mRsmpInUnrel -= stepCount;
6787    mRsmpInFront += stepCount;
6788    buffer->raw = NULL;
6789    buffer->frameCount = 0;
6790}
6791
6792AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6793        audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6794        uint32_t srcSampleRate,
6795        audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6796        uint32_t dstSampleRate) :
6797            mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6798            // mSrcFormat
6799            // mSrcSampleRate
6800            // mDstChannelMask
6801            // mDstFormat
6802            // mDstSampleRate
6803            // mSrcChannelCount
6804            // mDstChannelCount
6805            // mDstFrameSize
6806            mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
6807            mResampler(NULL),
6808            mIsLegacyDownmix(false),
6809            mIsLegacyUpmix(false),
6810            mRequiresFloat(false),
6811            mInputConverterProvider(NULL)
6812{
6813    (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6814            dstChannelMask, dstFormat, dstSampleRate);
6815}
6816
6817AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6818    free(mBuf);
6819    delete mResampler;
6820    delete mInputConverterProvider;
6821}
6822
6823size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6824        AudioBufferProvider *provider, size_t frames)
6825{
6826    if (mInputConverterProvider != NULL) {
6827        mInputConverterProvider->setBufferProvider(provider);
6828        provider = mInputConverterProvider;
6829    }
6830
6831    if (mResampler == NULL) {
6832        ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6833                mSrcSampleRate, mSrcFormat, mDstFormat);
6834
6835        AudioBufferProvider::Buffer buffer;
6836        for (size_t i = frames; i > 0; ) {
6837            buffer.frameCount = i;
6838            status_t status = provider->getNextBuffer(&buffer);
6839            if (status != OK || buffer.frameCount == 0) {
6840                frames -= i; // cannot fill request.
6841                break;
6842            }
6843            // format convert to destination buffer
6844            convertNoResampler(dst, buffer.raw, buffer.frameCount);
6845
6846            dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6847            i -= buffer.frameCount;
6848            provider->releaseBuffer(&buffer);
6849        }
6850    } else {
6851         ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6852                 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6853
6854         // reallocate buffer if needed
6855         if (mBufFrameSize != 0 && mBufFrames < frames) {
6856             free(mBuf);
6857             mBufFrames = frames;
6858             (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6859         }
6860        // resampler accumulates, but we only have one source track
6861        memset(mBuf, 0, frames * mBufFrameSize);
6862        frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6863        // format convert to destination buffer
6864        convertResampler(dst, mBuf, frames);
6865    }
6866    return frames;
6867}
6868
6869status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6870        audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6871        uint32_t srcSampleRate,
6872        audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6873        uint32_t dstSampleRate)
6874{
6875    // quick evaluation if there is any change.
6876    if (mSrcFormat == srcFormat
6877            && mSrcChannelMask == srcChannelMask
6878            && mSrcSampleRate == srcSampleRate
6879            && mDstFormat == dstFormat
6880            && mDstChannelMask == dstChannelMask
6881            && mDstSampleRate == dstSampleRate) {
6882        return NO_ERROR;
6883    }
6884
6885    ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6886            "  srcFormat:%#x dstFormat:%#x  srcRate:%u dstRate:%u",
6887            srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
6888    const bool valid =
6889            audio_is_input_channel(srcChannelMask)
6890            && audio_is_input_channel(dstChannelMask)
6891            && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6892            && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6893            && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6894            ; // no upsampling checks for now
6895    if (!valid) {
6896        return BAD_VALUE;
6897    }
6898
6899    mSrcFormat = srcFormat;
6900    mSrcChannelMask = srcChannelMask;
6901    mSrcSampleRate = srcSampleRate;
6902    mDstFormat = dstFormat;
6903    mDstChannelMask = dstChannelMask;
6904    mDstSampleRate = dstSampleRate;
6905
6906    // compute derived parameters
6907    mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6908    mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6909    mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6910
6911    // do we need to resample?
6912    delete mResampler;
6913    mResampler = NULL;
6914    if (mSrcSampleRate != mDstSampleRate) {
6915        mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6916                mSrcChannelCount, mDstSampleRate);
6917        mResampler->setSampleRate(mSrcSampleRate);
6918        mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6919    }
6920
6921    // are we running legacy channel conversion modes?
6922    mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6923                            || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6924                   && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6925    mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6926                   && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6927                            || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6928
6929    // do we need to process in float?
6930    mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6931
6932    // do we need a staging buffer to convert for destination (we can still optimize this)?
6933    // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6934    if (mResampler != NULL) {
6935        mBufFrameSize = max(mSrcChannelCount, FCC_2)
6936                * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6937    } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
6938        mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6939    } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
6940        mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6941    } else {
6942        mBufFrameSize = 0;
6943    }
6944    mBufFrames = 0; // force the buffer to be resized.
6945
6946    // do we need an input converter buffer provider to give us float?
6947    delete mInputConverterProvider;
6948    mInputConverterProvider = NULL;
6949    if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6950        mInputConverterProvider = new ReformatBufferProvider(
6951                audio_channel_count_from_in_mask(mSrcChannelMask),
6952                mSrcFormat,
6953                AUDIO_FORMAT_PCM_FLOAT,
6954                256 /* provider buffer frame count */);
6955    }
6956
6957    // do we need a remixer to do channel mask conversion
6958    if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6959        (void) memcpy_by_index_array_initialization_from_channel_mask(
6960                mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
6961    }
6962    return NO_ERROR;
6963}
6964
6965void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6966        void *dst, const void *src, size_t frames)
6967{
6968    // src is native type unless there is legacy upmix or downmix, whereupon it is float.
6969    if (mBufFrameSize != 0 && mBufFrames < frames) {
6970        free(mBuf);
6971        mBufFrames = frames;
6972        (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6973    }
6974    // do we need to do legacy upmix and downmix?
6975    if (mIsLegacyUpmix || mIsLegacyDownmix) {
6976        void *dstBuf = mBuf != NULL ? mBuf : dst;
6977        if (mIsLegacyUpmix) {
6978            upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6979                    (const float *)src, frames);
6980        } else /*mIsLegacyDownmix */ {
6981            downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6982                    (const float *)src, frames);
6983        }
6984        if (mBuf != NULL) {
6985            memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6986                    frames * mDstChannelCount);
6987        }
6988        return;
6989    }
6990    // do we need to do channel mask conversion?
6991    if (mSrcChannelMask != mDstChannelMask) {
6992        void *dstBuf = mBuf != NULL ? mBuf : dst;
6993        memcpy_by_index_array(dstBuf, mDstChannelCount,
6994                src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6995        if (dstBuf == dst) {
6996            return; // format is the same
6997        }
6998    }
6999    // convert to destination buffer
7000    const void *convertBuf = mBuf != NULL ? mBuf : src;
7001    memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7002            frames * mDstChannelCount);
7003}
7004
7005void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7006        void *dst, /*not-a-const*/ void *src, size_t frames)
7007{
7008    // src buffer format is ALWAYS float when entering this routine
7009    if (mIsLegacyUpmix) {
7010        ; // mono to stereo already handled by resampler
7011    } else if (mIsLegacyDownmix
7012            || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7013        // the resampler outputs stereo for mono input channel (a feature?)
7014        // must convert to mono
7015        downmix_to_mono_float_from_stereo_float((float *)src,
7016                (const float *)src, frames);
7017    } else if (mSrcChannelMask != mDstChannelMask) {
7018        // convert to mono channel again for channel mask conversion (could be skipped
7019        // with further optimization).
7020        if (mSrcChannelCount == 1) {
7021            downmix_to_mono_float_from_stereo_float((float *)src,
7022                (const float *)src, frames);
7023        }
7024        // convert to destination format (in place, OK as float is larger than other types)
7025        if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7026            memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7027                    frames * mSrcChannelCount);
7028        }
7029        // channel convert and save to dst
7030        memcpy_by_index_array(dst, mDstChannelCount,
7031                src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7032        return;
7033    }
7034    // convert to destination format and save to dst
7035    memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7036            frames * mDstChannelCount);
7037}
7038
7039bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7040                                                        status_t& status)
7041{
7042    bool reconfig = false;
7043
7044    status = NO_ERROR;
7045
7046    audio_format_t reqFormat = mFormat;
7047    uint32_t samplingRate = mSampleRate;
7048    // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
7049    audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7050
7051    AudioParameter param = AudioParameter(keyValuePair);
7052    int value;
7053    // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7054    //      channel count change can be requested. Do we mandate the first client defines the
7055    //      HAL sampling rate and channel count or do we allow changes on the fly?
7056    if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7057        samplingRate = value;
7058        reconfig = true;
7059    }
7060    if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
7061        if (!audio_is_linear_pcm((audio_format_t) value)) {
7062            status = BAD_VALUE;
7063        } else {
7064            reqFormat = (audio_format_t) value;
7065            reconfig = true;
7066        }
7067    }
7068    if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7069        audio_channel_mask_t mask = (audio_channel_mask_t) value;
7070        if (!audio_is_input_channel(mask) ||
7071                audio_channel_count_from_in_mask(mask) > FCC_8) {
7072            status = BAD_VALUE;
7073        } else {
7074            channelMask = mask;
7075            reconfig = true;
7076        }
7077    }
7078    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7079        // do not accept frame count changes if tracks are open as the track buffer
7080        // size depends on frame count and correct behavior would not be guaranteed
7081        // if frame count is changed after track creation
7082        if (mActiveTracks.size() > 0) {
7083            status = INVALID_OPERATION;
7084        } else {
7085            reconfig = true;
7086        }
7087    }
7088    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7089        // forward device change to effects that have requested to be
7090        // aware of attached audio device.
7091        for (size_t i = 0; i < mEffectChains.size(); i++) {
7092            mEffectChains[i]->setDevice_l(value);
7093        }
7094
7095        // store input device and output device but do not forward output device to audio HAL.
7096        // Note that status is ignored by the caller for output device
7097        // (see AudioFlinger::setParameters()
7098        if (audio_is_output_devices(value)) {
7099            mOutDevice = value;
7100            status = BAD_VALUE;
7101        } else {
7102            mInDevice = value;
7103            if (value != AUDIO_DEVICE_NONE) {
7104                mPrevInDevice = value;
7105            }
7106            // disable AEC and NS if the device is a BT SCO headset supporting those
7107            // pre processings
7108            if (mTracks.size() > 0) {
7109                bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7110                                    mAudioFlinger->btNrecIsOff();
7111                for (size_t i = 0; i < mTracks.size(); i++) {
7112                    sp<RecordTrack> track = mTracks[i];
7113                    setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7114                    setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7115                }
7116            }
7117        }
7118    }
7119    if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7120            mAudioSource != (audio_source_t)value) {
7121        // forward device change to effects that have requested to be
7122        // aware of attached audio device.
7123        for (size_t i = 0; i < mEffectChains.size(); i++) {
7124            mEffectChains[i]->setAudioSource_l((audio_source_t)value);
7125        }
7126        mAudioSource = (audio_source_t)value;
7127    }
7128
7129    if (status == NO_ERROR) {
7130        status = mInput->stream->common.set_parameters(&mInput->stream->common,
7131                keyValuePair.string());
7132        if (status == INVALID_OPERATION) {
7133            inputStandBy();
7134            status = mInput->stream->common.set_parameters(&mInput->stream->common,
7135                    keyValuePair.string());
7136        }
7137        if (reconfig) {
7138            if (status == BAD_VALUE &&
7139                audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7140                audio_is_linear_pcm(reqFormat) &&
7141                (mInput->stream->common.get_sample_rate(&mInput->stream->common)
7142                        <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
7143                audio_channel_count_from_in_mask(
7144                        mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
7145                status = NO_ERROR;
7146            }
7147            if (status == NO_ERROR) {
7148                readInputParameters_l();
7149                sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7150            }
7151        }
7152    }
7153
7154    return reconfig;
7155}
7156
7157String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7158{
7159    Mutex::Autolock _l(mLock);
7160    if (initCheck() != NO_ERROR) {
7161        return String8();
7162    }
7163
7164    char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7165    const String8 out_s8(s);
7166    free(s);
7167    return out_s8;
7168}
7169
7170void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7171    sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7172
7173    desc->mIoHandle = mId;
7174
7175    switch (event) {
7176    case AUDIO_INPUT_OPENED:
7177    case AUDIO_INPUT_CONFIG_CHANGED:
7178        desc->mPatch = mPatch;
7179        desc->mChannelMask = mChannelMask;
7180        desc->mSamplingRate = mSampleRate;
7181        desc->mFormat = mFormat;
7182        desc->mFrameCount = mFrameCount;
7183        desc->mLatency = 0;
7184        break;
7185
7186    case AUDIO_INPUT_CLOSED:
7187    default:
7188        break;
7189    }
7190    mAudioFlinger->ioConfigChanged(event, desc, pid);
7191}
7192
7193void AudioFlinger::RecordThread::readInputParameters_l()
7194{
7195    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7196    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
7197    mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
7198    if (mChannelCount > FCC_8) {
7199        ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7200    }
7201    mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7202    mFormat = mHALFormat;
7203    if (!audio_is_linear_pcm(mFormat)) {
7204        ALOGE("HAL format %#x is not linear pcm", mFormat);
7205    }
7206    mFrameSize = audio_stream_in_frame_size(mInput->stream);
7207    mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7208    mFrameCount = mBufferSize / mFrameSize;
7209    // This is the formula for calculating the temporary buffer size.
7210    // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
7211    // 1 full output buffer, regardless of the alignment of the available input.
7212    // The value is somewhat arbitrary, and could probably be even larger.
7213    // A larger value should allow more old data to be read after a track calls start(),
7214    // without increasing latency.
7215    //
7216    // Note this is independent of the maximum downsampling ratio permitted for capture.
7217    mRsmpInFrames = mFrameCount * 7;
7218    mRsmpInFramesP2 = roundup(mRsmpInFrames);
7219    free(mRsmpInBuffer);
7220    mRsmpInBuffer = NULL;
7221
7222    // TODO optimize audio capture buffer sizes ...
7223    // Here we calculate the size of the sliding buffer used as a source
7224    // for resampling.  mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7225    // For current HAL frame counts, this is usually 2048 = 40 ms.  It would
7226    // be better to have it derived from the pipe depth in the long term.
7227    // The current value is higher than necessary.  However it should not add to latency.
7228
7229    // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
7230    size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7231    (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7232    memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
7233
7234    // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7235    // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
7236}
7237
7238uint32_t AudioFlinger::RecordThread::getInputFramesLost()
7239{
7240    Mutex::Autolock _l(mLock);
7241    if (initCheck() != NO_ERROR) {
7242        return 0;
7243    }
7244
7245    return mInput->stream->get_input_frames_lost(mInput->stream);
7246}
7247
7248uint32_t AudioFlinger::RecordThread::hasAudioSession(audio_session_t sessionId) const
7249{
7250    Mutex::Autolock _l(mLock);
7251    uint32_t result = 0;
7252    if (getEffectChain_l(sessionId) != 0) {
7253        result = EFFECT_SESSION;
7254    }
7255
7256    for (size_t i = 0; i < mTracks.size(); ++i) {
7257        if (sessionId == mTracks[i]->sessionId()) {
7258            result |= TRACK_SESSION;
7259            break;
7260        }
7261    }
7262
7263    return result;
7264}
7265
7266KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
7267{
7268    KeyedVector<audio_session_t, bool> ids;
7269    Mutex::Autolock _l(mLock);
7270    for (size_t j = 0; j < mTracks.size(); ++j) {
7271        sp<RecordThread::RecordTrack> track = mTracks[j];
7272        audio_session_t sessionId = track->sessionId();
7273        if (ids.indexOfKey(sessionId) < 0) {
7274            ids.add(sessionId, true);
7275        }
7276    }
7277    return ids;
7278}
7279
7280AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7281{
7282    Mutex::Autolock _l(mLock);
7283    AudioStreamIn *input = mInput;
7284    mInput = NULL;
7285    return input;
7286}
7287
7288// this method must always be called either with ThreadBase mLock held or inside the thread loop
7289audio_stream_t* AudioFlinger::RecordThread::stream() const
7290{
7291    if (mInput == NULL) {
7292        return NULL;
7293    }
7294    return &mInput->stream->common;
7295}
7296
7297status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7298{
7299    // only one chain per input thread
7300    if (mEffectChains.size() != 0) {
7301        ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
7302        return INVALID_OPERATION;
7303    }
7304    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
7305    chain->setThread(this);
7306    chain->setInBuffer(NULL);
7307    chain->setOutBuffer(NULL);
7308
7309    checkSuspendOnAddEffectChain_l(chain);
7310
7311    // make sure enabled pre processing effects state is communicated to the HAL as we
7312    // just moved them to a new input stream.
7313    chain->syncHalEffectsState();
7314
7315    mEffectChains.add(chain);
7316
7317    return NO_ERROR;
7318}
7319
7320size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7321{
7322    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7323    ALOGW_IF(mEffectChains.size() != 1,
7324            "removeEffectChain_l() %p invalid chain size %d on thread %p",
7325            chain.get(), mEffectChains.size(), this);
7326    if (mEffectChains.size() == 1) {
7327        mEffectChains.removeAt(0);
7328    }
7329    return 0;
7330}
7331
7332status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7333                                                          audio_patch_handle_t *handle)
7334{
7335    status_t status = NO_ERROR;
7336
7337    // store new device and send to effects
7338    mInDevice = patch->sources[0].ext.device.type;
7339    mPatch = *patch;
7340    for (size_t i = 0; i < mEffectChains.size(); i++) {
7341        mEffectChains[i]->setDevice_l(mInDevice);
7342    }
7343
7344    // disable AEC and NS if the device is a BT SCO headset supporting those
7345    // pre processings
7346    if (mTracks.size() > 0) {
7347        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7348                            mAudioFlinger->btNrecIsOff();
7349        for (size_t i = 0; i < mTracks.size(); i++) {
7350            sp<RecordTrack> track = mTracks[i];
7351            setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7352            setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7353        }
7354    }
7355
7356    // store new source and send to effects
7357    if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7358        mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7359        for (size_t i = 0; i < mEffectChains.size(); i++) {
7360            mEffectChains[i]->setAudioSource_l(mAudioSource);
7361        }
7362    }
7363
7364    if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7365        audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7366        status = hwDevice->create_audio_patch(hwDevice,
7367                                               patch->num_sources,
7368                                               patch->sources,
7369                                               patch->num_sinks,
7370                                               patch->sinks,
7371                                               handle);
7372    } else {
7373        char *address;
7374        if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7375            address = audio_device_address_to_parameter(
7376                                                patch->sources[0].ext.device.type,
7377                                                patch->sources[0].ext.device.address);
7378        } else {
7379            address = (char *)calloc(1, 1);
7380        }
7381        AudioParameter param = AudioParameter(String8(address));
7382        free(address);
7383        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7384                     (int)patch->sources[0].ext.device.type);
7385        param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7386                                         (int)patch->sinks[0].ext.mix.usecase.source);
7387        status = mInput->stream->common.set_parameters(&mInput->stream->common,
7388                param.toString().string());
7389        *handle = AUDIO_PATCH_HANDLE_NONE;
7390    }
7391
7392    if (mInDevice != mPrevInDevice) {
7393        sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7394        mPrevInDevice = mInDevice;
7395    }
7396
7397    return status;
7398}
7399
7400status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7401{
7402    status_t status = NO_ERROR;
7403
7404    mInDevice = AUDIO_DEVICE_NONE;
7405
7406    if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7407        audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7408        status = hwDevice->release_audio_patch(hwDevice, handle);
7409    } else {
7410        AudioParameter param;
7411        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7412        status = mInput->stream->common.set_parameters(&mInput->stream->common,
7413                param.toString().string());
7414    }
7415    return status;
7416}
7417
7418void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7419{
7420    Mutex::Autolock _l(mLock);
7421    mTracks.add(record);
7422}
7423
7424void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7425{
7426    Mutex::Autolock _l(mLock);
7427    destroyTrack_l(record);
7428}
7429
7430void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7431{
7432    ThreadBase::getAudioPortConfig(config);
7433    config->role = AUDIO_PORT_ROLE_SINK;
7434    config->ext.mix.hw_module = mInput->audioHwDev->handle();
7435    config->ext.mix.usecase.source = mAudioSource;
7436}
7437
7438} // namespace android
7439