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