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