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