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