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