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