Threads.cpp revision f6ed423af92a56ef54bba23eba883b1f21448b54
1bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant/*
2bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant**
3f5256e16dfc425c1d466f6308d4026d529ce9e0bHoward Hinnant** Copyright 2012, The Android Open Source Project
4bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant**
5b64f8b07c104c6cc986570ac8ee0ed16a9f23976Howard Hinnant** Licensed under the Apache License, Version 2.0 (the "License");
6b64f8b07c104c6cc986570ac8ee0ed16a9f23976Howard Hinnant** you may not use this file except in compliance with the License.
7bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant** You may obtain a copy of the License at
8bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant**
9bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant**     http://www.apache.org/licenses/LICENSE-2.0
10bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant**
11bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant** Unless required by applicable law or agreed to in writing, software
12eb564e76cc3904d811c981a50ecce0659f444cc9Howard Hinnant** distributed under the License is distributed on an "AS IS" BASIS,
1398e5d974006989c505d7b2ec7b9e4b20b0f01e26Howard Hinnant** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant** See the License for the specific language governing permissions and
15bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant** limitations under the License.
16bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant*/
17bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
18bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
19bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#define LOG_TAG "AudioFlinger"
20bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant//#define LOG_NDEBUG 0
21e3e3291f3ab4af96b0403cf6e255c833143ae3f1Howard Hinnant#define ATRACE_TAG ATRACE_TAG_AUDIO
2298e5d974006989c505d7b2ec7b9e4b20b0f01e26Howard Hinnant
2398e5d974006989c505d7b2ec7b9e4b20b0f01e26Howard Hinnant#include "Configuration.h"
2498e5d974006989c505d7b2ec7b9e4b20b0f01e26Howard Hinnant#include <math.h>
2598e5d974006989c505d7b2ec7b9e4b20b0f01e26Howard Hinnant#include <fcntl.h>
2698e5d974006989c505d7b2ec7b9e4b20b0f01e26Howard Hinnant#include <sys/stat.h>
2798e5d974006989c505d7b2ec7b9e4b20b0f01e26Howard Hinnant#include <cutils/properties.h>
289d9463a3555aa559884809b8a7fc842a3968193eMarshall Clow#include <cutils/compiler.h>
299d9463a3555aa559884809b8a7fc842a3968193eMarshall Clow#include <media/AudioParameter.h>
309d9463a3555aa559884809b8a7fc842a3968193eMarshall Clow#include <utils/Log.h>
319d9463a3555aa559884809b8a7fc842a3968193eMarshall Clow#include <utils/Trace.h>
329d9463a3555aa559884809b8a7fc842a3968193eMarshall Clow
339d9463a3555aa559884809b8a7fc842a3968193eMarshall Clow#include <private/media/AudioTrackShared.h>
349d9463a3555aa559884809b8a7fc842a3968193eMarshall Clow#include <hardware/audio.h>
359d9463a3555aa559884809b8a7fc842a3968193eMarshall Clow#include <audio_effects/effect_ns.h>
369d9463a3555aa559884809b8a7fc842a3968193eMarshall Clow#include <audio_effects/effect_aec.h>
379d9463a3555aa559884809b8a7fc842a3968193eMarshall Clow#include <audio_utils/primitives.h>
38e3e3291f3ab4af96b0403cf6e255c833143ae3f1Howard Hinnant
39bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant// NBAIO implementations
40#include <media/nbaio/AudioStreamOutSink.h>
41#include <media/nbaio/MonoPipe.h>
42#include <media/nbaio/MonoPipeReader.h>
43#include <media/nbaio/Pipe.h>
44#include <media/nbaio/PipeReader.h>
45#include <media/nbaio/SourceAudioBufferProvider.h>
46
47#include <powermanager/PowerManager.h>
48
49#include <common_time/cc_helper.h>
50#include <common_time/local_clock.h>
51
52#include "AudioFlinger.h"
53#include "AudioMixer.h"
54#include "FastMixer.h"
55#include "ServiceUtilities.h"
56#include "SchedulingPolicyService.h"
57
58#ifdef ADD_BATTERY_DATA
59#include <media/IMediaPlayerService.h>
60#include <media/IMediaDeathNotifier.h>
61#endif
62
63#ifdef DEBUG_CPU_USAGE
64#include <cpustats/CentralTendencyStatistics.h>
65#include <cpustats/ThreadCpuUsage.h>
66#endif
67
68// ----------------------------------------------------------------------------
69
70// Note: the following macro is used for extremely verbose logging message.  In
71// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
72// 0; but one side effect of this is to turn all LOGV's as well.  Some messages
73// are so verbose that we want to suppress them even when we have ALOG_ASSERT
74// turned on.  Do not uncomment the #def below unless you really know what you
75// are doing and want to see all of the extremely verbose messages.
76//#define VERY_VERY_VERBOSE_LOGGING
77#ifdef VERY_VERY_VERBOSE_LOGGING
78#define ALOGVV ALOGV
79#else
80#define ALOGVV(a...) do { } while(0)
81#endif
82
83namespace android {
84
85// retry counts for buffer fill timeout
86// 50 * ~20msecs = 1 second
87static const int8_t kMaxTrackRetries = 50;
88static const int8_t kMaxTrackStartupRetries = 50;
89// allow less retry attempts on direct output thread.
90// direct outputs can be a scarce resource in audio hardware and should
91// be released as quickly as possible.
92static const int8_t kMaxTrackRetriesDirect = 2;
93
94// don't warn about blocked writes or record buffer overflows more often than this
95static const nsecs_t kWarningThrottleNs = seconds(5);
96
97// RecordThread loop sleep time upon application overrun or audio HAL read error
98static const int kRecordThreadSleepUs = 5000;
99
100// maximum time to wait for setParameters to complete
101static const nsecs_t kSetParametersTimeoutNs = seconds(2);
102
103// minimum sleep time for the mixer thread loop when tracks are active but in underrun
104static const uint32_t kMinThreadSleepTimeUs = 5000;
105// maximum divider applied to the active sleep time in the mixer thread loop
106static const uint32_t kMaxThreadSleepTimeShift = 2;
107
108// minimum normal mix buffer size, expressed in milliseconds rather than frames
109static const uint32_t kMinNormalMixBufferSizeMs = 20;
110// maximum normal mix buffer size
111static const uint32_t kMaxNormalMixBufferSizeMs = 24;
112
113// Whether to use fast mixer
114static const enum {
115    FastMixer_Never,    // never initialize or use: for debugging only
116    FastMixer_Always,   // always initialize and use, even if not needed: for debugging only
117                        // normal mixer multiplier is 1
118    FastMixer_Static,   // initialize if needed, then use all the time if initialized,
119                        // multiplier is calculated based on min & max normal mixer buffer size
120    FastMixer_Dynamic,  // initialize if needed, then use dynamically depending on track load,
121                        // multiplier is calculated based on min & max normal mixer buffer size
122    // FIXME for FastMixer_Dynamic:
123    //  Supporting this option will require fixing HALs that can't handle large writes.
124    //  For example, one HAL implementation returns an error from a large write,
125    //  and another HAL implementation corrupts memory, possibly in the sample rate converter.
126    //  We could either fix the HAL implementations, or provide a wrapper that breaks
127    //  up large writes into smaller ones, and the wrapper would need to deal with scheduler.
128} kUseFastMixer = FastMixer_Static;
129
130// Priorities for requestPriority
131static const int kPriorityAudioApp = 2;
132static const int kPriorityFastMixer = 3;
133
134// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
135// for the track.  The client then sub-divides this into smaller buffers for its use.
136// Currently the client uses double-buffering by default, but doesn't tell us about that.
137// So for now we just assume that client is double-buffered.
138// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
139// N-buffering, so AudioFlinger could allocate the right amount of memory.
140// See the client's minBufCount and mNotificationFramesAct calculations for details.
141static const int kFastTrackMultiplier = 1;
142
143// ----------------------------------------------------------------------------
144
145#ifdef ADD_BATTERY_DATA
146// To collect the amplifier usage
147static void addBatteryData(uint32_t params) {
148    sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
149    if (service == NULL) {
150        // it already logged
151        return;
152    }
153
154    service->addBatteryData(params);
155}
156#endif
157
158
159// ----------------------------------------------------------------------------
160//      CPU Stats
161// ----------------------------------------------------------------------------
162
163class CpuStats {
164public:
165    CpuStats();
166    void sample(const String8 &title);
167#ifdef DEBUG_CPU_USAGE
168private:
169    ThreadCpuUsage mCpuUsage;           // instantaneous thread CPU usage in wall clock ns
170    CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
171
172    CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
173
174    int mCpuNum;                        // thread's current CPU number
175    int mCpukHz;                        // frequency of thread's current CPU in kHz
176#endif
177};
178
179CpuStats::CpuStats()
180#ifdef DEBUG_CPU_USAGE
181    : mCpuNum(-1), mCpukHz(-1)
182#endif
183{
184}
185
186void CpuStats::sample(const String8 &title) {
187#ifdef DEBUG_CPU_USAGE
188    // get current thread's delta CPU time in wall clock ns
189    double wcNs;
190    bool valid = mCpuUsage.sampleAndEnable(wcNs);
191
192    // record sample for wall clock statistics
193    if (valid) {
194        mWcStats.sample(wcNs);
195    }
196
197    // get the current CPU number
198    int cpuNum = sched_getcpu();
199
200    // get the current CPU frequency in kHz
201    int cpukHz = mCpuUsage.getCpukHz(cpuNum);
202
203    // check if either CPU number or frequency changed
204    if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
205        mCpuNum = cpuNum;
206        mCpukHz = cpukHz;
207        // ignore sample for purposes of cycles
208        valid = false;
209    }
210
211    // if no change in CPU number or frequency, then record sample for cycle statistics
212    if (valid && mCpukHz > 0) {
213        double cycles = wcNs * cpukHz * 0.000001;
214        mHzStats.sample(cycles);
215    }
216
217    unsigned n = mWcStats.n();
218    // mCpuUsage.elapsed() is expensive, so don't call it every loop
219    if ((n & 127) == 1) {
220        long long elapsed = mCpuUsage.elapsed();
221        if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
222            double perLoop = elapsed / (double) n;
223            double perLoop100 = perLoop * 0.01;
224            double perLoop1k = perLoop * 0.001;
225            double mean = mWcStats.mean();
226            double stddev = mWcStats.stddev();
227            double minimum = mWcStats.minimum();
228            double maximum = mWcStats.maximum();
229            double meanCycles = mHzStats.mean();
230            double stddevCycles = mHzStats.stddev();
231            double minCycles = mHzStats.minimum();
232            double maxCycles = mHzStats.maximum();
233            mCpuUsage.resetElapsed();
234            mWcStats.reset();
235            mHzStats.reset();
236            ALOGD("CPU usage for %s over past %.1f secs\n"
237                "  (%u mixer loops at %.1f mean ms per loop):\n"
238                "  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
239                "  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
240                "  MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
241                    title.string(),
242                    elapsed * .000000001, n, perLoop * .000001,
243                    mean * .001,
244                    stddev * .001,
245                    minimum * .001,
246                    maximum * .001,
247                    mean / perLoop100,
248                    stddev / perLoop100,
249                    minimum / perLoop100,
250                    maximum / perLoop100,
251                    meanCycles / perLoop1k,
252                    stddevCycles / perLoop1k,
253                    minCycles / perLoop1k,
254                    maxCycles / perLoop1k);
255
256        }
257    }
258#endif
259};
260
261// ----------------------------------------------------------------------------
262//      ThreadBase
263// ----------------------------------------------------------------------------
264
265AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
266        audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
267    :   Thread(false /*canCallJava*/),
268        mType(type),
269        mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
270        // mChannelMask
271        mChannelCount(0),
272        mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
273        mParamStatus(NO_ERROR),
274        mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
275        mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
276        // mName will be set by concrete (non-virtual) subclass
277        mDeathRecipient(new PMDeathRecipient(this))
278{
279}
280
281AudioFlinger::ThreadBase::~ThreadBase()
282{
283    // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
284    for (size_t i = 0; i < mConfigEvents.size(); i++) {
285        delete mConfigEvents[i];
286    }
287    mConfigEvents.clear();
288
289    mParamCond.broadcast();
290    // do not lock the mutex in destructor
291    releaseWakeLock_l();
292    if (mPowerManager != 0) {
293        sp<IBinder> binder = mPowerManager->asBinder();
294        binder->unlinkToDeath(mDeathRecipient);
295    }
296}
297
298void AudioFlinger::ThreadBase::exit()
299{
300    ALOGV("ThreadBase::exit");
301    // do any cleanup required for exit to succeed
302    preExit();
303    {
304        // This lock prevents the following race in thread (uniprocessor for illustration):
305        //  if (!exitPending()) {
306        //      // context switch from here to exit()
307        //      // exit() calls requestExit(), what exitPending() observes
308        //      // exit() calls signal(), which is dropped since no waiters
309        //      // context switch back from exit() to here
310        //      mWaitWorkCV.wait(...);
311        //      // now thread is hung
312        //  }
313        AutoMutex lock(mLock);
314        requestExit();
315        mWaitWorkCV.broadcast();
316    }
317    // When Thread::requestExitAndWait is made virtual and this method is renamed to
318    // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
319    requestExitAndWait();
320}
321
322status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
323{
324    status_t status;
325
326    ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
327    Mutex::Autolock _l(mLock);
328
329    mNewParameters.add(keyValuePairs);
330    mWaitWorkCV.signal();
331    // wait condition with timeout in case the thread loop has exited
332    // before the request could be processed
333    if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
334        status = mParamStatus;
335        mWaitWorkCV.signal();
336    } else {
337        status = TIMED_OUT;
338    }
339    return status;
340}
341
342void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
343{
344    Mutex::Autolock _l(mLock);
345    sendIoConfigEvent_l(event, param);
346}
347
348// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
349void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
350{
351    IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
352    mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
353    ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
354            param);
355    mWaitWorkCV.signal();
356}
357
358// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
359void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
360{
361    PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
362    mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
363    ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
364          mConfigEvents.size(), pid, tid, prio);
365    mWaitWorkCV.signal();
366}
367
368void AudioFlinger::ThreadBase::processConfigEvents()
369{
370    mLock.lock();
371    while (!mConfigEvents.isEmpty()) {
372        ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
373        ConfigEvent *event = mConfigEvents[0];
374        mConfigEvents.removeAt(0);
375        // release mLock before locking AudioFlinger mLock: lock order is always
376        // AudioFlinger then ThreadBase to avoid cross deadlock
377        mLock.unlock();
378        switch(event->type()) {
379            case CFG_EVENT_PRIO: {
380                PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
381                // FIXME Need to understand why this has be done asynchronously
382                int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(),
383                        true /*asynchronous*/);
384                if (err != 0) {
385                    ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
386                          "error %d",
387                          prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
388                }
389            } break;
390            case CFG_EVENT_IO: {
391                IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
392                mAudioFlinger->mLock.lock();
393                audioConfigChanged_l(ioEvent->event(), ioEvent->param());
394                mAudioFlinger->mLock.unlock();
395            } break;
396            default:
397                ALOGE("processConfigEvents() unknown event type %d", event->type());
398                break;
399        }
400        delete event;
401        mLock.lock();
402    }
403    mLock.unlock();
404}
405
406void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
407{
408    const size_t SIZE = 256;
409    char buffer[SIZE];
410    String8 result;
411
412    bool locked = AudioFlinger::dumpTryLock(mLock);
413    if (!locked) {
414        snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
415        write(fd, buffer, strlen(buffer));
416    }
417
418    snprintf(buffer, SIZE, "io handle: %d\n", mId);
419    result.append(buffer);
420    snprintf(buffer, SIZE, "TID: %d\n", getTid());
421    result.append(buffer);
422    snprintf(buffer, SIZE, "standby: %d\n", mStandby);
423    result.append(buffer);
424    snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
425    result.append(buffer);
426    snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
427    result.append(buffer);
428    snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
429    result.append(buffer);
430    snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
431    result.append(buffer);
432    snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
433    result.append(buffer);
434    snprintf(buffer, SIZE, "Format: %d\n", mFormat);
435    result.append(buffer);
436    snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
437    result.append(buffer);
438
439    snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
440    result.append(buffer);
441    result.append(" Index Command");
442    for (size_t i = 0; i < mNewParameters.size(); ++i) {
443        snprintf(buffer, SIZE, "\n %02d    ", i);
444        result.append(buffer);
445        result.append(mNewParameters[i]);
446    }
447
448    snprintf(buffer, SIZE, "\n\nPending config events: \n");
449    result.append(buffer);
450    for (size_t i = 0; i < mConfigEvents.size(); i++) {
451        mConfigEvents[i]->dump(buffer, SIZE);
452        result.append(buffer);
453    }
454    result.append("\n");
455
456    write(fd, result.string(), result.size());
457
458    if (locked) {
459        mLock.unlock();
460    }
461}
462
463void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
464{
465    const size_t SIZE = 256;
466    char buffer[SIZE];
467    String8 result;
468
469    snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
470    write(fd, buffer, strlen(buffer));
471
472    for (size_t i = 0; i < mEffectChains.size(); ++i) {
473        sp<EffectChain> chain = mEffectChains[i];
474        if (chain != 0) {
475            chain->dump(fd, args);
476        }
477    }
478}
479
480void AudioFlinger::ThreadBase::acquireWakeLock()
481{
482    Mutex::Autolock _l(mLock);
483    acquireWakeLock_l();
484}
485
486void AudioFlinger::ThreadBase::acquireWakeLock_l()
487{
488    if (mPowerManager == 0) {
489        // use checkService() to avoid blocking if power service is not up yet
490        sp<IBinder> binder =
491            defaultServiceManager()->checkService(String16("power"));
492        if (binder == 0) {
493            ALOGW("Thread %s cannot connect to the power manager service", mName);
494        } else {
495            mPowerManager = interface_cast<IPowerManager>(binder);
496            binder->linkToDeath(mDeathRecipient);
497        }
498    }
499    if (mPowerManager != 0) {
500        sp<IBinder> binder = new BBinder();
501        status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
502                                                         binder,
503                                                         String16(mName),
504                                                         String16("media"));
505        if (status == NO_ERROR) {
506            mWakeLockToken = binder;
507        }
508        ALOGV("acquireWakeLock_l() %s status %d", mName, status);
509    }
510}
511
512void AudioFlinger::ThreadBase::releaseWakeLock()
513{
514    Mutex::Autolock _l(mLock);
515    releaseWakeLock_l();
516}
517
518void AudioFlinger::ThreadBase::releaseWakeLock_l()
519{
520    if (mWakeLockToken != 0) {
521        ALOGV("releaseWakeLock_l() %s", mName);
522        if (mPowerManager != 0) {
523            mPowerManager->releaseWakeLock(mWakeLockToken, 0);
524        }
525        mWakeLockToken.clear();
526    }
527}
528
529void AudioFlinger::ThreadBase::clearPowerManager()
530{
531    Mutex::Autolock _l(mLock);
532    releaseWakeLock_l();
533    mPowerManager.clear();
534}
535
536void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
537{
538    sp<ThreadBase> thread = mThread.promote();
539    if (thread != 0) {
540        thread->clearPowerManager();
541    }
542    ALOGW("power manager service died !!!");
543}
544
545void AudioFlinger::ThreadBase::setEffectSuspended(
546        const effect_uuid_t *type, bool suspend, int sessionId)
547{
548    Mutex::Autolock _l(mLock);
549    setEffectSuspended_l(type, suspend, sessionId);
550}
551
552void AudioFlinger::ThreadBase::setEffectSuspended_l(
553        const effect_uuid_t *type, bool suspend, int sessionId)
554{
555    sp<EffectChain> chain = getEffectChain_l(sessionId);
556    if (chain != 0) {
557        if (type != NULL) {
558            chain->setEffectSuspended_l(type, suspend);
559        } else {
560            chain->setEffectSuspendedAll_l(suspend);
561        }
562    }
563
564    updateSuspendedSessions_l(type, suspend, sessionId);
565}
566
567void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
568{
569    ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
570    if (index < 0) {
571        return;
572    }
573
574    const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
575            mSuspendedSessions.valueAt(index);
576
577    for (size_t i = 0; i < sessionEffects.size(); i++) {
578        sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
579        for (int j = 0; j < desc->mRefCount; j++) {
580            if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
581                chain->setEffectSuspendedAll_l(true);
582            } else {
583                ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
584                    desc->mType.timeLow);
585                chain->setEffectSuspended_l(&desc->mType, true);
586            }
587        }
588    }
589}
590
591void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
592                                                         bool suspend,
593                                                         int sessionId)
594{
595    ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
596
597    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
598
599    if (suspend) {
600        if (index >= 0) {
601            sessionEffects = mSuspendedSessions.valueAt(index);
602        } else {
603            mSuspendedSessions.add(sessionId, sessionEffects);
604        }
605    } else {
606        if (index < 0) {
607            return;
608        }
609        sessionEffects = mSuspendedSessions.valueAt(index);
610    }
611
612
613    int key = EffectChain::kKeyForSuspendAll;
614    if (type != NULL) {
615        key = type->timeLow;
616    }
617    index = sessionEffects.indexOfKey(key);
618
619    sp<SuspendedSessionDesc> desc;
620    if (suspend) {
621        if (index >= 0) {
622            desc = sessionEffects.valueAt(index);
623        } else {
624            desc = new SuspendedSessionDesc();
625            if (type != NULL) {
626                desc->mType = *type;
627            }
628            sessionEffects.add(key, desc);
629            ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
630        }
631        desc->mRefCount++;
632    } else {
633        if (index < 0) {
634            return;
635        }
636        desc = sessionEffects.valueAt(index);
637        if (--desc->mRefCount == 0) {
638            ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
639            sessionEffects.removeItemsAt(index);
640            if (sessionEffects.isEmpty()) {
641                ALOGV("updateSuspendedSessions_l() restore removing session %d",
642                                 sessionId);
643                mSuspendedSessions.removeItem(sessionId);
644            }
645        }
646    }
647    if (!sessionEffects.isEmpty()) {
648        mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
649    }
650}
651
652void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
653                                                            bool enabled,
654                                                            int sessionId)
655{
656    Mutex::Autolock _l(mLock);
657    checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
658}
659
660void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
661                                                            bool enabled,
662                                                            int sessionId)
663{
664    if (mType != RECORD) {
665        // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
666        // another session. This gives the priority to well behaved effect control panels
667        // and applications not using global effects.
668        // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
669        // global effects
670        if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
671            setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
672        }
673    }
674
675    sp<EffectChain> chain = getEffectChain_l(sessionId);
676    if (chain != 0) {
677        chain->checkSuspendOnEffectEnabled(effect, enabled);
678    }
679}
680
681// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
682sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
683        const sp<AudioFlinger::Client>& client,
684        const sp<IEffectClient>& effectClient,
685        int32_t priority,
686        int sessionId,
687        effect_descriptor_t *desc,
688        int *enabled,
689        status_t *status
690        )
691{
692    sp<EffectModule> effect;
693    sp<EffectHandle> handle;
694    status_t lStatus;
695    sp<EffectChain> chain;
696    bool chainCreated = false;
697    bool effectCreated = false;
698    bool effectRegistered = false;
699
700    lStatus = initCheck();
701    if (lStatus != NO_ERROR) {
702        ALOGW("createEffect_l() Audio driver not initialized.");
703        goto Exit;
704    }
705
706    // Do not allow effects with session ID 0 on direct output or duplicating threads
707    // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
708    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
709        ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
710                desc->name, sessionId);
711        lStatus = BAD_VALUE;
712        goto Exit;
713    }
714    // Only Pre processor effects are allowed on input threads and only on input threads
715    if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
716        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
717                desc->name, desc->flags, mType);
718        lStatus = BAD_VALUE;
719        goto Exit;
720    }
721
722    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
723
724    { // scope for mLock
725        Mutex::Autolock _l(mLock);
726
727        // check for existing effect chain with the requested audio session
728        chain = getEffectChain_l(sessionId);
729        if (chain == 0) {
730            // create a new chain for this session
731            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
732            chain = new EffectChain(this, sessionId);
733            addEffectChain_l(chain);
734            chain->setStrategy(getStrategyForSession_l(sessionId));
735            chainCreated = true;
736        } else {
737            effect = chain->getEffectFromDesc_l(desc);
738        }
739
740        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
741
742        if (effect == 0) {
743            int id = mAudioFlinger->nextUniqueId();
744            // Check CPU and memory usage
745            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
746            if (lStatus != NO_ERROR) {
747                goto Exit;
748            }
749            effectRegistered = true;
750            // create a new effect module if none present in the chain
751            effect = new EffectModule(this, chain, desc, id, sessionId);
752            lStatus = effect->status();
753            if (lStatus != NO_ERROR) {
754                goto Exit;
755            }
756            lStatus = chain->addEffect_l(effect);
757            if (lStatus != NO_ERROR) {
758                goto Exit;
759            }
760            effectCreated = true;
761
762            effect->setDevice(mOutDevice);
763            effect->setDevice(mInDevice);
764            effect->setMode(mAudioFlinger->getMode());
765            effect->setAudioSource(mAudioSource);
766        }
767        // create effect handle and connect it to effect module
768        handle = new EffectHandle(effect, client, effectClient, priority);
769        lStatus = effect->addHandle(handle.get());
770        if (enabled != NULL) {
771            *enabled = (int)effect->isEnabled();
772        }
773    }
774
775Exit:
776    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
777        Mutex::Autolock _l(mLock);
778        if (effectCreated) {
779            chain->removeEffect_l(effect);
780        }
781        if (effectRegistered) {
782            AudioSystem::unregisterEffect(effect->id());
783        }
784        if (chainCreated) {
785            removeEffectChain_l(chain);
786        }
787        handle.clear();
788    }
789
790    if (status != NULL) {
791        *status = lStatus;
792    }
793    return handle;
794}
795
796sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
797{
798    Mutex::Autolock _l(mLock);
799    return getEffect_l(sessionId, effectId);
800}
801
802sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
803{
804    sp<EffectChain> chain = getEffectChain_l(sessionId);
805    return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
806}
807
808// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
809// PlaybackThread::mLock held
810status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
811{
812    // check for existing effect chain with the requested audio session
813    int sessionId = effect->sessionId();
814    sp<EffectChain> chain = getEffectChain_l(sessionId);
815    bool chainCreated = false;
816
817    if (chain == 0) {
818        // create a new chain for this session
819        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
820        chain = new EffectChain(this, sessionId);
821        addEffectChain_l(chain);
822        chain->setStrategy(getStrategyForSession_l(sessionId));
823        chainCreated = true;
824    }
825    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
826
827    if (chain->getEffectFromId_l(effect->id()) != 0) {
828        ALOGW("addEffect_l() %p effect %s already present in chain %p",
829                this, effect->desc().name, chain.get());
830        return BAD_VALUE;
831    }
832
833    status_t status = chain->addEffect_l(effect);
834    if (status != NO_ERROR) {
835        if (chainCreated) {
836            removeEffectChain_l(chain);
837        }
838        return status;
839    }
840
841    effect->setDevice(mOutDevice);
842    effect->setDevice(mInDevice);
843    effect->setMode(mAudioFlinger->getMode());
844    effect->setAudioSource(mAudioSource);
845    return NO_ERROR;
846}
847
848void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
849
850    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
851    effect_descriptor_t desc = effect->desc();
852    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
853        detachAuxEffect_l(effect->id());
854    }
855
856    sp<EffectChain> chain = effect->chain().promote();
857    if (chain != 0) {
858        // remove effect chain if removing last effect
859        if (chain->removeEffect_l(effect) == 0) {
860            removeEffectChain_l(chain);
861        }
862    } else {
863        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
864    }
865}
866
867void AudioFlinger::ThreadBase::lockEffectChains_l(
868        Vector< sp<AudioFlinger::EffectChain> >& effectChains)
869{
870    effectChains = mEffectChains;
871    for (size_t i = 0; i < mEffectChains.size(); i++) {
872        mEffectChains[i]->lock();
873    }
874}
875
876void AudioFlinger::ThreadBase::unlockEffectChains(
877        const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
878{
879    for (size_t i = 0; i < effectChains.size(); i++) {
880        effectChains[i]->unlock();
881    }
882}
883
884sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
885{
886    Mutex::Autolock _l(mLock);
887    return getEffectChain_l(sessionId);
888}
889
890sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
891{
892    size_t size = mEffectChains.size();
893    for (size_t i = 0; i < size; i++) {
894        if (mEffectChains[i]->sessionId() == sessionId) {
895            return mEffectChains[i];
896        }
897    }
898    return 0;
899}
900
901void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
902{
903    Mutex::Autolock _l(mLock);
904    size_t size = mEffectChains.size();
905    for (size_t i = 0; i < size; i++) {
906        mEffectChains[i]->setMode_l(mode);
907    }
908}
909
910void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
911                                                    EffectHandle *handle,
912                                                    bool unpinIfLast) {
913
914    Mutex::Autolock _l(mLock);
915    ALOGV("disconnectEffect() %p effect %p", this, effect.get());
916    // delete the effect module if removing last handle on it
917    if (effect->removeHandle(handle) == 0) {
918        if (!effect->isPinned() || unpinIfLast) {
919            removeEffect_l(effect);
920            AudioSystem::unregisterEffect(effect->id());
921        }
922    }
923}
924
925// ----------------------------------------------------------------------------
926//      Playback
927// ----------------------------------------------------------------------------
928
929AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
930                                             AudioStreamOut* output,
931                                             audio_io_handle_t id,
932                                             audio_devices_t device,
933                                             type_t type)
934    :   ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
935        mAllocMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
936        // mStreamTypes[] initialized in constructor body
937        mOutput(output),
938        mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
939        mMixerStatus(MIXER_IDLE),
940        mMixerStatusIgnoringFastTracks(MIXER_IDLE),
941        standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
942        mBytesRemaining(0),
943        mCurrentWriteLength(0),
944        mUseAsyncWrite(false),
945        mWriteBlocked(false),
946        mDraining(false),
947        mScreenState(AudioFlinger::mScreenState),
948        // index 0 is reserved for normal mixer's submix
949        mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
950{
951    snprintf(mName, kNameLength, "AudioOut_%X", id);
952    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
953
954    // Assumes constructor is called by AudioFlinger with it's mLock held, but
955    // it would be safer to explicitly pass initial masterVolume/masterMute as
956    // parameter.
957    //
958    // If the HAL we are using has support for master volume or master mute,
959    // then do not attenuate or mute during mixing (just leave the volume at 1.0
960    // and the mute set to false).
961    mMasterVolume = audioFlinger->masterVolume_l();
962    mMasterMute = audioFlinger->masterMute_l();
963    if (mOutput && mOutput->audioHwDev) {
964        if (mOutput->audioHwDev->canSetMasterVolume()) {
965            mMasterVolume = 1.0;
966        }
967
968        if (mOutput->audioHwDev->canSetMasterMute()) {
969            mMasterMute = false;
970        }
971    }
972
973    readOutputParameters();
974
975    // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
976    // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
977    for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
978            stream = (audio_stream_type_t) (stream + 1)) {
979        mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
980        mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
981    }
982    // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
983    // because mAudioFlinger doesn't have one to copy from
984}
985
986AudioFlinger::PlaybackThread::~PlaybackThread()
987{
988    mAudioFlinger->unregisterWriter(mNBLogWriter);
989    delete [] mAllocMixBuffer;
990}
991
992void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
993{
994    dumpInternals(fd, args);
995    dumpTracks(fd, args);
996    dumpEffectChains(fd, args);
997}
998
999void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1000{
1001    const size_t SIZE = 256;
1002    char buffer[SIZE];
1003    String8 result;
1004
1005    result.appendFormat("Output thread %p stream volumes in dB:\n    ", this);
1006    for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1007        const stream_type_t *st = &mStreamTypes[i];
1008        if (i > 0) {
1009            result.appendFormat(", ");
1010        }
1011        result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1012        if (st->mute) {
1013            result.append("M");
1014        }
1015    }
1016    result.append("\n");
1017    write(fd, result.string(), result.length());
1018    result.clear();
1019
1020    snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1021    result.append(buffer);
1022    Track::appendDumpHeader(result);
1023    for (size_t i = 0; i < mTracks.size(); ++i) {
1024        sp<Track> track = mTracks[i];
1025        if (track != 0) {
1026            track->dump(buffer, SIZE);
1027            result.append(buffer);
1028        }
1029    }
1030
1031    snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1032    result.append(buffer);
1033    Track::appendDumpHeader(result);
1034    for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1035        sp<Track> track = mActiveTracks[i].promote();
1036        if (track != 0) {
1037            track->dump(buffer, SIZE);
1038            result.append(buffer);
1039        }
1040    }
1041    write(fd, result.string(), result.size());
1042
1043    // These values are "raw"; they will wrap around.  See prepareTracks_l() for a better way.
1044    FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1045    fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1046            underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1047}
1048
1049void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1050{
1051    const size_t SIZE = 256;
1052    char buffer[SIZE];
1053    String8 result;
1054
1055    snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1056    result.append(buffer);
1057    snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1058            ns2ms(systemTime() - mLastWriteTime));
1059    result.append(buffer);
1060    snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1061    result.append(buffer);
1062    snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1063    result.append(buffer);
1064    snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1065    result.append(buffer);
1066    snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1067    result.append(buffer);
1068    snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1069    result.append(buffer);
1070    write(fd, result.string(), result.size());
1071    fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1072
1073    dumpBase(fd, args);
1074}
1075
1076// Thread virtuals
1077status_t AudioFlinger::PlaybackThread::readyToRun()
1078{
1079    status_t status = initCheck();
1080    if (status == NO_ERROR) {
1081        ALOGI("AudioFlinger's thread %p ready to run", this);
1082    } else {
1083        ALOGE("No working audio driver found.");
1084    }
1085    return status;
1086}
1087
1088void AudioFlinger::PlaybackThread::onFirstRef()
1089{
1090    run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1091}
1092
1093// ThreadBase virtuals
1094void AudioFlinger::PlaybackThread::preExit()
1095{
1096    ALOGV("  preExit()");
1097    // FIXME this is using hard-coded strings but in the future, this functionality will be
1098    //       converted to use audio HAL extensions required to support tunneling
1099    mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1100}
1101
1102// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1103sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1104        const sp<AudioFlinger::Client>& client,
1105        audio_stream_type_t streamType,
1106        uint32_t sampleRate,
1107        audio_format_t format,
1108        audio_channel_mask_t channelMask,
1109        size_t frameCount,
1110        const sp<IMemory>& sharedBuffer,
1111        int sessionId,
1112        IAudioFlinger::track_flags_t *flags,
1113        pid_t tid,
1114        status_t *status)
1115{
1116    sp<Track> track;
1117    status_t lStatus;
1118
1119    bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1120
1121    // client expresses a preference for FAST, but we get the final say
1122    if (*flags & IAudioFlinger::TRACK_FAST) {
1123      if (
1124            // not timed
1125            (!isTimed) &&
1126            // either of these use cases:
1127            (
1128              // use case 1: shared buffer with any frame count
1129              (
1130                (sharedBuffer != 0)
1131              ) ||
1132              // use case 2: callback handler and frame count is default or at least as large as HAL
1133              (
1134                (tid != -1) &&
1135                ((frameCount == 0) ||
1136                (frameCount >= (mFrameCount * kFastTrackMultiplier)))
1137              )
1138            ) &&
1139            // PCM data
1140            audio_is_linear_pcm(format) &&
1141            // mono or stereo
1142            ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1143              (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1144#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1145            // hardware sample rate
1146            (sampleRate == mSampleRate) &&
1147#endif
1148            // normal mixer has an associated fast mixer
1149            hasFastMixer() &&
1150            // there are sufficient fast track slots available
1151            (mFastTrackAvailMask != 0)
1152            // FIXME test that MixerThread for this fast track has a capable output HAL
1153            // FIXME add a permission test also?
1154        ) {
1155        // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1156        if (frameCount == 0) {
1157            frameCount = mFrameCount * kFastTrackMultiplier;
1158        }
1159        ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1160                frameCount, mFrameCount);
1161      } else {
1162        ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1163                "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
1164                "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1165                isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1166                audio_is_linear_pcm(format),
1167                channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1168        *flags &= ~IAudioFlinger::TRACK_FAST;
1169        // For compatibility with AudioTrack calculation, buffer depth is forced
1170        // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1171        // This is probably too conservative, but legacy application code may depend on it.
1172        // If you change this calculation, also review the start threshold which is related.
1173        uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1174        uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1175        if (minBufCount < 2) {
1176            minBufCount = 2;
1177        }
1178        size_t minFrameCount = mNormalFrameCount * minBufCount;
1179        if (frameCount < minFrameCount) {
1180            frameCount = minFrameCount;
1181        }
1182      }
1183    }
1184
1185    if (mType == DIRECT) {
1186        if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1187            if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1188                ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
1189                        "for output %p with format %d",
1190                        sampleRate, format, channelMask, mOutput, mFormat);
1191                lStatus = BAD_VALUE;
1192                goto Exit;
1193            }
1194        }
1195    } else if (mType == OFFLOAD) {
1196        if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1197            ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1198                    "for output %p with format %d",
1199                    sampleRate, format, channelMask, mOutput, mFormat);
1200            lStatus = BAD_VALUE;
1201            goto Exit;
1202        }
1203    } else {
1204        if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
1205                ALOGE("createTrack_l() Bad parameter: format %d \""
1206                        "for output %p with format %d",
1207                        format, mOutput, mFormat);
1208                lStatus = BAD_VALUE;
1209                goto Exit;
1210        }
1211        // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1212        if (sampleRate > mSampleRate*2) {
1213            ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1214            lStatus = BAD_VALUE;
1215            goto Exit;
1216        }
1217    }
1218
1219    lStatus = initCheck();
1220    if (lStatus != NO_ERROR) {
1221        ALOGE("Audio driver not initialized.");
1222        goto Exit;
1223    }
1224
1225    { // scope for mLock
1226        Mutex::Autolock _l(mLock);
1227
1228        // all tracks in same audio session must share the same routing strategy otherwise
1229        // conflicts will happen when tracks are moved from one output to another by audio policy
1230        // manager
1231        uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1232        for (size_t i = 0; i < mTracks.size(); ++i) {
1233            sp<Track> t = mTracks[i];
1234            if (t != 0 && !t->isOutputTrack()) {
1235                uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1236                if (sessionId == t->sessionId() && strategy != actual) {
1237                    ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1238                            strategy, actual);
1239                    lStatus = BAD_VALUE;
1240                    goto Exit;
1241                }
1242            }
1243        }
1244
1245        if (!isTimed) {
1246            track = new Track(this, client, streamType, sampleRate, format,
1247                    channelMask, frameCount, sharedBuffer, sessionId, *flags);
1248        } else {
1249            track = TimedTrack::create(this, client, streamType, sampleRate, format,
1250                    channelMask, frameCount, sharedBuffer, sessionId);
1251        }
1252        if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1253            lStatus = NO_MEMORY;
1254            goto Exit;
1255        }
1256
1257        mTracks.add(track);
1258
1259        sp<EffectChain> chain = getEffectChain_l(sessionId);
1260        if (chain != 0) {
1261            ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1262            track->setMainBuffer(chain->inBuffer());
1263            chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1264            chain->incTrackCnt();
1265        }
1266
1267        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1268            pid_t callingPid = IPCThreadState::self()->getCallingPid();
1269            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1270            // so ask activity manager to do this on our behalf
1271            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1272        }
1273    }
1274
1275    lStatus = NO_ERROR;
1276
1277Exit:
1278    if (status) {
1279        *status = lStatus;
1280    }
1281    return track;
1282}
1283
1284uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1285{
1286    return latency;
1287}
1288
1289uint32_t AudioFlinger::PlaybackThread::latency() const
1290{
1291    Mutex::Autolock _l(mLock);
1292    return latency_l();
1293}
1294uint32_t AudioFlinger::PlaybackThread::latency_l() const
1295{
1296    if (initCheck() == NO_ERROR) {
1297        return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1298    } else {
1299        return 0;
1300    }
1301}
1302
1303void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1304{
1305    Mutex::Autolock _l(mLock);
1306    // Don't apply master volume in SW if our HAL can do it for us.
1307    if (mOutput && mOutput->audioHwDev &&
1308        mOutput->audioHwDev->canSetMasterVolume()) {
1309        mMasterVolume = 1.0;
1310    } else {
1311        mMasterVolume = value;
1312    }
1313}
1314
1315void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1316{
1317    Mutex::Autolock _l(mLock);
1318    // Don't apply master mute in SW if our HAL can do it for us.
1319    if (mOutput && mOutput->audioHwDev &&
1320        mOutput->audioHwDev->canSetMasterMute()) {
1321        mMasterMute = false;
1322    } else {
1323        mMasterMute = muted;
1324    }
1325}
1326
1327void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1328{
1329    Mutex::Autolock _l(mLock);
1330    mStreamTypes[stream].volume = value;
1331    signal_l();
1332}
1333
1334void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1335{
1336    Mutex::Autolock _l(mLock);
1337    mStreamTypes[stream].mute = muted;
1338    signal_l();
1339}
1340
1341float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1342{
1343    Mutex::Autolock _l(mLock);
1344    return mStreamTypes[stream].volume;
1345}
1346
1347// addTrack_l() must be called with ThreadBase::mLock held
1348status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1349{
1350    status_t status = ALREADY_EXISTS;
1351
1352    // set retry count for buffer fill
1353    track->mRetryCount = kMaxTrackStartupRetries;
1354    if (mActiveTracks.indexOf(track) < 0) {
1355        // the track is newly added, make sure it fills up all its
1356        // buffers before playing. This is to ensure the client will
1357        // effectively get the latency it requested.
1358        if (!track->isOutputTrack()) {
1359            TrackBase::track_state state = track->mState;
1360            mLock.unlock();
1361            status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1362            mLock.lock();
1363            // abort track was stopped/paused while we released the lock
1364            if (state != track->mState) {
1365                if (status == NO_ERROR) {
1366                    mLock.unlock();
1367                    AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1368                    mLock.lock();
1369                }
1370                return INVALID_OPERATION;
1371            }
1372            // abort if start is rejected by audio policy manager
1373            if (status != NO_ERROR) {
1374                return PERMISSION_DENIED;
1375            }
1376#ifdef ADD_BATTERY_DATA
1377            // to track the speaker usage
1378            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1379#endif
1380        }
1381
1382        track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
1383        track->mResetDone = false;
1384        track->mPresentationCompleteFrames = 0;
1385        mActiveTracks.add(track);
1386        sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1387        if (chain != 0) {
1388            ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1389                    track->sessionId());
1390            chain->incActiveTrackCnt();
1391        }
1392
1393        status = NO_ERROR;
1394    }
1395
1396    ALOGV("mWaitWorkCV.broadcast");
1397    mWaitWorkCV.broadcast();
1398
1399    return status;
1400}
1401
1402bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1403{
1404    track->terminate();
1405    // active tracks are removed by threadLoop()
1406    bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1407    track->mState = TrackBase::STOPPED;
1408    if (!trackActive) {
1409        removeTrack_l(track);
1410    } else if (track->isFastTrack() || track->isOffloaded()) {
1411        track->mState = TrackBase::STOPPING_1;
1412    }
1413
1414    return trackActive;
1415}
1416
1417void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1418{
1419    track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1420    mTracks.remove(track);
1421    deleteTrackName_l(track->name());
1422    // redundant as track is about to be destroyed, for dumpsys only
1423    track->mName = -1;
1424    if (track->isFastTrack()) {
1425        int index = track->mFastIndex;
1426        ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1427        ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1428        mFastTrackAvailMask |= 1 << index;
1429        // redundant as track is about to be destroyed, for dumpsys only
1430        track->mFastIndex = -1;
1431    }
1432    sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1433    if (chain != 0) {
1434        chain->decTrackCnt();
1435    }
1436}
1437
1438void AudioFlinger::PlaybackThread::signal_l()
1439{
1440    // Thread could be blocked waiting for async
1441    // so signal it to handle state changes immediately
1442    // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1443    // be lost so we also flag to prevent it blocking on mWaitWorkCV
1444    mSignalPending = true;
1445    mWaitWorkCV.signal();
1446}
1447
1448String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1449{
1450    String8 out_s8 = String8("");
1451    char *s;
1452
1453    Mutex::Autolock _l(mLock);
1454    if (initCheck() != NO_ERROR) {
1455        return out_s8;
1456    }
1457
1458    s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1459    out_s8 = String8(s);
1460    free(s);
1461    return out_s8;
1462}
1463
1464// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1465void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1466    AudioSystem::OutputDescriptor desc;
1467    void *param2 = NULL;
1468
1469    ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1470            param);
1471
1472    switch (event) {
1473    case AudioSystem::OUTPUT_OPENED:
1474    case AudioSystem::OUTPUT_CONFIG_CHANGED:
1475        desc.channels = mChannelMask;
1476        desc.samplingRate = mSampleRate;
1477        desc.format = mFormat;
1478        desc.frameCount = mNormalFrameCount; // FIXME see
1479                                             // AudioFlinger::frameCount(audio_io_handle_t)
1480        desc.latency = latency();
1481        param2 = &desc;
1482        break;
1483
1484    case AudioSystem::STREAM_CONFIG_CHANGED:
1485        param2 = &param;
1486    case AudioSystem::OUTPUT_CLOSED:
1487    default:
1488        break;
1489    }
1490    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1491}
1492
1493void AudioFlinger::PlaybackThread::writeCallback()
1494{
1495    ALOG_ASSERT(mCallbackThread != 0);
1496    mCallbackThread->setWriteBlocked(false);
1497}
1498
1499void AudioFlinger::PlaybackThread::drainCallback()
1500{
1501    ALOG_ASSERT(mCallbackThread != 0);
1502    mCallbackThread->setDraining(false);
1503}
1504
1505void AudioFlinger::PlaybackThread::setWriteBlocked(bool value)
1506{
1507    Mutex::Autolock _l(mLock);
1508    mWriteBlocked = value;
1509    if (!value) {
1510        mWaitWorkCV.signal();
1511    }
1512}
1513
1514void AudioFlinger::PlaybackThread::setDraining(bool value)
1515{
1516    Mutex::Autolock _l(mLock);
1517    mDraining = value;
1518    if (!value) {
1519        mWaitWorkCV.signal();
1520    }
1521}
1522
1523// static
1524int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1525                                                void *param,
1526                                                void *cookie)
1527{
1528    AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1529    ALOGV("asyncCallback() event %d", event);
1530    switch (event) {
1531    case STREAM_CBK_EVENT_WRITE_READY:
1532        me->writeCallback();
1533        break;
1534    case STREAM_CBK_EVENT_DRAIN_READY:
1535        me->drainCallback();
1536        break;
1537    default:
1538        ALOGW("asyncCallback() unknown event %d", event);
1539        break;
1540    }
1541    return 0;
1542}
1543
1544void AudioFlinger::PlaybackThread::readOutputParameters()
1545{
1546    // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
1547    mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1548    mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1549    if (!audio_is_output_channel(mChannelMask)) {
1550        LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1551    }
1552    if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1553        LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1554                "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1555    }
1556    mChannelCount = popcount(mChannelMask);
1557    mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1558    if (!audio_is_valid_format(mFormat)) {
1559        LOG_FATAL("HAL format %d not valid for output", mFormat);
1560    }
1561    if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1562        LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1563                mFormat);
1564    }
1565    mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1566    mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1567    if (mFrameCount & 15) {
1568        ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1569                mFrameCount);
1570    }
1571
1572    if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1573            (mOutput->stream->set_callback != NULL)) {
1574        if (mOutput->stream->set_callback(mOutput->stream,
1575                                      AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1576            mUseAsyncWrite = true;
1577        }
1578    }
1579
1580    // Calculate size of normal mix buffer relative to the HAL output buffer size
1581    double multiplier = 1.0;
1582    if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1583            kUseFastMixer == FastMixer_Dynamic)) {
1584        size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1585        size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1586        // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1587        minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1588        maxNormalFrameCount = maxNormalFrameCount & ~15;
1589        if (maxNormalFrameCount < minNormalFrameCount) {
1590            maxNormalFrameCount = minNormalFrameCount;
1591        }
1592        multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1593        if (multiplier <= 1.0) {
1594            multiplier = 1.0;
1595        } else if (multiplier <= 2.0) {
1596            if (2 * mFrameCount <= maxNormalFrameCount) {
1597                multiplier = 2.0;
1598            } else {
1599                multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1600            }
1601        } else {
1602            // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1603            // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1604            // track, but we sometimes have to do this to satisfy the maximum frame count
1605            // constraint)
1606            // FIXME this rounding up should not be done if no HAL SRC
1607            uint32_t truncMult = (uint32_t) multiplier;
1608            if ((truncMult & 1)) {
1609                if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1610                    ++truncMult;
1611                }
1612            }
1613            multiplier = (double) truncMult;
1614        }
1615    }
1616    mNormalFrameCount = multiplier * mFrameCount;
1617    // round up to nearest 16 frames to satisfy AudioMixer
1618    mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1619    ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1620            mNormalFrameCount);
1621
1622    delete[] mAllocMixBuffer;
1623    size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1624    mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1625    mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1626    memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
1627
1628    // force reconfiguration of effect chains and engines to take new buffer size and audio
1629    // parameters into account
1630    // Note that mLock is not held when readOutputParameters() is called from the constructor
1631    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1632    // matter.
1633    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1634    Vector< sp<EffectChain> > effectChains = mEffectChains;
1635    for (size_t i = 0; i < effectChains.size(); i ++) {
1636        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1637    }
1638}
1639
1640
1641status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
1642{
1643    if (halFrames == NULL || dspFrames == NULL) {
1644        return BAD_VALUE;
1645    }
1646    Mutex::Autolock _l(mLock);
1647    if (initCheck() != NO_ERROR) {
1648        return INVALID_OPERATION;
1649    }
1650    size_t framesWritten = mBytesWritten / mFrameSize;
1651    *halFrames = framesWritten;
1652
1653    if (isSuspended()) {
1654        // return an estimation of rendered frames when the output is suspended
1655        size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1656        *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1657        return NO_ERROR;
1658    } else {
1659        return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1660    }
1661}
1662
1663uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1664{
1665    Mutex::Autolock _l(mLock);
1666    uint32_t result = 0;
1667    if (getEffectChain_l(sessionId) != 0) {
1668        result = EFFECT_SESSION;
1669    }
1670
1671    for (size_t i = 0; i < mTracks.size(); ++i) {
1672        sp<Track> track = mTracks[i];
1673        if (sessionId == track->sessionId() && !track->isInvalid()) {
1674            result |= TRACK_SESSION;
1675            break;
1676        }
1677    }
1678
1679    return result;
1680}
1681
1682uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1683{
1684    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1685    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1686    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1687        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1688    }
1689    for (size_t i = 0; i < mTracks.size(); i++) {
1690        sp<Track> track = mTracks[i];
1691        if (sessionId == track->sessionId() && !track->isInvalid()) {
1692            return AudioSystem::getStrategyForStream(track->streamType());
1693        }
1694    }
1695    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1696}
1697
1698
1699AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1700{
1701    Mutex::Autolock _l(mLock);
1702    return mOutput;
1703}
1704
1705AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1706{
1707    Mutex::Autolock _l(mLock);
1708    AudioStreamOut *output = mOutput;
1709    mOutput = NULL;
1710    // FIXME FastMixer might also have a raw ptr to mOutputSink;
1711    //       must push a NULL and wait for ack
1712    mOutputSink.clear();
1713    mPipeSink.clear();
1714    mNormalSink.clear();
1715    return output;
1716}
1717
1718// this method must always be called either with ThreadBase mLock held or inside the thread loop
1719audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1720{
1721    if (mOutput == NULL) {
1722        return NULL;
1723    }
1724    return &mOutput->stream->common;
1725}
1726
1727uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1728{
1729    return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1730}
1731
1732status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1733{
1734    if (!isValidSyncEvent(event)) {
1735        return BAD_VALUE;
1736    }
1737
1738    Mutex::Autolock _l(mLock);
1739
1740    for (size_t i = 0; i < mTracks.size(); ++i) {
1741        sp<Track> track = mTracks[i];
1742        if (event->triggerSession() == track->sessionId()) {
1743            (void) track->setSyncEvent(event);
1744            return NO_ERROR;
1745        }
1746    }
1747
1748    return NAME_NOT_FOUND;
1749}
1750
1751bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1752{
1753    return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1754}
1755
1756void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1757        const Vector< sp<Track> >& tracksToRemove)
1758{
1759    size_t count = tracksToRemove.size();
1760    if (CC_UNLIKELY(count)) {
1761        for (size_t i = 0 ; i < count ; i++) {
1762            const sp<Track>& track = tracksToRemove.itemAt(i);
1763            if (!track->isOutputTrack()) {
1764                AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1765#ifdef ADD_BATTERY_DATA
1766                // to track the speaker usage
1767                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1768#endif
1769                if (track->isTerminated()) {
1770                    AudioSystem::releaseOutput(mId);
1771                }
1772            }
1773        }
1774    }
1775}
1776
1777void AudioFlinger::PlaybackThread::checkSilentMode_l()
1778{
1779    if (!mMasterMute) {
1780        char value[PROPERTY_VALUE_MAX];
1781        if (property_get("ro.audio.silent", value, "0") > 0) {
1782            char *endptr;
1783            unsigned long ul = strtoul(value, &endptr, 0);
1784            if (*endptr == '\0' && ul != 0) {
1785                ALOGD("Silence is golden");
1786                // The setprop command will not allow a property to be changed after
1787                // the first time it is set, so we don't have to worry about un-muting.
1788                setMasterMute_l(true);
1789            }
1790        }
1791    }
1792}
1793
1794// shared by MIXER and DIRECT, overridden by DUPLICATING
1795ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
1796{
1797    // FIXME rewrite to reduce number of system calls
1798    mLastWriteTime = systemTime();
1799    mInWrite = true;
1800    ssize_t bytesWritten;
1801
1802    // If an NBAIO sink is present, use it to write the normal mixer's submix
1803    if (mNormalSink != 0) {
1804#define mBitShift 2 // FIXME
1805        size_t count = mBytesRemaining >> mBitShift;
1806        size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
1807        ATRACE_BEGIN("write");
1808        // update the setpoint when AudioFlinger::mScreenState changes
1809        uint32_t screenState = AudioFlinger::mScreenState;
1810        if (screenState != mScreenState) {
1811            mScreenState = screenState;
1812            MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1813            if (pipe != NULL) {
1814                pipe->setAvgFrames((mScreenState & 1) ?
1815                        (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1816            }
1817        }
1818        ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
1819        ATRACE_END();
1820        if (framesWritten > 0) {
1821            bytesWritten = framesWritten << mBitShift;
1822        } else {
1823            bytesWritten = framesWritten;
1824        }
1825    // otherwise use the HAL / AudioStreamOut directly
1826    } else {
1827        // Direct output and offload threads
1828        size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1829        if (mUseAsyncWrite) {
1830            mWriteBlocked = true;
1831            ALOG_ASSERT(mCallbackThread != 0);
1832            mCallbackThread->setWriteBlocked(true);
1833        }
1834        bytesWritten = mOutput->stream->write(mOutput->stream,
1835                                                   mMixBuffer + offset, mBytesRemaining);
1836        if (mUseAsyncWrite &&
1837                ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1838            // do not wait for async callback in case of error of full write
1839            mWriteBlocked = false;
1840            ALOG_ASSERT(mCallbackThread != 0);
1841            mCallbackThread->setWriteBlocked(false);
1842        }
1843    }
1844
1845    mNumWrites++;
1846    mInWrite = false;
1847
1848    return bytesWritten;
1849}
1850
1851void AudioFlinger::PlaybackThread::threadLoop_drain()
1852{
1853    if (mOutput->stream->drain) {
1854        ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1855        if (mUseAsyncWrite) {
1856            mDraining = true;
1857            ALOG_ASSERT(mCallbackThread != 0);
1858            mCallbackThread->setDraining(true);
1859        }
1860        mOutput->stream->drain(mOutput->stream,
1861            (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1862                                                : AUDIO_DRAIN_ALL);
1863    }
1864}
1865
1866void AudioFlinger::PlaybackThread::threadLoop_exit()
1867{
1868    // Default implementation has nothing to do
1869}
1870
1871/*
1872The derived values that are cached:
1873 - mixBufferSize from frame count * frame size
1874 - activeSleepTime from activeSleepTimeUs()
1875 - idleSleepTime from idleSleepTimeUs()
1876 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1877 - maxPeriod from frame count and sample rate (MIXER only)
1878
1879The parameters that affect these derived values are:
1880 - frame count
1881 - frame size
1882 - sample rate
1883 - device type: A2DP or not
1884 - device latency
1885 - format: PCM or not
1886 - active sleep time
1887 - idle sleep time
1888*/
1889
1890void AudioFlinger::PlaybackThread::cacheParameters_l()
1891{
1892    mixBufferSize = mNormalFrameCount * mFrameSize;
1893    activeSleepTime = activeSleepTimeUs();
1894    idleSleepTime = idleSleepTimeUs();
1895}
1896
1897void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1898{
1899    ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1900            this,  streamType, mTracks.size());
1901    Mutex::Autolock _l(mLock);
1902
1903    size_t size = mTracks.size();
1904    for (size_t i = 0; i < size; i++) {
1905        sp<Track> t = mTracks[i];
1906        if (t->streamType() == streamType) {
1907            t->invalidate();
1908        }
1909    }
1910}
1911
1912status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
1913{
1914    int session = chain->sessionId();
1915    int16_t *buffer = mMixBuffer;
1916    bool ownsBuffer = false;
1917
1918    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
1919    if (session > 0) {
1920        // Only one effect chain can be present in direct output thread and it uses
1921        // the mix buffer as input
1922        if (mType != DIRECT) {
1923            size_t numSamples = mNormalFrameCount * mChannelCount;
1924            buffer = new int16_t[numSamples];
1925            memset(buffer, 0, numSamples * sizeof(int16_t));
1926            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
1927            ownsBuffer = true;
1928        }
1929
1930        // Attach all tracks with same session ID to this chain.
1931        for (size_t i = 0; i < mTracks.size(); ++i) {
1932            sp<Track> track = mTracks[i];
1933            if (session == track->sessionId()) {
1934                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
1935                        buffer);
1936                track->setMainBuffer(buffer);
1937                chain->incTrackCnt();
1938            }
1939        }
1940
1941        // indicate all active tracks in the chain
1942        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1943            sp<Track> track = mActiveTracks[i].promote();
1944            if (track == 0) {
1945                continue;
1946            }
1947            if (session == track->sessionId()) {
1948                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
1949                chain->incActiveTrackCnt();
1950            }
1951        }
1952    }
1953
1954    chain->setInBuffer(buffer, ownsBuffer);
1955    chain->setOutBuffer(mMixBuffer);
1956    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
1957    // chains list in order to be processed last as it contains output stage effects
1958    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
1959    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
1960    // after track specific effects and before output stage
1961    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
1962    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
1963    // Effect chain for other sessions are inserted at beginning of effect
1964    // chains list to be processed before output mix effects. Relative order between other
1965    // sessions is not important
1966    size_t size = mEffectChains.size();
1967    size_t i = 0;
1968    for (i = 0; i < size; i++) {
1969        if (mEffectChains[i]->sessionId() < session) {
1970            break;
1971        }
1972    }
1973    mEffectChains.insertAt(chain, i);
1974    checkSuspendOnAddEffectChain_l(chain);
1975
1976    return NO_ERROR;
1977}
1978
1979size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
1980{
1981    int session = chain->sessionId();
1982
1983    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
1984
1985    for (size_t i = 0; i < mEffectChains.size(); i++) {
1986        if (chain == mEffectChains[i]) {
1987            mEffectChains.removeAt(i);
1988            // detach all active tracks from the chain
1989            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
1990                sp<Track> track = mActiveTracks[i].promote();
1991                if (track == 0) {
1992                    continue;
1993                }
1994                if (session == track->sessionId()) {
1995                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
1996                            chain.get(), session);
1997                    chain->decActiveTrackCnt();
1998                }
1999            }
2000
2001            // detach all tracks with same session ID from this chain
2002            for (size_t i = 0; i < mTracks.size(); ++i) {
2003                sp<Track> track = mTracks[i];
2004                if (session == track->sessionId()) {
2005                    track->setMainBuffer(mMixBuffer);
2006                    chain->decTrackCnt();
2007                }
2008            }
2009            break;
2010        }
2011    }
2012    return mEffectChains.size();
2013}
2014
2015status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2016        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2017{
2018    Mutex::Autolock _l(mLock);
2019    return attachAuxEffect_l(track, EffectId);
2020}
2021
2022status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2023        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2024{
2025    status_t status = NO_ERROR;
2026
2027    if (EffectId == 0) {
2028        track->setAuxBuffer(0, NULL);
2029    } else {
2030        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2031        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2032        if (effect != 0) {
2033            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2034                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2035            } else {
2036                status = INVALID_OPERATION;
2037            }
2038        } else {
2039            status = BAD_VALUE;
2040        }
2041    }
2042    return status;
2043}
2044
2045void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2046{
2047    for (size_t i = 0; i < mTracks.size(); ++i) {
2048        sp<Track> track = mTracks[i];
2049        if (track->auxEffectId() == effectId) {
2050            attachAuxEffect_l(track, 0);
2051        }
2052    }
2053}
2054
2055bool AudioFlinger::PlaybackThread::threadLoop()
2056{
2057    Vector< sp<Track> > tracksToRemove;
2058
2059    standbyTime = systemTime();
2060
2061    // MIXER
2062    nsecs_t lastWarning = 0;
2063
2064    // DUPLICATING
2065    // FIXME could this be made local to while loop?
2066    writeFrames = 0;
2067
2068    cacheParameters_l();
2069    sleepTime = idleSleepTime;
2070
2071    if (mType == MIXER) {
2072        sleepTimeShift = 0;
2073    }
2074
2075    CpuStats cpuStats;
2076    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2077
2078    acquireWakeLock();
2079
2080    // mNBLogWriter->log can only be called while thread mutex mLock is held.
2081    // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2082    // and then that string will be logged at the next convenient opportunity.
2083    const char *logString = NULL;
2084
2085    while (!exitPending())
2086    {
2087        cpuStats.sample(myName);
2088
2089        Vector< sp<EffectChain> > effectChains;
2090
2091        processConfigEvents();
2092
2093        { // scope for mLock
2094
2095            Mutex::Autolock _l(mLock);
2096
2097            if (logString != NULL) {
2098                mNBLogWriter->logTimestamp();
2099                mNBLogWriter->log(logString);
2100                logString = NULL;
2101            }
2102
2103            if (checkForNewParameters_l()) {
2104                cacheParameters_l();
2105            }
2106
2107            saveOutputTracks();
2108
2109            if (mSignalPending) {
2110                // A signal was raised while we were unlocked
2111                mSignalPending = false;
2112            } else if (waitingAsyncCallback_l()) {
2113                if (exitPending()) {
2114                    break;
2115                }
2116                releaseWakeLock_l();
2117                ALOGV("wait async completion");
2118                mWaitWorkCV.wait(mLock);
2119                ALOGV("async completion/wake");
2120                acquireWakeLock_l();
2121                if (exitPending()) {
2122                    break;
2123                }
2124                if (!mActiveTracks.size() && (systemTime() > standbyTime)) {
2125                    continue;
2126                }
2127                sleepTime = 0;
2128            } else if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
2129                                   isSuspended()) {
2130                // put audio hardware into standby after short delay
2131                if (shouldStandby_l()) {
2132
2133                    threadLoop_standby();
2134
2135                    mStandby = true;
2136                }
2137
2138                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2139                    // we're about to wait, flush the binder command buffer
2140                    IPCThreadState::self()->flushCommands();
2141
2142                    clearOutputTracks();
2143
2144                    if (exitPending()) {
2145                        break;
2146                    }
2147
2148                    releaseWakeLock_l();
2149                    // wait until we have something to do...
2150                    ALOGV("%s going to sleep", myName.string());
2151                    mWaitWorkCV.wait(mLock);
2152                    ALOGV("%s waking up", myName.string());
2153                    acquireWakeLock_l();
2154
2155                    mMixerStatus = MIXER_IDLE;
2156                    mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2157                    mBytesWritten = 0;
2158                    mBytesRemaining = 0;
2159                    checkSilentMode_l();
2160
2161                    standbyTime = systemTime() + standbyDelay;
2162                    sleepTime = idleSleepTime;
2163                    if (mType == MIXER) {
2164                        sleepTimeShift = 0;
2165                    }
2166
2167                    continue;
2168                }
2169            }
2170
2171            // mMixerStatusIgnoringFastTracks is also updated internally
2172            mMixerStatus = prepareTracks_l(&tracksToRemove);
2173
2174            // prevent any changes in effect chain list and in each effect chain
2175            // during mixing and effect process as the audio buffers could be deleted
2176            // or modified if an effect is created or deleted
2177            lockEffectChains_l(effectChains);
2178        }
2179
2180        if (mBytesRemaining == 0) {
2181            mCurrentWriteLength = 0;
2182            if (mMixerStatus == MIXER_TRACKS_READY) {
2183                // threadLoop_mix() sets mCurrentWriteLength
2184                threadLoop_mix();
2185            } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2186                        && (mMixerStatus != MIXER_DRAIN_ALL)) {
2187                // threadLoop_sleepTime sets sleepTime to 0 if data
2188                // must be written to HAL
2189                threadLoop_sleepTime();
2190                if (sleepTime == 0) {
2191                    mCurrentWriteLength = mixBufferSize;
2192                }
2193            }
2194            mBytesRemaining = mCurrentWriteLength;
2195            if (isSuspended()) {
2196                sleepTime = suspendSleepTimeUs();
2197                // simulate write to HAL when suspended
2198                mBytesWritten += mixBufferSize;
2199                mBytesRemaining = 0;
2200            }
2201
2202            // only process effects if we're going to write
2203            if (sleepTime == 0) {
2204                for (size_t i = 0; i < effectChains.size(); i ++) {
2205                    effectChains[i]->process_l();
2206                }
2207            }
2208        }
2209
2210        // enable changes in effect chain
2211        unlockEffectChains(effectChains);
2212
2213        if (!waitingAsyncCallback()) {
2214            // sleepTime == 0 means we must write to audio hardware
2215            if (sleepTime == 0) {
2216                if (mBytesRemaining) {
2217                    ssize_t ret = threadLoop_write();
2218                    if (ret < 0) {
2219                        mBytesRemaining = 0;
2220                    } else {
2221                        mBytesWritten += ret;
2222                        mBytesRemaining -= ret;
2223                    }
2224                } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2225                        (mMixerStatus == MIXER_DRAIN_ALL)) {
2226                    threadLoop_drain();
2227                }
2228if (mType == MIXER) {
2229                // write blocked detection
2230                nsecs_t now = systemTime();
2231                nsecs_t delta = now - mLastWriteTime;
2232                if (!mStandby && delta > maxPeriod) {
2233                    mNumDelayedWrites++;
2234                    if ((now - lastWarning) > kWarningThrottleNs) {
2235                        ATRACE_NAME("underrun");
2236                        ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2237                                ns2ms(delta), mNumDelayedWrites, this);
2238                        lastWarning = now;
2239                    }
2240                }
2241}
2242
2243                mStandby = false;
2244            } else {
2245                usleep(sleepTime);
2246            }
2247        }
2248
2249        // Finally let go of removed track(s), without the lock held
2250        // since we can't guarantee the destructors won't acquire that
2251        // same lock.  This will also mutate and push a new fast mixer state.
2252        threadLoop_removeTracks(tracksToRemove);
2253        tracksToRemove.clear();
2254
2255        // FIXME I don't understand the need for this here;
2256        //       it was in the original code but maybe the
2257        //       assignment in saveOutputTracks() makes this unnecessary?
2258        clearOutputTracks();
2259
2260        // Effect chains will be actually deleted here if they were removed from
2261        // mEffectChains list during mixing or effects processing
2262        effectChains.clear();
2263
2264        // FIXME Note that the above .clear() is no longer necessary since effectChains
2265        // is now local to this block, but will keep it for now (at least until merge done).
2266    }
2267
2268    threadLoop_exit();
2269
2270    // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2271    if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
2272        // put output stream into standby mode
2273        if (!mStandby) {
2274            mOutput->stream->common.standby(&mOutput->stream->common);
2275        }
2276    }
2277
2278    releaseWakeLock();
2279
2280    ALOGV("Thread %p type %d exiting", this, mType);
2281    return false;
2282}
2283
2284// removeTracks_l() must be called with ThreadBase::mLock held
2285void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2286{
2287    size_t count = tracksToRemove.size();
2288    if (CC_UNLIKELY(count)) {
2289        for (size_t i=0 ; i<count ; i++) {
2290            const sp<Track>& track = tracksToRemove.itemAt(i);
2291            mActiveTracks.remove(track);
2292            ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2293            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2294            if (chain != 0) {
2295                ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2296                        track->sessionId());
2297                chain->decActiveTrackCnt();
2298            }
2299            if (track->isTerminated()) {
2300                removeTrack_l(track);
2301            }
2302        }
2303    }
2304
2305}
2306
2307// ----------------------------------------------------------------------------
2308
2309AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2310        audio_io_handle_t id, audio_devices_t device, type_t type)
2311    :   PlaybackThread(audioFlinger, output, id, device, type),
2312        // mAudioMixer below
2313        // mFastMixer below
2314        mFastMixerFutex(0)
2315        // mOutputSink below
2316        // mPipeSink below
2317        // mNormalSink below
2318{
2319    ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
2320    ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
2321            "mFrameCount=%d, mNormalFrameCount=%d",
2322            mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2323            mNormalFrameCount);
2324    mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2325
2326    // FIXME - Current mixer implementation only supports stereo output
2327    if (mChannelCount != FCC_2) {
2328        ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2329    }
2330
2331    // create an NBAIO sink for the HAL output stream, and negotiate
2332    mOutputSink = new AudioStreamOutSink(output->stream);
2333    size_t numCounterOffers = 0;
2334    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2335    ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2336    ALOG_ASSERT(index == 0);
2337
2338    // initialize fast mixer depending on configuration
2339    bool initFastMixer;
2340    switch (kUseFastMixer) {
2341    case FastMixer_Never:
2342        initFastMixer = false;
2343        break;
2344    case FastMixer_Always:
2345        initFastMixer = true;
2346        break;
2347    case FastMixer_Static:
2348    case FastMixer_Dynamic:
2349        initFastMixer = mFrameCount < mNormalFrameCount;
2350        break;
2351    }
2352    if (initFastMixer) {
2353
2354        // create a MonoPipe to connect our submix to FastMixer
2355        NBAIO_Format format = mOutputSink->format();
2356        // This pipe depth compensates for scheduling latency of the normal mixer thread.
2357        // When it wakes up after a maximum latency, it runs a few cycles quickly before
2358        // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
2359        MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2360        const NBAIO_Format offers[1] = {format};
2361        size_t numCounterOffers = 0;
2362        ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2363        ALOG_ASSERT(index == 0);
2364        monoPipe->setAvgFrames((mScreenState & 1) ?
2365                (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2366        mPipeSink = monoPipe;
2367
2368#ifdef TEE_SINK
2369        if (mTeeSinkOutputEnabled) {
2370            // create a Pipe to archive a copy of FastMixer's output for dumpsys
2371            Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2372            numCounterOffers = 0;
2373            index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2374            ALOG_ASSERT(index == 0);
2375            mTeeSink = teeSink;
2376            PipeReader *teeSource = new PipeReader(*teeSink);
2377            numCounterOffers = 0;
2378            index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2379            ALOG_ASSERT(index == 0);
2380            mTeeSource = teeSource;
2381        }
2382#endif
2383
2384        // create fast mixer and configure it initially with just one fast track for our submix
2385        mFastMixer = new FastMixer();
2386        FastMixerStateQueue *sq = mFastMixer->sq();
2387#ifdef STATE_QUEUE_DUMP
2388        sq->setObserverDump(&mStateQueueObserverDump);
2389        sq->setMutatorDump(&mStateQueueMutatorDump);
2390#endif
2391        FastMixerState *state = sq->begin();
2392        FastTrack *fastTrack = &state->mFastTracks[0];
2393        // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2394        fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2395        fastTrack->mVolumeProvider = NULL;
2396        fastTrack->mGeneration++;
2397        state->mFastTracksGen++;
2398        state->mTrackMask = 1;
2399        // fast mixer will use the HAL output sink
2400        state->mOutputSink = mOutputSink.get();
2401        state->mOutputSinkGen++;
2402        state->mFrameCount = mFrameCount;
2403        state->mCommand = FastMixerState::COLD_IDLE;
2404        // already done in constructor initialization list
2405        //mFastMixerFutex = 0;
2406        state->mColdFutexAddr = &mFastMixerFutex;
2407        state->mColdGen++;
2408        state->mDumpState = &mFastMixerDumpState;
2409#ifdef TEE_SINK
2410        state->mTeeSink = mTeeSink.get();
2411#endif
2412        mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2413        state->mNBLogWriter = mFastMixerNBLogWriter.get();
2414        sq->end();
2415        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2416
2417        // start the fast mixer
2418        mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2419        pid_t tid = mFastMixer->getTid();
2420        int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2421        if (err != 0) {
2422            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2423                    kPriorityFastMixer, getpid_cached, tid, err);
2424        }
2425
2426#ifdef AUDIO_WATCHDOG
2427        // create and start the watchdog
2428        mAudioWatchdog = new AudioWatchdog();
2429        mAudioWatchdog->setDump(&mAudioWatchdogDump);
2430        mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2431        tid = mAudioWatchdog->getTid();
2432        err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2433        if (err != 0) {
2434            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2435                    kPriorityFastMixer, getpid_cached, tid, err);
2436        }
2437#endif
2438
2439    } else {
2440        mFastMixer = NULL;
2441    }
2442
2443    switch (kUseFastMixer) {
2444    case FastMixer_Never:
2445    case FastMixer_Dynamic:
2446        mNormalSink = mOutputSink;
2447        break;
2448    case FastMixer_Always:
2449        mNormalSink = mPipeSink;
2450        break;
2451    case FastMixer_Static:
2452        mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2453        break;
2454    }
2455}
2456
2457AudioFlinger::MixerThread::~MixerThread()
2458{
2459    if (mFastMixer != NULL) {
2460        FastMixerStateQueue *sq = mFastMixer->sq();
2461        FastMixerState *state = sq->begin();
2462        if (state->mCommand == FastMixerState::COLD_IDLE) {
2463            int32_t old = android_atomic_inc(&mFastMixerFutex);
2464            if (old == -1) {
2465                __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2466            }
2467        }
2468        state->mCommand = FastMixerState::EXIT;
2469        sq->end();
2470        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2471        mFastMixer->join();
2472        // Though the fast mixer thread has exited, it's state queue is still valid.
2473        // We'll use that extract the final state which contains one remaining fast track
2474        // corresponding to our sub-mix.
2475        state = sq->begin();
2476        ALOG_ASSERT(state->mTrackMask == 1);
2477        FastTrack *fastTrack = &state->mFastTracks[0];
2478        ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2479        delete fastTrack->mBufferProvider;
2480        sq->end(false /*didModify*/);
2481        delete mFastMixer;
2482#ifdef AUDIO_WATCHDOG
2483        if (mAudioWatchdog != 0) {
2484            mAudioWatchdog->requestExit();
2485            mAudioWatchdog->requestExitAndWait();
2486            mAudioWatchdog.clear();
2487        }
2488#endif
2489    }
2490    mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
2491    delete mAudioMixer;
2492}
2493
2494
2495uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2496{
2497    if (mFastMixer != NULL) {
2498        MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2499        latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2500    }
2501    return latency;
2502}
2503
2504
2505void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2506{
2507    PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2508}
2509
2510ssize_t AudioFlinger::MixerThread::threadLoop_write()
2511{
2512    // FIXME we should only do one push per cycle; confirm this is true
2513    // Start the fast mixer if it's not already running
2514    if (mFastMixer != NULL) {
2515        FastMixerStateQueue *sq = mFastMixer->sq();
2516        FastMixerState *state = sq->begin();
2517        if (state->mCommand != FastMixerState::MIX_WRITE &&
2518                (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2519            if (state->mCommand == FastMixerState::COLD_IDLE) {
2520                int32_t old = android_atomic_inc(&mFastMixerFutex);
2521                if (old == -1) {
2522                    __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2523                }
2524#ifdef AUDIO_WATCHDOG
2525                if (mAudioWatchdog != 0) {
2526                    mAudioWatchdog->resume();
2527                }
2528#endif
2529            }
2530            state->mCommand = FastMixerState::MIX_WRITE;
2531            mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2532                    FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
2533            sq->end();
2534            sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2535            if (kUseFastMixer == FastMixer_Dynamic) {
2536                mNormalSink = mPipeSink;
2537            }
2538        } else {
2539            sq->end(false /*didModify*/);
2540        }
2541    }
2542    return PlaybackThread::threadLoop_write();
2543}
2544
2545void AudioFlinger::MixerThread::threadLoop_standby()
2546{
2547    // Idle the fast mixer if it's currently running
2548    if (mFastMixer != NULL) {
2549        FastMixerStateQueue *sq = mFastMixer->sq();
2550        FastMixerState *state = sq->begin();
2551        if (!(state->mCommand & FastMixerState::IDLE)) {
2552            state->mCommand = FastMixerState::COLD_IDLE;
2553            state->mColdFutexAddr = &mFastMixerFutex;
2554            state->mColdGen++;
2555            mFastMixerFutex = 0;
2556            sq->end();
2557            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2558            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2559            if (kUseFastMixer == FastMixer_Dynamic) {
2560                mNormalSink = mOutputSink;
2561            }
2562#ifdef AUDIO_WATCHDOG
2563            if (mAudioWatchdog != 0) {
2564                mAudioWatchdog->pause();
2565            }
2566#endif
2567        } else {
2568            sq->end(false /*didModify*/);
2569        }
2570    }
2571    PlaybackThread::threadLoop_standby();
2572}
2573
2574// Empty implementation for standard mixer
2575// Overridden for offloaded playback
2576void AudioFlinger::PlaybackThread::flushOutput_l()
2577{
2578}
2579
2580bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2581{
2582    return false;
2583}
2584
2585bool AudioFlinger::PlaybackThread::shouldStandby_l()
2586{
2587    return !mStandby;
2588}
2589
2590bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2591{
2592    Mutex::Autolock _l(mLock);
2593    return waitingAsyncCallback_l();
2594}
2595
2596// shared by MIXER and DIRECT, overridden by DUPLICATING
2597void AudioFlinger::PlaybackThread::threadLoop_standby()
2598{
2599    ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2600    mOutput->stream->common.standby(&mOutput->stream->common);
2601    if (mUseAsyncWrite != 0) {
2602        mWriteBlocked = false;
2603        mDraining = false;
2604        ALOG_ASSERT(mCallbackThread != 0);
2605        mCallbackThread->setWriteBlocked(false);
2606        mCallbackThread->setDraining(false);
2607    }
2608}
2609
2610void AudioFlinger::MixerThread::threadLoop_mix()
2611{
2612    // obtain the presentation timestamp of the next output buffer
2613    int64_t pts;
2614    status_t status = INVALID_OPERATION;
2615
2616    if (mNormalSink != 0) {
2617        status = mNormalSink->getNextWriteTimestamp(&pts);
2618    } else {
2619        status = mOutputSink->getNextWriteTimestamp(&pts);
2620    }
2621
2622    if (status != NO_ERROR) {
2623        pts = AudioBufferProvider::kInvalidPTS;
2624    }
2625
2626    // mix buffers...
2627    mAudioMixer->process(pts);
2628    mCurrentWriteLength = mixBufferSize;
2629    // increase sleep time progressively when application underrun condition clears.
2630    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2631    // that a steady state of alternating ready/not ready conditions keeps the sleep time
2632    // such that we would underrun the audio HAL.
2633    if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2634        sleepTimeShift--;
2635    }
2636    sleepTime = 0;
2637    standbyTime = systemTime() + standbyDelay;
2638    //TODO: delay standby when effects have a tail
2639}
2640
2641void AudioFlinger::MixerThread::threadLoop_sleepTime()
2642{
2643    // If no tracks are ready, sleep once for the duration of an output
2644    // buffer size, then write 0s to the output
2645    if (sleepTime == 0) {
2646        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2647            sleepTime = activeSleepTime >> sleepTimeShift;
2648            if (sleepTime < kMinThreadSleepTimeUs) {
2649                sleepTime = kMinThreadSleepTimeUs;
2650            }
2651            // reduce sleep time in case of consecutive application underruns to avoid
2652            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2653            // duration we would end up writing less data than needed by the audio HAL if
2654            // the condition persists.
2655            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2656                sleepTimeShift++;
2657            }
2658        } else {
2659            sleepTime = idleSleepTime;
2660        }
2661    } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2662        memset (mMixBuffer, 0, mixBufferSize);
2663        sleepTime = 0;
2664        ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2665                "anticipated start");
2666    }
2667    // TODO add standby time extension fct of effect tail
2668}
2669
2670// prepareTracks_l() must be called with ThreadBase::mLock held
2671AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2672        Vector< sp<Track> > *tracksToRemove)
2673{
2674
2675    mixer_state mixerStatus = MIXER_IDLE;
2676    // find out which tracks need to be processed
2677    size_t count = mActiveTracks.size();
2678    size_t mixedTracks = 0;
2679    size_t tracksWithEffect = 0;
2680    // counts only _active_ fast tracks
2681    size_t fastTracks = 0;
2682    uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2683
2684    float masterVolume = mMasterVolume;
2685    bool masterMute = mMasterMute;
2686
2687    if (masterMute) {
2688        masterVolume = 0;
2689    }
2690    // Delegate master volume control to effect in output mix effect chain if needed
2691    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2692    if (chain != 0) {
2693        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2694        chain->setVolume_l(&v, &v);
2695        masterVolume = (float)((v + (1 << 23)) >> 24);
2696        chain.clear();
2697    }
2698
2699    // prepare a new state to push
2700    FastMixerStateQueue *sq = NULL;
2701    FastMixerState *state = NULL;
2702    bool didModify = false;
2703    FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2704    if (mFastMixer != NULL) {
2705        sq = mFastMixer->sq();
2706        state = sq->begin();
2707    }
2708
2709    for (size_t i=0 ; i<count ; i++) {
2710        sp<Track> t = mActiveTracks[i].promote();
2711        if (t == 0) {
2712            continue;
2713        }
2714
2715        // this const just means the local variable doesn't change
2716        Track* const track = t.get();
2717
2718        // process fast tracks
2719        if (track->isFastTrack()) {
2720
2721            // It's theoretically possible (though unlikely) for a fast track to be created
2722            // and then removed within the same normal mix cycle.  This is not a problem, as
2723            // the track never becomes active so it's fast mixer slot is never touched.
2724            // The converse, of removing an (active) track and then creating a new track
2725            // at the identical fast mixer slot within the same normal mix cycle,
2726            // is impossible because the slot isn't marked available until the end of each cycle.
2727            int j = track->mFastIndex;
2728            ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2729            ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2730            FastTrack *fastTrack = &state->mFastTracks[j];
2731
2732            // Determine whether the track is currently in underrun condition,
2733            // and whether it had a recent underrun.
2734            FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2735            FastTrackUnderruns underruns = ftDump->mUnderruns;
2736            uint32_t recentFull = (underruns.mBitFields.mFull -
2737                    track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2738            uint32_t recentPartial = (underruns.mBitFields.mPartial -
2739                    track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2740            uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2741                    track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2742            uint32_t recentUnderruns = recentPartial + recentEmpty;
2743            track->mObservedUnderruns = underruns;
2744            // don't count underruns that occur while stopping or pausing
2745            // or stopped which can occur when flush() is called while active
2746            if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
2747                track->mUnderrunCount += recentUnderruns;
2748            }
2749
2750            // This is similar to the state machine for normal tracks,
2751            // with a few modifications for fast tracks.
2752            bool isActive = true;
2753            switch (track->mState) {
2754            case TrackBase::STOPPING_1:
2755                // track stays active in STOPPING_1 state until first underrun
2756                if (recentUnderruns > 0 || track->isTerminated()) {
2757                    track->mState = TrackBase::STOPPING_2;
2758                }
2759                break;
2760            case TrackBase::PAUSING:
2761                // ramp down is not yet implemented
2762                track->setPaused();
2763                break;
2764            case TrackBase::RESUMING:
2765                // ramp up is not yet implemented
2766                track->mState = TrackBase::ACTIVE;
2767                break;
2768            case TrackBase::ACTIVE:
2769                if (recentFull > 0 || recentPartial > 0) {
2770                    // track has provided at least some frames recently: reset retry count
2771                    track->mRetryCount = kMaxTrackRetries;
2772                }
2773                if (recentUnderruns == 0) {
2774                    // no recent underruns: stay active
2775                    break;
2776                }
2777                // there has recently been an underrun of some kind
2778                if (track->sharedBuffer() == 0) {
2779                    // were any of the recent underruns "empty" (no frames available)?
2780                    if (recentEmpty == 0) {
2781                        // no, then ignore the partial underruns as they are allowed indefinitely
2782                        break;
2783                    }
2784                    // there has recently been an "empty" underrun: decrement the retry counter
2785                    if (--(track->mRetryCount) > 0) {
2786                        break;
2787                    }
2788                    // indicate to client process that the track was disabled because of underrun;
2789                    // it will then automatically call start() when data is available
2790                    android_atomic_or(CBLK_DISABLED, &track->mCblk->flags);
2791                    // remove from active list, but state remains ACTIVE [confusing but true]
2792                    isActive = false;
2793                    break;
2794                }
2795                // fall through
2796            case TrackBase::STOPPING_2:
2797            case TrackBase::PAUSED:
2798            case TrackBase::STOPPED:
2799            case TrackBase::FLUSHED:   // flush() while active
2800                // Check for presentation complete if track is inactive
2801                // We have consumed all the buffers of this track.
2802                // This would be incomplete if we auto-paused on underrun
2803                {
2804                    size_t audioHALFrames =
2805                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2806                    size_t framesWritten = mBytesWritten / mFrameSize;
2807                    if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2808                        // track stays in active list until presentation is complete
2809                        break;
2810                    }
2811                }
2812                if (track->isStopping_2()) {
2813                    track->mState = TrackBase::STOPPED;
2814                }
2815                if (track->isStopped()) {
2816                    // Can't reset directly, as fast mixer is still polling this track
2817                    //   track->reset();
2818                    // So instead mark this track as needing to be reset after push with ack
2819                    resetMask |= 1 << i;
2820                }
2821                isActive = false;
2822                break;
2823            case TrackBase::IDLE:
2824            default:
2825                LOG_FATAL("unexpected track state %d", track->mState);
2826            }
2827
2828            if (isActive) {
2829                // was it previously inactive?
2830                if (!(state->mTrackMask & (1 << j))) {
2831                    ExtendedAudioBufferProvider *eabp = track;
2832                    VolumeProvider *vp = track;
2833                    fastTrack->mBufferProvider = eabp;
2834                    fastTrack->mVolumeProvider = vp;
2835                    fastTrack->mSampleRate = track->mSampleRate;
2836                    fastTrack->mChannelMask = track->mChannelMask;
2837                    fastTrack->mGeneration++;
2838                    state->mTrackMask |= 1 << j;
2839                    didModify = true;
2840                    // no acknowledgement required for newly active tracks
2841                }
2842                // cache the combined master volume and stream type volume for fast mixer; this
2843                // lacks any synchronization or barrier so VolumeProvider may read a stale value
2844                track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
2845                ++fastTracks;
2846            } else {
2847                // was it previously active?
2848                if (state->mTrackMask & (1 << j)) {
2849                    fastTrack->mBufferProvider = NULL;
2850                    fastTrack->mGeneration++;
2851                    state->mTrackMask &= ~(1 << j);
2852                    didModify = true;
2853                    // If any fast tracks were removed, we must wait for acknowledgement
2854                    // because we're about to decrement the last sp<> on those tracks.
2855                    block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2856                } else {
2857                    LOG_FATAL("fast track %d should have been active", j);
2858                }
2859                tracksToRemove->add(track);
2860                // Avoids a misleading display in dumpsys
2861                track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
2862            }
2863            continue;
2864        }
2865
2866        {   // local variable scope to avoid goto warning
2867
2868        audio_track_cblk_t* cblk = track->cblk();
2869
2870        // The first time a track is added we wait
2871        // for all its buffers to be filled before processing it
2872        int name = track->name();
2873        // make sure that we have enough frames to mix one full buffer.
2874        // enforce this condition only once to enable draining the buffer in case the client
2875        // app does not call stop() and relies on underrun to stop:
2876        // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2877        // during last round
2878        size_t desiredFrames;
2879        if (t->sampleRate() == mSampleRate) {
2880            desiredFrames = mNormalFrameCount;
2881        } else {
2882            // +1 for rounding and +1 for additional sample needed for interpolation
2883            desiredFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2884            // add frames already consumed but not yet released by the resampler
2885            // because cblk->framesReady() will include these frames
2886            desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
2887            // the minimum track buffer size is normally twice the number of frames necessary
2888            // to fill one buffer and the resampler should not leave more than one buffer worth
2889            // of unreleased frames after each pass, but just in case...
2890            ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
2891        }
2892        uint32_t minFrames = 1;
2893        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
2894                (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
2895            minFrames = desiredFrames;
2896        }
2897        // It's not safe to call framesReady() for a static buffer track, so assume it's ready
2898        size_t framesReady;
2899        if (track->sharedBuffer() == 0) {
2900            framesReady = track->framesReady();
2901        } else if (track->isStopped()) {
2902            framesReady = 0;
2903        } else {
2904            framesReady = 1;
2905        }
2906        if ((framesReady >= minFrames) && track->isReady() &&
2907                !track->isPaused() && !track->isTerminated())
2908        {
2909            ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->server, this);
2910
2911            mixedTracks++;
2912
2913            // track->mainBuffer() != mMixBuffer means there is an effect chain
2914            // connected to the track
2915            chain.clear();
2916            if (track->mainBuffer() != mMixBuffer) {
2917                chain = getEffectChain_l(track->sessionId());
2918                // Delegate volume control to effect in track effect chain if needed
2919                if (chain != 0) {
2920                    tracksWithEffect++;
2921                } else {
2922                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
2923                            "session %d",
2924                            name, track->sessionId());
2925                }
2926            }
2927
2928
2929            int param = AudioMixer::VOLUME;
2930            if (track->mFillingUpStatus == Track::FS_FILLED) {
2931                // no ramp for the first volume setting
2932                track->mFillingUpStatus = Track::FS_ACTIVE;
2933                if (track->mState == TrackBase::RESUMING) {
2934                    track->mState = TrackBase::ACTIVE;
2935                    param = AudioMixer::RAMP_VOLUME;
2936                }
2937                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
2938            } else if (cblk->server != 0) {
2939                // If the track is stopped before the first frame was mixed,
2940                // do not apply ramp
2941                param = AudioMixer::RAMP_VOLUME;
2942            }
2943
2944            // compute volume for this track
2945            uint32_t vl, vr, va;
2946            if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
2947                vl = vr = va = 0;
2948                if (track->isPausing()) {
2949                    track->setPaused();
2950                }
2951            } else {
2952
2953                // read original volumes with volume control
2954                float typeVolume = mStreamTypes[track->streamType()].volume;
2955                float v = masterVolume * typeVolume;
2956                AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
2957                uint32_t vlr = proxy->getVolumeLR();
2958                vl = vlr & 0xFFFF;
2959                vr = vlr >> 16;
2960                // track volumes come from shared memory, so can't be trusted and must be clamped
2961                if (vl > MAX_GAIN_INT) {
2962                    ALOGV("Track left volume out of range: %04X", vl);
2963                    vl = MAX_GAIN_INT;
2964                }
2965                if (vr > MAX_GAIN_INT) {
2966                    ALOGV("Track right volume out of range: %04X", vr);
2967                    vr = MAX_GAIN_INT;
2968                }
2969                // now apply the master volume and stream type volume
2970                vl = (uint32_t)(v * vl) << 12;
2971                vr = (uint32_t)(v * vr) << 12;
2972                // assuming master volume and stream type volume each go up to 1.0,
2973                // vl and vr are now in 8.24 format
2974
2975                uint16_t sendLevel = proxy->getSendLevel_U4_12();
2976                // send level comes from shared memory and so may be corrupt
2977                if (sendLevel > MAX_GAIN_INT) {
2978                    ALOGV("Track send level out of range: %04X", sendLevel);
2979                    sendLevel = MAX_GAIN_INT;
2980                }
2981                va = (uint32_t)(v * sendLevel);
2982            }
2983
2984            // Delegate volume control to effect in track effect chain if needed
2985            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2986                // Do not ramp volume if volume is controlled by effect
2987                param = AudioMixer::VOLUME;
2988                track->mHasVolumeController = true;
2989            } else {
2990                // force no volume ramp when volume controller was just disabled or removed
2991                // from effect chain to avoid volume spike
2992                if (track->mHasVolumeController) {
2993                    param = AudioMixer::VOLUME;
2994                }
2995                track->mHasVolumeController = false;
2996            }
2997
2998            // Convert volumes from 8.24 to 4.12 format
2999            // This additional clamping is needed in case chain->setVolume_l() overshot
3000            vl = (vl + (1 << 11)) >> 12;
3001            if (vl > MAX_GAIN_INT) {
3002                vl = MAX_GAIN_INT;
3003            }
3004            vr = (vr + (1 << 11)) >> 12;
3005            if (vr > MAX_GAIN_INT) {
3006                vr = MAX_GAIN_INT;
3007            }
3008
3009            if (va > MAX_GAIN_INT) {
3010                va = MAX_GAIN_INT;   // va is uint32_t, so no need to check for -
3011            }
3012
3013            // XXX: these things DON'T need to be done each time
3014            mAudioMixer->setBufferProvider(name, track);
3015            mAudioMixer->enable(name);
3016
3017            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3018            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3019            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3020            mAudioMixer->setParameter(
3021                name,
3022                AudioMixer::TRACK,
3023                AudioMixer::FORMAT, (void *)track->format());
3024            mAudioMixer->setParameter(
3025                name,
3026                AudioMixer::TRACK,
3027                AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
3028            // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3029            uint32_t maxSampleRate = mSampleRate * 2;
3030            uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
3031            if (reqSampleRate == 0) {
3032                reqSampleRate = mSampleRate;
3033            } else if (reqSampleRate > maxSampleRate) {
3034                reqSampleRate = maxSampleRate;
3035            }
3036            mAudioMixer->setParameter(
3037                name,
3038                AudioMixer::RESAMPLE,
3039                AudioMixer::SAMPLE_RATE,
3040                (void *)reqSampleRate);
3041            mAudioMixer->setParameter(
3042                name,
3043                AudioMixer::TRACK,
3044                AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3045            mAudioMixer->setParameter(
3046                name,
3047                AudioMixer::TRACK,
3048                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3049
3050            // reset retry count
3051            track->mRetryCount = kMaxTrackRetries;
3052
3053            // If one track is ready, set the mixer ready if:
3054            //  - the mixer was not ready during previous round OR
3055            //  - no other track is not ready
3056            if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3057                    mixerStatus != MIXER_TRACKS_ENABLED) {
3058                mixerStatus = MIXER_TRACKS_READY;
3059            }
3060        } else {
3061            // only implemented for normal tracks, not fast tracks
3062            if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
3063                // we missed desiredFrames whatever the actual number of frames missing was
3064                cblk->u.mStreaming.mUnderrunFrames += desiredFrames;
3065                // FIXME also wake futex so that underrun is noticed more quickly
3066                (void) android_atomic_or(CBLK_UNDERRUN, &cblk->flags);
3067            }
3068            // clear effect chain input buffer if an active track underruns to avoid sending
3069            // previous audio buffer again to effects
3070            chain = getEffectChain_l(track->sessionId());
3071            if (chain != 0) {
3072                chain->clearInputBuffer();
3073            }
3074
3075            ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->server, this);
3076            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3077                    track->isStopped() || track->isPaused()) {
3078                // We have consumed all the buffers of this track.
3079                // Remove it from the list of active tracks.
3080                // TODO: use actual buffer filling status instead of latency when available from
3081                // audio HAL
3082                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3083                size_t framesWritten = mBytesWritten / mFrameSize;
3084                if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3085                    if (track->isStopped()) {
3086                        track->reset();
3087                    }
3088                    tracksToRemove->add(track);
3089                }
3090            } else {
3091                track->mUnderrunCount++;
3092                // No buffers for this track. Give it a few chances to
3093                // fill a buffer, then remove it from active list.
3094                if (--(track->mRetryCount) <= 0) {
3095                    ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
3096                    tracksToRemove->add(track);
3097                    // indicate to client process that the track was disabled because of underrun;
3098                    // it will then automatically call start() when data is available
3099                    android_atomic_or(CBLK_DISABLED, &cblk->flags);
3100                // If one track is not ready, mark the mixer also not ready if:
3101                //  - the mixer was ready during previous round OR
3102                //  - no other track is ready
3103                } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3104                                mixerStatus != MIXER_TRACKS_READY) {
3105                    mixerStatus = MIXER_TRACKS_ENABLED;
3106                }
3107            }
3108            mAudioMixer->disable(name);
3109        }
3110
3111        }   // local variable scope to avoid goto warning
3112track_is_ready: ;
3113
3114    }
3115
3116    // Push the new FastMixer state if necessary
3117    bool pauseAudioWatchdog = false;
3118    if (didModify) {
3119        state->mFastTracksGen++;
3120        // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3121        if (kUseFastMixer == FastMixer_Dynamic &&
3122                state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3123            state->mCommand = FastMixerState::COLD_IDLE;
3124            state->mColdFutexAddr = &mFastMixerFutex;
3125            state->mColdGen++;
3126            mFastMixerFutex = 0;
3127            if (kUseFastMixer == FastMixer_Dynamic) {
3128                mNormalSink = mOutputSink;
3129            }
3130            // If we go into cold idle, need to wait for acknowledgement
3131            // so that fast mixer stops doing I/O.
3132            block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3133            pauseAudioWatchdog = true;
3134        }
3135    }
3136    if (sq != NULL) {
3137        sq->end(didModify);
3138        sq->push(block);
3139    }
3140#ifdef AUDIO_WATCHDOG
3141    if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3142        mAudioWatchdog->pause();
3143    }
3144#endif
3145
3146    // Now perform the deferred reset on fast tracks that have stopped
3147    while (resetMask != 0) {
3148        size_t i = __builtin_ctz(resetMask);
3149        ALOG_ASSERT(i < count);
3150        resetMask &= ~(1 << i);
3151        sp<Track> t = mActiveTracks[i].promote();
3152        if (t == 0) {
3153            continue;
3154        }
3155        Track* track = t.get();
3156        ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3157        track->reset();
3158    }
3159
3160    // remove all the tracks that need to be...
3161    removeTracks_l(*tracksToRemove);
3162
3163    // mix buffer must be cleared if all tracks are connected to an
3164    // effect chain as in this case the mixer will not write to
3165    // mix buffer and track effects will accumulate into it
3166    if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3167            (mixedTracks == 0 && fastTracks > 0))) {
3168        // FIXME as a performance optimization, should remember previous zero status
3169        memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3170    }
3171
3172    // if any fast tracks, then status is ready
3173    mMixerStatusIgnoringFastTracks = mixerStatus;
3174    if (fastTracks > 0) {
3175        mixerStatus = MIXER_TRACKS_READY;
3176    }
3177    return mixerStatus;
3178}
3179
3180// getTrackName_l() must be called with ThreadBase::mLock held
3181int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3182{
3183    return mAudioMixer->getTrackName(channelMask, sessionId);
3184}
3185
3186// deleteTrackName_l() must be called with ThreadBase::mLock held
3187void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3188{
3189    ALOGV("remove track (%d) and delete from mixer", name);
3190    mAudioMixer->deleteTrackName(name);
3191}
3192
3193// checkForNewParameters_l() must be called with ThreadBase::mLock held
3194bool AudioFlinger::MixerThread::checkForNewParameters_l()
3195{
3196    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3197    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3198    bool reconfig = false;
3199
3200    while (!mNewParameters.isEmpty()) {
3201
3202        if (mFastMixer != NULL) {
3203            FastMixerStateQueue *sq = mFastMixer->sq();
3204            FastMixerState *state = sq->begin();
3205            if (!(state->mCommand & FastMixerState::IDLE)) {
3206                previousCommand = state->mCommand;
3207                state->mCommand = FastMixerState::HOT_IDLE;
3208                sq->end();
3209                sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3210            } else {
3211                sq->end(false /*didModify*/);
3212            }
3213        }
3214
3215        status_t status = NO_ERROR;
3216        String8 keyValuePair = mNewParameters[0];
3217        AudioParameter param = AudioParameter(keyValuePair);
3218        int value;
3219
3220        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3221            reconfig = true;
3222        }
3223        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3224            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3225                status = BAD_VALUE;
3226            } else {
3227                reconfig = true;
3228            }
3229        }
3230        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3231            if (value != AUDIO_CHANNEL_OUT_STEREO) {
3232                status = BAD_VALUE;
3233            } else {
3234                reconfig = true;
3235            }
3236        }
3237        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3238            // do not accept frame count changes if tracks are open as the track buffer
3239            // size depends on frame count and correct behavior would not be guaranteed
3240            // if frame count is changed after track creation
3241            if (!mTracks.isEmpty()) {
3242                status = INVALID_OPERATION;
3243            } else {
3244                reconfig = true;
3245            }
3246        }
3247        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3248#ifdef ADD_BATTERY_DATA
3249            // when changing the audio output device, call addBatteryData to notify
3250            // the change
3251            if (mOutDevice != value) {
3252                uint32_t params = 0;
3253                // check whether speaker is on
3254                if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3255                    params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3256                }
3257
3258                audio_devices_t deviceWithoutSpeaker
3259                    = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3260                // check if any other device (except speaker) is on
3261                if (value & deviceWithoutSpeaker ) {
3262                    params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3263                }
3264
3265                if (params != 0) {
3266                    addBatteryData(params);
3267                }
3268            }
3269#endif
3270
3271            // forward device change to effects that have requested to be
3272            // aware of attached audio device.
3273            if (value != AUDIO_DEVICE_NONE) {
3274                mOutDevice = value;
3275                for (size_t i = 0; i < mEffectChains.size(); i++) {
3276                    mEffectChains[i]->setDevice_l(mOutDevice);
3277                }
3278            }
3279        }
3280
3281        if (status == NO_ERROR) {
3282            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3283                                                    keyValuePair.string());
3284            if (!mStandby && status == INVALID_OPERATION) {
3285                mOutput->stream->common.standby(&mOutput->stream->common);
3286                mStandby = true;
3287                mBytesWritten = 0;
3288                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3289                                                       keyValuePair.string());
3290            }
3291            if (status == NO_ERROR && reconfig) {
3292                readOutputParameters();
3293                delete mAudioMixer;
3294                mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3295                for (size_t i = 0; i < mTracks.size() ; i++) {
3296                    int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3297                    if (name < 0) {
3298                        break;
3299                    }
3300                    mTracks[i]->mName = name;
3301                }
3302                sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3303            }
3304        }
3305
3306        mNewParameters.removeAt(0);
3307
3308        mParamStatus = status;
3309        mParamCond.signal();
3310        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3311        // already timed out waiting for the status and will never signal the condition.
3312        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3313    }
3314
3315    if (!(previousCommand & FastMixerState::IDLE)) {
3316        ALOG_ASSERT(mFastMixer != NULL);
3317        FastMixerStateQueue *sq = mFastMixer->sq();
3318        FastMixerState *state = sq->begin();
3319        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3320        state->mCommand = previousCommand;
3321        sq->end();
3322        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3323    }
3324
3325    return reconfig;
3326}
3327
3328
3329void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3330{
3331    const size_t SIZE = 256;
3332    char buffer[SIZE];
3333    String8 result;
3334
3335    PlaybackThread::dumpInternals(fd, args);
3336
3337    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3338    result.append(buffer);
3339    write(fd, result.string(), result.size());
3340
3341    // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3342    const FastMixerDumpState copy(mFastMixerDumpState);
3343    copy.dump(fd);
3344
3345#ifdef STATE_QUEUE_DUMP
3346    // Similar for state queue
3347    StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3348    observerCopy.dump(fd);
3349    StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3350    mutatorCopy.dump(fd);
3351#endif
3352
3353#ifdef TEE_SINK
3354    // Write the tee output to a .wav file
3355    dumpTee(fd, mTeeSource, mId);
3356#endif
3357
3358#ifdef AUDIO_WATCHDOG
3359    if (mAudioWatchdog != 0) {
3360        // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3361        AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3362        wdCopy.dump(fd);
3363    }
3364#endif
3365}
3366
3367uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3368{
3369    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3370}
3371
3372uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3373{
3374    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3375}
3376
3377void AudioFlinger::MixerThread::cacheParameters_l()
3378{
3379    PlaybackThread::cacheParameters_l();
3380
3381    // FIXME: Relaxed timing because of a certain device that can't meet latency
3382    // Should be reduced to 2x after the vendor fixes the driver issue
3383    // increase threshold again due to low power audio mode. The way this warning
3384    // threshold is calculated and its usefulness should be reconsidered anyway.
3385    maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3386}
3387
3388// ----------------------------------------------------------------------------
3389
3390AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3391        AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3392    :   PlaybackThread(audioFlinger, output, id, device, DIRECT)
3393        // mLeftVolFloat, mRightVolFloat
3394{
3395}
3396
3397AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3398        AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3399        ThreadBase::type_t type)
3400    :   PlaybackThread(audioFlinger, output, id, device, type)
3401        // mLeftVolFloat, mRightVolFloat
3402{
3403}
3404
3405AudioFlinger::DirectOutputThread::~DirectOutputThread()
3406{
3407}
3408
3409void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3410{
3411    audio_track_cblk_t* cblk = track->cblk();
3412    float left, right;
3413
3414    if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3415        left = right = 0;
3416    } else {
3417        float typeVolume = mStreamTypes[track->streamType()].volume;
3418        float v = mMasterVolume * typeVolume;
3419        AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3420        uint32_t vlr = proxy->getVolumeLR();
3421        float v_clamped = v * (vlr & 0xFFFF);
3422        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3423        left = v_clamped/MAX_GAIN;
3424        v_clamped = v * (vlr >> 16);
3425        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3426        right = v_clamped/MAX_GAIN;
3427    }
3428
3429    if (lastTrack) {
3430        if (left != mLeftVolFloat || right != mRightVolFloat) {
3431            mLeftVolFloat = left;
3432            mRightVolFloat = right;
3433
3434            // Convert volumes from float to 8.24
3435            uint32_t vl = (uint32_t)(left * (1 << 24));
3436            uint32_t vr = (uint32_t)(right * (1 << 24));
3437
3438            // Delegate volume control to effect in track effect chain if needed
3439            // only one effect chain can be present on DirectOutputThread, so if
3440            // there is one, the track is connected to it
3441            if (!mEffectChains.isEmpty()) {
3442                mEffectChains[0]->setVolume_l(&vl, &vr);
3443                left = (float)vl / (1 << 24);
3444                right = (float)vr / (1 << 24);
3445            }
3446            if (mOutput->stream->set_volume) {
3447                mOutput->stream->set_volume(mOutput->stream, left, right);
3448            }
3449        }
3450    }
3451}
3452
3453
3454AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3455    Vector< sp<Track> > *tracksToRemove
3456)
3457{
3458    size_t count = mActiveTracks.size();
3459    mixer_state mixerStatus = MIXER_IDLE;
3460
3461    // find out which tracks need to be processed
3462    for (size_t i = 0; i < count; i++) {
3463        sp<Track> t = mActiveTracks[i].promote();
3464        // The track died recently
3465        if (t == 0) {
3466            continue;
3467        }
3468
3469        Track* const track = t.get();
3470        audio_track_cblk_t* cblk = track->cblk();
3471
3472        // The first time a track is added we wait
3473        // for all its buffers to be filled before processing it
3474        uint32_t minFrames;
3475        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3476            minFrames = mNormalFrameCount;
3477        } else {
3478            minFrames = 1;
3479        }
3480        // Only consider last track started for volume and mixer state control.
3481        // This is the last entry in mActiveTracks unless a track underruns.
3482        // As we only care about the transition phase between two tracks on a
3483        // direct output, it is not a problem to ignore the underrun case.
3484        bool last = (i == (count - 1));
3485
3486        if ((track->framesReady() >= minFrames) && track->isReady() &&
3487                !track->isPaused() && !track->isTerminated())
3488        {
3489            ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
3490
3491            if (track->mFillingUpStatus == Track::FS_FILLED) {
3492                track->mFillingUpStatus = Track::FS_ACTIVE;
3493                mLeftVolFloat = mRightVolFloat = 0;
3494                if (track->mState == TrackBase::RESUMING) {
3495                    track->mState = TrackBase::ACTIVE;
3496                }
3497            }
3498
3499            // compute volume for this track
3500            processVolume_l(track, last);
3501            if (last) {
3502                // reset retry count
3503                track->mRetryCount = kMaxTrackRetriesDirect;
3504                mActiveTrack = t;
3505                mixerStatus = MIXER_TRACKS_READY;
3506            }
3507        } else {
3508            // clear effect chain input buffer if the last active track started underruns
3509            // to avoid sending previous audio buffer again to effects
3510            if (!mEffectChains.isEmpty() && (i == (count -1))) {
3511                mEffectChains[0]->clearInputBuffer();
3512            }
3513
3514            ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3515            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3516                    track->isStopped() || track->isPaused()) {
3517                // We have consumed all the buffers of this track.
3518                // Remove it from the list of active tracks.
3519                // TODO: implement behavior for compressed audio
3520                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3521                size_t framesWritten = mBytesWritten / mFrameSize;
3522                if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3523                    if (track->isStopped()) {
3524                        track->reset();
3525                    }
3526                    tracksToRemove->add(track);
3527                }
3528            } else {
3529                // No buffers for this track. Give it a few chances to
3530                // fill a buffer, then remove it from active list.
3531                // Only consider last track started for mixer state control
3532                if (--(track->mRetryCount) <= 0) {
3533                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3534                    tracksToRemove->add(track);
3535                } else if (last) {
3536                    mixerStatus = MIXER_TRACKS_ENABLED;
3537                }
3538            }
3539        }
3540    }
3541
3542    // remove all the tracks that need to be...
3543    removeTracks_l(*tracksToRemove);
3544
3545    return mixerStatus;
3546}
3547
3548void AudioFlinger::DirectOutputThread::threadLoop_mix()
3549{
3550    size_t frameCount = mFrameCount;
3551    int8_t *curBuf = (int8_t *)mMixBuffer;
3552    // output audio to hardware
3553    while (frameCount) {
3554        AudioBufferProvider::Buffer buffer;
3555        buffer.frameCount = frameCount;
3556        mActiveTrack->getNextBuffer(&buffer);
3557        if (CC_UNLIKELY(buffer.raw == NULL)) {
3558            memset(curBuf, 0, frameCount * mFrameSize);
3559            break;
3560        }
3561        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3562        frameCount -= buffer.frameCount;
3563        curBuf += buffer.frameCount * mFrameSize;
3564        mActiveTrack->releaseBuffer(&buffer);
3565    }
3566    mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
3567    sleepTime = 0;
3568    standbyTime = systemTime() + standbyDelay;
3569    mActiveTrack.clear();
3570}
3571
3572void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3573{
3574    if (sleepTime == 0) {
3575        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3576            sleepTime = activeSleepTime;
3577        } else {
3578            sleepTime = idleSleepTime;
3579        }
3580    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3581        memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3582        sleepTime = 0;
3583    }
3584}
3585
3586// getTrackName_l() must be called with ThreadBase::mLock held
3587int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3588        int sessionId)
3589{
3590    return 0;
3591}
3592
3593// deleteTrackName_l() must be called with ThreadBase::mLock held
3594void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3595{
3596}
3597
3598// checkForNewParameters_l() must be called with ThreadBase::mLock held
3599bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3600{
3601    bool reconfig = false;
3602
3603    while (!mNewParameters.isEmpty()) {
3604        status_t status = NO_ERROR;
3605        String8 keyValuePair = mNewParameters[0];
3606        AudioParameter param = AudioParameter(keyValuePair);
3607        int value;
3608
3609        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3610            // do not accept frame count changes if tracks are open as the track buffer
3611            // size depends on frame count and correct behavior would not be garantied
3612            // if frame count is changed after track creation
3613            if (!mTracks.isEmpty()) {
3614                status = INVALID_OPERATION;
3615            } else {
3616                reconfig = true;
3617            }
3618        }
3619        if (status == NO_ERROR) {
3620            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3621                                                    keyValuePair.string());
3622            if (!mStandby && status == INVALID_OPERATION) {
3623                mOutput->stream->common.standby(&mOutput->stream->common);
3624                mStandby = true;
3625                mBytesWritten = 0;
3626                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3627                                                       keyValuePair.string());
3628            }
3629            if (status == NO_ERROR && reconfig) {
3630                readOutputParameters();
3631                sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3632            }
3633        }
3634
3635        mNewParameters.removeAt(0);
3636
3637        mParamStatus = status;
3638        mParamCond.signal();
3639        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3640        // already timed out waiting for the status and will never signal the condition.
3641        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3642    }
3643    return reconfig;
3644}
3645
3646uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3647{
3648    uint32_t time;
3649    if (audio_is_linear_pcm(mFormat)) {
3650        time = PlaybackThread::activeSleepTimeUs();
3651    } else {
3652        time = 10000;
3653    }
3654    return time;
3655}
3656
3657uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3658{
3659    uint32_t time;
3660    if (audio_is_linear_pcm(mFormat)) {
3661        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3662    } else {
3663        time = 10000;
3664    }
3665    return time;
3666}
3667
3668uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3669{
3670    uint32_t time;
3671    if (audio_is_linear_pcm(mFormat)) {
3672        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3673    } else {
3674        time = 10000;
3675    }
3676    return time;
3677}
3678
3679void AudioFlinger::DirectOutputThread::cacheParameters_l()
3680{
3681    PlaybackThread::cacheParameters_l();
3682
3683    // use shorter standby delay as on normal output to release
3684    // hardware resources as soon as possible
3685    standbyDelay = microseconds(activeSleepTime*2);
3686}
3687
3688// ----------------------------------------------------------------------------
3689
3690AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
3691        const sp<AudioFlinger::OffloadThread>& offloadThread)
3692    :   Thread(false /*canCallJava*/),
3693        mOffloadThread(offloadThread),
3694        mWriteBlocked(false),
3695        mDraining(false)
3696{
3697}
3698
3699AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3700{
3701}
3702
3703void AudioFlinger::AsyncCallbackThread::onFirstRef()
3704{
3705    run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3706}
3707
3708bool AudioFlinger::AsyncCallbackThread::threadLoop()
3709{
3710    while (!exitPending()) {
3711        bool writeBlocked;
3712        bool draining;
3713
3714        {
3715            Mutex::Autolock _l(mLock);
3716            mWaitWorkCV.wait(mLock);
3717            if (exitPending()) {
3718                break;
3719            }
3720            writeBlocked = mWriteBlocked;
3721            draining = mDraining;
3722            ALOGV("AsyncCallbackThread mWriteBlocked %d mDraining %d", mWriteBlocked, mDraining);
3723        }
3724        {
3725            sp<AudioFlinger::OffloadThread> offloadThread = mOffloadThread.promote();
3726            if (offloadThread != 0) {
3727                if (writeBlocked == false) {
3728                    offloadThread->setWriteBlocked(false);
3729                }
3730                if (draining == false) {
3731                    offloadThread->setDraining(false);
3732                }
3733            }
3734        }
3735    }
3736    return false;
3737}
3738
3739void AudioFlinger::AsyncCallbackThread::exit()
3740{
3741    ALOGV("AsyncCallbackThread::exit");
3742    Mutex::Autolock _l(mLock);
3743    requestExit();
3744    mWaitWorkCV.broadcast();
3745}
3746
3747void AudioFlinger::AsyncCallbackThread::setWriteBlocked(bool value)
3748{
3749    Mutex::Autolock _l(mLock);
3750    mWriteBlocked = value;
3751    if (!value) {
3752        mWaitWorkCV.signal();
3753    }
3754}
3755
3756void AudioFlinger::AsyncCallbackThread::setDraining(bool value)
3757{
3758    Mutex::Autolock _l(mLock);
3759    mDraining = value;
3760    if (!value) {
3761        mWaitWorkCV.signal();
3762    }
3763}
3764
3765
3766// ----------------------------------------------------------------------------
3767AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3768        AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3769    :   DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3770        mHwPaused(false),
3771        mPausedBytesRemaining(0)
3772{
3773    mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
3774}
3775
3776AudioFlinger::OffloadThread::~OffloadThread()
3777{
3778    mPreviousTrack.clear();
3779}
3780
3781void AudioFlinger::OffloadThread::threadLoop_exit()
3782{
3783    if (mFlushPending || mHwPaused) {
3784        // If a flush is pending or track was paused, just discard buffered data
3785        flushHw_l();
3786    } else {
3787        mMixerStatus = MIXER_DRAIN_ALL;
3788        threadLoop_drain();
3789    }
3790    mCallbackThread->exit();
3791    PlaybackThread::threadLoop_exit();
3792}
3793
3794AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3795    Vector< sp<Track> > *tracksToRemove
3796)
3797{
3798    ALOGV("OffloadThread::prepareTracks_l");
3799    size_t count = mActiveTracks.size();
3800
3801    mixer_state mixerStatus = MIXER_IDLE;
3802    if (mFlushPending) {
3803        flushHw_l();
3804        mFlushPending = false;
3805    }
3806    // find out which tracks need to be processed
3807    for (size_t i = 0; i < count; i++) {
3808        sp<Track> t = mActiveTracks[i].promote();
3809        // The track died recently
3810        if (t == 0) {
3811            continue;
3812        }
3813        Track* const track = t.get();
3814        audio_track_cblk_t* cblk = track->cblk();
3815        if (mPreviousTrack != NULL) {
3816            if (t != mPreviousTrack) {
3817                // Flush any data still being written from last track
3818                mBytesRemaining = 0;
3819                if (mPausedBytesRemaining) {
3820                    // Last track was paused so we also need to flush saved
3821                    // mixbuffer state and invalidate track so that it will
3822                    // re-submit that unwritten data when it is next resumed
3823                    mPausedBytesRemaining = 0;
3824                    // Invalidate is a bit drastic - would be more efficient
3825                    // to have a flag to tell client that some of the
3826                    // previously written data was lost
3827                    mPreviousTrack->invalidate();
3828                }
3829            }
3830        }
3831        mPreviousTrack = t;
3832        bool last = (i == (count - 1));
3833        if (track->isPausing()) {
3834            track->setPaused();
3835            if (last) {
3836                if (!mHwPaused) {
3837                    mOutput->stream->pause(mOutput->stream);
3838                    mHwPaused = true;
3839                }
3840                // If we were part way through writing the mixbuffer to
3841                // the HAL we must save this until we resume
3842                // BUG - this will be wrong if a different track is made active,
3843                // in that case we want to discard the pending data in the
3844                // mixbuffer and tell the client to present it again when the
3845                // track is resumed
3846                mPausedWriteLength = mCurrentWriteLength;
3847                mPausedBytesRemaining = mBytesRemaining;
3848                mBytesRemaining = 0;    // stop writing
3849            }
3850            tracksToRemove->add(track);
3851        } else if (track->framesReady() && track->isReady() &&
3852                !track->isPaused() && !track->isTerminated()) {
3853            ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->server);
3854            if (track->mFillingUpStatus == Track::FS_FILLED) {
3855                track->mFillingUpStatus = Track::FS_ACTIVE;
3856                mLeftVolFloat = mRightVolFloat = 0;
3857                if (track->mState == TrackBase::RESUMING) {
3858                    if (CC_UNLIKELY(mPausedBytesRemaining)) {
3859                        // Need to continue write that was interrupted
3860                        mCurrentWriteLength = mPausedWriteLength;
3861                        mBytesRemaining = mPausedBytesRemaining;
3862                        mPausedBytesRemaining = 0;
3863                    }
3864                    track->mState = TrackBase::ACTIVE;
3865                }
3866            }
3867
3868            if (last) {
3869                if (mHwPaused) {
3870                    mOutput->stream->resume(mOutput->stream);
3871                    mHwPaused = false;
3872                    // threadLoop_mix() will handle the case that we need to
3873                    // resume an interrupted write
3874                }
3875                // reset retry count
3876                track->mRetryCount = kMaxTrackRetriesOffload;
3877                mActiveTrack = t;
3878                mixerStatus = MIXER_TRACKS_READY;
3879            }
3880        } else {
3881            ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->server);
3882            if (track->isStopping_1()) {
3883                // Hardware buffer can hold a large amount of audio so we must
3884                // wait for all current track's data to drain before we say
3885                // that the track is stopped.
3886                if (mBytesRemaining == 0) {
3887                    // Only start draining when all data in mixbuffer
3888                    // has been written
3889                    ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
3890                    track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
3891                    sleepTime = 0;
3892                    standbyTime = systemTime() + standbyDelay;
3893                    if (last) {
3894                        mixerStatus = MIXER_DRAIN_TRACK;
3895                        if (mHwPaused) {
3896                            // It is possible to move from PAUSED to STOPPING_1 without
3897                            // a resume so we must ensure hardware is running
3898                            mOutput->stream->resume(mOutput->stream);
3899                            mHwPaused = false;
3900                        }
3901                    }
3902                }
3903            } else if (track->isStopping_2()) {
3904                // Drain has completed, signal presentation complete
3905                if (!mDraining || !last) {
3906                    track->mState = TrackBase::STOPPED;
3907                    size_t audioHALFrames =
3908                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3909                    size_t framesWritten =
3910                            mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3911                    track->presentationComplete(framesWritten, audioHALFrames);
3912                    track->reset();
3913                    tracksToRemove->add(track);
3914                }
3915            } else {
3916                // No buffers for this track. Give it a few chances to
3917                // fill a buffer, then remove it from active list.
3918                if (--(track->mRetryCount) <= 0) {
3919                    ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
3920                          track->name());
3921                    tracksToRemove->add(track);
3922                } else if (last){
3923                    mixerStatus = MIXER_TRACKS_ENABLED;
3924                }
3925            }
3926        }
3927        // compute volume for this track
3928        processVolume_l(track, last);
3929    }
3930    // remove all the tracks that need to be...
3931    removeTracks_l(*tracksToRemove);
3932
3933    return mixerStatus;
3934}
3935
3936void AudioFlinger::OffloadThread::flushOutput_l()
3937{
3938    mFlushPending = true;
3939}
3940
3941// must be called with thread mutex locked
3942bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
3943{
3944    ALOGV("waitingAsyncCallback_l mWriteBlocked %d mDraining %d", mWriteBlocked, mDraining);
3945    if (mUseAsyncWrite && (mWriteBlocked || mDraining)) {
3946        return true;
3947    }
3948    return false;
3949}
3950
3951// must be called with thread mutex locked
3952bool AudioFlinger::OffloadThread::shouldStandby_l()
3953{
3954    bool TrackPaused = false;
3955
3956    // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
3957    // after a timeout and we will enter standby then.
3958    if (mTracks.size() > 0) {
3959        TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
3960    }
3961
3962    return !mStandby && !TrackPaused;
3963}
3964
3965
3966bool AudioFlinger::OffloadThread::waitingAsyncCallback()
3967{
3968    Mutex::Autolock _l(mLock);
3969    return waitingAsyncCallback_l();
3970}
3971
3972void AudioFlinger::OffloadThread::flushHw_l()
3973{
3974    mOutput->stream->flush(mOutput->stream);
3975    // Flush anything still waiting in the mixbuffer
3976    mCurrentWriteLength = 0;
3977    mBytesRemaining = 0;
3978    mPausedWriteLength = 0;
3979    mPausedBytesRemaining = 0;
3980    if (mUseAsyncWrite) {
3981        mWriteBlocked = false;
3982        mDraining = false;
3983        ALOG_ASSERT(mCallbackThread != 0);
3984        mCallbackThread->setWriteBlocked(false);
3985        mCallbackThread->setDraining(false);
3986    }
3987}
3988
3989// ----------------------------------------------------------------------------
3990
3991AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3992        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3993    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
3994                DUPLICATING),
3995        mWaitTimeMs(UINT_MAX)
3996{
3997    addOutputTrack(mainThread);
3998}
3999
4000AudioFlinger::DuplicatingThread::~DuplicatingThread()
4001{
4002    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4003        mOutputTracks[i]->destroy();
4004    }
4005}
4006
4007void AudioFlinger::DuplicatingThread::threadLoop_mix()
4008{
4009    // mix buffers...
4010    if (outputsReady(outputTracks)) {
4011        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4012    } else {
4013        memset(mMixBuffer, 0, mixBufferSize);
4014    }
4015    sleepTime = 0;
4016    writeFrames = mNormalFrameCount;
4017    mCurrentWriteLength = mixBufferSize;
4018    standbyTime = systemTime() + standbyDelay;
4019}
4020
4021void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4022{
4023    if (sleepTime == 0) {
4024        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4025            sleepTime = activeSleepTime;
4026        } else {
4027            sleepTime = idleSleepTime;
4028        }
4029    } else if (mBytesWritten != 0) {
4030        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4031            writeFrames = mNormalFrameCount;
4032            memset(mMixBuffer, 0, mixBufferSize);
4033        } else {
4034            // flush remaining overflow buffers in output tracks
4035            writeFrames = 0;
4036        }
4037        sleepTime = 0;
4038    }
4039}
4040
4041ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
4042{
4043    for (size_t i = 0; i < outputTracks.size(); i++) {
4044        outputTracks[i]->write(mMixBuffer, writeFrames);
4045    }
4046    return (ssize_t)mixBufferSize;
4047}
4048
4049void AudioFlinger::DuplicatingThread::threadLoop_standby()
4050{
4051    // DuplicatingThread implements standby by stopping all tracks
4052    for (size_t i = 0; i < outputTracks.size(); i++) {
4053        outputTracks[i]->stop();
4054    }
4055}
4056
4057void AudioFlinger::DuplicatingThread::saveOutputTracks()
4058{
4059    outputTracks = mOutputTracks;
4060}
4061
4062void AudioFlinger::DuplicatingThread::clearOutputTracks()
4063{
4064    outputTracks.clear();
4065}
4066
4067void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4068{
4069    Mutex::Autolock _l(mLock);
4070    // FIXME explain this formula
4071    size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4072    OutputTrack *outputTrack = new OutputTrack(thread,
4073                                            this,
4074                                            mSampleRate,
4075                                            mFormat,
4076                                            mChannelMask,
4077                                            frameCount);
4078    if (outputTrack->cblk() != NULL) {
4079        thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4080        mOutputTracks.add(outputTrack);
4081        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4082        updateWaitTime_l();
4083    }
4084}
4085
4086void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4087{
4088    Mutex::Autolock _l(mLock);
4089    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4090        if (mOutputTracks[i]->thread() == thread) {
4091            mOutputTracks[i]->destroy();
4092            mOutputTracks.removeAt(i);
4093            updateWaitTime_l();
4094            return;
4095        }
4096    }
4097    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4098}
4099
4100// caller must hold mLock
4101void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4102{
4103    mWaitTimeMs = UINT_MAX;
4104    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4105        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4106        if (strong != 0) {
4107            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4108            if (waitTimeMs < mWaitTimeMs) {
4109                mWaitTimeMs = waitTimeMs;
4110            }
4111        }
4112    }
4113}
4114
4115
4116bool AudioFlinger::DuplicatingThread::outputsReady(
4117        const SortedVector< sp<OutputTrack> > &outputTracks)
4118{
4119    for (size_t i = 0; i < outputTracks.size(); i++) {
4120        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4121        if (thread == 0) {
4122            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4123                    outputTracks[i].get());
4124            return false;
4125        }
4126        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4127        // see note at standby() declaration
4128        if (playbackThread->standby() && !playbackThread->isSuspended()) {
4129            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4130                    thread.get());
4131            return false;
4132        }
4133    }
4134    return true;
4135}
4136
4137uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4138{
4139    return (mWaitTimeMs * 1000) / 2;
4140}
4141
4142void AudioFlinger::DuplicatingThread::cacheParameters_l()
4143{
4144    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4145    updateWaitTime_l();
4146
4147    MixerThread::cacheParameters_l();
4148}
4149
4150// ----------------------------------------------------------------------------
4151//      Record
4152// ----------------------------------------------------------------------------
4153
4154AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4155                                         AudioStreamIn *input,
4156                                         uint32_t sampleRate,
4157                                         audio_channel_mask_t channelMask,
4158                                         audio_io_handle_t id,
4159                                         audio_devices_t outDevice,
4160                                         audio_devices_t inDevice
4161#ifdef TEE_SINK
4162                                         , const sp<NBAIO_Sink>& teeSink
4163#endif
4164                                         ) :
4165    ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
4166    mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4167    // mRsmpInIndex and mInputBytes set by readInputParameters()
4168    mReqChannelCount(popcount(channelMask)),
4169    mReqSampleRate(sampleRate)
4170    // mBytesRead is only meaningful while active, and so is cleared in start()
4171    // (but might be better to also clear here for dump?)
4172#ifdef TEE_SINK
4173    , mTeeSink(teeSink)
4174#endif
4175{
4176    snprintf(mName, kNameLength, "AudioIn_%X", id);
4177
4178    readInputParameters();
4179
4180}
4181
4182
4183AudioFlinger::RecordThread::~RecordThread()
4184{
4185    delete[] mRsmpInBuffer;
4186    delete mResampler;
4187    delete[] mRsmpOutBuffer;
4188}
4189
4190void AudioFlinger::RecordThread::onFirstRef()
4191{
4192    run(mName, PRIORITY_URGENT_AUDIO);
4193}
4194
4195status_t AudioFlinger::RecordThread::readyToRun()
4196{
4197    status_t status = initCheck();
4198    ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4199    return status;
4200}
4201
4202bool AudioFlinger::RecordThread::threadLoop()
4203{
4204    AudioBufferProvider::Buffer buffer;
4205    sp<RecordTrack> activeTrack;
4206    Vector< sp<EffectChain> > effectChains;
4207
4208    nsecs_t lastWarning = 0;
4209
4210    inputStandBy();
4211    acquireWakeLock();
4212
4213    // used to verify we've read at least once before evaluating how many bytes were read
4214    bool readOnce = false;
4215
4216    // start recording
4217    while (!exitPending()) {
4218
4219        processConfigEvents();
4220
4221        { // scope for mLock
4222            Mutex::Autolock _l(mLock);
4223            checkForNewParameters_l();
4224            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4225                standby();
4226
4227                if (exitPending()) {
4228                    break;
4229                }
4230
4231                releaseWakeLock_l();
4232                ALOGV("RecordThread: loop stopping");
4233                // go to sleep
4234                mWaitWorkCV.wait(mLock);
4235                ALOGV("RecordThread: loop starting");
4236                acquireWakeLock_l();
4237                continue;
4238            }
4239            if (mActiveTrack != 0) {
4240                if (mActiveTrack->isTerminated()) {
4241                    removeTrack_l(mActiveTrack);
4242                    mActiveTrack.clear();
4243                } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4244                    standby();
4245                    mActiveTrack.clear();
4246                    mStartStopCond.broadcast();
4247                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4248                    if (mReqChannelCount != mActiveTrack->channelCount()) {
4249                        mActiveTrack.clear();
4250                        mStartStopCond.broadcast();
4251                    } else if (readOnce) {
4252                        // record start succeeds only if first read from audio input
4253                        // succeeds
4254                        if (mBytesRead >= 0) {
4255                            mActiveTrack->mState = TrackBase::ACTIVE;
4256                        } else {
4257                            mActiveTrack.clear();
4258                        }
4259                        mStartStopCond.broadcast();
4260                    }
4261                    mStandby = false;
4262                }
4263            }
4264            lockEffectChains_l(effectChains);
4265        }
4266
4267        if (mActiveTrack != 0) {
4268            if (mActiveTrack->mState != TrackBase::ACTIVE &&
4269                mActiveTrack->mState != TrackBase::RESUMING) {
4270                unlockEffectChains(effectChains);
4271                usleep(kRecordThreadSleepUs);
4272                continue;
4273            }
4274            for (size_t i = 0; i < effectChains.size(); i ++) {
4275                effectChains[i]->process_l();
4276            }
4277
4278            buffer.frameCount = mFrameCount;
4279            status_t status = mActiveTrack->getNextBuffer(&buffer);
4280            if (CC_LIKELY(status == NO_ERROR)) {
4281                readOnce = true;
4282                size_t framesOut = buffer.frameCount;
4283                if (mResampler == NULL) {
4284                    // no resampling
4285                    while (framesOut) {
4286                        size_t framesIn = mFrameCount - mRsmpInIndex;
4287                        if (framesIn) {
4288                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4289                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4290                                    mActiveTrack->mFrameSize;
4291                            if (framesIn > framesOut)
4292                                framesIn = framesOut;
4293                            mRsmpInIndex += framesIn;
4294                            framesOut -= framesIn;
4295                            if (mChannelCount == mReqChannelCount ||
4296                                mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4297                                memcpy(dst, src, framesIn * mFrameSize);
4298                            } else {
4299                                if (mChannelCount == 1) {
4300                                    upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4301                                            (int16_t *)src, framesIn);
4302                                } else {
4303                                    downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4304                                            (int16_t *)src, framesIn);
4305                                }
4306                            }
4307                        }
4308                        if (framesOut && mFrameCount == mRsmpInIndex) {
4309                            void *readInto;
4310                            if (framesOut == mFrameCount &&
4311                                (mChannelCount == mReqChannelCount ||
4312                                        mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
4313                                readInto = buffer.raw;
4314                                framesOut = 0;
4315                            } else {
4316                                readInto = mRsmpInBuffer;
4317                                mRsmpInIndex = 0;
4318                            }
4319                            mBytesRead = mInput->stream->read(mInput->stream, readInto,
4320                                    mInputBytes);
4321                            if (mBytesRead <= 0) {
4322                                if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4323                                {
4324                                    ALOGE("Error reading audio input");
4325                                    // Force input into standby so that it tries to
4326                                    // recover at next read attempt
4327                                    inputStandBy();
4328                                    usleep(kRecordThreadSleepUs);
4329                                }
4330                                mRsmpInIndex = mFrameCount;
4331                                framesOut = 0;
4332                                buffer.frameCount = 0;
4333                            }
4334#ifdef TEE_SINK
4335                            else if (mTeeSink != 0) {
4336                                (void) mTeeSink->write(readInto,
4337                                        mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4338                            }
4339#endif
4340                        }
4341                    }
4342                } else {
4343                    // resampling
4344
4345                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4346                    // alter output frame count as if we were expecting stereo samples
4347                    if (mChannelCount == 1 && mReqChannelCount == 1) {
4348                        framesOut >>= 1;
4349                    }
4350                    mResampler->resample(mRsmpOutBuffer, framesOut,
4351                            this /* AudioBufferProvider* */);
4352                    // ditherAndClamp() works as long as all buffers returned by
4353                    // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4354                    if (mChannelCount == 2 && mReqChannelCount == 1) {
4355                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4356                        // the resampler always outputs stereo samples:
4357                        // do post stereo to mono conversion
4358                        downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4359                                framesOut);
4360                    } else {
4361                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4362                    }
4363
4364                }
4365                if (mFramestoDrop == 0) {
4366                    mActiveTrack->releaseBuffer(&buffer);
4367                } else {
4368                    if (mFramestoDrop > 0) {
4369                        mFramestoDrop -= buffer.frameCount;
4370                        if (mFramestoDrop <= 0) {
4371                            clearSyncStartEvent();
4372                        }
4373                    } else {
4374                        mFramestoDrop += buffer.frameCount;
4375                        if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4376                                mSyncStartEvent->isCancelled()) {
4377                            ALOGW("Synced record %s, session %d, trigger session %d",
4378                                  (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4379                                  mActiveTrack->sessionId(),
4380                                  (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4381                            clearSyncStartEvent();
4382                        }
4383                    }
4384                }
4385                mActiveTrack->clearOverflow();
4386            }
4387            // client isn't retrieving buffers fast enough
4388            else {
4389                if (!mActiveTrack->setOverflow()) {
4390                    nsecs_t now = systemTime();
4391                    if ((now - lastWarning) > kWarningThrottleNs) {
4392                        ALOGW("RecordThread: buffer overflow");
4393                        lastWarning = now;
4394                    }
4395                }
4396                // Release the processor for a while before asking for a new buffer.
4397                // This will give the application more chance to read from the buffer and
4398                // clear the overflow.
4399                usleep(kRecordThreadSleepUs);
4400            }
4401        }
4402        // enable changes in effect chain
4403        unlockEffectChains(effectChains);
4404        effectChains.clear();
4405    }
4406
4407    standby();
4408
4409    {
4410        Mutex::Autolock _l(mLock);
4411        mActiveTrack.clear();
4412        mStartStopCond.broadcast();
4413    }
4414
4415    releaseWakeLock();
4416
4417    ALOGV("RecordThread %p exiting", this);
4418    return false;
4419}
4420
4421void AudioFlinger::RecordThread::standby()
4422{
4423    if (!mStandby) {
4424        inputStandBy();
4425        mStandby = true;
4426    }
4427}
4428
4429void AudioFlinger::RecordThread::inputStandBy()
4430{
4431    mInput->stream->common.standby(&mInput->stream->common);
4432}
4433
4434sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
4435        const sp<AudioFlinger::Client>& client,
4436        uint32_t sampleRate,
4437        audio_format_t format,
4438        audio_channel_mask_t channelMask,
4439        size_t frameCount,
4440        int sessionId,
4441        IAudioFlinger::track_flags_t flags,
4442        pid_t tid,
4443        status_t *status)
4444{
4445    sp<RecordTrack> track;
4446    status_t lStatus;
4447
4448    lStatus = initCheck();
4449    if (lStatus != NO_ERROR) {
4450        ALOGE("Audio driver not initialized.");
4451        goto Exit;
4452    }
4453
4454    // FIXME use flags and tid similar to createTrack_l()
4455
4456    { // scope for mLock
4457        Mutex::Autolock _l(mLock);
4458
4459        track = new RecordTrack(this, client, sampleRate,
4460                      format, channelMask, frameCount, sessionId);
4461
4462        if (track->getCblk() == 0) {
4463            lStatus = NO_MEMORY;
4464            goto Exit;
4465        }
4466        mTracks.add(track);
4467
4468        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4469        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4470                        mAudioFlinger->btNrecIsOff();
4471        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4472        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
4473    }
4474    lStatus = NO_ERROR;
4475
4476Exit:
4477    if (status) {
4478        *status = lStatus;
4479    }
4480    return track;
4481}
4482
4483status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4484                                           AudioSystem::sync_event_t event,
4485                                           int triggerSession)
4486{
4487    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4488    sp<ThreadBase> strongMe = this;
4489    status_t status = NO_ERROR;
4490
4491    if (event == AudioSystem::SYNC_EVENT_NONE) {
4492        clearSyncStartEvent();
4493    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4494        mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4495                                       triggerSession,
4496                                       recordTrack->sessionId(),
4497                                       syncStartEventCallback,
4498                                       this);
4499        // Sync event can be cancelled by the trigger session if the track is not in a
4500        // compatible state in which case we start record immediately
4501        if (mSyncStartEvent->isCancelled()) {
4502            clearSyncStartEvent();
4503        } else {
4504            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4505            mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4506        }
4507    }
4508
4509    {
4510        AutoMutex lock(mLock);
4511        if (mActiveTrack != 0) {
4512            if (recordTrack != mActiveTrack.get()) {
4513                status = -EBUSY;
4514            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4515                mActiveTrack->mState = TrackBase::ACTIVE;
4516            }
4517            return status;
4518        }
4519
4520        recordTrack->mState = TrackBase::IDLE;
4521        mActiveTrack = recordTrack;
4522        mLock.unlock();
4523        status_t status = AudioSystem::startInput(mId);
4524        mLock.lock();
4525        if (status != NO_ERROR) {
4526            mActiveTrack.clear();
4527            clearSyncStartEvent();
4528            return status;
4529        }
4530        mRsmpInIndex = mFrameCount;
4531        mBytesRead = 0;
4532        if (mResampler != NULL) {
4533            mResampler->reset();
4534        }
4535        mActiveTrack->mState = TrackBase::RESUMING;
4536        // signal thread to start
4537        ALOGV("Signal record thread");
4538        mWaitWorkCV.broadcast();
4539        // do not wait for mStartStopCond if exiting
4540        if (exitPending()) {
4541            mActiveTrack.clear();
4542            status = INVALID_OPERATION;
4543            goto startError;
4544        }
4545        mStartStopCond.wait(mLock);
4546        if (mActiveTrack == 0) {
4547            ALOGV("Record failed to start");
4548            status = BAD_VALUE;
4549            goto startError;
4550        }
4551        ALOGV("Record started OK");
4552        return status;
4553    }
4554
4555startError:
4556    AudioSystem::stopInput(mId);
4557    clearSyncStartEvent();
4558    return status;
4559}
4560
4561void AudioFlinger::RecordThread::clearSyncStartEvent()
4562{
4563    if (mSyncStartEvent != 0) {
4564        mSyncStartEvent->cancel();
4565    }
4566    mSyncStartEvent.clear();
4567    mFramestoDrop = 0;
4568}
4569
4570void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4571{
4572    sp<SyncEvent> strongEvent = event.promote();
4573
4574    if (strongEvent != 0) {
4575        RecordThread *me = (RecordThread *)strongEvent->cookie();
4576        me->handleSyncStartEvent(strongEvent);
4577    }
4578}
4579
4580void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4581{
4582    if (event == mSyncStartEvent) {
4583        // TODO: use actual buffer filling status instead of 2 buffers when info is available
4584        // from audio HAL
4585        mFramestoDrop = mFrameCount * 2;
4586    }
4587}
4588
4589bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4590    ALOGV("RecordThread::stop");
4591    AutoMutex _l(mLock);
4592    if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4593        return false;
4594    }
4595    recordTrack->mState = TrackBase::PAUSING;
4596    // do not wait for mStartStopCond if exiting
4597    if (exitPending()) {
4598        return true;
4599    }
4600    mStartStopCond.wait(mLock);
4601    // if we have been restarted, recordTrack == mActiveTrack.get() here
4602    if (exitPending() || recordTrack != mActiveTrack.get()) {
4603        ALOGV("Record stopped OK");
4604        return true;
4605    }
4606    return false;
4607}
4608
4609bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4610{
4611    return false;
4612}
4613
4614status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4615{
4616#if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
4617    if (!isValidSyncEvent(event)) {
4618        return BAD_VALUE;
4619    }
4620
4621    int eventSession = event->triggerSession();
4622    status_t ret = NAME_NOT_FOUND;
4623
4624    Mutex::Autolock _l(mLock);
4625
4626    for (size_t i = 0; i < mTracks.size(); i++) {
4627        sp<RecordTrack> track = mTracks[i];
4628        if (eventSession == track->sessionId()) {
4629            (void) track->setSyncEvent(event);
4630            ret = NO_ERROR;
4631        }
4632    }
4633    return ret;
4634#else
4635    return BAD_VALUE;
4636#endif
4637}
4638
4639// destroyTrack_l() must be called with ThreadBase::mLock held
4640void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4641{
4642    track->terminate();
4643    track->mState = TrackBase::STOPPED;
4644    // active tracks are removed by threadLoop()
4645    if (mActiveTrack != track) {
4646        removeTrack_l(track);
4647    }
4648}
4649
4650void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4651{
4652    mTracks.remove(track);
4653    // need anything related to effects here?
4654}
4655
4656void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4657{
4658    dumpInternals(fd, args);
4659    dumpTracks(fd, args);
4660    dumpEffectChains(fd, args);
4661}
4662
4663void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4664{
4665    const size_t SIZE = 256;
4666    char buffer[SIZE];
4667    String8 result;
4668
4669    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4670    result.append(buffer);
4671
4672    if (mActiveTrack != 0) {
4673        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4674        result.append(buffer);
4675        snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4676        result.append(buffer);
4677        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4678        result.append(buffer);
4679        snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4680        result.append(buffer);
4681        snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4682        result.append(buffer);
4683    } else {
4684        result.append("No active record client\n");
4685    }
4686
4687    write(fd, result.string(), result.size());
4688
4689    dumpBase(fd, args);
4690}
4691
4692void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4693{
4694    const size_t SIZE = 256;
4695    char buffer[SIZE];
4696    String8 result;
4697
4698    snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4699    result.append(buffer);
4700    RecordTrack::appendDumpHeader(result);
4701    for (size_t i = 0; i < mTracks.size(); ++i) {
4702        sp<RecordTrack> track = mTracks[i];
4703        if (track != 0) {
4704            track->dump(buffer, SIZE);
4705            result.append(buffer);
4706        }
4707    }
4708
4709    if (mActiveTrack != 0) {
4710        snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4711        result.append(buffer);
4712        RecordTrack::appendDumpHeader(result);
4713        mActiveTrack->dump(buffer, SIZE);
4714        result.append(buffer);
4715
4716    }
4717    write(fd, result.string(), result.size());
4718}
4719
4720// AudioBufferProvider interface
4721status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4722{
4723    size_t framesReq = buffer->frameCount;
4724    size_t framesReady = mFrameCount - mRsmpInIndex;
4725    int channelCount;
4726
4727    if (framesReady == 0) {
4728        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
4729        if (mBytesRead <= 0) {
4730            if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4731                ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4732                // Force input into standby so that it tries to
4733                // recover at next read attempt
4734                inputStandBy();
4735                usleep(kRecordThreadSleepUs);
4736            }
4737            buffer->raw = NULL;
4738            buffer->frameCount = 0;
4739            return NOT_ENOUGH_DATA;
4740        }
4741        mRsmpInIndex = 0;
4742        framesReady = mFrameCount;
4743    }
4744
4745    if (framesReq > framesReady) {
4746        framesReq = framesReady;
4747    }
4748
4749    if (mChannelCount == 1 && mReqChannelCount == 2) {
4750        channelCount = 1;
4751    } else {
4752        channelCount = 2;
4753    }
4754    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4755    buffer->frameCount = framesReq;
4756    return NO_ERROR;
4757}
4758
4759// AudioBufferProvider interface
4760void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4761{
4762    mRsmpInIndex += buffer->frameCount;
4763    buffer->frameCount = 0;
4764}
4765
4766bool AudioFlinger::RecordThread::checkForNewParameters_l()
4767{
4768    bool reconfig = false;
4769
4770    while (!mNewParameters.isEmpty()) {
4771        status_t status = NO_ERROR;
4772        String8 keyValuePair = mNewParameters[0];
4773        AudioParameter param = AudioParameter(keyValuePair);
4774        int value;
4775        audio_format_t reqFormat = mFormat;
4776        uint32_t reqSamplingRate = mReqSampleRate;
4777        uint32_t reqChannelCount = mReqChannelCount;
4778
4779        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4780            reqSamplingRate = value;
4781            reconfig = true;
4782        }
4783        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4784            reqFormat = (audio_format_t) value;
4785            reconfig = true;
4786        }
4787        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4788            reqChannelCount = popcount(value);
4789            reconfig = true;
4790        }
4791        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4792            // do not accept frame count changes if tracks are open as the track buffer
4793            // size depends on frame count and correct behavior would not be guaranteed
4794            // if frame count is changed after track creation
4795            if (mActiveTrack != 0) {
4796                status = INVALID_OPERATION;
4797            } else {
4798                reconfig = true;
4799            }
4800        }
4801        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4802            // forward device change to effects that have requested to be
4803            // aware of attached audio device.
4804            for (size_t i = 0; i < mEffectChains.size(); i++) {
4805                mEffectChains[i]->setDevice_l(value);
4806            }
4807
4808            // store input device and output device but do not forward output device to audio HAL.
4809            // Note that status is ignored by the caller for output device
4810            // (see AudioFlinger::setParameters()
4811            if (audio_is_output_devices(value)) {
4812                mOutDevice = value;
4813                status = BAD_VALUE;
4814            } else {
4815                mInDevice = value;
4816                // disable AEC and NS if the device is a BT SCO headset supporting those
4817                // pre processings
4818                if (mTracks.size() > 0) {
4819                    bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4820                                        mAudioFlinger->btNrecIsOff();
4821                    for (size_t i = 0; i < mTracks.size(); i++) {
4822                        sp<RecordTrack> track = mTracks[i];
4823                        setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
4824                        setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
4825                    }
4826                }
4827            }
4828        }
4829        if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
4830                mAudioSource != (audio_source_t)value) {
4831            // forward device change to effects that have requested to be
4832            // aware of attached audio device.
4833            for (size_t i = 0; i < mEffectChains.size(); i++) {
4834                mEffectChains[i]->setAudioSource_l((audio_source_t)value);
4835            }
4836            mAudioSource = (audio_source_t)value;
4837        }
4838        if (status == NO_ERROR) {
4839            status = mInput->stream->common.set_parameters(&mInput->stream->common,
4840                    keyValuePair.string());
4841            if (status == INVALID_OPERATION) {
4842                inputStandBy();
4843                status = mInput->stream->common.set_parameters(&mInput->stream->common,
4844                        keyValuePair.string());
4845            }
4846            if (reconfig) {
4847                if (status == BAD_VALUE &&
4848                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4849                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
4850                    (mInput->stream->common.get_sample_rate(&mInput->stream->common)
4851                            <= (2 * reqSamplingRate)) &&
4852                    popcount(mInput->stream->common.get_channels(&mInput->stream->common))
4853                            <= FCC_2 &&
4854                    (reqChannelCount <= FCC_2)) {
4855                    status = NO_ERROR;
4856                }
4857                if (status == NO_ERROR) {
4858                    readInputParameters();
4859                    sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4860                }
4861            }
4862        }
4863
4864        mNewParameters.removeAt(0);
4865
4866        mParamStatus = status;
4867        mParamCond.signal();
4868        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4869        // already timed out waiting for the status and will never signal the condition.
4870        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4871    }
4872    return reconfig;
4873}
4874
4875String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4876{
4877    char *s;
4878    String8 out_s8 = String8();
4879
4880    Mutex::Autolock _l(mLock);
4881    if (initCheck() != NO_ERROR) {
4882        return out_s8;
4883    }
4884
4885    s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
4886    out_s8 = String8(s);
4887    free(s);
4888    return out_s8;
4889}
4890
4891void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4892    AudioSystem::OutputDescriptor desc;
4893    void *param2 = NULL;
4894
4895    switch (event) {
4896    case AudioSystem::INPUT_OPENED:
4897    case AudioSystem::INPUT_CONFIG_CHANGED:
4898        desc.channels = mChannelMask;
4899        desc.samplingRate = mSampleRate;
4900        desc.format = mFormat;
4901        desc.frameCount = mFrameCount;
4902        desc.latency = 0;
4903        param2 = &desc;
4904        break;
4905
4906    case AudioSystem::INPUT_CLOSED:
4907    default:
4908        break;
4909    }
4910    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4911}
4912
4913void AudioFlinger::RecordThread::readInputParameters()
4914{
4915    delete mRsmpInBuffer;
4916    // mRsmpInBuffer is always assigned a new[] below
4917    delete mRsmpOutBuffer;
4918    mRsmpOutBuffer = NULL;
4919    delete mResampler;
4920    mResampler = NULL;
4921
4922    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
4923    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4924    mChannelCount = popcount(mChannelMask);
4925    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4926    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
4927    mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
4928    mFrameCount = mInputBytes / mFrameSize;
4929    mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
4930    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4931
4932    if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
4933    {
4934        int channelCount;
4935        // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4936        // stereo to mono post process as the resampler always outputs stereo.
4937        if (mChannelCount == 1 && mReqChannelCount == 2) {
4938            channelCount = 1;
4939        } else {
4940            channelCount = 2;
4941        }
4942        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4943        mResampler->setSampleRate(mSampleRate);
4944        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4945        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4946
4947        // optmization: if mono to mono, alter input frame count as if we were inputing
4948        // stereo samples
4949        if (mChannelCount == 1 && mReqChannelCount == 1) {
4950            mFrameCount >>= 1;
4951        }
4952
4953    }
4954    mRsmpInIndex = mFrameCount;
4955}
4956
4957unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4958{
4959    Mutex::Autolock _l(mLock);
4960    if (initCheck() != NO_ERROR) {
4961        return 0;
4962    }
4963
4964    return mInput->stream->get_input_frames_lost(mInput->stream);
4965}
4966
4967uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
4968{
4969    Mutex::Autolock _l(mLock);
4970    uint32_t result = 0;
4971    if (getEffectChain_l(sessionId) != 0) {
4972        result = EFFECT_SESSION;
4973    }
4974
4975    for (size_t i = 0; i < mTracks.size(); ++i) {
4976        if (sessionId == mTracks[i]->sessionId()) {
4977            result |= TRACK_SESSION;
4978            break;
4979        }
4980    }
4981
4982    return result;
4983}
4984
4985KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
4986{
4987    KeyedVector<int, bool> ids;
4988    Mutex::Autolock _l(mLock);
4989    for (size_t j = 0; j < mTracks.size(); ++j) {
4990        sp<RecordThread::RecordTrack> track = mTracks[j];
4991        int sessionId = track->sessionId();
4992        if (ids.indexOfKey(sessionId) < 0) {
4993            ids.add(sessionId, true);
4994        }
4995    }
4996    return ids;
4997}
4998
4999AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5000{
5001    Mutex::Autolock _l(mLock);
5002    AudioStreamIn *input = mInput;
5003    mInput = NULL;
5004    return input;
5005}
5006
5007// this method must always be called either with ThreadBase mLock held or inside the thread loop
5008audio_stream_t* AudioFlinger::RecordThread::stream() const
5009{
5010    if (mInput == NULL) {
5011        return NULL;
5012    }
5013    return &mInput->stream->common;
5014}
5015
5016status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5017{
5018    // only one chain per input thread
5019    if (mEffectChains.size() != 0) {
5020        return INVALID_OPERATION;
5021    }
5022    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5023
5024    chain->setInBuffer(NULL);
5025    chain->setOutBuffer(NULL);
5026
5027    checkSuspendOnAddEffectChain_l(chain);
5028
5029    mEffectChains.add(chain);
5030
5031    return NO_ERROR;
5032}
5033
5034size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5035{
5036    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5037    ALOGW_IF(mEffectChains.size() != 1,
5038            "removeEffectChain_l() %p invalid chain size %d on thread %p",
5039            chain.get(), mEffectChains.size(), this);
5040    if (mEffectChains.size() == 1) {
5041        mEffectChains.removeAt(0);
5042    }
5043    return 0;
5044}
5045
5046}; // namespace android
5047