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