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