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