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