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