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