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