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