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