Threads.cpp revision 77e1512aee8092069514973379a59a318e721be3
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    fdprintf(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    fdprintf(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        if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1328            lStatus = NO_MEMORY;
1329            // track must be cleared from the caller as the caller has the AF lock
1330            goto Exit;
1331        }
1332
1333        mTracks.add(track);
1334
1335        sp<EffectChain> chain = getEffectChain_l(sessionId);
1336        if (chain != 0) {
1337            ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1338            track->setMainBuffer(chain->inBuffer());
1339            chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1340            chain->incTrackCnt();
1341        }
1342
1343        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1344            pid_t callingPid = IPCThreadState::self()->getCallingPid();
1345            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1346            // so ask activity manager to do this on our behalf
1347            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1348        }
1349    }
1350
1351    lStatus = NO_ERROR;
1352
1353Exit:
1354    if (status) {
1355        *status = lStatus;
1356    }
1357    return track;
1358}
1359
1360uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1361{
1362    return latency;
1363}
1364
1365uint32_t AudioFlinger::PlaybackThread::latency() const
1366{
1367    Mutex::Autolock _l(mLock);
1368    return latency_l();
1369}
1370uint32_t AudioFlinger::PlaybackThread::latency_l() const
1371{
1372    if (initCheck() == NO_ERROR) {
1373        return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1374    } else {
1375        return 0;
1376    }
1377}
1378
1379void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1380{
1381    Mutex::Autolock _l(mLock);
1382    // Don't apply master volume in SW if our HAL can do it for us.
1383    if (mOutput && mOutput->audioHwDev &&
1384        mOutput->audioHwDev->canSetMasterVolume()) {
1385        mMasterVolume = 1.0;
1386    } else {
1387        mMasterVolume = value;
1388    }
1389}
1390
1391void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1392{
1393    Mutex::Autolock _l(mLock);
1394    // Don't apply master mute in SW if our HAL can do it for us.
1395    if (mOutput && mOutput->audioHwDev &&
1396        mOutput->audioHwDev->canSetMasterMute()) {
1397        mMasterMute = false;
1398    } else {
1399        mMasterMute = muted;
1400    }
1401}
1402
1403void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1404{
1405    Mutex::Autolock _l(mLock);
1406    mStreamTypes[stream].volume = value;
1407    broadcast_l();
1408}
1409
1410void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1411{
1412    Mutex::Autolock _l(mLock);
1413    mStreamTypes[stream].mute = muted;
1414    broadcast_l();
1415}
1416
1417float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1418{
1419    Mutex::Autolock _l(mLock);
1420    return mStreamTypes[stream].volume;
1421}
1422
1423// addTrack_l() must be called with ThreadBase::mLock held
1424status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1425{
1426    status_t status = ALREADY_EXISTS;
1427
1428    // set retry count for buffer fill
1429    track->mRetryCount = kMaxTrackStartupRetries;
1430    if (mActiveTracks.indexOf(track) < 0) {
1431        // the track is newly added, make sure it fills up all its
1432        // buffers before playing. This is to ensure the client will
1433        // effectively get the latency it requested.
1434        if (!track->isOutputTrack()) {
1435            TrackBase::track_state state = track->mState;
1436            mLock.unlock();
1437            status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1438            mLock.lock();
1439            // abort track was stopped/paused while we released the lock
1440            if (state != track->mState) {
1441                if (status == NO_ERROR) {
1442                    mLock.unlock();
1443                    AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1444                    mLock.lock();
1445                }
1446                return INVALID_OPERATION;
1447            }
1448            // abort if start is rejected by audio policy manager
1449            if (status != NO_ERROR) {
1450                return PERMISSION_DENIED;
1451            }
1452#ifdef ADD_BATTERY_DATA
1453            // to track the speaker usage
1454            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1455#endif
1456        }
1457
1458        track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
1459        track->mResetDone = false;
1460        track->mPresentationCompleteFrames = 0;
1461        mActiveTracks.add(track);
1462        mWakeLockUids.add(track->uid());
1463        mActiveTracksGeneration++;
1464        mLatestActiveTrack = track;
1465        sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1466        if (chain != 0) {
1467            ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1468                    track->sessionId());
1469            chain->incActiveTrackCnt();
1470        }
1471
1472        status = NO_ERROR;
1473    }
1474
1475    ALOGV("signal playback thread");
1476    broadcast_l();
1477
1478    return status;
1479}
1480
1481bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1482{
1483    track->terminate();
1484    // active tracks are removed by threadLoop()
1485    bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1486    track->mState = TrackBase::STOPPED;
1487    if (!trackActive) {
1488        removeTrack_l(track);
1489    } else if (track->isFastTrack() || track->isOffloaded()) {
1490        track->mState = TrackBase::STOPPING_1;
1491    }
1492
1493    return trackActive;
1494}
1495
1496void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1497{
1498    track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1499    mTracks.remove(track);
1500    deleteTrackName_l(track->name());
1501    // redundant as track is about to be destroyed, for dumpsys only
1502    track->mName = -1;
1503    if (track->isFastTrack()) {
1504        int index = track->mFastIndex;
1505        ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1506        ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1507        mFastTrackAvailMask |= 1 << index;
1508        // redundant as track is about to be destroyed, for dumpsys only
1509        track->mFastIndex = -1;
1510    }
1511    sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1512    if (chain != 0) {
1513        chain->decTrackCnt();
1514    }
1515}
1516
1517void AudioFlinger::PlaybackThread::broadcast_l()
1518{
1519    // Thread could be blocked waiting for async
1520    // so signal it to handle state changes immediately
1521    // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1522    // be lost so we also flag to prevent it blocking on mWaitWorkCV
1523    mSignalPending = true;
1524    mWaitWorkCV.broadcast();
1525}
1526
1527String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1528{
1529    Mutex::Autolock _l(mLock);
1530    if (initCheck() != NO_ERROR) {
1531        return String8();
1532    }
1533
1534    char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1535    const String8 out_s8(s);
1536    free(s);
1537    return out_s8;
1538}
1539
1540// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1541void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1542    AudioSystem::OutputDescriptor desc;
1543    void *param2 = NULL;
1544
1545    ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1546            param);
1547
1548    switch (event) {
1549    case AudioSystem::OUTPUT_OPENED:
1550    case AudioSystem::OUTPUT_CONFIG_CHANGED:
1551        desc.channelMask = mChannelMask;
1552        desc.samplingRate = mSampleRate;
1553        desc.format = mFormat;
1554        desc.frameCount = mNormalFrameCount; // FIXME see
1555                                             // AudioFlinger::frameCount(audio_io_handle_t)
1556        desc.latency = latency();
1557        param2 = &desc;
1558        break;
1559
1560    case AudioSystem::STREAM_CONFIG_CHANGED:
1561        param2 = &param;
1562    case AudioSystem::OUTPUT_CLOSED:
1563    default:
1564        break;
1565    }
1566    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1567}
1568
1569void AudioFlinger::PlaybackThread::writeCallback()
1570{
1571    ALOG_ASSERT(mCallbackThread != 0);
1572    mCallbackThread->resetWriteBlocked();
1573}
1574
1575void AudioFlinger::PlaybackThread::drainCallback()
1576{
1577    ALOG_ASSERT(mCallbackThread != 0);
1578    mCallbackThread->resetDraining();
1579}
1580
1581void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
1582{
1583    Mutex::Autolock _l(mLock);
1584    // reject out of sequence requests
1585    if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1586        mWriteAckSequence &= ~1;
1587        mWaitWorkCV.signal();
1588    }
1589}
1590
1591void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
1592{
1593    Mutex::Autolock _l(mLock);
1594    // reject out of sequence requests
1595    if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1596        mDrainSequence &= ~1;
1597        mWaitWorkCV.signal();
1598    }
1599}
1600
1601// static
1602int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1603                                                void *param,
1604                                                void *cookie)
1605{
1606    AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1607    ALOGV("asyncCallback() event %d", event);
1608    switch (event) {
1609    case STREAM_CBK_EVENT_WRITE_READY:
1610        me->writeCallback();
1611        break;
1612    case STREAM_CBK_EVENT_DRAIN_READY:
1613        me->drainCallback();
1614        break;
1615    default:
1616        ALOGW("asyncCallback() unknown event %d", event);
1617        break;
1618    }
1619    return 0;
1620}
1621
1622void AudioFlinger::PlaybackThread::readOutputParameters()
1623{
1624    // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL
1625    mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1626    mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1627    if (!audio_is_output_channel(mChannelMask)) {
1628        LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1629    }
1630    if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1631        LOG_FATAL("HAL channel mask %#x not supported for mixed output; "
1632                "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1633    }
1634    mChannelCount = popcount(mChannelMask);
1635    mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1636    if (!audio_is_valid_format(mFormat)) {
1637        LOG_FATAL("HAL format %d not valid for output", mFormat);
1638    }
1639    if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1640        LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
1641                mFormat);
1642    }
1643    mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1644    mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1645    if (mFrameCount & 15) {
1646        ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1647                mFrameCount);
1648    }
1649
1650    if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1651            (mOutput->stream->set_callback != NULL)) {
1652        if (mOutput->stream->set_callback(mOutput->stream,
1653                                      AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1654            mUseAsyncWrite = true;
1655            mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
1656        }
1657    }
1658
1659    // Calculate size of normal mix buffer relative to the HAL output buffer size
1660    double multiplier = 1.0;
1661    if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1662            kUseFastMixer == FastMixer_Dynamic)) {
1663        size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1664        size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1665        // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1666        minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1667        maxNormalFrameCount = maxNormalFrameCount & ~15;
1668        if (maxNormalFrameCount < minNormalFrameCount) {
1669            maxNormalFrameCount = minNormalFrameCount;
1670        }
1671        multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1672        if (multiplier <= 1.0) {
1673            multiplier = 1.0;
1674        } else if (multiplier <= 2.0) {
1675            if (2 * mFrameCount <= maxNormalFrameCount) {
1676                multiplier = 2.0;
1677            } else {
1678                multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1679            }
1680        } else {
1681            // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1682            // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
1683            // track, but we sometimes have to do this to satisfy the maximum frame count
1684            // constraint)
1685            // FIXME this rounding up should not be done if no HAL SRC
1686            uint32_t truncMult = (uint32_t) multiplier;
1687            if ((truncMult & 1)) {
1688                if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1689                    ++truncMult;
1690                }
1691            }
1692            multiplier = (double) truncMult;
1693        }
1694    }
1695    mNormalFrameCount = multiplier * mFrameCount;
1696    // round up to nearest 16 frames to satisfy AudioMixer
1697    mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1698    ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
1699            mNormalFrameCount);
1700
1701    delete[] mAllocMixBuffer;
1702    size_t align = (mFrameSize < sizeof(int16_t)) ? sizeof(int16_t) : mFrameSize;
1703    mAllocMixBuffer = new int8_t[mNormalFrameCount * mFrameSize + align - 1];
1704    mMixBuffer = (int16_t *) ((((size_t)mAllocMixBuffer + align - 1) / align) * align);
1705    memset(mMixBuffer, 0, mNormalFrameCount * mFrameSize);
1706
1707    // force reconfiguration of effect chains and engines to take new buffer size and audio
1708    // parameters into account
1709    // Note that mLock is not held when readOutputParameters() is called from the constructor
1710    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1711    // matter.
1712    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1713    Vector< sp<EffectChain> > effectChains = mEffectChains;
1714    for (size_t i = 0; i < effectChains.size(); i ++) {
1715        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1716    }
1717}
1718
1719
1720status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1721{
1722    if (halFrames == NULL || dspFrames == NULL) {
1723        return BAD_VALUE;
1724    }
1725    Mutex::Autolock _l(mLock);
1726    if (initCheck() != NO_ERROR) {
1727        return INVALID_OPERATION;
1728    }
1729    size_t framesWritten = mBytesWritten / mFrameSize;
1730    *halFrames = framesWritten;
1731
1732    if (isSuspended()) {
1733        // return an estimation of rendered frames when the output is suspended
1734        size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1735        *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1736        return NO_ERROR;
1737    } else {
1738        status_t status;
1739        uint32_t frames;
1740        status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1741        *dspFrames = (size_t)frames;
1742        return status;
1743    }
1744}
1745
1746uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1747{
1748    Mutex::Autolock _l(mLock);
1749    uint32_t result = 0;
1750    if (getEffectChain_l(sessionId) != 0) {
1751        result = EFFECT_SESSION;
1752    }
1753
1754    for (size_t i = 0; i < mTracks.size(); ++i) {
1755        sp<Track> track = mTracks[i];
1756        if (sessionId == track->sessionId() && !track->isInvalid()) {
1757            result |= TRACK_SESSION;
1758            break;
1759        }
1760    }
1761
1762    return result;
1763}
1764
1765uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1766{
1767    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1768    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1769    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1770        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1771    }
1772    for (size_t i = 0; i < mTracks.size(); i++) {
1773        sp<Track> track = mTracks[i];
1774        if (sessionId == track->sessionId() && !track->isInvalid()) {
1775            return AudioSystem::getStrategyForStream(track->streamType());
1776        }
1777    }
1778    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1779}
1780
1781
1782AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1783{
1784    Mutex::Autolock _l(mLock);
1785    return mOutput;
1786}
1787
1788AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1789{
1790    Mutex::Autolock _l(mLock);
1791    AudioStreamOut *output = mOutput;
1792    mOutput = NULL;
1793    // FIXME FastMixer might also have a raw ptr to mOutputSink;
1794    //       must push a NULL and wait for ack
1795    mOutputSink.clear();
1796    mPipeSink.clear();
1797    mNormalSink.clear();
1798    return output;
1799}
1800
1801// this method must always be called either with ThreadBase mLock held or inside the thread loop
1802audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1803{
1804    if (mOutput == NULL) {
1805        return NULL;
1806    }
1807    return &mOutput->stream->common;
1808}
1809
1810uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1811{
1812    return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1813}
1814
1815status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1816{
1817    if (!isValidSyncEvent(event)) {
1818        return BAD_VALUE;
1819    }
1820
1821    Mutex::Autolock _l(mLock);
1822
1823    for (size_t i = 0; i < mTracks.size(); ++i) {
1824        sp<Track> track = mTracks[i];
1825        if (event->triggerSession() == track->sessionId()) {
1826            (void) track->setSyncEvent(event);
1827            return NO_ERROR;
1828        }
1829    }
1830
1831    return NAME_NOT_FOUND;
1832}
1833
1834bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1835{
1836    return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1837}
1838
1839void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1840        const Vector< sp<Track> >& tracksToRemove)
1841{
1842    size_t count = tracksToRemove.size();
1843    if (count) {
1844        for (size_t i = 0 ; i < count ; i++) {
1845            const sp<Track>& track = tracksToRemove.itemAt(i);
1846            if (!track->isOutputTrack()) {
1847                AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1848#ifdef ADD_BATTERY_DATA
1849                // to track the speaker usage
1850                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1851#endif
1852                if (track->isTerminated()) {
1853                    AudioSystem::releaseOutput(mId);
1854                }
1855            }
1856        }
1857    }
1858}
1859
1860void AudioFlinger::PlaybackThread::checkSilentMode_l()
1861{
1862    if (!mMasterMute) {
1863        char value[PROPERTY_VALUE_MAX];
1864        if (property_get("ro.audio.silent", value, "0") > 0) {
1865            char *endptr;
1866            unsigned long ul = strtoul(value, &endptr, 0);
1867            if (*endptr == '\0' && ul != 0) {
1868                ALOGD("Silence is golden");
1869                // The setprop command will not allow a property to be changed after
1870                // the first time it is set, so we don't have to worry about un-muting.
1871                setMasterMute_l(true);
1872            }
1873        }
1874    }
1875}
1876
1877// shared by MIXER and DIRECT, overridden by DUPLICATING
1878ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
1879{
1880    // FIXME rewrite to reduce number of system calls
1881    mLastWriteTime = systemTime();
1882    mInWrite = true;
1883    ssize_t bytesWritten;
1884
1885    // If an NBAIO sink is present, use it to write the normal mixer's submix
1886    if (mNormalSink != 0) {
1887#define mBitShift 2 // FIXME
1888        size_t count = mBytesRemaining >> mBitShift;
1889        size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1;
1890        ATRACE_BEGIN("write");
1891        // update the setpoint when AudioFlinger::mScreenState changes
1892        uint32_t screenState = AudioFlinger::mScreenState;
1893        if (screenState != mScreenState) {
1894            mScreenState = screenState;
1895            MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1896            if (pipe != NULL) {
1897                pipe->setAvgFrames((mScreenState & 1) ?
1898                        (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
1899            }
1900        }
1901        ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count);
1902        ATRACE_END();
1903        if (framesWritten > 0) {
1904            bytesWritten = framesWritten << mBitShift;
1905        } else {
1906            bytesWritten = framesWritten;
1907        }
1908        status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
1909        if (status == NO_ERROR) {
1910            size_t totalFramesWritten = mNormalSink->framesWritten();
1911            if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
1912                mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
1913                mLatchDValid = true;
1914            }
1915        }
1916    // otherwise use the HAL / AudioStreamOut directly
1917    } else {
1918        // Direct output and offload threads
1919        size_t offset = (mCurrentWriteLength - mBytesRemaining) / sizeof(int16_t);
1920        if (mUseAsyncWrite) {
1921            ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
1922            mWriteAckSequence += 2;
1923            mWriteAckSequence |= 1;
1924            ALOG_ASSERT(mCallbackThread != 0);
1925            mCallbackThread->setWriteBlocked(mWriteAckSequence);
1926        }
1927        // FIXME We should have an implementation of timestamps for direct output threads.
1928        // They are used e.g for multichannel PCM playback over HDMI.
1929        bytesWritten = mOutput->stream->write(mOutput->stream,
1930                                                   mMixBuffer + offset, mBytesRemaining);
1931        if (mUseAsyncWrite &&
1932                ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
1933            // do not wait for async callback in case of error of full write
1934            mWriteAckSequence &= ~1;
1935            ALOG_ASSERT(mCallbackThread != 0);
1936            mCallbackThread->setWriteBlocked(mWriteAckSequence);
1937        }
1938    }
1939
1940    mNumWrites++;
1941    mInWrite = false;
1942    mStandby = false;
1943    return bytesWritten;
1944}
1945
1946void AudioFlinger::PlaybackThread::threadLoop_drain()
1947{
1948    if (mOutput->stream->drain) {
1949        ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
1950        if (mUseAsyncWrite) {
1951            ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
1952            mDrainSequence |= 1;
1953            ALOG_ASSERT(mCallbackThread != 0);
1954            mCallbackThread->setDraining(mDrainSequence);
1955        }
1956        mOutput->stream->drain(mOutput->stream,
1957            (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
1958                                                : AUDIO_DRAIN_ALL);
1959    }
1960}
1961
1962void AudioFlinger::PlaybackThread::threadLoop_exit()
1963{
1964    // Default implementation has nothing to do
1965}
1966
1967/*
1968The derived values that are cached:
1969 - mixBufferSize from frame count * frame size
1970 - activeSleepTime from activeSleepTimeUs()
1971 - idleSleepTime from idleSleepTimeUs()
1972 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
1973 - maxPeriod from frame count and sample rate (MIXER only)
1974
1975The parameters that affect these derived values are:
1976 - frame count
1977 - frame size
1978 - sample rate
1979 - device type: A2DP or not
1980 - device latency
1981 - format: PCM or not
1982 - active sleep time
1983 - idle sleep time
1984*/
1985
1986void AudioFlinger::PlaybackThread::cacheParameters_l()
1987{
1988    mixBufferSize = mNormalFrameCount * mFrameSize;
1989    activeSleepTime = activeSleepTimeUs();
1990    idleSleepTime = idleSleepTimeUs();
1991}
1992
1993void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
1994{
1995    ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1996            this,  streamType, mTracks.size());
1997    Mutex::Autolock _l(mLock);
1998
1999    size_t size = mTracks.size();
2000    for (size_t i = 0; i < size; i++) {
2001        sp<Track> t = mTracks[i];
2002        if (t->streamType() == streamType) {
2003            t->invalidate();
2004        }
2005    }
2006}
2007
2008status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2009{
2010    int session = chain->sessionId();
2011    int16_t *buffer = mMixBuffer;
2012    bool ownsBuffer = false;
2013
2014    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2015    if (session > 0) {
2016        // Only one effect chain can be present in direct output thread and it uses
2017        // the mix buffer as input
2018        if (mType != DIRECT) {
2019            size_t numSamples = mNormalFrameCount * mChannelCount;
2020            buffer = new int16_t[numSamples];
2021            memset(buffer, 0, numSamples * sizeof(int16_t));
2022            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2023            ownsBuffer = true;
2024        }
2025
2026        // Attach all tracks with same session ID to this chain.
2027        for (size_t i = 0; i < mTracks.size(); ++i) {
2028            sp<Track> track = mTracks[i];
2029            if (session == track->sessionId()) {
2030                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2031                        buffer);
2032                track->setMainBuffer(buffer);
2033                chain->incTrackCnt();
2034            }
2035        }
2036
2037        // indicate all active tracks in the chain
2038        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2039            sp<Track> track = mActiveTracks[i].promote();
2040            if (track == 0) {
2041                continue;
2042            }
2043            if (session == track->sessionId()) {
2044                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2045                chain->incActiveTrackCnt();
2046            }
2047        }
2048    }
2049
2050    chain->setInBuffer(buffer, ownsBuffer);
2051    chain->setOutBuffer(mMixBuffer);
2052    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2053    // chains list in order to be processed last as it contains output stage effects
2054    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2055    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2056    // after track specific effects and before output stage
2057    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2058    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2059    // Effect chain for other sessions are inserted at beginning of effect
2060    // chains list to be processed before output mix effects. Relative order between other
2061    // sessions is not important
2062    size_t size = mEffectChains.size();
2063    size_t i = 0;
2064    for (i = 0; i < size; i++) {
2065        if (mEffectChains[i]->sessionId() < session) {
2066            break;
2067        }
2068    }
2069    mEffectChains.insertAt(chain, i);
2070    checkSuspendOnAddEffectChain_l(chain);
2071
2072    return NO_ERROR;
2073}
2074
2075size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2076{
2077    int session = chain->sessionId();
2078
2079    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2080
2081    for (size_t i = 0; i < mEffectChains.size(); i++) {
2082        if (chain == mEffectChains[i]) {
2083            mEffectChains.removeAt(i);
2084            // detach all active tracks from the chain
2085            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2086                sp<Track> track = mActiveTracks[i].promote();
2087                if (track == 0) {
2088                    continue;
2089                }
2090                if (session == track->sessionId()) {
2091                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2092                            chain.get(), session);
2093                    chain->decActiveTrackCnt();
2094                }
2095            }
2096
2097            // detach all tracks with same session ID from this chain
2098            for (size_t i = 0; i < mTracks.size(); ++i) {
2099                sp<Track> track = mTracks[i];
2100                if (session == track->sessionId()) {
2101                    track->setMainBuffer(mMixBuffer);
2102                    chain->decTrackCnt();
2103                }
2104            }
2105            break;
2106        }
2107    }
2108    return mEffectChains.size();
2109}
2110
2111status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2112        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2113{
2114    Mutex::Autolock _l(mLock);
2115    return attachAuxEffect_l(track, EffectId);
2116}
2117
2118status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2119        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2120{
2121    status_t status = NO_ERROR;
2122
2123    if (EffectId == 0) {
2124        track->setAuxBuffer(0, NULL);
2125    } else {
2126        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2127        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2128        if (effect != 0) {
2129            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2130                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2131            } else {
2132                status = INVALID_OPERATION;
2133            }
2134        } else {
2135            status = BAD_VALUE;
2136        }
2137    }
2138    return status;
2139}
2140
2141void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2142{
2143    for (size_t i = 0; i < mTracks.size(); ++i) {
2144        sp<Track> track = mTracks[i];
2145        if (track->auxEffectId() == effectId) {
2146            attachAuxEffect_l(track, 0);
2147        }
2148    }
2149}
2150
2151bool AudioFlinger::PlaybackThread::threadLoop()
2152{
2153    Vector< sp<Track> > tracksToRemove;
2154
2155    standbyTime = systemTime();
2156
2157    // MIXER
2158    nsecs_t lastWarning = 0;
2159
2160    // DUPLICATING
2161    // FIXME could this be made local to while loop?
2162    writeFrames = 0;
2163
2164    int lastGeneration = 0;
2165
2166    cacheParameters_l();
2167    sleepTime = idleSleepTime;
2168
2169    if (mType == MIXER) {
2170        sleepTimeShift = 0;
2171    }
2172
2173    CpuStats cpuStats;
2174    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2175
2176    acquireWakeLock();
2177
2178    // mNBLogWriter->log can only be called while thread mutex mLock is held.
2179    // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2180    // and then that string will be logged at the next convenient opportunity.
2181    const char *logString = NULL;
2182
2183    checkSilentMode_l();
2184
2185    while (!exitPending())
2186    {
2187        cpuStats.sample(myName);
2188
2189        Vector< sp<EffectChain> > effectChains;
2190
2191        processConfigEvents();
2192
2193        { // scope for mLock
2194
2195            Mutex::Autolock _l(mLock);
2196
2197            if (logString != NULL) {
2198                mNBLogWriter->logTimestamp();
2199                mNBLogWriter->log(logString);
2200                logString = NULL;
2201            }
2202
2203            if (mLatchDValid) {
2204                mLatchQ = mLatchD;
2205                mLatchDValid = false;
2206                mLatchQValid = true;
2207            }
2208
2209            if (checkForNewParameters_l()) {
2210                cacheParameters_l();
2211            }
2212
2213            saveOutputTracks();
2214            if (mSignalPending) {
2215                // A signal was raised while we were unlocked
2216                mSignalPending = false;
2217            } else if (waitingAsyncCallback_l()) {
2218                if (exitPending()) {
2219                    break;
2220                }
2221                releaseWakeLock_l();
2222                mWakeLockUids.clear();
2223                mActiveTracksGeneration++;
2224                ALOGV("wait async completion");
2225                mWaitWorkCV.wait(mLock);
2226                ALOGV("async completion/wake");
2227                acquireWakeLock_l();
2228                standbyTime = systemTime() + standbyDelay;
2229                sleepTime = 0;
2230
2231                continue;
2232            }
2233            if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
2234                                   isSuspended()) {
2235                // put audio hardware into standby after short delay
2236                if (shouldStandby_l()) {
2237
2238                    threadLoop_standby();
2239
2240                    mStandby = true;
2241                }
2242
2243                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2244                    // we're about to wait, flush the binder command buffer
2245                    IPCThreadState::self()->flushCommands();
2246
2247                    clearOutputTracks();
2248
2249                    if (exitPending()) {
2250                        break;
2251                    }
2252
2253                    releaseWakeLock_l();
2254                    mWakeLockUids.clear();
2255                    mActiveTracksGeneration++;
2256                    // wait until we have something to do...
2257                    ALOGV("%s going to sleep", myName.string());
2258                    mWaitWorkCV.wait(mLock);
2259                    ALOGV("%s waking up", myName.string());
2260                    acquireWakeLock_l();
2261
2262                    mMixerStatus = MIXER_IDLE;
2263                    mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2264                    mBytesWritten = 0;
2265                    mBytesRemaining = 0;
2266                    checkSilentMode_l();
2267
2268                    standbyTime = systemTime() + standbyDelay;
2269                    sleepTime = idleSleepTime;
2270                    if (mType == MIXER) {
2271                        sleepTimeShift = 0;
2272                    }
2273
2274                    continue;
2275                }
2276            }
2277            // mMixerStatusIgnoringFastTracks is also updated internally
2278            mMixerStatus = prepareTracks_l(&tracksToRemove);
2279
2280            // compare with previously applied list
2281            if (lastGeneration != mActiveTracksGeneration) {
2282                // update wakelock
2283                updateWakeLockUids_l(mWakeLockUids);
2284                lastGeneration = mActiveTracksGeneration;
2285            }
2286
2287            // prevent any changes in effect chain list and in each effect chain
2288            // during mixing and effect process as the audio buffers could be deleted
2289            // or modified if an effect is created or deleted
2290            lockEffectChains_l(effectChains);
2291        } // mLock scope ends
2292
2293        if (mBytesRemaining == 0) {
2294            mCurrentWriteLength = 0;
2295            if (mMixerStatus == MIXER_TRACKS_READY) {
2296                // threadLoop_mix() sets mCurrentWriteLength
2297                threadLoop_mix();
2298            } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2299                        && (mMixerStatus != MIXER_DRAIN_ALL)) {
2300                // threadLoop_sleepTime sets sleepTime to 0 if data
2301                // must be written to HAL
2302                threadLoop_sleepTime();
2303                if (sleepTime == 0) {
2304                    mCurrentWriteLength = mixBufferSize;
2305                }
2306            }
2307            mBytesRemaining = mCurrentWriteLength;
2308            if (isSuspended()) {
2309                sleepTime = suspendSleepTimeUs();
2310                // simulate write to HAL when suspended
2311                mBytesWritten += mixBufferSize;
2312                mBytesRemaining = 0;
2313            }
2314
2315            // only process effects if we're going to write
2316            if (sleepTime == 0 && mType != OFFLOAD) {
2317                for (size_t i = 0; i < effectChains.size(); i ++) {
2318                    effectChains[i]->process_l();
2319                }
2320            }
2321        }
2322        // Process effect chains for offloaded thread even if no audio
2323        // was read from audio track: process only updates effect state
2324        // and thus does have to be synchronized with audio writes but may have
2325        // to be called while waiting for async write callback
2326        if (mType == OFFLOAD) {
2327            for (size_t i = 0; i < effectChains.size(); i ++) {
2328                effectChains[i]->process_l();
2329            }
2330        }
2331
2332        // enable changes in effect chain
2333        unlockEffectChains(effectChains);
2334
2335        if (!waitingAsyncCallback()) {
2336            // sleepTime == 0 means we must write to audio hardware
2337            if (sleepTime == 0) {
2338                if (mBytesRemaining) {
2339                    ssize_t ret = threadLoop_write();
2340                    if (ret < 0) {
2341                        mBytesRemaining = 0;
2342                    } else {
2343                        mBytesWritten += ret;
2344                        mBytesRemaining -= ret;
2345                    }
2346                } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2347                        (mMixerStatus == MIXER_DRAIN_ALL)) {
2348                    threadLoop_drain();
2349                }
2350if (mType == MIXER) {
2351                // write blocked detection
2352                nsecs_t now = systemTime();
2353                nsecs_t delta = now - mLastWriteTime;
2354                if (!mStandby && delta > maxPeriod) {
2355                    mNumDelayedWrites++;
2356                    if ((now - lastWarning) > kWarningThrottleNs) {
2357                        ATRACE_NAME("underrun");
2358                        ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2359                                ns2ms(delta), mNumDelayedWrites, this);
2360                        lastWarning = now;
2361                    }
2362                }
2363}
2364
2365            } else {
2366                usleep(sleepTime);
2367            }
2368        }
2369
2370        // Finally let go of removed track(s), without the lock held
2371        // since we can't guarantee the destructors won't acquire that
2372        // same lock.  This will also mutate and push a new fast mixer state.
2373        threadLoop_removeTracks(tracksToRemove);
2374        tracksToRemove.clear();
2375
2376        // FIXME I don't understand the need for this here;
2377        //       it was in the original code but maybe the
2378        //       assignment in saveOutputTracks() makes this unnecessary?
2379        clearOutputTracks();
2380
2381        // Effect chains will be actually deleted here if they were removed from
2382        // mEffectChains list during mixing or effects processing
2383        effectChains.clear();
2384
2385        // FIXME Note that the above .clear() is no longer necessary since effectChains
2386        // is now local to this block, but will keep it for now (at least until merge done).
2387    }
2388
2389    threadLoop_exit();
2390
2391    // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2392    if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
2393        // put output stream into standby mode
2394        if (!mStandby) {
2395            mOutput->stream->common.standby(&mOutput->stream->common);
2396        }
2397    }
2398
2399    releaseWakeLock();
2400    mWakeLockUids.clear();
2401    mActiveTracksGeneration++;
2402
2403    ALOGV("Thread %p type %d exiting", this, mType);
2404    return false;
2405}
2406
2407// removeTracks_l() must be called with ThreadBase::mLock held
2408void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2409{
2410    size_t count = tracksToRemove.size();
2411    if (count) {
2412        for (size_t i=0 ; i<count ; i++) {
2413            const sp<Track>& track = tracksToRemove.itemAt(i);
2414            mActiveTracks.remove(track);
2415            mWakeLockUids.remove(track->uid());
2416            mActiveTracksGeneration++;
2417            ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2418            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2419            if (chain != 0) {
2420                ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2421                        track->sessionId());
2422                chain->decActiveTrackCnt();
2423            }
2424            if (track->isTerminated()) {
2425                removeTrack_l(track);
2426            }
2427        }
2428    }
2429
2430}
2431
2432status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2433{
2434    if (mNormalSink != 0) {
2435        return mNormalSink->getTimestamp(timestamp);
2436    }
2437    if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2438        uint64_t position64;
2439        int ret = mOutput->stream->get_presentation_position(
2440                                                mOutput->stream, &position64, &timestamp.mTime);
2441        if (ret == 0) {
2442            timestamp.mPosition = (uint32_t)position64;
2443            return NO_ERROR;
2444        }
2445    }
2446    return INVALID_OPERATION;
2447}
2448// ----------------------------------------------------------------------------
2449
2450AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2451        audio_io_handle_t id, audio_devices_t device, type_t type)
2452    :   PlaybackThread(audioFlinger, output, id, device, type),
2453        // mAudioMixer below
2454        // mFastMixer below
2455        mFastMixerFutex(0)
2456        // mOutputSink below
2457        // mPipeSink below
2458        // mNormalSink below
2459{
2460    ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
2461    ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
2462            "mFrameCount=%d, mNormalFrameCount=%d",
2463            mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2464            mNormalFrameCount);
2465    mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2466
2467    // FIXME - Current mixer implementation only supports stereo output
2468    if (mChannelCount != FCC_2) {
2469        ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2470    }
2471
2472    // create an NBAIO sink for the HAL output stream, and negotiate
2473    mOutputSink = new AudioStreamOutSink(output->stream);
2474    size_t numCounterOffers = 0;
2475    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2476    ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2477    ALOG_ASSERT(index == 0);
2478
2479    // initialize fast mixer depending on configuration
2480    bool initFastMixer;
2481    switch (kUseFastMixer) {
2482    case FastMixer_Never:
2483        initFastMixer = false;
2484        break;
2485    case FastMixer_Always:
2486        initFastMixer = true;
2487        break;
2488    case FastMixer_Static:
2489    case FastMixer_Dynamic:
2490        initFastMixer = mFrameCount < mNormalFrameCount;
2491        break;
2492    }
2493    if (initFastMixer) {
2494
2495        // create a MonoPipe to connect our submix to FastMixer
2496        NBAIO_Format format = mOutputSink->format();
2497        // This pipe depth compensates for scheduling latency of the normal mixer thread.
2498        // When it wakes up after a maximum latency, it runs a few cycles quickly before
2499        // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
2500        MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2501        const NBAIO_Format offers[1] = {format};
2502        size_t numCounterOffers = 0;
2503        ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2504        ALOG_ASSERT(index == 0);
2505        monoPipe->setAvgFrames((mScreenState & 1) ?
2506                (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2507        mPipeSink = monoPipe;
2508
2509#ifdef TEE_SINK
2510        if (mTeeSinkOutputEnabled) {
2511            // create a Pipe to archive a copy of FastMixer's output for dumpsys
2512            Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2513            numCounterOffers = 0;
2514            index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2515            ALOG_ASSERT(index == 0);
2516            mTeeSink = teeSink;
2517            PipeReader *teeSource = new PipeReader(*teeSink);
2518            numCounterOffers = 0;
2519            index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2520            ALOG_ASSERT(index == 0);
2521            mTeeSource = teeSource;
2522        }
2523#endif
2524
2525        // create fast mixer and configure it initially with just one fast track for our submix
2526        mFastMixer = new FastMixer();
2527        FastMixerStateQueue *sq = mFastMixer->sq();
2528#ifdef STATE_QUEUE_DUMP
2529        sq->setObserverDump(&mStateQueueObserverDump);
2530        sq->setMutatorDump(&mStateQueueMutatorDump);
2531#endif
2532        FastMixerState *state = sq->begin();
2533        FastTrack *fastTrack = &state->mFastTracks[0];
2534        // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2535        fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2536        fastTrack->mVolumeProvider = NULL;
2537        fastTrack->mGeneration++;
2538        state->mFastTracksGen++;
2539        state->mTrackMask = 1;
2540        // fast mixer will use the HAL output sink
2541        state->mOutputSink = mOutputSink.get();
2542        state->mOutputSinkGen++;
2543        state->mFrameCount = mFrameCount;
2544        state->mCommand = FastMixerState::COLD_IDLE;
2545        // already done in constructor initialization list
2546        //mFastMixerFutex = 0;
2547        state->mColdFutexAddr = &mFastMixerFutex;
2548        state->mColdGen++;
2549        state->mDumpState = &mFastMixerDumpState;
2550#ifdef TEE_SINK
2551        state->mTeeSink = mTeeSink.get();
2552#endif
2553        mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2554        state->mNBLogWriter = mFastMixerNBLogWriter.get();
2555        sq->end();
2556        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2557
2558        // start the fast mixer
2559        mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2560        pid_t tid = mFastMixer->getTid();
2561        int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2562        if (err != 0) {
2563            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2564                    kPriorityFastMixer, getpid_cached, tid, err);
2565        }
2566
2567#ifdef AUDIO_WATCHDOG
2568        // create and start the watchdog
2569        mAudioWatchdog = new AudioWatchdog();
2570        mAudioWatchdog->setDump(&mAudioWatchdogDump);
2571        mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2572        tid = mAudioWatchdog->getTid();
2573        err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2574        if (err != 0) {
2575            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2576                    kPriorityFastMixer, getpid_cached, tid, err);
2577        }
2578#endif
2579
2580    } else {
2581        mFastMixer = NULL;
2582    }
2583
2584    switch (kUseFastMixer) {
2585    case FastMixer_Never:
2586    case FastMixer_Dynamic:
2587        mNormalSink = mOutputSink;
2588        break;
2589    case FastMixer_Always:
2590        mNormalSink = mPipeSink;
2591        break;
2592    case FastMixer_Static:
2593        mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2594        break;
2595    }
2596}
2597
2598AudioFlinger::MixerThread::~MixerThread()
2599{
2600    if (mFastMixer != NULL) {
2601        FastMixerStateQueue *sq = mFastMixer->sq();
2602        FastMixerState *state = sq->begin();
2603        if (state->mCommand == FastMixerState::COLD_IDLE) {
2604            int32_t old = android_atomic_inc(&mFastMixerFutex);
2605            if (old == -1) {
2606                __futex_syscall4(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1, NULL);
2607            }
2608        }
2609        state->mCommand = FastMixerState::EXIT;
2610        sq->end();
2611        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2612        mFastMixer->join();
2613        // Though the fast mixer thread has exited, it's state queue is still valid.
2614        // We'll use that extract the final state which contains one remaining fast track
2615        // corresponding to our sub-mix.
2616        state = sq->begin();
2617        ALOG_ASSERT(state->mTrackMask == 1);
2618        FastTrack *fastTrack = &state->mFastTracks[0];
2619        ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2620        delete fastTrack->mBufferProvider;
2621        sq->end(false /*didModify*/);
2622        delete mFastMixer;
2623#ifdef AUDIO_WATCHDOG
2624        if (mAudioWatchdog != 0) {
2625            mAudioWatchdog->requestExit();
2626            mAudioWatchdog->requestExitAndWait();
2627            mAudioWatchdog.clear();
2628        }
2629#endif
2630    }
2631    mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
2632    delete mAudioMixer;
2633}
2634
2635
2636uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2637{
2638    if (mFastMixer != NULL) {
2639        MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2640        latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2641    }
2642    return latency;
2643}
2644
2645
2646void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2647{
2648    PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2649}
2650
2651ssize_t AudioFlinger::MixerThread::threadLoop_write()
2652{
2653    // FIXME we should only do one push per cycle; confirm this is true
2654    // Start the fast mixer if it's not already running
2655    if (mFastMixer != NULL) {
2656        FastMixerStateQueue *sq = mFastMixer->sq();
2657        FastMixerState *state = sq->begin();
2658        if (state->mCommand != FastMixerState::MIX_WRITE &&
2659                (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2660            if (state->mCommand == FastMixerState::COLD_IDLE) {
2661                int32_t old = android_atomic_inc(&mFastMixerFutex);
2662                if (old == -1) {
2663                    __futex_syscall4(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1, NULL);
2664                }
2665#ifdef AUDIO_WATCHDOG
2666                if (mAudioWatchdog != 0) {
2667                    mAudioWatchdog->resume();
2668                }
2669#endif
2670            }
2671            state->mCommand = FastMixerState::MIX_WRITE;
2672            mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2673                    FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
2674            sq->end();
2675            sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2676            if (kUseFastMixer == FastMixer_Dynamic) {
2677                mNormalSink = mPipeSink;
2678            }
2679        } else {
2680            sq->end(false /*didModify*/);
2681        }
2682    }
2683    return PlaybackThread::threadLoop_write();
2684}
2685
2686void AudioFlinger::MixerThread::threadLoop_standby()
2687{
2688    // Idle the fast mixer if it's currently running
2689    if (mFastMixer != NULL) {
2690        FastMixerStateQueue *sq = mFastMixer->sq();
2691        FastMixerState *state = sq->begin();
2692        if (!(state->mCommand & FastMixerState::IDLE)) {
2693            state->mCommand = FastMixerState::COLD_IDLE;
2694            state->mColdFutexAddr = &mFastMixerFutex;
2695            state->mColdGen++;
2696            mFastMixerFutex = 0;
2697            sq->end();
2698            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2699            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2700            if (kUseFastMixer == FastMixer_Dynamic) {
2701                mNormalSink = mOutputSink;
2702            }
2703#ifdef AUDIO_WATCHDOG
2704            if (mAudioWatchdog != 0) {
2705                mAudioWatchdog->pause();
2706            }
2707#endif
2708        } else {
2709            sq->end(false /*didModify*/);
2710        }
2711    }
2712    PlaybackThread::threadLoop_standby();
2713}
2714
2715// Empty implementation for standard mixer
2716// Overridden for offloaded playback
2717void AudioFlinger::PlaybackThread::flushOutput_l()
2718{
2719}
2720
2721bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2722{
2723    return false;
2724}
2725
2726bool AudioFlinger::PlaybackThread::shouldStandby_l()
2727{
2728    return !mStandby;
2729}
2730
2731bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2732{
2733    Mutex::Autolock _l(mLock);
2734    return waitingAsyncCallback_l();
2735}
2736
2737// shared by MIXER and DIRECT, overridden by DUPLICATING
2738void AudioFlinger::PlaybackThread::threadLoop_standby()
2739{
2740    ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2741    mOutput->stream->common.standby(&mOutput->stream->common);
2742    if (mUseAsyncWrite != 0) {
2743        // discard any pending drain or write ack by incrementing sequence
2744        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2745        mDrainSequence = (mDrainSequence + 2) & ~1;
2746        ALOG_ASSERT(mCallbackThread != 0);
2747        mCallbackThread->setWriteBlocked(mWriteAckSequence);
2748        mCallbackThread->setDraining(mDrainSequence);
2749    }
2750}
2751
2752void AudioFlinger::MixerThread::threadLoop_mix()
2753{
2754    // obtain the presentation timestamp of the next output buffer
2755    int64_t pts;
2756    status_t status = INVALID_OPERATION;
2757
2758    if (mNormalSink != 0) {
2759        status = mNormalSink->getNextWriteTimestamp(&pts);
2760    } else {
2761        status = mOutputSink->getNextWriteTimestamp(&pts);
2762    }
2763
2764    if (status != NO_ERROR) {
2765        pts = AudioBufferProvider::kInvalidPTS;
2766    }
2767
2768    // mix buffers...
2769    mAudioMixer->process(pts);
2770    mCurrentWriteLength = mixBufferSize;
2771    // increase sleep time progressively when application underrun condition clears.
2772    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2773    // that a steady state of alternating ready/not ready conditions keeps the sleep time
2774    // such that we would underrun the audio HAL.
2775    if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2776        sleepTimeShift--;
2777    }
2778    sleepTime = 0;
2779    standbyTime = systemTime() + standbyDelay;
2780    //TODO: delay standby when effects have a tail
2781}
2782
2783void AudioFlinger::MixerThread::threadLoop_sleepTime()
2784{
2785    // If no tracks are ready, sleep once for the duration of an output
2786    // buffer size, then write 0s to the output
2787    if (sleepTime == 0) {
2788        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2789            sleepTime = activeSleepTime >> sleepTimeShift;
2790            if (sleepTime < kMinThreadSleepTimeUs) {
2791                sleepTime = kMinThreadSleepTimeUs;
2792            }
2793            // reduce sleep time in case of consecutive application underruns to avoid
2794            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2795            // duration we would end up writing less data than needed by the audio HAL if
2796            // the condition persists.
2797            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2798                sleepTimeShift++;
2799            }
2800        } else {
2801            sleepTime = idleSleepTime;
2802        }
2803    } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2804        memset (mMixBuffer, 0, mixBufferSize);
2805        sleepTime = 0;
2806        ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2807                "anticipated start");
2808    }
2809    // TODO add standby time extension fct of effect tail
2810}
2811
2812// prepareTracks_l() must be called with ThreadBase::mLock held
2813AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2814        Vector< sp<Track> > *tracksToRemove)
2815{
2816
2817    mixer_state mixerStatus = MIXER_IDLE;
2818    // find out which tracks need to be processed
2819    size_t count = mActiveTracks.size();
2820    size_t mixedTracks = 0;
2821    size_t tracksWithEffect = 0;
2822    // counts only _active_ fast tracks
2823    size_t fastTracks = 0;
2824    uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2825
2826    float masterVolume = mMasterVolume;
2827    bool masterMute = mMasterMute;
2828
2829    if (masterMute) {
2830        masterVolume = 0;
2831    }
2832    // Delegate master volume control to effect in output mix effect chain if needed
2833    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2834    if (chain != 0) {
2835        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2836        chain->setVolume_l(&v, &v);
2837        masterVolume = (float)((v + (1 << 23)) >> 24);
2838        chain.clear();
2839    }
2840
2841    // prepare a new state to push
2842    FastMixerStateQueue *sq = NULL;
2843    FastMixerState *state = NULL;
2844    bool didModify = false;
2845    FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2846    if (mFastMixer != NULL) {
2847        sq = mFastMixer->sq();
2848        state = sq->begin();
2849    }
2850
2851    for (size_t i=0 ; i<count ; i++) {
2852        const sp<Track> t = mActiveTracks[i].promote();
2853        if (t == 0) {
2854            continue;
2855        }
2856
2857        // this const just means the local variable doesn't change
2858        Track* const track = t.get();
2859
2860        // process fast tracks
2861        if (track->isFastTrack()) {
2862
2863            // It's theoretically possible (though unlikely) for a fast track to be created
2864            // and then removed within the same normal mix cycle.  This is not a problem, as
2865            // the track never becomes active so it's fast mixer slot is never touched.
2866            // The converse, of removing an (active) track and then creating a new track
2867            // at the identical fast mixer slot within the same normal mix cycle,
2868            // is impossible because the slot isn't marked available until the end of each cycle.
2869            int j = track->mFastIndex;
2870            ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2871            ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2872            FastTrack *fastTrack = &state->mFastTracks[j];
2873
2874            // Determine whether the track is currently in underrun condition,
2875            // and whether it had a recent underrun.
2876            FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2877            FastTrackUnderruns underruns = ftDump->mUnderruns;
2878            uint32_t recentFull = (underruns.mBitFields.mFull -
2879                    track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2880            uint32_t recentPartial = (underruns.mBitFields.mPartial -
2881                    track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2882            uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2883                    track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2884            uint32_t recentUnderruns = recentPartial + recentEmpty;
2885            track->mObservedUnderruns = underruns;
2886            // don't count underruns that occur while stopping or pausing
2887            // or stopped which can occur when flush() is called while active
2888            if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
2889                    recentUnderruns > 0) {
2890                // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
2891                track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
2892            }
2893
2894            // This is similar to the state machine for normal tracks,
2895            // with a few modifications for fast tracks.
2896            bool isActive = true;
2897            switch (track->mState) {
2898            case TrackBase::STOPPING_1:
2899                // track stays active in STOPPING_1 state until first underrun
2900                if (recentUnderruns > 0 || track->isTerminated()) {
2901                    track->mState = TrackBase::STOPPING_2;
2902                }
2903                break;
2904            case TrackBase::PAUSING:
2905                // ramp down is not yet implemented
2906                track->setPaused();
2907                break;
2908            case TrackBase::RESUMING:
2909                // ramp up is not yet implemented
2910                track->mState = TrackBase::ACTIVE;
2911                break;
2912            case TrackBase::ACTIVE:
2913                if (recentFull > 0 || recentPartial > 0) {
2914                    // track has provided at least some frames recently: reset retry count
2915                    track->mRetryCount = kMaxTrackRetries;
2916                }
2917                if (recentUnderruns == 0) {
2918                    // no recent underruns: stay active
2919                    break;
2920                }
2921                // there has recently been an underrun of some kind
2922                if (track->sharedBuffer() == 0) {
2923                    // were any of the recent underruns "empty" (no frames available)?
2924                    if (recentEmpty == 0) {
2925                        // no, then ignore the partial underruns as they are allowed indefinitely
2926                        break;
2927                    }
2928                    // there has recently been an "empty" underrun: decrement the retry counter
2929                    if (--(track->mRetryCount) > 0) {
2930                        break;
2931                    }
2932                    // indicate to client process that the track was disabled because of underrun;
2933                    // it will then automatically call start() when data is available
2934                    android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
2935                    // remove from active list, but state remains ACTIVE [confusing but true]
2936                    isActive = false;
2937                    break;
2938                }
2939                // fall through
2940            case TrackBase::STOPPING_2:
2941            case TrackBase::PAUSED:
2942            case TrackBase::STOPPED:
2943            case TrackBase::FLUSHED:   // flush() while active
2944                // Check for presentation complete if track is inactive
2945                // We have consumed all the buffers of this track.
2946                // This would be incomplete if we auto-paused on underrun
2947                {
2948                    size_t audioHALFrames =
2949                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2950                    size_t framesWritten = mBytesWritten / mFrameSize;
2951                    if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
2952                        // track stays in active list until presentation is complete
2953                        break;
2954                    }
2955                }
2956                if (track->isStopping_2()) {
2957                    track->mState = TrackBase::STOPPED;
2958                }
2959                if (track->isStopped()) {
2960                    // Can't reset directly, as fast mixer is still polling this track
2961                    //   track->reset();
2962                    // So instead mark this track as needing to be reset after push with ack
2963                    resetMask |= 1 << i;
2964                }
2965                isActive = false;
2966                break;
2967            case TrackBase::IDLE:
2968            default:
2969                LOG_FATAL("unexpected track state %d", track->mState);
2970            }
2971
2972            if (isActive) {
2973                // was it previously inactive?
2974                if (!(state->mTrackMask & (1 << j))) {
2975                    ExtendedAudioBufferProvider *eabp = track;
2976                    VolumeProvider *vp = track;
2977                    fastTrack->mBufferProvider = eabp;
2978                    fastTrack->mVolumeProvider = vp;
2979                    fastTrack->mChannelMask = track->mChannelMask;
2980                    fastTrack->mGeneration++;
2981                    state->mTrackMask |= 1 << j;
2982                    didModify = true;
2983                    // no acknowledgement required for newly active tracks
2984                }
2985                // cache the combined master volume and stream type volume for fast mixer; this
2986                // lacks any synchronization or barrier so VolumeProvider may read a stale value
2987                track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
2988                ++fastTracks;
2989            } else {
2990                // was it previously active?
2991                if (state->mTrackMask & (1 << j)) {
2992                    fastTrack->mBufferProvider = NULL;
2993                    fastTrack->mGeneration++;
2994                    state->mTrackMask &= ~(1 << j);
2995                    didModify = true;
2996                    // If any fast tracks were removed, we must wait for acknowledgement
2997                    // because we're about to decrement the last sp<> on those tracks.
2998                    block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2999                } else {
3000                    LOG_FATAL("fast track %d should have been active", j);
3001                }
3002                tracksToRemove->add(track);
3003                // Avoids a misleading display in dumpsys
3004                track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3005            }
3006            continue;
3007        }
3008
3009        {   // local variable scope to avoid goto warning
3010
3011        audio_track_cblk_t* cblk = track->cblk();
3012
3013        // The first time a track is added we wait
3014        // for all its buffers to be filled before processing it
3015        int name = track->name();
3016        // make sure that we have enough frames to mix one full buffer.
3017        // enforce this condition only once to enable draining the buffer in case the client
3018        // app does not call stop() and relies on underrun to stop:
3019        // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3020        // during last round
3021        size_t desiredFrames;
3022        uint32_t sr = track->sampleRate();
3023        if (sr == mSampleRate) {
3024            desiredFrames = mNormalFrameCount;
3025        } else {
3026            // +1 for rounding and +1 for additional sample needed for interpolation
3027            desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
3028            // add frames already consumed but not yet released by the resampler
3029            // because cblk->framesReady() will include these frames
3030            desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3031            // the minimum track buffer size is normally twice the number of frames necessary
3032            // to fill one buffer and the resampler should not leave more than one buffer worth
3033            // of unreleased frames after each pass, but just in case...
3034            ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
3035        }
3036        uint32_t minFrames = 1;
3037        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3038                (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
3039            minFrames = desiredFrames;
3040        }
3041
3042        size_t framesReady = track->framesReady();
3043        if ((framesReady >= minFrames) && track->isReady() &&
3044                !track->isPaused() && !track->isTerminated())
3045        {
3046            ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
3047
3048            mixedTracks++;
3049
3050            // track->mainBuffer() != mMixBuffer means there is an effect chain
3051            // connected to the track
3052            chain.clear();
3053            if (track->mainBuffer() != mMixBuffer) {
3054                chain = getEffectChain_l(track->sessionId());
3055                // Delegate volume control to effect in track effect chain if needed
3056                if (chain != 0) {
3057                    tracksWithEffect++;
3058                } else {
3059                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3060                            "session %d",
3061                            name, track->sessionId());
3062                }
3063            }
3064
3065
3066            int param = AudioMixer::VOLUME;
3067            if (track->mFillingUpStatus == Track::FS_FILLED) {
3068                // no ramp for the first volume setting
3069                track->mFillingUpStatus = Track::FS_ACTIVE;
3070                if (track->mState == TrackBase::RESUMING) {
3071                    track->mState = TrackBase::ACTIVE;
3072                    param = AudioMixer::RAMP_VOLUME;
3073                }
3074                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
3075            // FIXME should not make a decision based on mServer
3076            } else if (cblk->mServer != 0) {
3077                // If the track is stopped before the first frame was mixed,
3078                // do not apply ramp
3079                param = AudioMixer::RAMP_VOLUME;
3080            }
3081
3082            // compute volume for this track
3083            uint32_t vl, vr, va;
3084            if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
3085                vl = vr = va = 0;
3086                if (track->isPausing()) {
3087                    track->setPaused();
3088                }
3089            } else {
3090
3091                // read original volumes with volume control
3092                float typeVolume = mStreamTypes[track->streamType()].volume;
3093                float v = masterVolume * typeVolume;
3094                AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3095                uint32_t vlr = proxy->getVolumeLR();
3096                vl = vlr & 0xFFFF;
3097                vr = vlr >> 16;
3098                // track volumes come from shared memory, so can't be trusted and must be clamped
3099                if (vl > MAX_GAIN_INT) {
3100                    ALOGV("Track left volume out of range: %04X", vl);
3101                    vl = MAX_GAIN_INT;
3102                }
3103                if (vr > MAX_GAIN_INT) {
3104                    ALOGV("Track right volume out of range: %04X", vr);
3105                    vr = MAX_GAIN_INT;
3106                }
3107                // now apply the master volume and stream type volume
3108                vl = (uint32_t)(v * vl) << 12;
3109                vr = (uint32_t)(v * vr) << 12;
3110                // assuming master volume and stream type volume each go up to 1.0,
3111                // vl and vr are now in 8.24 format
3112
3113                uint16_t sendLevel = proxy->getSendLevel_U4_12();
3114                // send level comes from shared memory and so may be corrupt
3115                if (sendLevel > MAX_GAIN_INT) {
3116                    ALOGV("Track send level out of range: %04X", sendLevel);
3117                    sendLevel = MAX_GAIN_INT;
3118                }
3119                va = (uint32_t)(v * sendLevel);
3120            }
3121
3122            // Delegate volume control to effect in track effect chain if needed
3123            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3124                // Do not ramp volume if volume is controlled by effect
3125                param = AudioMixer::VOLUME;
3126                track->mHasVolumeController = true;
3127            } else {
3128                // force no volume ramp when volume controller was just disabled or removed
3129                // from effect chain to avoid volume spike
3130                if (track->mHasVolumeController) {
3131                    param = AudioMixer::VOLUME;
3132                }
3133                track->mHasVolumeController = false;
3134            }
3135
3136            // Convert volumes from 8.24 to 4.12 format
3137            // This additional clamping is needed in case chain->setVolume_l() overshot
3138            vl = (vl + (1 << 11)) >> 12;
3139            if (vl > MAX_GAIN_INT) {
3140                vl = MAX_GAIN_INT;
3141            }
3142            vr = (vr + (1 << 11)) >> 12;
3143            if (vr > MAX_GAIN_INT) {
3144                vr = MAX_GAIN_INT;
3145            }
3146
3147            if (va > MAX_GAIN_INT) {
3148                va = MAX_GAIN_INT;   // va is uint32_t, so no need to check for -
3149            }
3150
3151            // XXX: these things DON'T need to be done each time
3152            mAudioMixer->setBufferProvider(name, track);
3153            mAudioMixer->enable(name);
3154
3155            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3156            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3157            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
3158            mAudioMixer->setParameter(
3159                name,
3160                AudioMixer::TRACK,
3161                AudioMixer::FORMAT, (void *)track->format());
3162            mAudioMixer->setParameter(
3163                name,
3164                AudioMixer::TRACK,
3165                AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
3166            // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3167            uint32_t maxSampleRate = mSampleRate * 2;
3168            uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
3169            if (reqSampleRate == 0) {
3170                reqSampleRate = mSampleRate;
3171            } else if (reqSampleRate > maxSampleRate) {
3172                reqSampleRate = maxSampleRate;
3173            }
3174            mAudioMixer->setParameter(
3175                name,
3176                AudioMixer::RESAMPLE,
3177                AudioMixer::SAMPLE_RATE,
3178                (void *)(uintptr_t)reqSampleRate);
3179            mAudioMixer->setParameter(
3180                name,
3181                AudioMixer::TRACK,
3182                AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3183            mAudioMixer->setParameter(
3184                name,
3185                AudioMixer::TRACK,
3186                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3187
3188            // reset retry count
3189            track->mRetryCount = kMaxTrackRetries;
3190
3191            // If one track is ready, set the mixer ready if:
3192            //  - the mixer was not ready during previous round OR
3193            //  - no other track is not ready
3194            if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3195                    mixerStatus != MIXER_TRACKS_ENABLED) {
3196                mixerStatus = MIXER_TRACKS_READY;
3197            }
3198        } else {
3199            if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
3200                track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
3201            }
3202            // clear effect chain input buffer if an active track underruns to avoid sending
3203            // previous audio buffer again to effects
3204            chain = getEffectChain_l(track->sessionId());
3205            if (chain != 0) {
3206                chain->clearInputBuffer();
3207            }
3208
3209            ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
3210            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3211                    track->isStopped() || track->isPaused()) {
3212                // We have consumed all the buffers of this track.
3213                // Remove it from the list of active tracks.
3214                // TODO: use actual buffer filling status instead of latency when available from
3215                // audio HAL
3216                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3217                size_t framesWritten = mBytesWritten / mFrameSize;
3218                if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3219                    if (track->isStopped()) {
3220                        track->reset();
3221                    }
3222                    tracksToRemove->add(track);
3223                }
3224            } else {
3225                // No buffers for this track. Give it a few chances to
3226                // fill a buffer, then remove it from active list.
3227                if (--(track->mRetryCount) <= 0) {
3228                    ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
3229                    tracksToRemove->add(track);
3230                    // indicate to client process that the track was disabled because of underrun;
3231                    // it will then automatically call start() when data is available
3232                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
3233                // If one track is not ready, mark the mixer also not ready if:
3234                //  - the mixer was ready during previous round OR
3235                //  - no other track is ready
3236                } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3237                                mixerStatus != MIXER_TRACKS_READY) {
3238                    mixerStatus = MIXER_TRACKS_ENABLED;
3239                }
3240            }
3241            mAudioMixer->disable(name);
3242        }
3243
3244        }   // local variable scope to avoid goto warning
3245track_is_ready: ;
3246
3247    }
3248
3249    // Push the new FastMixer state if necessary
3250    bool pauseAudioWatchdog = false;
3251    if (didModify) {
3252        state->mFastTracksGen++;
3253        // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3254        if (kUseFastMixer == FastMixer_Dynamic &&
3255                state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3256            state->mCommand = FastMixerState::COLD_IDLE;
3257            state->mColdFutexAddr = &mFastMixerFutex;
3258            state->mColdGen++;
3259            mFastMixerFutex = 0;
3260            if (kUseFastMixer == FastMixer_Dynamic) {
3261                mNormalSink = mOutputSink;
3262            }
3263            // If we go into cold idle, need to wait for acknowledgement
3264            // so that fast mixer stops doing I/O.
3265            block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3266            pauseAudioWatchdog = true;
3267        }
3268    }
3269    if (sq != NULL) {
3270        sq->end(didModify);
3271        sq->push(block);
3272    }
3273#ifdef AUDIO_WATCHDOG
3274    if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3275        mAudioWatchdog->pause();
3276    }
3277#endif
3278
3279    // Now perform the deferred reset on fast tracks that have stopped
3280    while (resetMask != 0) {
3281        size_t i = __builtin_ctz(resetMask);
3282        ALOG_ASSERT(i < count);
3283        resetMask &= ~(1 << i);
3284        sp<Track> t = mActiveTracks[i].promote();
3285        if (t == 0) {
3286            continue;
3287        }
3288        Track* track = t.get();
3289        ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3290        track->reset();
3291    }
3292
3293    // remove all the tracks that need to be...
3294    removeTracks_l(*tracksToRemove);
3295
3296    // mix buffer must be cleared if all tracks are connected to an
3297    // effect chain as in this case the mixer will not write to
3298    // mix buffer and track effects will accumulate into it
3299    if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3300            (mixedTracks == 0 && fastTracks > 0))) {
3301        // FIXME as a performance optimization, should remember previous zero status
3302        memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3303    }
3304
3305    // if any fast tracks, then status is ready
3306    mMixerStatusIgnoringFastTracks = mixerStatus;
3307    if (fastTracks > 0) {
3308        mixerStatus = MIXER_TRACKS_READY;
3309    }
3310    return mixerStatus;
3311}
3312
3313// getTrackName_l() must be called with ThreadBase::mLock held
3314int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3315{
3316    return mAudioMixer->getTrackName(channelMask, sessionId);
3317}
3318
3319// deleteTrackName_l() must be called with ThreadBase::mLock held
3320void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3321{
3322    ALOGV("remove track (%d) and delete from mixer", name);
3323    mAudioMixer->deleteTrackName(name);
3324}
3325
3326// checkForNewParameters_l() must be called with ThreadBase::mLock held
3327bool AudioFlinger::MixerThread::checkForNewParameters_l()
3328{
3329    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3330    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3331    bool reconfig = false;
3332
3333    while (!mNewParameters.isEmpty()) {
3334
3335        if (mFastMixer != NULL) {
3336            FastMixerStateQueue *sq = mFastMixer->sq();
3337            FastMixerState *state = sq->begin();
3338            if (!(state->mCommand & FastMixerState::IDLE)) {
3339                previousCommand = state->mCommand;
3340                state->mCommand = FastMixerState::HOT_IDLE;
3341                sq->end();
3342                sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3343            } else {
3344                sq->end(false /*didModify*/);
3345            }
3346        }
3347
3348        status_t status = NO_ERROR;
3349        String8 keyValuePair = mNewParameters[0];
3350        AudioParameter param = AudioParameter(keyValuePair);
3351        int value;
3352
3353        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3354            reconfig = true;
3355        }
3356        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3357            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3358                status = BAD_VALUE;
3359            } else {
3360                reconfig = true;
3361            }
3362        }
3363        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3364            if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3365                status = BAD_VALUE;
3366            } else {
3367                reconfig = true;
3368            }
3369        }
3370        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3371            // do not accept frame count changes if tracks are open as the track buffer
3372            // size depends on frame count and correct behavior would not be guaranteed
3373            // if frame count is changed after track creation
3374            if (!mTracks.isEmpty()) {
3375                status = INVALID_OPERATION;
3376            } else {
3377                reconfig = true;
3378            }
3379        }
3380        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3381#ifdef ADD_BATTERY_DATA
3382            // when changing the audio output device, call addBatteryData to notify
3383            // the change
3384            if (mOutDevice != value) {
3385                uint32_t params = 0;
3386                // check whether speaker is on
3387                if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3388                    params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3389                }
3390
3391                audio_devices_t deviceWithoutSpeaker
3392                    = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3393                // check if any other device (except speaker) is on
3394                if (value & deviceWithoutSpeaker ) {
3395                    params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3396                }
3397
3398                if (params != 0) {
3399                    addBatteryData(params);
3400                }
3401            }
3402#endif
3403
3404            // forward device change to effects that have requested to be
3405            // aware of attached audio device.
3406            if (value != AUDIO_DEVICE_NONE) {
3407                mOutDevice = value;
3408                for (size_t i = 0; i < mEffectChains.size(); i++) {
3409                    mEffectChains[i]->setDevice_l(mOutDevice);
3410                }
3411            }
3412        }
3413
3414        if (status == NO_ERROR) {
3415            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3416                                                    keyValuePair.string());
3417            if (!mStandby && status == INVALID_OPERATION) {
3418                mOutput->stream->common.standby(&mOutput->stream->common);
3419                mStandby = true;
3420                mBytesWritten = 0;
3421                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3422                                                       keyValuePair.string());
3423            }
3424            if (status == NO_ERROR && reconfig) {
3425                readOutputParameters();
3426                delete mAudioMixer;
3427                mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3428                for (size_t i = 0; i < mTracks.size() ; i++) {
3429                    int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3430                    if (name < 0) {
3431                        break;
3432                    }
3433                    mTracks[i]->mName = name;
3434                }
3435                sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3436            }
3437        }
3438
3439        mNewParameters.removeAt(0);
3440
3441        mParamStatus = status;
3442        mParamCond.signal();
3443        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3444        // already timed out waiting for the status and will never signal the condition.
3445        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3446    }
3447
3448    if (!(previousCommand & FastMixerState::IDLE)) {
3449        ALOG_ASSERT(mFastMixer != NULL);
3450        FastMixerStateQueue *sq = mFastMixer->sq();
3451        FastMixerState *state = sq->begin();
3452        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3453        state->mCommand = previousCommand;
3454        sq->end();
3455        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3456    }
3457
3458    return reconfig;
3459}
3460
3461
3462void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3463{
3464    const size_t SIZE = 256;
3465    char buffer[SIZE];
3466    String8 result;
3467
3468    PlaybackThread::dumpInternals(fd, args);
3469
3470    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3471    result.append(buffer);
3472    write(fd, result.string(), result.size());
3473
3474    // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3475    const FastMixerDumpState copy(mFastMixerDumpState);
3476    copy.dump(fd);
3477
3478#ifdef STATE_QUEUE_DUMP
3479    // Similar for state queue
3480    StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3481    observerCopy.dump(fd);
3482    StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3483    mutatorCopy.dump(fd);
3484#endif
3485
3486#ifdef TEE_SINK
3487    // Write the tee output to a .wav file
3488    dumpTee(fd, mTeeSource, mId);
3489#endif
3490
3491#ifdef AUDIO_WATCHDOG
3492    if (mAudioWatchdog != 0) {
3493        // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3494        AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3495        wdCopy.dump(fd);
3496    }
3497#endif
3498}
3499
3500uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3501{
3502    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3503}
3504
3505uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3506{
3507    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3508}
3509
3510void AudioFlinger::MixerThread::cacheParameters_l()
3511{
3512    PlaybackThread::cacheParameters_l();
3513
3514    // FIXME: Relaxed timing because of a certain device that can't meet latency
3515    // Should be reduced to 2x after the vendor fixes the driver issue
3516    // increase threshold again due to low power audio mode. The way this warning
3517    // threshold is calculated and its usefulness should be reconsidered anyway.
3518    maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3519}
3520
3521// ----------------------------------------------------------------------------
3522
3523AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3524        AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3525    :   PlaybackThread(audioFlinger, output, id, device, DIRECT)
3526        // mLeftVolFloat, mRightVolFloat
3527{
3528}
3529
3530AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3531        AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3532        ThreadBase::type_t type)
3533    :   PlaybackThread(audioFlinger, output, id, device, type)
3534        // mLeftVolFloat, mRightVolFloat
3535{
3536}
3537
3538AudioFlinger::DirectOutputThread::~DirectOutputThread()
3539{
3540}
3541
3542void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3543{
3544    audio_track_cblk_t* cblk = track->cblk();
3545    float left, right;
3546
3547    if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3548        left = right = 0;
3549    } else {
3550        float typeVolume = mStreamTypes[track->streamType()].volume;
3551        float v = mMasterVolume * typeVolume;
3552        AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3553        uint32_t vlr = proxy->getVolumeLR();
3554        float v_clamped = v * (vlr & 0xFFFF);
3555        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3556        left = v_clamped/MAX_GAIN;
3557        v_clamped = v * (vlr >> 16);
3558        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3559        right = v_clamped/MAX_GAIN;
3560    }
3561
3562    if (lastTrack) {
3563        if (left != mLeftVolFloat || right != mRightVolFloat) {
3564            mLeftVolFloat = left;
3565            mRightVolFloat = right;
3566
3567            // Convert volumes from float to 8.24
3568            uint32_t vl = (uint32_t)(left * (1 << 24));
3569            uint32_t vr = (uint32_t)(right * (1 << 24));
3570
3571            // Delegate volume control to effect in track effect chain if needed
3572            // only one effect chain can be present on DirectOutputThread, so if
3573            // there is one, the track is connected to it
3574            if (!mEffectChains.isEmpty()) {
3575                mEffectChains[0]->setVolume_l(&vl, &vr);
3576                left = (float)vl / (1 << 24);
3577                right = (float)vr / (1 << 24);
3578            }
3579            if (mOutput->stream->set_volume) {
3580                mOutput->stream->set_volume(mOutput->stream, left, right);
3581            }
3582        }
3583    }
3584}
3585
3586
3587AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3588    Vector< sp<Track> > *tracksToRemove
3589)
3590{
3591    size_t count = mActiveTracks.size();
3592    mixer_state mixerStatus = MIXER_IDLE;
3593
3594    // find out which tracks need to be processed
3595    for (size_t i = 0; i < count; i++) {
3596        sp<Track> t = mActiveTracks[i].promote();
3597        // The track died recently
3598        if (t == 0) {
3599            continue;
3600        }
3601
3602        Track* const track = t.get();
3603        audio_track_cblk_t* cblk = track->cblk();
3604        // Only consider last track started for volume and mixer state control.
3605        // In theory an older track could underrun and restart after the new one starts
3606        // but as we only care about the transition phase between two tracks on a
3607        // direct output, it is not a problem to ignore the underrun case.
3608        sp<Track> l = mLatestActiveTrack.promote();
3609        bool last = l.get() == track;
3610
3611        // The first time a track is added we wait
3612        // for all its buffers to be filled before processing it
3613        uint32_t minFrames;
3614        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3615            minFrames = mNormalFrameCount;
3616        } else {
3617            minFrames = 1;
3618        }
3619
3620        if ((track->framesReady() >= minFrames) && track->isReady() &&
3621                !track->isPaused() && !track->isTerminated())
3622        {
3623            ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
3624
3625            if (track->mFillingUpStatus == Track::FS_FILLED) {
3626                track->mFillingUpStatus = Track::FS_ACTIVE;
3627                // make sure processVolume_l() will apply new volume even if 0
3628                mLeftVolFloat = mRightVolFloat = -1.0;
3629                if (track->mState == TrackBase::RESUMING) {
3630                    track->mState = TrackBase::ACTIVE;
3631                }
3632            }
3633
3634            // compute volume for this track
3635            processVolume_l(track, last);
3636            if (last) {
3637                // reset retry count
3638                track->mRetryCount = kMaxTrackRetriesDirect;
3639                mActiveTrack = t;
3640                mixerStatus = MIXER_TRACKS_READY;
3641            }
3642        } else {
3643            // clear effect chain input buffer if the last active track started underruns
3644            // to avoid sending previous audio buffer again to effects
3645            if (!mEffectChains.isEmpty() && last) {
3646                mEffectChains[0]->clearInputBuffer();
3647            }
3648
3649            ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
3650            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3651                    track->isStopped() || track->isPaused()) {
3652                // We have consumed all the buffers of this track.
3653                // Remove it from the list of active tracks.
3654                // TODO: implement behavior for compressed audio
3655                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3656                size_t framesWritten = mBytesWritten / mFrameSize;
3657                if (mStandby || !last ||
3658                        track->presentationComplete(framesWritten, audioHALFrames)) {
3659                    if (track->isStopped()) {
3660                        track->reset();
3661                    }
3662                    tracksToRemove->add(track);
3663                }
3664            } else {
3665                // No buffers for this track. Give it a few chances to
3666                // fill a buffer, then remove it from active list.
3667                // Only consider last track started for mixer state control
3668                if (--(track->mRetryCount) <= 0) {
3669                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3670                    tracksToRemove->add(track);
3671                    // indicate to client process that the track was disabled because of underrun;
3672                    // it will then automatically call start() when data is available
3673                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
3674                } else if (last) {
3675                    mixerStatus = MIXER_TRACKS_ENABLED;
3676                }
3677            }
3678        }
3679    }
3680
3681    // remove all the tracks that need to be...
3682    removeTracks_l(*tracksToRemove);
3683
3684    return mixerStatus;
3685}
3686
3687void AudioFlinger::DirectOutputThread::threadLoop_mix()
3688{
3689    size_t frameCount = mFrameCount;
3690    int8_t *curBuf = (int8_t *)mMixBuffer;
3691    // output audio to hardware
3692    while (frameCount) {
3693        AudioBufferProvider::Buffer buffer;
3694        buffer.frameCount = frameCount;
3695        mActiveTrack->getNextBuffer(&buffer);
3696        if (buffer.raw == NULL) {
3697            memset(curBuf, 0, frameCount * mFrameSize);
3698            break;
3699        }
3700        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3701        frameCount -= buffer.frameCount;
3702        curBuf += buffer.frameCount * mFrameSize;
3703        mActiveTrack->releaseBuffer(&buffer);
3704    }
3705    mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
3706    sleepTime = 0;
3707    standbyTime = systemTime() + standbyDelay;
3708    mActiveTrack.clear();
3709}
3710
3711void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3712{
3713    if (sleepTime == 0) {
3714        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3715            sleepTime = activeSleepTime;
3716        } else {
3717            sleepTime = idleSleepTime;
3718        }
3719    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3720        memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3721        sleepTime = 0;
3722    }
3723}
3724
3725// getTrackName_l() must be called with ThreadBase::mLock held
3726int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3727        int sessionId)
3728{
3729    return 0;
3730}
3731
3732// deleteTrackName_l() must be called with ThreadBase::mLock held
3733void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3734{
3735}
3736
3737// checkForNewParameters_l() must be called with ThreadBase::mLock held
3738bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3739{
3740    bool reconfig = false;
3741
3742    while (!mNewParameters.isEmpty()) {
3743        status_t status = NO_ERROR;
3744        String8 keyValuePair = mNewParameters[0];
3745        AudioParameter param = AudioParameter(keyValuePair);
3746        int value;
3747
3748        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3749            // do not accept frame count changes if tracks are open as the track buffer
3750            // size depends on frame count and correct behavior would not be garantied
3751            // if frame count is changed after track creation
3752            if (!mTracks.isEmpty()) {
3753                status = INVALID_OPERATION;
3754            } else {
3755                reconfig = true;
3756            }
3757        }
3758        if (status == NO_ERROR) {
3759            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3760                                                    keyValuePair.string());
3761            if (!mStandby && status == INVALID_OPERATION) {
3762                mOutput->stream->common.standby(&mOutput->stream->common);
3763                mStandby = true;
3764                mBytesWritten = 0;
3765                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3766                                                       keyValuePair.string());
3767            }
3768            if (status == NO_ERROR && reconfig) {
3769                readOutputParameters();
3770                sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3771            }
3772        }
3773
3774        mNewParameters.removeAt(0);
3775
3776        mParamStatus = status;
3777        mParamCond.signal();
3778        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3779        // already timed out waiting for the status and will never signal the condition.
3780        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3781    }
3782    return reconfig;
3783}
3784
3785uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3786{
3787    uint32_t time;
3788    if (audio_is_linear_pcm(mFormat)) {
3789        time = PlaybackThread::activeSleepTimeUs();
3790    } else {
3791        time = 10000;
3792    }
3793    return time;
3794}
3795
3796uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3797{
3798    uint32_t time;
3799    if (audio_is_linear_pcm(mFormat)) {
3800        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3801    } else {
3802        time = 10000;
3803    }
3804    return time;
3805}
3806
3807uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3808{
3809    uint32_t time;
3810    if (audio_is_linear_pcm(mFormat)) {
3811        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3812    } else {
3813        time = 10000;
3814    }
3815    return time;
3816}
3817
3818void AudioFlinger::DirectOutputThread::cacheParameters_l()
3819{
3820    PlaybackThread::cacheParameters_l();
3821
3822    // use shorter standby delay as on normal output to release
3823    // hardware resources as soon as possible
3824    if (audio_is_linear_pcm(mFormat)) {
3825        standbyDelay = microseconds(activeSleepTime*2);
3826    } else {
3827        standbyDelay = kOffloadStandbyDelayNs;
3828    }
3829}
3830
3831// ----------------------------------------------------------------------------
3832
3833AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
3834        const wp<AudioFlinger::PlaybackThread>& playbackThread)
3835    :   Thread(false /*canCallJava*/),
3836        mPlaybackThread(playbackThread),
3837        mWriteAckSequence(0),
3838        mDrainSequence(0)
3839{
3840}
3841
3842AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3843{
3844}
3845
3846void AudioFlinger::AsyncCallbackThread::onFirstRef()
3847{
3848    run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3849}
3850
3851bool AudioFlinger::AsyncCallbackThread::threadLoop()
3852{
3853    while (!exitPending()) {
3854        uint32_t writeAckSequence;
3855        uint32_t drainSequence;
3856
3857        {
3858            Mutex::Autolock _l(mLock);
3859            while (!((mWriteAckSequence & 1) ||
3860                     (mDrainSequence & 1) ||
3861                     exitPending())) {
3862                mWaitWorkCV.wait(mLock);
3863            }
3864
3865            if (exitPending()) {
3866                break;
3867            }
3868            ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3869                  mWriteAckSequence, mDrainSequence);
3870            writeAckSequence = mWriteAckSequence;
3871            mWriteAckSequence &= ~1;
3872            drainSequence = mDrainSequence;
3873            mDrainSequence &= ~1;
3874        }
3875        {
3876            sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
3877            if (playbackThread != 0) {
3878                if (writeAckSequence & 1) {
3879                    playbackThread->resetWriteBlocked(writeAckSequence >> 1);
3880                }
3881                if (drainSequence & 1) {
3882                    playbackThread->resetDraining(drainSequence >> 1);
3883                }
3884            }
3885        }
3886    }
3887    return false;
3888}
3889
3890void AudioFlinger::AsyncCallbackThread::exit()
3891{
3892    ALOGV("AsyncCallbackThread::exit");
3893    Mutex::Autolock _l(mLock);
3894    requestExit();
3895    mWaitWorkCV.broadcast();
3896}
3897
3898void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
3899{
3900    Mutex::Autolock _l(mLock);
3901    // bit 0 is cleared
3902    mWriteAckSequence = sequence << 1;
3903}
3904
3905void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3906{
3907    Mutex::Autolock _l(mLock);
3908    // ignore unexpected callbacks
3909    if (mWriteAckSequence & 2) {
3910        mWriteAckSequence |= 1;
3911        mWaitWorkCV.signal();
3912    }
3913}
3914
3915void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
3916{
3917    Mutex::Autolock _l(mLock);
3918    // bit 0 is cleared
3919    mDrainSequence = sequence << 1;
3920}
3921
3922void AudioFlinger::AsyncCallbackThread::resetDraining()
3923{
3924    Mutex::Autolock _l(mLock);
3925    // ignore unexpected callbacks
3926    if (mDrainSequence & 2) {
3927        mDrainSequence |= 1;
3928        mWaitWorkCV.signal();
3929    }
3930}
3931
3932
3933// ----------------------------------------------------------------------------
3934AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3935        AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3936    :   DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3937        mHwPaused(false),
3938        mFlushPending(false),
3939        mPausedBytesRemaining(0)
3940{
3941    //FIXME: mStandby should be set to true by ThreadBase constructor
3942    mStandby = true;
3943}
3944
3945void AudioFlinger::OffloadThread::threadLoop_exit()
3946{
3947    if (mFlushPending || mHwPaused) {
3948        // If a flush is pending or track was paused, just discard buffered data
3949        flushHw_l();
3950    } else {
3951        mMixerStatus = MIXER_DRAIN_ALL;
3952        threadLoop_drain();
3953    }
3954    if (mUseAsyncWrite) {
3955        ALOG_ASSERT(mCallbackThread != 0);
3956        mCallbackThread->exit();
3957    }
3958    PlaybackThread::threadLoop_exit();
3959}
3960
3961AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3962    Vector< sp<Track> > *tracksToRemove
3963)
3964{
3965    size_t count = mActiveTracks.size();
3966
3967    mixer_state mixerStatus = MIXER_IDLE;
3968    bool doHwPause = false;
3969    bool doHwResume = false;
3970
3971    ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
3972
3973    // find out which tracks need to be processed
3974    for (size_t i = 0; i < count; i++) {
3975        sp<Track> t = mActiveTracks[i].promote();
3976        // The track died recently
3977        if (t == 0) {
3978            continue;
3979        }
3980        Track* const track = t.get();
3981        audio_track_cblk_t* cblk = track->cblk();
3982        // Only consider last track started for volume and mixer state control.
3983        // In theory an older track could underrun and restart after the new one starts
3984        // but as we only care about the transition phase between two tracks on a
3985        // direct output, it is not a problem to ignore the underrun case.
3986        sp<Track> l = mLatestActiveTrack.promote();
3987        bool last = l.get() == track;
3988
3989        if (track->isPausing()) {
3990            track->setPaused();
3991            if (last) {
3992                if (!mHwPaused) {
3993                    doHwPause = true;
3994                    mHwPaused = true;
3995                }
3996                // If we were part way through writing the mixbuffer to
3997                // the HAL we must save this until we resume
3998                // BUG - this will be wrong if a different track is made active,
3999                // in that case we want to discard the pending data in the
4000                // mixbuffer and tell the client to present it again when the
4001                // track is resumed
4002                mPausedWriteLength = mCurrentWriteLength;
4003                mPausedBytesRemaining = mBytesRemaining;
4004                mBytesRemaining = 0;    // stop writing
4005            }
4006            tracksToRemove->add(track);
4007        } else if (track->framesReady() && track->isReady() &&
4008                !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
4009            ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
4010            if (track->mFillingUpStatus == Track::FS_FILLED) {
4011                track->mFillingUpStatus = Track::FS_ACTIVE;
4012                // make sure processVolume_l() will apply new volume even if 0
4013                mLeftVolFloat = mRightVolFloat = -1.0;
4014                if (track->mState == TrackBase::RESUMING) {
4015                    track->mState = TrackBase::ACTIVE;
4016                    if (last) {
4017                        if (mPausedBytesRemaining) {
4018                            // Need to continue write that was interrupted
4019                            mCurrentWriteLength = mPausedWriteLength;
4020                            mBytesRemaining = mPausedBytesRemaining;
4021                            mPausedBytesRemaining = 0;
4022                        }
4023                        if (mHwPaused) {
4024                            doHwResume = true;
4025                            mHwPaused = false;
4026                            // threadLoop_mix() will handle the case that we need to
4027                            // resume an interrupted write
4028                        }
4029                        // enable write to audio HAL
4030                        sleepTime = 0;
4031                    }
4032                }
4033            }
4034
4035            if (last) {
4036                sp<Track> previousTrack = mPreviousTrack.promote();
4037                if (previousTrack != 0) {
4038                    if (track != previousTrack.get()) {
4039                        // Flush any data still being written from last track
4040                        mBytesRemaining = 0;
4041                        if (mPausedBytesRemaining) {
4042                            // Last track was paused so we also need to flush saved
4043                            // mixbuffer state and invalidate track so that it will
4044                            // re-submit that unwritten data when it is next resumed
4045                            mPausedBytesRemaining = 0;
4046                            // Invalidate is a bit drastic - would be more efficient
4047                            // to have a flag to tell client that some of the
4048                            // previously written data was lost
4049                            previousTrack->invalidate();
4050                        }
4051                        // flush data already sent to the DSP if changing audio session as audio
4052                        // comes from a different source. Also invalidate previous track to force a
4053                        // seek when resuming.
4054                        if (previousTrack->sessionId() != track->sessionId()) {
4055                            previousTrack->invalidate();
4056                            mFlushPending = true;
4057                        }
4058                    }
4059                }
4060                mPreviousTrack = track;
4061                // reset retry count
4062                track->mRetryCount = kMaxTrackRetriesOffload;
4063                mActiveTrack = t;
4064                mixerStatus = MIXER_TRACKS_READY;
4065            }
4066        } else {
4067            ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
4068            if (track->isStopping_1()) {
4069                // Hardware buffer can hold a large amount of audio so we must
4070                // wait for all current track's data to drain before we say
4071                // that the track is stopped.
4072                if (mBytesRemaining == 0) {
4073                    // Only start draining when all data in mixbuffer
4074                    // has been written
4075                    ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4076                    track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
4077                    // do not drain if no data was ever sent to HAL (mStandby == true)
4078                    if (last && !mStandby) {
4079                        // do not modify drain sequence if we are already draining. This happens
4080                        // when resuming from pause after drain.
4081                        if ((mDrainSequence & 1) == 0) {
4082                            sleepTime = 0;
4083                            standbyTime = systemTime() + standbyDelay;
4084                            mixerStatus = MIXER_DRAIN_TRACK;
4085                            mDrainSequence += 2;
4086                        }
4087                        if (mHwPaused) {
4088                            // It is possible to move from PAUSED to STOPPING_1 without
4089                            // a resume so we must ensure hardware is running
4090                            doHwResume = true;
4091                            mHwPaused = false;
4092                        }
4093                    }
4094                }
4095            } else if (track->isStopping_2()) {
4096                // Drain has completed or we are in standby, signal presentation complete
4097                if (!(mDrainSequence & 1) || !last || mStandby) {
4098                    track->mState = TrackBase::STOPPED;
4099                    size_t audioHALFrames =
4100                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4101                    size_t framesWritten =
4102                            mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4103                    track->presentationComplete(framesWritten, audioHALFrames);
4104                    track->reset();
4105                    tracksToRemove->add(track);
4106                }
4107            } else {
4108                // No buffers for this track. Give it a few chances to
4109                // fill a buffer, then remove it from active list.
4110                if (--(track->mRetryCount) <= 0) {
4111                    ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4112                          track->name());
4113                    tracksToRemove->add(track);
4114                    // indicate to client process that the track was disabled because of underrun;
4115                    // it will then automatically call start() when data is available
4116                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
4117                } else if (last){
4118                    mixerStatus = MIXER_TRACKS_ENABLED;
4119                }
4120            }
4121        }
4122        // compute volume for this track
4123        processVolume_l(track, last);
4124    }
4125
4126    // make sure the pause/flush/resume sequence is executed in the right order.
4127    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4128    // before flush and then resume HW. This can happen in case of pause/flush/resume
4129    // if resume is received before pause is executed.
4130    if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
4131        mOutput->stream->pause(mOutput->stream);
4132        if (!doHwPause) {
4133            doHwResume = true;
4134        }
4135    }
4136    if (mFlushPending) {
4137        flushHw_l();
4138        mFlushPending = false;
4139    }
4140    if (!mStandby && doHwResume) {
4141        mOutput->stream->resume(mOutput->stream);
4142    }
4143
4144    // remove all the tracks that need to be...
4145    removeTracks_l(*tracksToRemove);
4146
4147    return mixerStatus;
4148}
4149
4150void AudioFlinger::OffloadThread::flushOutput_l()
4151{
4152    mFlushPending = true;
4153}
4154
4155// must be called with thread mutex locked
4156bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4157{
4158    ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4159          mWriteAckSequence, mDrainSequence);
4160    if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
4161        return true;
4162    }
4163    return false;
4164}
4165
4166// must be called with thread mutex locked
4167bool AudioFlinger::OffloadThread::shouldStandby_l()
4168{
4169    bool TrackPaused = false;
4170
4171    // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4172    // after a timeout and we will enter standby then.
4173    if (mTracks.size() > 0) {
4174        TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4175    }
4176
4177    return !mStandby && !TrackPaused;
4178}
4179
4180
4181bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4182{
4183    Mutex::Autolock _l(mLock);
4184    return waitingAsyncCallback_l();
4185}
4186
4187void AudioFlinger::OffloadThread::flushHw_l()
4188{
4189    mOutput->stream->flush(mOutput->stream);
4190    // Flush anything still waiting in the mixbuffer
4191    mCurrentWriteLength = 0;
4192    mBytesRemaining = 0;
4193    mPausedWriteLength = 0;
4194    mPausedBytesRemaining = 0;
4195    if (mUseAsyncWrite) {
4196        // discard any pending drain or write ack by incrementing sequence
4197        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4198        mDrainSequence = (mDrainSequence + 2) & ~1;
4199        ALOG_ASSERT(mCallbackThread != 0);
4200        mCallbackThread->setWriteBlocked(mWriteAckSequence);
4201        mCallbackThread->setDraining(mDrainSequence);
4202    }
4203}
4204
4205// ----------------------------------------------------------------------------
4206
4207AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4208        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4209    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4210                DUPLICATING),
4211        mWaitTimeMs(UINT_MAX)
4212{
4213    addOutputTrack(mainThread);
4214}
4215
4216AudioFlinger::DuplicatingThread::~DuplicatingThread()
4217{
4218    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4219        mOutputTracks[i]->destroy();
4220    }
4221}
4222
4223void AudioFlinger::DuplicatingThread::threadLoop_mix()
4224{
4225    // mix buffers...
4226    if (outputsReady(outputTracks)) {
4227        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4228    } else {
4229        memset(mMixBuffer, 0, mixBufferSize);
4230    }
4231    sleepTime = 0;
4232    writeFrames = mNormalFrameCount;
4233    mCurrentWriteLength = mixBufferSize;
4234    standbyTime = systemTime() + standbyDelay;
4235}
4236
4237void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4238{
4239    if (sleepTime == 0) {
4240        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4241            sleepTime = activeSleepTime;
4242        } else {
4243            sleepTime = idleSleepTime;
4244        }
4245    } else if (mBytesWritten != 0) {
4246        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4247            writeFrames = mNormalFrameCount;
4248            memset(mMixBuffer, 0, mixBufferSize);
4249        } else {
4250            // flush remaining overflow buffers in output tracks
4251            writeFrames = 0;
4252        }
4253        sleepTime = 0;
4254    }
4255}
4256
4257ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
4258{
4259    for (size_t i = 0; i < outputTracks.size(); i++) {
4260        outputTracks[i]->write(mMixBuffer, writeFrames);
4261    }
4262    mStandby = false;
4263    return (ssize_t)mixBufferSize;
4264}
4265
4266void AudioFlinger::DuplicatingThread::threadLoop_standby()
4267{
4268    // DuplicatingThread implements standby by stopping all tracks
4269    for (size_t i = 0; i < outputTracks.size(); i++) {
4270        outputTracks[i]->stop();
4271    }
4272}
4273
4274void AudioFlinger::DuplicatingThread::saveOutputTracks()
4275{
4276    outputTracks = mOutputTracks;
4277}
4278
4279void AudioFlinger::DuplicatingThread::clearOutputTracks()
4280{
4281    outputTracks.clear();
4282}
4283
4284void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4285{
4286    Mutex::Autolock _l(mLock);
4287    // FIXME explain this formula
4288    size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4289    OutputTrack *outputTrack = new OutputTrack(thread,
4290                                            this,
4291                                            mSampleRate,
4292                                            mFormat,
4293                                            mChannelMask,
4294                                            frameCount,
4295                                            IPCThreadState::self()->getCallingUid());
4296    if (outputTrack->cblk() != NULL) {
4297        thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4298        mOutputTracks.add(outputTrack);
4299        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4300        updateWaitTime_l();
4301    }
4302}
4303
4304void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4305{
4306    Mutex::Autolock _l(mLock);
4307    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4308        if (mOutputTracks[i]->thread() == thread) {
4309            mOutputTracks[i]->destroy();
4310            mOutputTracks.removeAt(i);
4311            updateWaitTime_l();
4312            return;
4313        }
4314    }
4315    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4316}
4317
4318// caller must hold mLock
4319void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4320{
4321    mWaitTimeMs = UINT_MAX;
4322    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4323        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4324        if (strong != 0) {
4325            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4326            if (waitTimeMs < mWaitTimeMs) {
4327                mWaitTimeMs = waitTimeMs;
4328            }
4329        }
4330    }
4331}
4332
4333
4334bool AudioFlinger::DuplicatingThread::outputsReady(
4335        const SortedVector< sp<OutputTrack> > &outputTracks)
4336{
4337    for (size_t i = 0; i < outputTracks.size(); i++) {
4338        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4339        if (thread == 0) {
4340            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4341                    outputTracks[i].get());
4342            return false;
4343        }
4344        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4345        // see note at standby() declaration
4346        if (playbackThread->standby() && !playbackThread->isSuspended()) {
4347            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4348                    thread.get());
4349            return false;
4350        }
4351    }
4352    return true;
4353}
4354
4355uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4356{
4357    return (mWaitTimeMs * 1000) / 2;
4358}
4359
4360void AudioFlinger::DuplicatingThread::cacheParameters_l()
4361{
4362    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4363    updateWaitTime_l();
4364
4365    MixerThread::cacheParameters_l();
4366}
4367
4368// ----------------------------------------------------------------------------
4369//      Record
4370// ----------------------------------------------------------------------------
4371
4372AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4373                                         AudioStreamIn *input,
4374                                         uint32_t sampleRate,
4375                                         audio_channel_mask_t channelMask,
4376                                         audio_io_handle_t id,
4377                                         audio_devices_t outDevice,
4378                                         audio_devices_t inDevice
4379#ifdef TEE_SINK
4380                                         , const sp<NBAIO_Sink>& teeSink
4381#endif
4382                                         ) :
4383    ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
4384    mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4385    // mRsmpInIndex and mBufferSize set by readInputParameters()
4386    mReqChannelCount(popcount(channelMask)),
4387    mReqSampleRate(sampleRate)
4388    // mBytesRead is only meaningful while active, and so is cleared in start()
4389    // (but might be better to also clear here for dump?)
4390#ifdef TEE_SINK
4391    , mTeeSink(teeSink)
4392#endif
4393{
4394    snprintf(mName, kNameLength, "AudioIn_%X", id);
4395
4396    readInputParameters();
4397}
4398
4399
4400AudioFlinger::RecordThread::~RecordThread()
4401{
4402    delete[] mRsmpInBuffer;
4403    delete mResampler;
4404    delete[] mRsmpOutBuffer;
4405}
4406
4407void AudioFlinger::RecordThread::onFirstRef()
4408{
4409    run(mName, PRIORITY_URGENT_AUDIO);
4410}
4411
4412status_t AudioFlinger::RecordThread::readyToRun()
4413{
4414    status_t status = initCheck();
4415    ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4416    return status;
4417}
4418
4419bool AudioFlinger::RecordThread::threadLoop()
4420{
4421    AudioBufferProvider::Buffer buffer;
4422    sp<RecordTrack> activeTrack;
4423    Vector< sp<EffectChain> > effectChains;
4424
4425    nsecs_t lastWarning = 0;
4426
4427    inputStandBy();
4428    {
4429        Mutex::Autolock _l(mLock);
4430        activeTrack = mActiveTrack;
4431        acquireWakeLock_l(activeTrack != 0 ? activeTrack->uid() : -1);
4432    }
4433
4434    // used to verify we've read at least once before evaluating how many bytes were read
4435    bool readOnce = false;
4436
4437    // start recording
4438    while (!exitPending()) {
4439
4440        processConfigEvents();
4441
4442        { // scope for mLock
4443            Mutex::Autolock _l(mLock);
4444            checkForNewParameters_l();
4445            if (mActiveTrack != 0 && activeTrack != mActiveTrack) {
4446                SortedVector<int> tmp;
4447                tmp.add(mActiveTrack->uid());
4448                updateWakeLockUids_l(tmp);
4449            }
4450            activeTrack = mActiveTrack;
4451            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4452                standby();
4453
4454                if (exitPending()) {
4455                    break;
4456                }
4457
4458                releaseWakeLock_l();
4459                ALOGV("RecordThread: loop stopping");
4460                // go to sleep
4461                mWaitWorkCV.wait(mLock);
4462                ALOGV("RecordThread: loop starting");
4463                acquireWakeLock_l(mActiveTrack != 0 ? mActiveTrack->uid() : -1);
4464                continue;
4465            }
4466            if (mActiveTrack != 0) {
4467                if (mActiveTrack->isTerminated()) {
4468                    removeTrack_l(mActiveTrack);
4469                    mActiveTrack.clear();
4470                } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4471                    standby();
4472                    mActiveTrack.clear();
4473                    mStartStopCond.broadcast();
4474                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4475                    if (mReqChannelCount != mActiveTrack->channelCount()) {
4476                        mActiveTrack.clear();
4477                        mStartStopCond.broadcast();
4478                    } else if (readOnce) {
4479                        // record start succeeds only if first read from audio input
4480                        // succeeds
4481                        if (mBytesRead >= 0) {
4482                            mActiveTrack->mState = TrackBase::ACTIVE;
4483                        } else {
4484                            mActiveTrack.clear();
4485                        }
4486                        mStartStopCond.broadcast();
4487                    }
4488                    mStandby = false;
4489                }
4490            }
4491
4492            lockEffectChains_l(effectChains);
4493        }
4494
4495        if (mActiveTrack != 0) {
4496            if (mActiveTrack->mState != TrackBase::ACTIVE &&
4497                mActiveTrack->mState != TrackBase::RESUMING) {
4498                unlockEffectChains(effectChains);
4499                usleep(kRecordThreadSleepUs);
4500                continue;
4501            }
4502            for (size_t i = 0; i < effectChains.size(); i ++) {
4503                effectChains[i]->process_l();
4504            }
4505
4506            buffer.frameCount = mFrameCount;
4507            status_t status = mActiveTrack->getNextBuffer(&buffer);
4508            if (status == NO_ERROR) {
4509                readOnce = true;
4510                size_t framesOut = buffer.frameCount;
4511                if (mResampler == NULL) {
4512                    // no resampling
4513                    while (framesOut) {
4514                        size_t framesIn = mFrameCount - mRsmpInIndex;
4515                        if (framesIn) {
4516                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4517                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4518                                    mActiveTrack->mFrameSize;
4519                            if (framesIn > framesOut)
4520                                framesIn = framesOut;
4521                            mRsmpInIndex += framesIn;
4522                            framesOut -= framesIn;
4523                            if (mChannelCount == mReqChannelCount) {
4524                                memcpy(dst, src, framesIn * mFrameSize);
4525                            } else {
4526                                if (mChannelCount == 1) {
4527                                    upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4528                                            (int16_t *)src, framesIn);
4529                                } else {
4530                                    downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4531                                            (int16_t *)src, framesIn);
4532                                }
4533                            }
4534                        }
4535                        if (framesOut && mFrameCount == mRsmpInIndex) {
4536                            void *readInto;
4537                            if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4538                                readInto = buffer.raw;
4539                                framesOut = 0;
4540                            } else {
4541                                readInto = mRsmpInBuffer;
4542                                mRsmpInIndex = 0;
4543                            }
4544                            mBytesRead = mInput->stream->read(mInput->stream, readInto,
4545                                    mBufferSize);
4546                            if (mBytesRead <= 0) {
4547                                if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
4548                                {
4549                                    ALOGE("Error reading audio input");
4550                                    // Force input into standby so that it tries to
4551                                    // recover at next read attempt
4552                                    inputStandBy();
4553                                    usleep(kRecordThreadSleepUs);
4554                                }
4555                                mRsmpInIndex = mFrameCount;
4556                                framesOut = 0;
4557                                buffer.frameCount = 0;
4558                            }
4559#ifdef TEE_SINK
4560                            else if (mTeeSink != 0) {
4561                                (void) mTeeSink->write(readInto,
4562                                        mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4563                            }
4564#endif
4565                        }
4566                    }
4567                } else {
4568                    // resampling
4569
4570                    // resampler accumulates, but we only have one source track
4571                    memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4572                    // alter output frame count as if we were expecting stereo samples
4573                    if (mChannelCount == 1 && mReqChannelCount == 1) {
4574                        framesOut >>= 1;
4575                    }
4576                    mResampler->resample(mRsmpOutBuffer, framesOut,
4577                            this /* AudioBufferProvider* */);
4578                    // ditherAndClamp() works as long as all buffers returned by
4579                    // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
4580                    if (mChannelCount == 2 && mReqChannelCount == 1) {
4581                        // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4582                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4583                        // the resampler always outputs stereo samples:
4584                        // do post stereo to mono conversion
4585                        downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4586                                framesOut);
4587                    } else {
4588                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4589                    }
4590                    // now done with mRsmpOutBuffer
4591
4592                }
4593                if (mFramestoDrop == 0) {
4594                    mActiveTrack->releaseBuffer(&buffer);
4595                } else {
4596                    if (mFramestoDrop > 0) {
4597                        mFramestoDrop -= buffer.frameCount;
4598                        if (mFramestoDrop <= 0) {
4599                            clearSyncStartEvent();
4600                        }
4601                    } else {
4602                        mFramestoDrop += buffer.frameCount;
4603                        if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4604                                mSyncStartEvent->isCancelled()) {
4605                            ALOGW("Synced record %s, session %d, trigger session %d",
4606                                  (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4607                                  mActiveTrack->sessionId(),
4608                                  (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4609                            clearSyncStartEvent();
4610                        }
4611                    }
4612                }
4613                mActiveTrack->clearOverflow();
4614            }
4615            // client isn't retrieving buffers fast enough
4616            else {
4617                if (!mActiveTrack->setOverflow()) {
4618                    nsecs_t now = systemTime();
4619                    if ((now - lastWarning) > kWarningThrottleNs) {
4620                        ALOGW("RecordThread: buffer overflow");
4621                        lastWarning = now;
4622                    }
4623                }
4624                // Release the processor for a while before asking for a new buffer.
4625                // This will give the application more chance to read from the buffer and
4626                // clear the overflow.
4627                usleep(kRecordThreadSleepUs);
4628            }
4629        }
4630        // enable changes in effect chain
4631        unlockEffectChains(effectChains);
4632        effectChains.clear();
4633    }
4634
4635    standby();
4636
4637    {
4638        Mutex::Autolock _l(mLock);
4639        for (size_t i = 0; i < mTracks.size(); i++) {
4640            sp<RecordTrack> track = mTracks[i];
4641            track->invalidate();
4642        }
4643        mActiveTrack.clear();
4644        mStartStopCond.broadcast();
4645    }
4646
4647    releaseWakeLock();
4648
4649    ALOGV("RecordThread %p exiting", this);
4650    return false;
4651}
4652
4653void AudioFlinger::RecordThread::standby()
4654{
4655    if (!mStandby) {
4656        inputStandBy();
4657        mStandby = true;
4658    }
4659}
4660
4661void AudioFlinger::RecordThread::inputStandBy()
4662{
4663    mInput->stream->common.standby(&mInput->stream->common);
4664}
4665
4666sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
4667        const sp<AudioFlinger::Client>& client,
4668        uint32_t sampleRate,
4669        audio_format_t format,
4670        audio_channel_mask_t channelMask,
4671        size_t frameCount,
4672        int sessionId,
4673        int uid,
4674        IAudioFlinger::track_flags_t *flags,
4675        pid_t tid,
4676        status_t *status)
4677{
4678    sp<RecordTrack> track;
4679    status_t lStatus;
4680
4681    lStatus = initCheck();
4682    if (lStatus != NO_ERROR) {
4683        ALOGE("createRecordTrack_l() audio driver not initialized");
4684        goto Exit;
4685    }
4686    // client expresses a preference for FAST, but we get the final say
4687    if (*flags & IAudioFlinger::TRACK_FAST) {
4688      if (
4689            // use case: callback handler and frame count is default or at least as large as HAL
4690            (
4691                (tid != -1) &&
4692                ((frameCount == 0) ||
4693                (frameCount >= mFrameCount))
4694            ) &&
4695            // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4696            // mono or stereo
4697            ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4698              (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4699            // hardware sample rate
4700            (sampleRate == mSampleRate) &&
4701            // record thread has an associated fast recorder
4702            hasFastRecorder()
4703            // FIXME test that RecordThread for this fast track has a capable output HAL
4704            // FIXME add a permission test also?
4705        ) {
4706        // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4707        if (frameCount == 0) {
4708            frameCount = mFrameCount * kFastTrackMultiplier;
4709        }
4710        ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4711                frameCount, mFrameCount);
4712      } else {
4713        ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4714                "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4715                "hasFastRecorder=%d tid=%d",
4716                frameCount, mFrameCount, format,
4717                audio_is_linear_pcm(format),
4718                channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4719        *flags &= ~IAudioFlinger::TRACK_FAST;
4720        // For compatibility with AudioRecord calculation, buffer depth is forced
4721        // to be at least 2 x the record thread frame count and cover audio hardware latency.
4722        // This is probably too conservative, but legacy application code may depend on it.
4723        // If you change this calculation, also review the start threshold which is related.
4724        uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4725        size_t mNormalFrameCount = 2048; // FIXME
4726        uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4727        if (minBufCount < 2) {
4728            minBufCount = 2;
4729        }
4730        size_t minFrameCount = mNormalFrameCount * minBufCount;
4731        if (frameCount < minFrameCount) {
4732            frameCount = minFrameCount;
4733        }
4734      }
4735    }
4736
4737    // FIXME use flags and tid similar to createTrack_l()
4738
4739    { // scope for mLock
4740        Mutex::Autolock _l(mLock);
4741
4742        track = new RecordTrack(this, client, sampleRate,
4743                      format, channelMask, frameCount, sessionId, uid);
4744
4745        if (track->getCblk() == 0) {
4746            ALOGE("createRecordTrack_l() no control block");
4747            lStatus = NO_MEMORY;
4748            // track must be cleared from the caller as the caller has the AF lock
4749            goto Exit;
4750        }
4751        mTracks.add(track);
4752
4753        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4754        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4755                        mAudioFlinger->btNrecIsOff();
4756        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4757        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
4758
4759        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4760            pid_t callingPid = IPCThreadState::self()->getCallingPid();
4761            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4762            // so ask activity manager to do this on our behalf
4763            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4764        }
4765    }
4766    lStatus = NO_ERROR;
4767
4768Exit:
4769    if (status) {
4770        *status = lStatus;
4771    }
4772    return track;
4773}
4774
4775status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4776                                           AudioSystem::sync_event_t event,
4777                                           int triggerSession)
4778{
4779    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4780    sp<ThreadBase> strongMe = this;
4781    status_t status = NO_ERROR;
4782
4783    if (event == AudioSystem::SYNC_EVENT_NONE) {
4784        clearSyncStartEvent();
4785    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4786        mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4787                                       triggerSession,
4788                                       recordTrack->sessionId(),
4789                                       syncStartEventCallback,
4790                                       this);
4791        // Sync event can be cancelled by the trigger session if the track is not in a
4792        // compatible state in which case we start record immediately
4793        if (mSyncStartEvent->isCancelled()) {
4794            clearSyncStartEvent();
4795        } else {
4796            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4797            mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4798        }
4799    }
4800
4801    {
4802        AutoMutex lock(mLock);
4803        if (mActiveTrack != 0) {
4804            if (recordTrack != mActiveTrack.get()) {
4805                status = -EBUSY;
4806            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4807                mActiveTrack->mState = TrackBase::ACTIVE;
4808            }
4809            return status;
4810        }
4811
4812        recordTrack->mState = TrackBase::IDLE;
4813        mActiveTrack = recordTrack;
4814        mLock.unlock();
4815        status_t status = AudioSystem::startInput(mId);
4816        mLock.lock();
4817        if (status != NO_ERROR) {
4818            mActiveTrack.clear();
4819            clearSyncStartEvent();
4820            return status;
4821        }
4822        mRsmpInIndex = mFrameCount;
4823        mBytesRead = 0;
4824        if (mResampler != NULL) {
4825            mResampler->reset();
4826        }
4827        mActiveTrack->mState = TrackBase::RESUMING;
4828        // signal thread to start
4829        ALOGV("Signal record thread");
4830        mWaitWorkCV.broadcast();
4831        // do not wait for mStartStopCond if exiting
4832        if (exitPending()) {
4833            mActiveTrack.clear();
4834            status = INVALID_OPERATION;
4835            goto startError;
4836        }
4837        mStartStopCond.wait(mLock);
4838        if (mActiveTrack == 0) {
4839            ALOGV("Record failed to start");
4840            status = BAD_VALUE;
4841            goto startError;
4842        }
4843        ALOGV("Record started OK");
4844        return status;
4845    }
4846
4847startError:
4848    AudioSystem::stopInput(mId);
4849    clearSyncStartEvent();
4850    return status;
4851}
4852
4853void AudioFlinger::RecordThread::clearSyncStartEvent()
4854{
4855    if (mSyncStartEvent != 0) {
4856        mSyncStartEvent->cancel();
4857    }
4858    mSyncStartEvent.clear();
4859    mFramestoDrop = 0;
4860}
4861
4862void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4863{
4864    sp<SyncEvent> strongEvent = event.promote();
4865
4866    if (strongEvent != 0) {
4867        RecordThread *me = (RecordThread *)strongEvent->cookie();
4868        me->handleSyncStartEvent(strongEvent);
4869    }
4870}
4871
4872void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4873{
4874    if (event == mSyncStartEvent) {
4875        // TODO: use actual buffer filling status instead of 2 buffers when info is available
4876        // from audio HAL
4877        mFramestoDrop = mFrameCount * 2;
4878    }
4879}
4880
4881bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4882    ALOGV("RecordThread::stop");
4883    AutoMutex _l(mLock);
4884    if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4885        return false;
4886    }
4887    recordTrack->mState = TrackBase::PAUSING;
4888    // do not wait for mStartStopCond if exiting
4889    if (exitPending()) {
4890        return true;
4891    }
4892    mStartStopCond.wait(mLock);
4893    // if we have been restarted, recordTrack == mActiveTrack.get() here
4894    if (exitPending() || recordTrack != mActiveTrack.get()) {
4895        ALOGV("Record stopped OK");
4896        return true;
4897    }
4898    return false;
4899}
4900
4901bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4902{
4903    return false;
4904}
4905
4906status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4907{
4908#if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
4909    if (!isValidSyncEvent(event)) {
4910        return BAD_VALUE;
4911    }
4912
4913    int eventSession = event->triggerSession();
4914    status_t ret = NAME_NOT_FOUND;
4915
4916    Mutex::Autolock _l(mLock);
4917
4918    for (size_t i = 0; i < mTracks.size(); i++) {
4919        sp<RecordTrack> track = mTracks[i];
4920        if (eventSession == track->sessionId()) {
4921            (void) track->setSyncEvent(event);
4922            ret = NO_ERROR;
4923        }
4924    }
4925    return ret;
4926#else
4927    return BAD_VALUE;
4928#endif
4929}
4930
4931// destroyTrack_l() must be called with ThreadBase::mLock held
4932void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4933{
4934    track->terminate();
4935    track->mState = TrackBase::STOPPED;
4936    // active tracks are removed by threadLoop()
4937    if (mActiveTrack != track) {
4938        removeTrack_l(track);
4939    }
4940}
4941
4942void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4943{
4944    mTracks.remove(track);
4945    // need anything related to effects here?
4946}
4947
4948void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4949{
4950    dumpInternals(fd, args);
4951    dumpTracks(fd, args);
4952    dumpEffectChains(fd, args);
4953}
4954
4955void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4956{
4957    const size_t SIZE = 256;
4958    char buffer[SIZE];
4959    String8 result;
4960
4961    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4962    result.append(buffer);
4963
4964    if (mActiveTrack != 0) {
4965        snprintf(buffer, SIZE, "In index: %zu\n", mRsmpInIndex);
4966        result.append(buffer);
4967        snprintf(buffer, SIZE, "Buffer size: %zu bytes\n", mBufferSize);
4968        result.append(buffer);
4969        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4970        result.append(buffer);
4971        snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4972        result.append(buffer);
4973        snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4974        result.append(buffer);
4975    } else {
4976        result.append("No active record client\n");
4977    }
4978
4979    write(fd, result.string(), result.size());
4980
4981    dumpBase(fd, args);
4982}
4983
4984void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4985{
4986    const size_t SIZE = 256;
4987    char buffer[SIZE];
4988    String8 result;
4989
4990    snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4991    result.append(buffer);
4992    RecordTrack::appendDumpHeader(result);
4993    for (size_t i = 0; i < mTracks.size(); ++i) {
4994        sp<RecordTrack> track = mTracks[i];
4995        if (track != 0) {
4996            track->dump(buffer, SIZE);
4997            result.append(buffer);
4998        }
4999    }
5000
5001    if (mActiveTrack != 0) {
5002        snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
5003        result.append(buffer);
5004        RecordTrack::appendDumpHeader(result);
5005        mActiveTrack->dump(buffer, SIZE);
5006        result.append(buffer);
5007
5008    }
5009    write(fd, result.string(), result.size());
5010}
5011
5012// AudioBufferProvider interface
5013status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5014{
5015    size_t framesReq = buffer->frameCount;
5016    size_t framesReady = mFrameCount - mRsmpInIndex;
5017    int channelCount;
5018
5019    if (framesReady == 0) {
5020        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
5021        if (mBytesRead <= 0) {
5022            if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
5023                ALOGE("RecordThread::getNextBuffer() Error reading audio input");
5024                // Force input into standby so that it tries to
5025                // recover at next read attempt
5026                inputStandBy();
5027                usleep(kRecordThreadSleepUs);
5028            }
5029            buffer->raw = NULL;
5030            buffer->frameCount = 0;
5031            return NOT_ENOUGH_DATA;
5032        }
5033        mRsmpInIndex = 0;
5034        framesReady = mFrameCount;
5035    }
5036
5037    if (framesReq > framesReady) {
5038        framesReq = framesReady;
5039    }
5040
5041    if (mChannelCount == 1 && mReqChannelCount == 2) {
5042        channelCount = 1;
5043    } else {
5044        channelCount = 2;
5045    }
5046    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5047    buffer->frameCount = framesReq;
5048    return NO_ERROR;
5049}
5050
5051// AudioBufferProvider interface
5052void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5053{
5054    mRsmpInIndex += buffer->frameCount;
5055    buffer->frameCount = 0;
5056}
5057
5058bool AudioFlinger::RecordThread::checkForNewParameters_l()
5059{
5060    bool reconfig = false;
5061
5062    while (!mNewParameters.isEmpty()) {
5063        status_t status = NO_ERROR;
5064        String8 keyValuePair = mNewParameters[0];
5065        AudioParameter param = AudioParameter(keyValuePair);
5066        int value;
5067        audio_format_t reqFormat = mFormat;
5068        uint32_t reqSamplingRate = mReqSampleRate;
5069        uint32_t reqChannelCount = mReqChannelCount;
5070
5071        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5072            reqSamplingRate = value;
5073            reconfig = true;
5074        }
5075        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5076            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5077                status = BAD_VALUE;
5078            } else {
5079                reqFormat = (audio_format_t) value;
5080                reconfig = true;
5081            }
5082        }
5083        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5084            reqChannelCount = popcount(value);
5085            reconfig = true;
5086        }
5087        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5088            // do not accept frame count changes if tracks are open as the track buffer
5089            // size depends on frame count and correct behavior would not be guaranteed
5090            // if frame count is changed after track creation
5091            if (mActiveTrack != 0) {
5092                status = INVALID_OPERATION;
5093            } else {
5094                reconfig = true;
5095            }
5096        }
5097        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5098            // forward device change to effects that have requested to be
5099            // aware of attached audio device.
5100            for (size_t i = 0; i < mEffectChains.size(); i++) {
5101                mEffectChains[i]->setDevice_l(value);
5102            }
5103
5104            // store input device and output device but do not forward output device to audio HAL.
5105            // Note that status is ignored by the caller for output device
5106            // (see AudioFlinger::setParameters()
5107            if (audio_is_output_devices(value)) {
5108                mOutDevice = value;
5109                status = BAD_VALUE;
5110            } else {
5111                mInDevice = value;
5112                // disable AEC and NS if the device is a BT SCO headset supporting those
5113                // pre processings
5114                if (mTracks.size() > 0) {
5115                    bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5116                                        mAudioFlinger->btNrecIsOff();
5117                    for (size_t i = 0; i < mTracks.size(); i++) {
5118                        sp<RecordTrack> track = mTracks[i];
5119                        setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5120                        setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5121                    }
5122                }
5123            }
5124        }
5125        if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5126                mAudioSource != (audio_source_t)value) {
5127            // forward device change to effects that have requested to be
5128            // aware of attached audio device.
5129            for (size_t i = 0; i < mEffectChains.size(); i++) {
5130                mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5131            }
5132            mAudioSource = (audio_source_t)value;
5133        }
5134        if (status == NO_ERROR) {
5135            status = mInput->stream->common.set_parameters(&mInput->stream->common,
5136                    keyValuePair.string());
5137            if (status == INVALID_OPERATION) {
5138                inputStandBy();
5139                status = mInput->stream->common.set_parameters(&mInput->stream->common,
5140                        keyValuePair.string());
5141            }
5142            if (reconfig) {
5143                if (status == BAD_VALUE &&
5144                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5145                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5146                    (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5147                            <= (2 * reqSamplingRate)) &&
5148                    popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5149                            <= FCC_2 &&
5150                    (reqChannelCount <= FCC_2)) {
5151                    status = NO_ERROR;
5152                }
5153                if (status == NO_ERROR) {
5154                    readInputParameters();
5155                    sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5156                }
5157            }
5158        }
5159
5160        mNewParameters.removeAt(0);
5161
5162        mParamStatus = status;
5163        mParamCond.signal();
5164        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5165        // already timed out waiting for the status and will never signal the condition.
5166        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5167    }
5168    return reconfig;
5169}
5170
5171String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5172{
5173    Mutex::Autolock _l(mLock);
5174    if (initCheck() != NO_ERROR) {
5175        return String8();
5176    }
5177
5178    char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5179    const String8 out_s8(s);
5180    free(s);
5181    return out_s8;
5182}
5183
5184void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5185    AudioSystem::OutputDescriptor desc;
5186    void *param2 = NULL;
5187
5188    switch (event) {
5189    case AudioSystem::INPUT_OPENED:
5190    case AudioSystem::INPUT_CONFIG_CHANGED:
5191        desc.channelMask = mChannelMask;
5192        desc.samplingRate = mSampleRate;
5193        desc.format = mFormat;
5194        desc.frameCount = mFrameCount;
5195        desc.latency = 0;
5196        param2 = &desc;
5197        break;
5198
5199    case AudioSystem::INPUT_CLOSED:
5200    default:
5201        break;
5202    }
5203    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5204}
5205
5206void AudioFlinger::RecordThread::readInputParameters()
5207{
5208    delete[] mRsmpInBuffer;
5209    // mRsmpInBuffer is always assigned a new[] below
5210    delete[] mRsmpOutBuffer;
5211    mRsmpOutBuffer = NULL;
5212    delete mResampler;
5213    mResampler = NULL;
5214
5215    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5216    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5217    mChannelCount = popcount(mChannelMask);
5218    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
5219    if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5220        ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5221    }
5222    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
5223    mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5224    mFrameCount = mBufferSize / mFrameSize;
5225    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5226
5227    if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
5228    {
5229        int channelCount;
5230        // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5231        // stereo to mono post process as the resampler always outputs stereo.
5232        if (mChannelCount == 1 && mReqChannelCount == 2) {
5233            channelCount = 1;
5234        } else {
5235            channelCount = 2;
5236        }
5237        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5238        mResampler->setSampleRate(mSampleRate);
5239        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5240        mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
5241
5242        // optmization: if mono to mono, alter input frame count as if we were inputing
5243        // stereo samples
5244        if (mChannelCount == 1 && mReqChannelCount == 1) {
5245            mFrameCount >>= 1;
5246        }
5247
5248    }
5249    mRsmpInIndex = mFrameCount;
5250}
5251
5252unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5253{
5254    Mutex::Autolock _l(mLock);
5255    if (initCheck() != NO_ERROR) {
5256        return 0;
5257    }
5258
5259    return mInput->stream->get_input_frames_lost(mInput->stream);
5260}
5261
5262uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5263{
5264    Mutex::Autolock _l(mLock);
5265    uint32_t result = 0;
5266    if (getEffectChain_l(sessionId) != 0) {
5267        result = EFFECT_SESSION;
5268    }
5269
5270    for (size_t i = 0; i < mTracks.size(); ++i) {
5271        if (sessionId == mTracks[i]->sessionId()) {
5272            result |= TRACK_SESSION;
5273            break;
5274        }
5275    }
5276
5277    return result;
5278}
5279
5280KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5281{
5282    KeyedVector<int, bool> ids;
5283    Mutex::Autolock _l(mLock);
5284    for (size_t j = 0; j < mTracks.size(); ++j) {
5285        sp<RecordThread::RecordTrack> track = mTracks[j];
5286        int sessionId = track->sessionId();
5287        if (ids.indexOfKey(sessionId) < 0) {
5288            ids.add(sessionId, true);
5289        }
5290    }
5291    return ids;
5292}
5293
5294AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5295{
5296    Mutex::Autolock _l(mLock);
5297    AudioStreamIn *input = mInput;
5298    mInput = NULL;
5299    return input;
5300}
5301
5302// this method must always be called either with ThreadBase mLock held or inside the thread loop
5303audio_stream_t* AudioFlinger::RecordThread::stream() const
5304{
5305    if (mInput == NULL) {
5306        return NULL;
5307    }
5308    return &mInput->stream->common;
5309}
5310
5311status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5312{
5313    // only one chain per input thread
5314    if (mEffectChains.size() != 0) {
5315        return INVALID_OPERATION;
5316    }
5317    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5318
5319    chain->setInBuffer(NULL);
5320    chain->setOutBuffer(NULL);
5321
5322    checkSuspendOnAddEffectChain_l(chain);
5323
5324    mEffectChains.add(chain);
5325
5326    return NO_ERROR;
5327}
5328
5329size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5330{
5331    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5332    ALOGW_IF(mEffectChains.size() != 1,
5333            "removeEffectChain_l() %p invalid chain size %d on thread %p",
5334            chain.get(), mEffectChains.size(), this);
5335    if (mEffectChains.size() == 1) {
5336        mEffectChains.removeAt(0);
5337    }
5338    return 0;
5339}
5340
5341}; // namespace android
5342