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