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