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