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