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