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