Threads.cpp revision 6d07d9bd2e0549ca2682ad9e94118feee1f733f6
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                // make sure processVolume_l() will apply new volume even if 0
3524                mLeftVolFloat = mRightVolFloat = -1.0;
3525                if (track->mState == TrackBase::RESUMING) {
3526                    track->mState = TrackBase::ACTIVE;
3527                }
3528            }
3529
3530            // compute volume for this track
3531            processVolume_l(track, last);
3532            if (last) {
3533                // reset retry count
3534                track->mRetryCount = kMaxTrackRetriesDirect;
3535                mActiveTrack = t;
3536                mixerStatus = MIXER_TRACKS_READY;
3537            }
3538        } else {
3539            // clear effect chain input buffer if the last active track started underruns
3540            // to avoid sending previous audio buffer again to effects
3541            if (!mEffectChains.isEmpty() && (i == (count -1))) {
3542                mEffectChains[0]->clearInputBuffer();
3543            }
3544
3545            ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
3546            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3547                    track->isStopped() || track->isPaused()) {
3548                // We have consumed all the buffers of this track.
3549                // Remove it from the list of active tracks.
3550                // TODO: implement behavior for compressed audio
3551                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3552                size_t framesWritten = mBytesWritten / mFrameSize;
3553                if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3554                    if (track->isStopped()) {
3555                        track->reset();
3556                    }
3557                    tracksToRemove->add(track);
3558                }
3559            } else {
3560                // No buffers for this track. Give it a few chances to
3561                // fill a buffer, then remove it from active list.
3562                // Only consider last track started for mixer state control
3563                if (--(track->mRetryCount) <= 0) {
3564                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3565                    tracksToRemove->add(track);
3566                } else if (last) {
3567                    mixerStatus = MIXER_TRACKS_ENABLED;
3568                }
3569            }
3570        }
3571    }
3572
3573    // remove all the tracks that need to be...
3574    removeTracks_l(*tracksToRemove);
3575
3576    return mixerStatus;
3577}
3578
3579void AudioFlinger::DirectOutputThread::threadLoop_mix()
3580{
3581    size_t frameCount = mFrameCount;
3582    int8_t *curBuf = (int8_t *)mMixBuffer;
3583    // output audio to hardware
3584    while (frameCount) {
3585        AudioBufferProvider::Buffer buffer;
3586        buffer.frameCount = frameCount;
3587        mActiveTrack->getNextBuffer(&buffer);
3588        if (buffer.raw == NULL) {
3589            memset(curBuf, 0, frameCount * mFrameSize);
3590            break;
3591        }
3592        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3593        frameCount -= buffer.frameCount;
3594        curBuf += buffer.frameCount * mFrameSize;
3595        mActiveTrack->releaseBuffer(&buffer);
3596    }
3597    mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer;
3598    sleepTime = 0;
3599    standbyTime = systemTime() + standbyDelay;
3600    mActiveTrack.clear();
3601}
3602
3603void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3604{
3605    if (sleepTime == 0) {
3606        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3607            sleepTime = activeSleepTime;
3608        } else {
3609            sleepTime = idleSleepTime;
3610        }
3611    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3612        memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3613        sleepTime = 0;
3614    }
3615}
3616
3617// getTrackName_l() must be called with ThreadBase::mLock held
3618int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3619        int sessionId)
3620{
3621    return 0;
3622}
3623
3624// deleteTrackName_l() must be called with ThreadBase::mLock held
3625void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3626{
3627}
3628
3629// checkForNewParameters_l() must be called with ThreadBase::mLock held
3630bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3631{
3632    bool reconfig = false;
3633
3634    while (!mNewParameters.isEmpty()) {
3635        status_t status = NO_ERROR;
3636        String8 keyValuePair = mNewParameters[0];
3637        AudioParameter param = AudioParameter(keyValuePair);
3638        int value;
3639
3640        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3641            // do not accept frame count changes if tracks are open as the track buffer
3642            // size depends on frame count and correct behavior would not be garantied
3643            // if frame count is changed after track creation
3644            if (!mTracks.isEmpty()) {
3645                status = INVALID_OPERATION;
3646            } else {
3647                reconfig = true;
3648            }
3649        }
3650        if (status == NO_ERROR) {
3651            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3652                                                    keyValuePair.string());
3653            if (!mStandby && status == INVALID_OPERATION) {
3654                mOutput->stream->common.standby(&mOutput->stream->common);
3655                mStandby = true;
3656                mBytesWritten = 0;
3657                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3658                                                       keyValuePair.string());
3659            }
3660            if (status == NO_ERROR && reconfig) {
3661                readOutputParameters();
3662                sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3663            }
3664        }
3665
3666        mNewParameters.removeAt(0);
3667
3668        mParamStatus = status;
3669        mParamCond.signal();
3670        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3671        // already timed out waiting for the status and will never signal the condition.
3672        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3673    }
3674    return reconfig;
3675}
3676
3677uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3678{
3679    uint32_t time;
3680    if (audio_is_linear_pcm(mFormat)) {
3681        time = PlaybackThread::activeSleepTimeUs();
3682    } else {
3683        time = 10000;
3684    }
3685    return time;
3686}
3687
3688uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3689{
3690    uint32_t time;
3691    if (audio_is_linear_pcm(mFormat)) {
3692        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3693    } else {
3694        time = 10000;
3695    }
3696    return time;
3697}
3698
3699uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3700{
3701    uint32_t time;
3702    if (audio_is_linear_pcm(mFormat)) {
3703        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3704    } else {
3705        time = 10000;
3706    }
3707    return time;
3708}
3709
3710void AudioFlinger::DirectOutputThread::cacheParameters_l()
3711{
3712    PlaybackThread::cacheParameters_l();
3713
3714    // use shorter standby delay as on normal output to release
3715    // hardware resources as soon as possible
3716    if (audio_is_linear_pcm(mFormat)) {
3717        standbyDelay = microseconds(activeSleepTime*2);
3718    } else {
3719        standbyDelay = kOffloadStandbyDelayNs;
3720    }
3721}
3722
3723// ----------------------------------------------------------------------------
3724
3725AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
3726        const sp<AudioFlinger::OffloadThread>& offloadThread)
3727    :   Thread(false /*canCallJava*/),
3728        mOffloadThread(offloadThread),
3729        mWriteAckSequence(0),
3730        mDrainSequence(0)
3731{
3732}
3733
3734AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
3735{
3736}
3737
3738void AudioFlinger::AsyncCallbackThread::onFirstRef()
3739{
3740    run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
3741}
3742
3743bool AudioFlinger::AsyncCallbackThread::threadLoop()
3744{
3745    while (!exitPending()) {
3746        uint32_t writeAckSequence;
3747        uint32_t drainSequence;
3748
3749        {
3750            Mutex::Autolock _l(mLock);
3751            mWaitWorkCV.wait(mLock);
3752            if (exitPending()) {
3753                break;
3754            }
3755            ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
3756                  mWriteAckSequence, mDrainSequence);
3757            writeAckSequence = mWriteAckSequence;
3758            mWriteAckSequence &= ~1;
3759            drainSequence = mDrainSequence;
3760            mDrainSequence &= ~1;
3761        }
3762        {
3763            sp<AudioFlinger::OffloadThread> offloadThread = mOffloadThread.promote();
3764            if (offloadThread != 0) {
3765                if (writeAckSequence & 1) {
3766                    offloadThread->resetWriteBlocked(writeAckSequence >> 1);
3767                }
3768                if (drainSequence & 1) {
3769                    offloadThread->resetDraining(drainSequence >> 1);
3770                }
3771            }
3772        }
3773    }
3774    return false;
3775}
3776
3777void AudioFlinger::AsyncCallbackThread::exit()
3778{
3779    ALOGV("AsyncCallbackThread::exit");
3780    Mutex::Autolock _l(mLock);
3781    requestExit();
3782    mWaitWorkCV.broadcast();
3783}
3784
3785void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
3786{
3787    Mutex::Autolock _l(mLock);
3788    // bit 0 is cleared
3789    mWriteAckSequence = sequence << 1;
3790}
3791
3792void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
3793{
3794    Mutex::Autolock _l(mLock);
3795    // ignore unexpected callbacks
3796    if (mWriteAckSequence & 2) {
3797        mWriteAckSequence |= 1;
3798        mWaitWorkCV.signal();
3799    }
3800}
3801
3802void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
3803{
3804    Mutex::Autolock _l(mLock);
3805    // bit 0 is cleared
3806    mDrainSequence = sequence << 1;
3807}
3808
3809void AudioFlinger::AsyncCallbackThread::resetDraining()
3810{
3811    Mutex::Autolock _l(mLock);
3812    // ignore unexpected callbacks
3813    if (mDrainSequence & 2) {
3814        mDrainSequence |= 1;
3815        mWaitWorkCV.signal();
3816    }
3817}
3818
3819
3820// ----------------------------------------------------------------------------
3821AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
3822        AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
3823    :   DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
3824        mHwPaused(false),
3825        mPausedBytesRemaining(0)
3826{
3827    mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
3828}
3829
3830AudioFlinger::OffloadThread::~OffloadThread()
3831{
3832    mPreviousTrack.clear();
3833}
3834
3835void AudioFlinger::OffloadThread::threadLoop_exit()
3836{
3837    if (mFlushPending || mHwPaused) {
3838        // If a flush is pending or track was paused, just discard buffered data
3839        flushHw_l();
3840    } else {
3841        mMixerStatus = MIXER_DRAIN_ALL;
3842        threadLoop_drain();
3843    }
3844    mCallbackThread->exit();
3845    PlaybackThread::threadLoop_exit();
3846}
3847
3848AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
3849    Vector< sp<Track> > *tracksToRemove
3850)
3851{
3852    ALOGV("OffloadThread::prepareTracks_l");
3853    size_t count = mActiveTracks.size();
3854
3855    mixer_state mixerStatus = MIXER_IDLE;
3856    bool doHwPause = false;
3857    bool doHwResume = false;
3858
3859    // find out which tracks need to be processed
3860    for (size_t i = 0; i < count; i++) {
3861        sp<Track> t = mActiveTracks[i].promote();
3862        // The track died recently
3863        if (t == 0) {
3864            continue;
3865        }
3866        Track* const track = t.get();
3867        audio_track_cblk_t* cblk = track->cblk();
3868        if (mPreviousTrack != NULL) {
3869            if (t != mPreviousTrack) {
3870                // Flush any data still being written from last track
3871                mBytesRemaining = 0;
3872                if (mPausedBytesRemaining) {
3873                    // Last track was paused so we also need to flush saved
3874                    // mixbuffer state and invalidate track so that it will
3875                    // re-submit that unwritten data when it is next resumed
3876                    mPausedBytesRemaining = 0;
3877                    // Invalidate is a bit drastic - would be more efficient
3878                    // to have a flag to tell client that some of the
3879                    // previously written data was lost
3880                    mPreviousTrack->invalidate();
3881                }
3882            }
3883        }
3884        mPreviousTrack = t;
3885        bool last = (i == (count - 1));
3886        if (track->isPausing()) {
3887            track->setPaused();
3888            if (last) {
3889                if (!mHwPaused) {
3890                    doHwPause = true;
3891                    mHwPaused = true;
3892                }
3893                // If we were part way through writing the mixbuffer to
3894                // the HAL we must save this until we resume
3895                // BUG - this will be wrong if a different track is made active,
3896                // in that case we want to discard the pending data in the
3897                // mixbuffer and tell the client to present it again when the
3898                // track is resumed
3899                mPausedWriteLength = mCurrentWriteLength;
3900                mPausedBytesRemaining = mBytesRemaining;
3901                mBytesRemaining = 0;    // stop writing
3902            }
3903            tracksToRemove->add(track);
3904        } else if (track->framesReady() && track->isReady() &&
3905                !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
3906            ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
3907            if (track->mFillingUpStatus == Track::FS_FILLED) {
3908                track->mFillingUpStatus = Track::FS_ACTIVE;
3909                // make sure processVolume_l() will apply new volume even if 0
3910                mLeftVolFloat = mRightVolFloat = -1.0;
3911                if (track->mState == TrackBase::RESUMING) {
3912                    if (mPausedBytesRemaining) {
3913                        // Need to continue write that was interrupted
3914                        mCurrentWriteLength = mPausedWriteLength;
3915                        mBytesRemaining = mPausedBytesRemaining;
3916                        mPausedBytesRemaining = 0;
3917                    }
3918                    track->mState = TrackBase::ACTIVE;
3919                }
3920            }
3921
3922            if (last) {
3923                if (mHwPaused) {
3924                    doHwResume = true;
3925                    mHwPaused = false;
3926                    // threadLoop_mix() will handle the case that we need to
3927                    // resume an interrupted write
3928                }
3929                // reset retry count
3930                track->mRetryCount = kMaxTrackRetriesOffload;
3931                mActiveTrack = t;
3932                mixerStatus = MIXER_TRACKS_READY;
3933            }
3934        } else {
3935            ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
3936            if (track->isStopping_1()) {
3937                // Hardware buffer can hold a large amount of audio so we must
3938                // wait for all current track's data to drain before we say
3939                // that the track is stopped.
3940                if (mBytesRemaining == 0) {
3941                    // Only start draining when all data in mixbuffer
3942                    // has been written
3943                    ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
3944                    track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
3945                    sleepTime = 0;
3946                    standbyTime = systemTime() + standbyDelay;
3947                    if (last) {
3948                        mixerStatus = MIXER_DRAIN_TRACK;
3949                        mDrainSequence += 2;
3950                        if (mHwPaused) {
3951                            // It is possible to move from PAUSED to STOPPING_1 without
3952                            // a resume so we must ensure hardware is running
3953                            mOutput->stream->resume(mOutput->stream);
3954                            mHwPaused = false;
3955                        }
3956                    }
3957                }
3958            } else if (track->isStopping_2()) {
3959                // Drain has completed, signal presentation complete
3960                if (!(mDrainSequence & 1) || !last) {
3961                    track->mState = TrackBase::STOPPED;
3962                    size_t audioHALFrames =
3963                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3964                    size_t framesWritten =
3965                            mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3966                    track->presentationComplete(framesWritten, audioHALFrames);
3967                    track->reset();
3968                    tracksToRemove->add(track);
3969                }
3970            } else {
3971                // No buffers for this track. Give it a few chances to
3972                // fill a buffer, then remove it from active list.
3973                if (--(track->mRetryCount) <= 0) {
3974                    ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
3975                          track->name());
3976                    tracksToRemove->add(track);
3977                } else if (last){
3978                    mixerStatus = MIXER_TRACKS_ENABLED;
3979                }
3980            }
3981        }
3982        // compute volume for this track
3983        processVolume_l(track, last);
3984    }
3985
3986    // make sure the pause/flush/resume sequence is executed in the right order
3987    if (doHwPause) {
3988        mOutput->stream->pause(mOutput->stream);
3989    }
3990    if (mFlushPending) {
3991        flushHw_l();
3992        mFlushPending = false;
3993    }
3994    if (doHwResume) {
3995        mOutput->stream->resume(mOutput->stream);
3996    }
3997
3998    // remove all the tracks that need to be...
3999    removeTracks_l(*tracksToRemove);
4000
4001    return mixerStatus;
4002}
4003
4004void AudioFlinger::OffloadThread::flushOutput_l()
4005{
4006    mFlushPending = true;
4007}
4008
4009// must be called with thread mutex locked
4010bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4011{
4012    ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4013          mWriteAckSequence, mDrainSequence);
4014    if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
4015        return true;
4016    }
4017    return false;
4018}
4019
4020// must be called with thread mutex locked
4021bool AudioFlinger::OffloadThread::shouldStandby_l()
4022{
4023    bool TrackPaused = false;
4024
4025    // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4026    // after a timeout and we will enter standby then.
4027    if (mTracks.size() > 0) {
4028        TrackPaused = mTracks[mTracks.size() - 1]->isPaused();
4029    }
4030
4031    return !mStandby && !TrackPaused;
4032}
4033
4034
4035bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4036{
4037    Mutex::Autolock _l(mLock);
4038    return waitingAsyncCallback_l();
4039}
4040
4041void AudioFlinger::OffloadThread::flushHw_l()
4042{
4043    mOutput->stream->flush(mOutput->stream);
4044    // Flush anything still waiting in the mixbuffer
4045    mCurrentWriteLength = 0;
4046    mBytesRemaining = 0;
4047    mPausedWriteLength = 0;
4048    mPausedBytesRemaining = 0;
4049    if (mUseAsyncWrite) {
4050        // discard any pending drain or write ack by incrementing sequence
4051        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4052        mDrainSequence = (mDrainSequence + 2) & ~1;
4053        ALOG_ASSERT(mCallbackThread != 0);
4054        mCallbackThread->setWriteBlocked(mWriteAckSequence);
4055        mCallbackThread->setDraining(mDrainSequence);
4056    }
4057}
4058
4059// ----------------------------------------------------------------------------
4060
4061AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4062        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4063    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4064                DUPLICATING),
4065        mWaitTimeMs(UINT_MAX)
4066{
4067    addOutputTrack(mainThread);
4068}
4069
4070AudioFlinger::DuplicatingThread::~DuplicatingThread()
4071{
4072    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4073        mOutputTracks[i]->destroy();
4074    }
4075}
4076
4077void AudioFlinger::DuplicatingThread::threadLoop_mix()
4078{
4079    // mix buffers...
4080    if (outputsReady(outputTracks)) {
4081        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4082    } else {
4083        memset(mMixBuffer, 0, mixBufferSize);
4084    }
4085    sleepTime = 0;
4086    writeFrames = mNormalFrameCount;
4087    mCurrentWriteLength = mixBufferSize;
4088    standbyTime = systemTime() + standbyDelay;
4089}
4090
4091void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4092{
4093    if (sleepTime == 0) {
4094        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4095            sleepTime = activeSleepTime;
4096        } else {
4097            sleepTime = idleSleepTime;
4098        }
4099    } else if (mBytesWritten != 0) {
4100        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4101            writeFrames = mNormalFrameCount;
4102            memset(mMixBuffer, 0, mixBufferSize);
4103        } else {
4104            // flush remaining overflow buffers in output tracks
4105            writeFrames = 0;
4106        }
4107        sleepTime = 0;
4108    }
4109}
4110
4111ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
4112{
4113    for (size_t i = 0; i < outputTracks.size(); i++) {
4114        outputTracks[i]->write(mMixBuffer, writeFrames);
4115    }
4116    return (ssize_t)mixBufferSize;
4117}
4118
4119void AudioFlinger::DuplicatingThread::threadLoop_standby()
4120{
4121    // DuplicatingThread implements standby by stopping all tracks
4122    for (size_t i = 0; i < outputTracks.size(); i++) {
4123        outputTracks[i]->stop();
4124    }
4125}
4126
4127void AudioFlinger::DuplicatingThread::saveOutputTracks()
4128{
4129    outputTracks = mOutputTracks;
4130}
4131
4132void AudioFlinger::DuplicatingThread::clearOutputTracks()
4133{
4134    outputTracks.clear();
4135}
4136
4137void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4138{
4139    Mutex::Autolock _l(mLock);
4140    // FIXME explain this formula
4141    size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4142    OutputTrack *outputTrack = new OutputTrack(thread,
4143                                            this,
4144                                            mSampleRate,
4145                                            mFormat,
4146                                            mChannelMask,
4147                                            frameCount);
4148    if (outputTrack->cblk() != NULL) {
4149        thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4150        mOutputTracks.add(outputTrack);
4151        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4152        updateWaitTime_l();
4153    }
4154}
4155
4156void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4157{
4158    Mutex::Autolock _l(mLock);
4159    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4160        if (mOutputTracks[i]->thread() == thread) {
4161            mOutputTracks[i]->destroy();
4162            mOutputTracks.removeAt(i);
4163            updateWaitTime_l();
4164            return;
4165        }
4166    }
4167    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4168}
4169
4170// caller must hold mLock
4171void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4172{
4173    mWaitTimeMs = UINT_MAX;
4174    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4175        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4176        if (strong != 0) {
4177            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4178            if (waitTimeMs < mWaitTimeMs) {
4179                mWaitTimeMs = waitTimeMs;
4180            }
4181        }
4182    }
4183}
4184
4185
4186bool AudioFlinger::DuplicatingThread::outputsReady(
4187        const SortedVector< sp<OutputTrack> > &outputTracks)
4188{
4189    for (size_t i = 0; i < outputTracks.size(); i++) {
4190        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4191        if (thread == 0) {
4192            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4193                    outputTracks[i].get());
4194            return false;
4195        }
4196        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4197        // see note at standby() declaration
4198        if (playbackThread->standby() && !playbackThread->isSuspended()) {
4199            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4200                    thread.get());
4201            return false;
4202        }
4203    }
4204    return true;
4205}
4206
4207uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4208{
4209    return (mWaitTimeMs * 1000) / 2;
4210}
4211
4212void AudioFlinger::DuplicatingThread::cacheParameters_l()
4213{
4214    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4215    updateWaitTime_l();
4216
4217    MixerThread::cacheParameters_l();
4218}
4219
4220// ----------------------------------------------------------------------------
4221//      Record
4222// ----------------------------------------------------------------------------
4223
4224AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4225                                         AudioStreamIn *input,
4226                                         uint32_t sampleRate,
4227                                         audio_channel_mask_t channelMask,
4228                                         audio_io_handle_t id,
4229                                         audio_devices_t outDevice,
4230                                         audio_devices_t inDevice
4231#ifdef TEE_SINK
4232                                         , const sp<NBAIO_Sink>& teeSink
4233#endif
4234                                         ) :
4235    ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
4236    mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4237    // mRsmpInIndex set by readInputParameters()
4238    mReqChannelCount(popcount(channelMask)),
4239    mReqSampleRate(sampleRate)
4240    // mBytesRead is only meaningful while active, and so is cleared in start()
4241    // (but might be better to also clear here for dump?)
4242#ifdef TEE_SINK
4243    , mTeeSink(teeSink)
4244#endif
4245{
4246    snprintf(mName, kNameLength, "AudioIn_%X", id);
4247
4248    readInputParameters();
4249
4250}
4251
4252
4253AudioFlinger::RecordThread::~RecordThread()
4254{
4255    delete[] mRsmpInBuffer;
4256    delete mResampler;
4257    delete[] mRsmpOutBuffer;
4258}
4259
4260void AudioFlinger::RecordThread::onFirstRef()
4261{
4262    run(mName, PRIORITY_URGENT_AUDIO);
4263}
4264
4265bool AudioFlinger::RecordThread::threadLoop()
4266{
4267    AudioBufferProvider::Buffer buffer;
4268
4269    nsecs_t lastWarning = 0;
4270
4271    inputStandBy();
4272    acquireWakeLock();
4273
4274    // used to verify we've read at least once before evaluating how many bytes were read
4275    bool readOnce = false;
4276
4277    // used to request a deferred sleep, to be executed later while mutex is unlocked
4278    bool doSleep = false;
4279
4280    // start recording
4281    for (;;) {
4282        sp<RecordTrack> activeTrack;
4283        TrackBase::track_state activeTrackState;
4284        Vector< sp<EffectChain> > effectChains;
4285
4286        // sleep with mutex unlocked
4287        if (doSleep) {
4288            doSleep = false;
4289            usleep(kRecordThreadSleepUs);
4290        }
4291
4292        { // scope for mLock
4293            Mutex::Autolock _l(mLock);
4294            if (exitPending()) {
4295                break;
4296            }
4297            processConfigEvents_l();
4298            // return value 'reconfig' is currently unused
4299            bool reconfig = checkForNewParameters_l();
4300            // make a stable copy of mActiveTrack
4301            activeTrack = mActiveTrack;
4302            if (activeTrack == 0) {
4303                standby();
4304                // exitPending() can't become true here
4305                releaseWakeLock_l();
4306                ALOGV("RecordThread: loop stopping");
4307                // go to sleep
4308                mWaitWorkCV.wait(mLock);
4309                ALOGV("RecordThread: loop starting");
4310                acquireWakeLock_l();
4311                continue;
4312            }
4313
4314            if (activeTrack->isTerminated()) {
4315                removeTrack_l(activeTrack);
4316                mActiveTrack.clear();
4317                continue;
4318            }
4319
4320            activeTrackState = activeTrack->mState;
4321            switch (activeTrackState) {
4322            case TrackBase::PAUSING:
4323                standby();
4324                mActiveTrack.clear();
4325                mStartStopCond.broadcast();
4326                doSleep = true;
4327                continue;
4328
4329            case TrackBase::RESUMING:
4330                mStandby = false;
4331                if (mReqChannelCount != activeTrack->channelCount()) {
4332                    mActiveTrack.clear();
4333                    mStartStopCond.broadcast();
4334                    continue;
4335                }
4336                if (readOnce) {
4337                    mStartStopCond.broadcast();
4338                    // record start succeeds only if first read from audio input succeeds
4339                    if (mBytesRead < 0) {
4340                        mActiveTrack.clear();
4341                        continue;
4342                    }
4343                    activeTrack->mState = TrackBase::ACTIVE;
4344                }
4345                break;
4346
4347            case TrackBase::ACTIVE:
4348                break;
4349
4350            case TrackBase::IDLE:
4351                doSleep = true;
4352                continue;
4353
4354            default:
4355                LOG_FATAL("Unexpected activeTrackState %d", activeTrackState);
4356            }
4357
4358            lockEffectChains_l(effectChains);
4359        }
4360
4361        // thread mutex is now unlocked, mActiveTrack unknown, activeTrack != 0, kept, immutable
4362        // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING
4363
4364        for (size_t i = 0; i < effectChains.size(); i ++) {
4365            // thread mutex is not locked, but effect chain is locked
4366            effectChains[i]->process_l();
4367        }
4368
4369        buffer.frameCount = mFrameCount;
4370        status_t status = activeTrack->getNextBuffer(&buffer);
4371        if (status == NO_ERROR) {
4372            readOnce = true;
4373            size_t framesOut = buffer.frameCount;
4374            if (mResampler == NULL) {
4375                // no resampling
4376                while (framesOut) {
4377                    size_t framesIn = mFrameCount - mRsmpInIndex;
4378                    if (framesIn > 0) {
4379                        int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4380                        int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
4381                                activeTrack->mFrameSize;
4382                        if (framesIn > framesOut) {
4383                            framesIn = framesOut;
4384                        }
4385                        mRsmpInIndex += framesIn;
4386                        framesOut -= framesIn;
4387                        if (mChannelCount == mReqChannelCount) {
4388                            memcpy(dst, src, framesIn * mFrameSize);
4389                        } else {
4390                            if (mChannelCount == 1) {
4391                                upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
4392                                        (int16_t *)src, framesIn);
4393                            } else {
4394                                downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
4395                                        (int16_t *)src, framesIn);
4396                            }
4397                        }
4398                    }
4399                    if (framesOut > 0 && mFrameCount == mRsmpInIndex) {
4400                        void *readInto;
4401                        if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) {
4402                            readInto = buffer.raw;
4403                            framesOut = 0;
4404                        } else {
4405                            readInto = mRsmpInBuffer;
4406                            mRsmpInIndex = 0;
4407                        }
4408                        mBytesRead = mInput->stream->read(mInput->stream, readInto,
4409                                mBufferSize);
4410                        if (mBytesRead <= 0) {
4411                            // TODO: verify that it's benign to use a stale track state
4412                            if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE))
4413                            {
4414                                ALOGE("Error reading audio input");
4415                                // Force input into standby so that it tries to
4416                                // recover at next read attempt
4417                                inputStandBy();
4418                                doSleep = true;
4419                            }
4420                            mRsmpInIndex = mFrameCount;
4421                            framesOut = 0;
4422                            buffer.frameCount = 0;
4423                        }
4424#ifdef TEE_SINK
4425                        else if (mTeeSink != 0) {
4426                            (void) mTeeSink->write(readInto,
4427                                    mBytesRead >> Format_frameBitShift(mTeeSink->format()));
4428                        }
4429#endif
4430                    }
4431                }
4432            } else {
4433                // resampling
4434
4435                // resampler accumulates, but we only have one source track
4436                memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4437                // alter output frame count as if we were expecting stereo samples
4438                if (mChannelCount == 1 && mReqChannelCount == 1) {
4439                    framesOut >>= 1;
4440                }
4441                mResampler->resample(mRsmpOutBuffer, framesOut,
4442                        this /* AudioBufferProvider* */);
4443                // ditherAndClamp() works as long as all buffers returned by
4444                // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
4445                if (mChannelCount == 2 && mReqChannelCount == 1) {
4446                    // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t
4447                    ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4448                    // the resampler always outputs stereo samples:
4449                    // do post stereo to mono conversion
4450                    downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
4451                            framesOut);
4452                } else {
4453                    ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4454                }
4455                // now done with mRsmpOutBuffer
4456
4457            }
4458            if (mFramestoDrop == 0) {
4459                activeTrack->releaseBuffer(&buffer);
4460            } else {
4461                if (mFramestoDrop > 0) {
4462                    mFramestoDrop -= buffer.frameCount;
4463                    if (mFramestoDrop <= 0) {
4464                        clearSyncStartEvent();
4465                    }
4466                } else {
4467                    mFramestoDrop += buffer.frameCount;
4468                    if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
4469                            mSyncStartEvent->isCancelled()) {
4470                        ALOGW("Synced record %s, session %d, trigger session %d",
4471                              (mFramestoDrop >= 0) ? "timed out" : "cancelled",
4472                              activeTrack->sessionId(),
4473                              (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
4474                        clearSyncStartEvent();
4475                    }
4476                }
4477            }
4478            activeTrack->clearOverflow();
4479        }
4480        // client isn't retrieving buffers fast enough
4481        else {
4482            if (!activeTrack->setOverflow()) {
4483                nsecs_t now = systemTime();
4484                if ((now - lastWarning) > kWarningThrottleNs) {
4485                    ALOGW("RecordThread: buffer overflow");
4486                    lastWarning = now;
4487                }
4488            }
4489            // Release the processor for a while before asking for a new buffer.
4490            // This will give the application more chance to read from the buffer and
4491            // clear the overflow.
4492            doSleep = true;
4493        }
4494
4495        // enable changes in effect chain
4496        unlockEffectChains(effectChains);
4497        // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
4498    }
4499
4500    standby();
4501
4502    {
4503        Mutex::Autolock _l(mLock);
4504        for (size_t i = 0; i < mTracks.size(); i++) {
4505            sp<RecordTrack> track = mTracks[i];
4506            track->invalidate();
4507        }
4508        mActiveTrack.clear();
4509        mStartStopCond.broadcast();
4510    }
4511
4512    releaseWakeLock();
4513
4514    ALOGV("RecordThread %p exiting", this);
4515    return false;
4516}
4517
4518void AudioFlinger::RecordThread::standby()
4519{
4520    if (!mStandby) {
4521        inputStandBy();
4522        mStandby = true;
4523    }
4524}
4525
4526void AudioFlinger::RecordThread::inputStandBy()
4527{
4528    mInput->stream->common.standby(&mInput->stream->common);
4529}
4530
4531sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4532        const sp<AudioFlinger::Client>& client,
4533        uint32_t sampleRate,
4534        audio_format_t format,
4535        audio_channel_mask_t channelMask,
4536        size_t frameCount,
4537        int sessionId,
4538        IAudioFlinger::track_flags_t *flags,
4539        pid_t tid,
4540        status_t *status)
4541{
4542    sp<RecordTrack> track;
4543    status_t lStatus;
4544
4545    lStatus = initCheck();
4546    if (lStatus != NO_ERROR) {
4547        ALOGE("Audio driver not initialized.");
4548        goto Exit;
4549    }
4550
4551    // client expresses a preference for FAST, but we get the final say
4552    if (*flags & IAudioFlinger::TRACK_FAST) {
4553      if (
4554            // use case: callback handler and frame count is default or at least as large as HAL
4555            (
4556                (tid != -1) &&
4557                ((frameCount == 0) ||
4558                (frameCount >= (mFrameCount * kFastTrackMultiplier)))
4559            ) &&
4560            // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format)
4561            // mono or stereo
4562            ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
4563              (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
4564            // hardware sample rate
4565            (sampleRate == mSampleRate) &&
4566            // record thread has an associated fast recorder
4567            hasFastRecorder()
4568            // FIXME test that RecordThread for this fast track has a capable output HAL
4569            // FIXME add a permission test also?
4570        ) {
4571        // if frameCount not specified, then it defaults to fast recorder (HAL) frame count
4572        if (frameCount == 0) {
4573            frameCount = mFrameCount * kFastTrackMultiplier;
4574        }
4575        ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
4576                frameCount, mFrameCount);
4577      } else {
4578        ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
4579                "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
4580                "hasFastRecorder=%d tid=%d",
4581                frameCount, mFrameCount, format,
4582                audio_is_linear_pcm(format),
4583                channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid);
4584        *flags &= ~IAudioFlinger::TRACK_FAST;
4585        // For compatibility with AudioRecord calculation, buffer depth is forced
4586        // to be at least 2 x the record thread frame count and cover audio hardware latency.
4587        // This is probably too conservative, but legacy application code may depend on it.
4588        // If you change this calculation, also review the start threshold which is related.
4589        uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
4590        size_t mNormalFrameCount = 2048; // FIXME
4591        uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
4592        if (minBufCount < 2) {
4593            minBufCount = 2;
4594        }
4595        size_t minFrameCount = mNormalFrameCount * minBufCount;
4596        if (frameCount < minFrameCount) {
4597            frameCount = minFrameCount;
4598        }
4599      }
4600    }
4601
4602    // FIXME use flags and tid similar to createTrack_l()
4603
4604    { // scope for mLock
4605        Mutex::Autolock _l(mLock);
4606
4607        track = new RecordTrack(this, client, sampleRate,
4608                      format, channelMask, frameCount, sessionId);
4609
4610        lStatus = track->initCheck();
4611        if (lStatus != NO_ERROR) {
4612            track.clear();
4613            goto Exit;
4614        }
4615        mTracks.add(track);
4616
4617        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4618        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4619                        mAudioFlinger->btNrecIsOff();
4620        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4621        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
4622
4623        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
4624            pid_t callingPid = IPCThreadState::self()->getCallingPid();
4625            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
4626            // so ask activity manager to do this on our behalf
4627            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
4628        }
4629    }
4630    lStatus = NO_ERROR;
4631
4632Exit:
4633    *status = lStatus;
4634    return track;
4635}
4636
4637status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
4638                                           AudioSystem::sync_event_t event,
4639                                           int triggerSession)
4640{
4641    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
4642    sp<ThreadBase> strongMe = this;
4643    status_t status = NO_ERROR;
4644
4645    if (event == AudioSystem::SYNC_EVENT_NONE) {
4646        clearSyncStartEvent();
4647    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
4648        mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
4649                                       triggerSession,
4650                                       recordTrack->sessionId(),
4651                                       syncStartEventCallback,
4652                                       this);
4653        // Sync event can be cancelled by the trigger session if the track is not in a
4654        // compatible state in which case we start record immediately
4655        if (mSyncStartEvent->isCancelled()) {
4656            clearSyncStartEvent();
4657        } else {
4658            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
4659            mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
4660        }
4661    }
4662
4663    {
4664        // This section is a rendezvous between binder thread executing start() and RecordThread
4665        AutoMutex lock(mLock);
4666        if (mActiveTrack != 0) {
4667            if (recordTrack != mActiveTrack.get()) {
4668                status = -EBUSY;
4669            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4670                mActiveTrack->mState = TrackBase::ACTIVE;
4671            }
4672            return status;
4673        }
4674
4675        // FIXME why? already set in constructor, 'STARTING_1' would be more accurate
4676        recordTrack->mState = TrackBase::IDLE;
4677        mActiveTrack = recordTrack;
4678        mLock.unlock();
4679        status_t status = AudioSystem::startInput(mId);
4680        mLock.lock();
4681        // FIXME should verify that mActiveTrack is still == recordTrack
4682        if (status != NO_ERROR) {
4683            mActiveTrack.clear();
4684            clearSyncStartEvent();
4685            return status;
4686        }
4687        mRsmpInIndex = mFrameCount;
4688        mBytesRead = 0;
4689        if (mResampler != NULL) {
4690            mResampler->reset();
4691        }
4692        // FIXME hijacking a playback track state name which was intended for start after pause;
4693        //       here 'STARTING_2' would be more accurate
4694        mActiveTrack->mState = TrackBase::RESUMING;
4695        // signal thread to start
4696        ALOGV("Signal record thread");
4697        mWaitWorkCV.broadcast();
4698        // do not wait for mStartStopCond if exiting
4699        if (exitPending()) {
4700            mActiveTrack.clear();
4701            status = INVALID_OPERATION;
4702            goto startError;
4703        }
4704        // FIXME incorrect usage of wait: no explicit predicate or loop
4705        mStartStopCond.wait(mLock);
4706        if (mActiveTrack == 0) {
4707            ALOGV("Record failed to start");
4708            status = BAD_VALUE;
4709            goto startError;
4710        }
4711        ALOGV("Record started OK");
4712        return status;
4713    }
4714
4715startError:
4716    AudioSystem::stopInput(mId);
4717    clearSyncStartEvent();
4718    return status;
4719}
4720
4721void AudioFlinger::RecordThread::clearSyncStartEvent()
4722{
4723    if (mSyncStartEvent != 0) {
4724        mSyncStartEvent->cancel();
4725    }
4726    mSyncStartEvent.clear();
4727    mFramestoDrop = 0;
4728}
4729
4730void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
4731{
4732    sp<SyncEvent> strongEvent = event.promote();
4733
4734    if (strongEvent != 0) {
4735        RecordThread *me = (RecordThread *)strongEvent->cookie();
4736        me->handleSyncStartEvent(strongEvent);
4737    }
4738}
4739
4740void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
4741{
4742    if (event == mSyncStartEvent) {
4743        // TODO: use actual buffer filling status instead of 2 buffers when info is available
4744        // from audio HAL
4745        mFramestoDrop = mFrameCount * 2;
4746    }
4747}
4748
4749bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4750    ALOGV("RecordThread::stop");
4751    AutoMutex _l(mLock);
4752    if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
4753        return false;
4754    }
4755    // note that threadLoop may still be processing the track at this point [without lock]
4756    recordTrack->mState = TrackBase::PAUSING;
4757    // do not wait for mStartStopCond if exiting
4758    if (exitPending()) {
4759        return true;
4760    }
4761    // FIXME incorrect usage of wait: no explicit predicate or loop
4762    mStartStopCond.wait(mLock);
4763    // if we have been restarted, recordTrack == mActiveTrack.get() here
4764    if (exitPending() || recordTrack != mActiveTrack.get()) {
4765        ALOGV("Record stopped OK");
4766        return true;
4767    }
4768    return false;
4769}
4770
4771bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
4772{
4773    return false;
4774}
4775
4776status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
4777{
4778#if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
4779    if (!isValidSyncEvent(event)) {
4780        return BAD_VALUE;
4781    }
4782
4783    int eventSession = event->triggerSession();
4784    status_t ret = NAME_NOT_FOUND;
4785
4786    Mutex::Autolock _l(mLock);
4787
4788    for (size_t i = 0; i < mTracks.size(); i++) {
4789        sp<RecordTrack> track = mTracks[i];
4790        if (eventSession == track->sessionId()) {
4791            (void) track->setSyncEvent(event);
4792            ret = NO_ERROR;
4793        }
4794    }
4795    return ret;
4796#else
4797    return BAD_VALUE;
4798#endif
4799}
4800
4801// destroyTrack_l() must be called with ThreadBase::mLock held
4802void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
4803{
4804    track->terminate();
4805    track->mState = TrackBase::STOPPED;
4806    // active tracks are removed by threadLoop()
4807    if (mActiveTrack != track) {
4808        removeTrack_l(track);
4809    }
4810}
4811
4812void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
4813{
4814    mTracks.remove(track);
4815    // need anything related to effects here?
4816}
4817
4818void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4819{
4820    dumpInternals(fd, args);
4821    dumpTracks(fd, args);
4822    dumpEffectChains(fd, args);
4823}
4824
4825void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
4826{
4827    const size_t SIZE = 256;
4828    char buffer[SIZE];
4829    String8 result;
4830
4831    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4832    result.append(buffer);
4833
4834    if (mActiveTrack != 0) {
4835        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4836        result.append(buffer);
4837        snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
4838        result.append(buffer);
4839        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4840        result.append(buffer);
4841        snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
4842        result.append(buffer);
4843        snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
4844        result.append(buffer);
4845    } else {
4846        result.append("No active record client\n");
4847    }
4848
4849    write(fd, result.string(), result.size());
4850
4851    dumpBase(fd, args);
4852}
4853
4854void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
4855{
4856    const size_t SIZE = 256;
4857    char buffer[SIZE];
4858    String8 result;
4859
4860    snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
4861    result.append(buffer);
4862    RecordTrack::appendDumpHeader(result);
4863    for (size_t i = 0; i < mTracks.size(); ++i) {
4864        sp<RecordTrack> track = mTracks[i];
4865        if (track != 0) {
4866            track->dump(buffer, SIZE);
4867            result.append(buffer);
4868        }
4869    }
4870
4871    if (mActiveTrack != 0) {
4872        snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
4873        result.append(buffer);
4874        RecordTrack::appendDumpHeader(result);
4875        mActiveTrack->dump(buffer, SIZE);
4876        result.append(buffer);
4877
4878    }
4879    write(fd, result.string(), result.size());
4880}
4881
4882// AudioBufferProvider interface
4883status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
4884{
4885    size_t framesReq = buffer->frameCount;
4886    size_t framesReady = mFrameCount - mRsmpInIndex;
4887    int channelCount;
4888
4889    if (framesReady == 0) {
4890        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize);
4891        if (mBytesRead <= 0) {
4892            if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
4893                ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4894                // Force input into standby so that it tries to
4895                // recover at next read attempt
4896                inputStandBy();
4897                // FIXME an awkward place to sleep, consider using doSleep when this is pulled up
4898                usleep(kRecordThreadSleepUs);
4899            }
4900            buffer->raw = NULL;
4901            buffer->frameCount = 0;
4902            return NOT_ENOUGH_DATA;
4903        }
4904        mRsmpInIndex = 0;
4905        framesReady = mFrameCount;
4906    }
4907
4908    if (framesReq > framesReady) {
4909        framesReq = framesReady;
4910    }
4911
4912    if (mChannelCount == 1 && mReqChannelCount == 2) {
4913        channelCount = 1;
4914    } else {
4915        channelCount = 2;
4916    }
4917    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4918    buffer->frameCount = framesReq;
4919    return NO_ERROR;
4920}
4921
4922// AudioBufferProvider interface
4923void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4924{
4925    mRsmpInIndex += buffer->frameCount;
4926    buffer->frameCount = 0;
4927}
4928
4929bool AudioFlinger::RecordThread::checkForNewParameters_l()
4930{
4931    bool reconfig = false;
4932
4933    while (!mNewParameters.isEmpty()) {
4934        status_t status = NO_ERROR;
4935        String8 keyValuePair = mNewParameters[0];
4936        AudioParameter param = AudioParameter(keyValuePair);
4937        int value;
4938        audio_format_t reqFormat = mFormat;
4939        uint32_t reqSamplingRate = mReqSampleRate;
4940        audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount);
4941
4942        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4943            reqSamplingRate = value;
4944            reconfig = true;
4945        }
4946        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4947            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
4948                status = BAD_VALUE;
4949            } else {
4950                reqFormat = (audio_format_t) value;
4951                reconfig = true;
4952            }
4953        }
4954        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4955            audio_channel_mask_t mask = (audio_channel_mask_t) value;
4956            if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
4957                status = BAD_VALUE;
4958            } else {
4959                reqChannelMask = mask;
4960                reconfig = true;
4961            }
4962        }
4963        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4964            // do not accept frame count changes if tracks are open as the track buffer
4965            // size depends on frame count and correct behavior would not be guaranteed
4966            // if frame count is changed after track creation
4967            if (mActiveTrack != 0) {
4968                status = INVALID_OPERATION;
4969            } else {
4970                reconfig = true;
4971            }
4972        }
4973        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4974            // forward device change to effects that have requested to be
4975            // aware of attached audio device.
4976            for (size_t i = 0; i < mEffectChains.size(); i++) {
4977                mEffectChains[i]->setDevice_l(value);
4978            }
4979
4980            // store input device and output device but do not forward output device to audio HAL.
4981            // Note that status is ignored by the caller for output device
4982            // (see AudioFlinger::setParameters()
4983            if (audio_is_output_devices(value)) {
4984                mOutDevice = value;
4985                status = BAD_VALUE;
4986            } else {
4987                mInDevice = value;
4988                // disable AEC and NS if the device is a BT SCO headset supporting those
4989                // pre processings
4990                if (mTracks.size() > 0) {
4991                    bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
4992                                        mAudioFlinger->btNrecIsOff();
4993                    for (size_t i = 0; i < mTracks.size(); i++) {
4994                        sp<RecordTrack> track = mTracks[i];
4995                        setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
4996                        setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
4997                    }
4998                }
4999            }
5000        }
5001        if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5002                mAudioSource != (audio_source_t)value) {
5003            // forward device change to effects that have requested to be
5004            // aware of attached audio device.
5005            for (size_t i = 0; i < mEffectChains.size(); i++) {
5006                mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5007            }
5008            mAudioSource = (audio_source_t)value;
5009        }
5010
5011        if (status == NO_ERROR) {
5012            status = mInput->stream->common.set_parameters(&mInput->stream->common,
5013                    keyValuePair.string());
5014            if (status == INVALID_OPERATION) {
5015                inputStandBy();
5016                status = mInput->stream->common.set_parameters(&mInput->stream->common,
5017                        keyValuePair.string());
5018            }
5019            if (reconfig) {
5020                if (status == BAD_VALUE &&
5021                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5022                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5023                    (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5024                            <= (2 * reqSamplingRate)) &&
5025                    popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5026                            <= FCC_2 &&
5027                    (reqChannelMask == AUDIO_CHANNEL_IN_MONO ||
5028                            reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) {
5029                    status = NO_ERROR;
5030                }
5031                if (status == NO_ERROR) {
5032                    readInputParameters();
5033                    sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5034                }
5035            }
5036        }
5037
5038        mNewParameters.removeAt(0);
5039
5040        mParamStatus = status;
5041        mParamCond.signal();
5042        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5043        // already timed out waiting for the status and will never signal the condition.
5044        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5045    }
5046    return reconfig;
5047}
5048
5049String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5050{
5051    Mutex::Autolock _l(mLock);
5052    if (initCheck() != NO_ERROR) {
5053        return String8();
5054    }
5055
5056    char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5057    const String8 out_s8(s);
5058    free(s);
5059    return out_s8;
5060}
5061
5062void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5063    AudioSystem::OutputDescriptor desc;
5064    void *param2 = NULL;
5065
5066    switch (event) {
5067    case AudioSystem::INPUT_OPENED:
5068    case AudioSystem::INPUT_CONFIG_CHANGED:
5069        desc.channelMask = mChannelMask;
5070        desc.samplingRate = mSampleRate;
5071        desc.format = mFormat;
5072        desc.frameCount = mFrameCount;
5073        desc.latency = 0;
5074        param2 = &desc;
5075        break;
5076
5077    case AudioSystem::INPUT_CLOSED:
5078    default:
5079        break;
5080    }
5081    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5082}
5083
5084void AudioFlinger::RecordThread::readInputParameters()
5085{
5086    delete[] mRsmpInBuffer;
5087    // mRsmpInBuffer is always assigned a new[] below
5088    delete[] mRsmpOutBuffer;
5089    mRsmpOutBuffer = NULL;
5090    delete mResampler;
5091    mResampler = NULL;
5092
5093    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5094    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5095    mChannelCount = popcount(mChannelMask);
5096    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
5097    if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5098        ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5099    }
5100    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
5101    mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5102    mFrameCount = mBufferSize / mFrameSize;
5103    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5104
5105    if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) {
5106        int channelCount;
5107        // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5108        // stereo to mono post process as the resampler always outputs stereo.
5109        if (mChannelCount == 1 && mReqChannelCount == 2) {
5110            channelCount = 1;
5111        } else {
5112            channelCount = 2;
5113        }
5114        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5115        mResampler->setSampleRate(mSampleRate);
5116        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5117        mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2];
5118
5119        // optmization: if mono to mono, alter input frame count as if we were inputing
5120        // stereo samples
5121        if (mChannelCount == 1 && mReqChannelCount == 1) {
5122            mFrameCount >>= 1;
5123        }
5124
5125    }
5126    mRsmpInIndex = mFrameCount;
5127}
5128
5129unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5130{
5131    Mutex::Autolock _l(mLock);
5132    if (initCheck() != NO_ERROR) {
5133        return 0;
5134    }
5135
5136    return mInput->stream->get_input_frames_lost(mInput->stream);
5137}
5138
5139uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5140{
5141    Mutex::Autolock _l(mLock);
5142    uint32_t result = 0;
5143    if (getEffectChain_l(sessionId) != 0) {
5144        result = EFFECT_SESSION;
5145    }
5146
5147    for (size_t i = 0; i < mTracks.size(); ++i) {
5148        if (sessionId == mTracks[i]->sessionId()) {
5149            result |= TRACK_SESSION;
5150            break;
5151        }
5152    }
5153
5154    return result;
5155}
5156
5157KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5158{
5159    KeyedVector<int, bool> ids;
5160    Mutex::Autolock _l(mLock);
5161    for (size_t j = 0; j < mTracks.size(); ++j) {
5162        sp<RecordThread::RecordTrack> track = mTracks[j];
5163        int sessionId = track->sessionId();
5164        if (ids.indexOfKey(sessionId) < 0) {
5165            ids.add(sessionId, true);
5166        }
5167    }
5168    return ids;
5169}
5170
5171AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5172{
5173    Mutex::Autolock _l(mLock);
5174    AudioStreamIn *input = mInput;
5175    mInput = NULL;
5176    return input;
5177}
5178
5179// this method must always be called either with ThreadBase mLock held or inside the thread loop
5180audio_stream_t* AudioFlinger::RecordThread::stream() const
5181{
5182    if (mInput == NULL) {
5183        return NULL;
5184    }
5185    return &mInput->stream->common;
5186}
5187
5188status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5189{
5190    // only one chain per input thread
5191    if (mEffectChains.size() != 0) {
5192        return INVALID_OPERATION;
5193    }
5194    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5195
5196    chain->setInBuffer(NULL);
5197    chain->setOutBuffer(NULL);
5198
5199    checkSuspendOnAddEffectChain_l(chain);
5200
5201    mEffectChains.add(chain);
5202
5203    return NO_ERROR;
5204}
5205
5206size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5207{
5208    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5209    ALOGW_IF(mEffectChains.size() != 1,
5210            "removeEffectChain_l() %p invalid chain size %d on thread %p",
5211            chain.get(), mEffectChains.size(), this);
5212    if (mEffectChains.size() == 1) {
5213        mEffectChains.removeAt(0);
5214    }
5215    return 0;
5216}
5217
5218}; // namespace android
5219