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