Threads.cpp revision 993fa0603707e94ce259e95e56838a85b5ccbdc5
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_MIN; 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    free(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    switch (mType) {
1344
1345    case DIRECT:
1346        if (audio_is_linear_pcm(format)) {
1347            if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1348                ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1349                        "for output %p with format %#x",
1350                        sampleRate, format, channelMask, mOutput, mFormat);
1351                lStatus = BAD_VALUE;
1352                goto Exit;
1353            }
1354        }
1355        break;
1356
1357    case OFFLOAD:
1358        if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1359            ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1360                    "for output %p with format %#x",
1361                    sampleRate, format, channelMask, mOutput, mFormat);
1362            lStatus = BAD_VALUE;
1363            goto Exit;
1364        }
1365        break;
1366
1367    default:
1368        if (!audio_is_linear_pcm(format)) {
1369                ALOGE("createTrack_l() Bad parameter: format %#x \""
1370                        "for output %p with format %#x",
1371                        format, mOutput, mFormat);
1372                lStatus = BAD_VALUE;
1373                goto Exit;
1374        }
1375        // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1376        if (sampleRate > mSampleRate*2) {
1377            ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1378            lStatus = BAD_VALUE;
1379            goto Exit;
1380        }
1381        break;
1382
1383    }
1384
1385    lStatus = initCheck();
1386    if (lStatus != NO_ERROR) {
1387        ALOGE("createTrack_l() audio driver not initialized");
1388        goto Exit;
1389    }
1390
1391    { // scope for mLock
1392        Mutex::Autolock _l(mLock);
1393
1394        // all tracks in same audio session must share the same routing strategy otherwise
1395        // conflicts will happen when tracks are moved from one output to another by audio policy
1396        // manager
1397        uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1398        for (size_t i = 0; i < mTracks.size(); ++i) {
1399            sp<Track> t = mTracks[i];
1400            if (t != 0 && !t->isOutputTrack()) {
1401                uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1402                if (sessionId == t->sessionId() && strategy != actual) {
1403                    ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1404                            strategy, actual);
1405                    lStatus = BAD_VALUE;
1406                    goto Exit;
1407                }
1408            }
1409        }
1410
1411        if (!isTimed) {
1412            track = new Track(this, client, streamType, sampleRate, format,
1413                    channelMask, frameCount, sharedBuffer, sessionId, uid, *flags);
1414        } else {
1415            track = TimedTrack::create(this, client, streamType, sampleRate, format,
1416                    channelMask, frameCount, sharedBuffer, sessionId, uid);
1417        }
1418
1419        // new Track always returns non-NULL,
1420        // but TimedTrack::create() is a factory that could fail by returning NULL
1421        lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1422        if (lStatus != NO_ERROR) {
1423            ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
1424            // track must be cleared from the caller as the caller has the AF lock
1425            goto Exit;
1426        }
1427        mTracks.add(track);
1428
1429        sp<EffectChain> chain = getEffectChain_l(sessionId);
1430        if (chain != 0) {
1431            ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1432            track->setMainBuffer(chain->inBuffer());
1433            chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1434            chain->incTrackCnt();
1435        }
1436
1437        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1438            pid_t callingPid = IPCThreadState::self()->getCallingPid();
1439            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1440            // so ask activity manager to do this on our behalf
1441            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1442        }
1443    }
1444
1445    lStatus = NO_ERROR;
1446
1447Exit:
1448    *status = lStatus;
1449    return track;
1450}
1451
1452uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1453{
1454    return latency;
1455}
1456
1457uint32_t AudioFlinger::PlaybackThread::latency() const
1458{
1459    Mutex::Autolock _l(mLock);
1460    return latency_l();
1461}
1462uint32_t AudioFlinger::PlaybackThread::latency_l() const
1463{
1464    if (initCheck() == NO_ERROR) {
1465        return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1466    } else {
1467        return 0;
1468    }
1469}
1470
1471void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1472{
1473    Mutex::Autolock _l(mLock);
1474    // Don't apply master volume in SW if our HAL can do it for us.
1475    if (mOutput && mOutput->audioHwDev &&
1476        mOutput->audioHwDev->canSetMasterVolume()) {
1477        mMasterVolume = 1.0;
1478    } else {
1479        mMasterVolume = value;
1480    }
1481}
1482
1483void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1484{
1485    Mutex::Autolock _l(mLock);
1486    // Don't apply master mute in SW if our HAL can do it for us.
1487    if (mOutput && mOutput->audioHwDev &&
1488        mOutput->audioHwDev->canSetMasterMute()) {
1489        mMasterMute = false;
1490    } else {
1491        mMasterMute = muted;
1492    }
1493}
1494
1495void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1496{
1497    Mutex::Autolock _l(mLock);
1498    mStreamTypes[stream].volume = value;
1499    broadcast_l();
1500}
1501
1502void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1503{
1504    Mutex::Autolock _l(mLock);
1505    mStreamTypes[stream].mute = muted;
1506    broadcast_l();
1507}
1508
1509float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1510{
1511    Mutex::Autolock _l(mLock);
1512    return mStreamTypes[stream].volume;
1513}
1514
1515// addTrack_l() must be called with ThreadBase::mLock held
1516status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1517{
1518    status_t status = ALREADY_EXISTS;
1519
1520    // set retry count for buffer fill
1521    track->mRetryCount = kMaxTrackStartupRetries;
1522    if (mActiveTracks.indexOf(track) < 0) {
1523        // the track is newly added, make sure it fills up all its
1524        // buffers before playing. This is to ensure the client will
1525        // effectively get the latency it requested.
1526        if (!track->isOutputTrack()) {
1527            TrackBase::track_state state = track->mState;
1528            mLock.unlock();
1529            status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId());
1530            mLock.lock();
1531            // abort track was stopped/paused while we released the lock
1532            if (state != track->mState) {
1533                if (status == NO_ERROR) {
1534                    mLock.unlock();
1535                    AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1536                    mLock.lock();
1537                }
1538                return INVALID_OPERATION;
1539            }
1540            // abort if start is rejected by audio policy manager
1541            if (status != NO_ERROR) {
1542                return PERMISSION_DENIED;
1543            }
1544#ifdef ADD_BATTERY_DATA
1545            // to track the speaker usage
1546            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1547#endif
1548        }
1549
1550        track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
1551        track->mResetDone = false;
1552        track->mPresentationCompleteFrames = 0;
1553        mActiveTracks.add(track);
1554        mWakeLockUids.add(track->uid());
1555        mActiveTracksGeneration++;
1556        mLatestActiveTrack = track;
1557        sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1558        if (chain != 0) {
1559            ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1560                    track->sessionId());
1561            chain->incActiveTrackCnt();
1562        }
1563
1564        status = NO_ERROR;
1565    }
1566
1567    onAddNewTrack_l();
1568    return status;
1569}
1570
1571bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1572{
1573    track->terminate();
1574    // active tracks are removed by threadLoop()
1575    bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1576    track->mState = TrackBase::STOPPED;
1577    if (!trackActive) {
1578        removeTrack_l(track);
1579    } else if (track->isFastTrack() || track->isOffloaded()) {
1580        track->mState = TrackBase::STOPPING_1;
1581    }
1582
1583    return trackActive;
1584}
1585
1586void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1587{
1588    track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1589    mTracks.remove(track);
1590    deleteTrackName_l(track->name());
1591    // redundant as track is about to be destroyed, for dumpsys only
1592    track->mName = -1;
1593    if (track->isFastTrack()) {
1594        int index = track->mFastIndex;
1595        ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1596        ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1597        mFastTrackAvailMask |= 1 << index;
1598        // redundant as track is about to be destroyed, for dumpsys only
1599        track->mFastIndex = -1;
1600    }
1601    sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1602    if (chain != 0) {
1603        chain->decTrackCnt();
1604    }
1605}
1606
1607void AudioFlinger::PlaybackThread::broadcast_l()
1608{
1609    // Thread could be blocked waiting for async
1610    // so signal it to handle state changes immediately
1611    // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1612    // be lost so we also flag to prevent it blocking on mWaitWorkCV
1613    mSignalPending = true;
1614    mWaitWorkCV.broadcast();
1615}
1616
1617String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1618{
1619    Mutex::Autolock _l(mLock);
1620    if (initCheck() != NO_ERROR) {
1621        return String8();
1622    }
1623
1624    char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1625    const String8 out_s8(s);
1626    free(s);
1627    return out_s8;
1628}
1629
1630// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1631void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1632    AudioSystem::OutputDescriptor desc;
1633    void *param2 = NULL;
1634
1635    ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
1636            param);
1637
1638    switch (event) {
1639    case AudioSystem::OUTPUT_OPENED:
1640    case AudioSystem::OUTPUT_CONFIG_CHANGED:
1641        desc.channelMask = mChannelMask;
1642        desc.samplingRate = mSampleRate;
1643        desc.format = mFormat;
1644        desc.frameCount = mNormalFrameCount; // FIXME see
1645                                             // AudioFlinger::frameCount(audio_io_handle_t)
1646        desc.latency = latency();
1647        param2 = &desc;
1648        break;
1649
1650    case AudioSystem::STREAM_CONFIG_CHANGED:
1651        param2 = &param;
1652    case AudioSystem::OUTPUT_CLOSED:
1653    default:
1654        break;
1655    }
1656    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1657}
1658
1659void AudioFlinger::PlaybackThread::writeCallback()
1660{
1661    ALOG_ASSERT(mCallbackThread != 0);
1662    mCallbackThread->resetWriteBlocked();
1663}
1664
1665void AudioFlinger::PlaybackThread::drainCallback()
1666{
1667    ALOG_ASSERT(mCallbackThread != 0);
1668    mCallbackThread->resetDraining();
1669}
1670
1671void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
1672{
1673    Mutex::Autolock _l(mLock);
1674    // reject out of sequence requests
1675    if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1676        mWriteAckSequence &= ~1;
1677        mWaitWorkCV.signal();
1678    }
1679}
1680
1681void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
1682{
1683    Mutex::Autolock _l(mLock);
1684    // reject out of sequence requests
1685    if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1686        mDrainSequence &= ~1;
1687        mWaitWorkCV.signal();
1688    }
1689}
1690
1691// static
1692int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1693                                                void *param __unused,
1694                                                void *cookie)
1695{
1696    AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1697    ALOGV("asyncCallback() event %d", event);
1698    switch (event) {
1699    case STREAM_CBK_EVENT_WRITE_READY:
1700        me->writeCallback();
1701        break;
1702    case STREAM_CBK_EVENT_DRAIN_READY:
1703        me->drainCallback();
1704        break;
1705    default:
1706        ALOGW("asyncCallback() unknown event %d", event);
1707        break;
1708    }
1709    return 0;
1710}
1711
1712void AudioFlinger::PlaybackThread::readOutputParameters_l()
1713{
1714    // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
1715    mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1716    mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1717    if (!audio_is_output_channel(mChannelMask)) {
1718        LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
1719    }
1720    if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) {
1721        LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output; "
1722                "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask);
1723    }
1724    mChannelCount = popcount(mChannelMask);
1725    mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1726    if (!audio_is_valid_format(mFormat)) {
1727        LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
1728    }
1729    if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
1730        LOG_ALWAYS_FATAL("HAL format %#x not supported for mixed output; "
1731                "must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
1732    }
1733    mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1734    mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
1735    mFrameCount = mBufferSize / mFrameSize;
1736    if (mFrameCount & 15) {
1737        ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1738                mFrameCount);
1739    }
1740
1741    if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
1742            (mOutput->stream->set_callback != NULL)) {
1743        if (mOutput->stream->set_callback(mOutput->stream,
1744                                      AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
1745            mUseAsyncWrite = true;
1746            mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
1747        }
1748    }
1749
1750    // Calculate size of normal sink buffer relative to the HAL output buffer size
1751    double multiplier = 1.0;
1752    if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
1753            kUseFastMixer == FastMixer_Dynamic)) {
1754        size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
1755        size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
1756        // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
1757        minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
1758        maxNormalFrameCount = maxNormalFrameCount & ~15;
1759        if (maxNormalFrameCount < minNormalFrameCount) {
1760            maxNormalFrameCount = minNormalFrameCount;
1761        }
1762        multiplier = (double) minNormalFrameCount / (double) mFrameCount;
1763        if (multiplier <= 1.0) {
1764            multiplier = 1.0;
1765        } else if (multiplier <= 2.0) {
1766            if (2 * mFrameCount <= maxNormalFrameCount) {
1767                multiplier = 2.0;
1768            } else {
1769                multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
1770            }
1771        } else {
1772            // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
1773            // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
1774            // track, but we sometimes have to do this to satisfy the maximum frame count
1775            // constraint)
1776            // FIXME this rounding up should not be done if no HAL SRC
1777            uint32_t truncMult = (uint32_t) multiplier;
1778            if ((truncMult & 1)) {
1779                if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
1780                    ++truncMult;
1781                }
1782            }
1783            multiplier = (double) truncMult;
1784        }
1785    }
1786    mNormalFrameCount = multiplier * mFrameCount;
1787    // round up to nearest 16 frames to satisfy AudioMixer
1788    mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
1789    ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
1790            mNormalFrameCount);
1791
1792    // mSinkBuffer is the sink buffer.  Size is always multiple-of-16 frames.
1793    // Originally this was int16_t[] array, need to remove legacy implications.
1794    free(mSinkBuffer);
1795    mSinkBuffer = NULL;
1796    // For sink buffer size, we use the frame size from the downstream sink to avoid problems
1797    // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
1798    const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
1799    (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
1800
1801    // We resize the mMixerBuffer according to the requirements of the sink buffer which
1802    // drives the output.
1803    free(mMixerBuffer);
1804    mMixerBuffer = NULL;
1805    if (mMixerBufferEnabled) {
1806        mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
1807        mMixerBufferSize = mNormalFrameCount * mChannelCount
1808                * audio_bytes_per_sample(mMixerBufferFormat);
1809        (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
1810    }
1811    free(mEffectBuffer);
1812    mEffectBuffer = NULL;
1813    if (mEffectBufferEnabled) {
1814        mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
1815        mEffectBufferSize = mNormalFrameCount * mChannelCount
1816                * audio_bytes_per_sample(mEffectBufferFormat);
1817        (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
1818    }
1819
1820    // force reconfiguration of effect chains and engines to take new buffer size and audio
1821    // parameters into account
1822    // Note that mLock is not held when readOutputParameters_l() is called from the constructor
1823    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1824    // matter.
1825    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1826    Vector< sp<EffectChain> > effectChains = mEffectChains;
1827    for (size_t i = 0; i < effectChains.size(); i ++) {
1828        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1829    }
1830}
1831
1832
1833status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1834{
1835    if (halFrames == NULL || dspFrames == NULL) {
1836        return BAD_VALUE;
1837    }
1838    Mutex::Autolock _l(mLock);
1839    if (initCheck() != NO_ERROR) {
1840        return INVALID_OPERATION;
1841    }
1842    size_t framesWritten = mBytesWritten / mFrameSize;
1843    *halFrames = framesWritten;
1844
1845    if (isSuspended()) {
1846        // return an estimation of rendered frames when the output is suspended
1847        size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
1848        *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
1849        return NO_ERROR;
1850    } else {
1851        status_t status;
1852        uint32_t frames;
1853        status = mOutput->stream->get_render_position(mOutput->stream, &frames);
1854        *dspFrames = (size_t)frames;
1855        return status;
1856    }
1857}
1858
1859uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
1860{
1861    Mutex::Autolock _l(mLock);
1862    uint32_t result = 0;
1863    if (getEffectChain_l(sessionId) != 0) {
1864        result = EFFECT_SESSION;
1865    }
1866
1867    for (size_t i = 0; i < mTracks.size(); ++i) {
1868        sp<Track> track = mTracks[i];
1869        if (sessionId == track->sessionId() && !track->isInvalid()) {
1870            result |= TRACK_SESSION;
1871            break;
1872        }
1873    }
1874
1875    return result;
1876}
1877
1878uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1879{
1880    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1881    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1882    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1883        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1884    }
1885    for (size_t i = 0; i < mTracks.size(); i++) {
1886        sp<Track> track = mTracks[i];
1887        if (sessionId == track->sessionId() && !track->isInvalid()) {
1888            return AudioSystem::getStrategyForStream(track->streamType());
1889        }
1890    }
1891    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1892}
1893
1894
1895AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1896{
1897    Mutex::Autolock _l(mLock);
1898    return mOutput;
1899}
1900
1901AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1902{
1903    Mutex::Autolock _l(mLock);
1904    AudioStreamOut *output = mOutput;
1905    mOutput = NULL;
1906    // FIXME FastMixer might also have a raw ptr to mOutputSink;
1907    //       must push a NULL and wait for ack
1908    mOutputSink.clear();
1909    mPipeSink.clear();
1910    mNormalSink.clear();
1911    return output;
1912}
1913
1914// this method must always be called either with ThreadBase mLock held or inside the thread loop
1915audio_stream_t* AudioFlinger::PlaybackThread::stream() const
1916{
1917    if (mOutput == NULL) {
1918        return NULL;
1919    }
1920    return &mOutput->stream->common;
1921}
1922
1923uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
1924{
1925    return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
1926}
1927
1928status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
1929{
1930    if (!isValidSyncEvent(event)) {
1931        return BAD_VALUE;
1932    }
1933
1934    Mutex::Autolock _l(mLock);
1935
1936    for (size_t i = 0; i < mTracks.size(); ++i) {
1937        sp<Track> track = mTracks[i];
1938        if (event->triggerSession() == track->sessionId()) {
1939            (void) track->setSyncEvent(event);
1940            return NO_ERROR;
1941        }
1942    }
1943
1944    return NAME_NOT_FOUND;
1945}
1946
1947bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
1948{
1949    return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
1950}
1951
1952void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
1953        const Vector< sp<Track> >& tracksToRemove)
1954{
1955    size_t count = tracksToRemove.size();
1956    if (count > 0) {
1957        for (size_t i = 0 ; i < count ; i++) {
1958            const sp<Track>& track = tracksToRemove.itemAt(i);
1959            if (!track->isOutputTrack()) {
1960                AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
1961#ifdef ADD_BATTERY_DATA
1962                // to track the speaker usage
1963                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
1964#endif
1965                if (track->isTerminated()) {
1966                    AudioSystem::releaseOutput(mId);
1967                }
1968            }
1969        }
1970    }
1971}
1972
1973void AudioFlinger::PlaybackThread::checkSilentMode_l()
1974{
1975    if (!mMasterMute) {
1976        char value[PROPERTY_VALUE_MAX];
1977        if (property_get("ro.audio.silent", value, "0") > 0) {
1978            char *endptr;
1979            unsigned long ul = strtoul(value, &endptr, 0);
1980            if (*endptr == '\0' && ul != 0) {
1981                ALOGD("Silence is golden");
1982                // The setprop command will not allow a property to be changed after
1983                // the first time it is set, so we don't have to worry about un-muting.
1984                setMasterMute_l(true);
1985            }
1986        }
1987    }
1988}
1989
1990// shared by MIXER and DIRECT, overridden by DUPLICATING
1991ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
1992{
1993    // FIXME rewrite to reduce number of system calls
1994    mLastWriteTime = systemTime();
1995    mInWrite = true;
1996    ssize_t bytesWritten;
1997    const size_t offset = mCurrentWriteLength - mBytesRemaining;
1998
1999    // If an NBAIO sink is present, use it to write the normal mixer's submix
2000    if (mNormalSink != 0) {
2001        const size_t count = mBytesRemaining / mFrameSize;
2002
2003        ATRACE_BEGIN("write");
2004        // update the setpoint when AudioFlinger::mScreenState changes
2005        uint32_t screenState = AudioFlinger::mScreenState;
2006        if (screenState != mScreenState) {
2007            mScreenState = screenState;
2008            MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2009            if (pipe != NULL) {
2010                pipe->setAvgFrames((mScreenState & 1) ?
2011                        (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2012            }
2013        }
2014        ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
2015        ATRACE_END();
2016        if (framesWritten > 0) {
2017            bytesWritten = framesWritten * mFrameSize;
2018        } else {
2019            bytesWritten = framesWritten;
2020        }
2021        status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
2022        if (status == NO_ERROR) {
2023            size_t totalFramesWritten = mNormalSink->framesWritten();
2024            if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2025                mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2026                mLatchDValid = true;
2027            }
2028        }
2029    // otherwise use the HAL / AudioStreamOut directly
2030    } else {
2031        // Direct output and offload threads
2032
2033        if (mUseAsyncWrite) {
2034            ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2035            mWriteAckSequence += 2;
2036            mWriteAckSequence |= 1;
2037            ALOG_ASSERT(mCallbackThread != 0);
2038            mCallbackThread->setWriteBlocked(mWriteAckSequence);
2039        }
2040        // FIXME We should have an implementation of timestamps for direct output threads.
2041        // They are used e.g for multichannel PCM playback over HDMI.
2042        bytesWritten = mOutput->stream->write(mOutput->stream,
2043                                                   (char *)mSinkBuffer + offset, mBytesRemaining);
2044        if (mUseAsyncWrite &&
2045                ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2046            // do not wait for async callback in case of error of full write
2047            mWriteAckSequence &= ~1;
2048            ALOG_ASSERT(mCallbackThread != 0);
2049            mCallbackThread->setWriteBlocked(mWriteAckSequence);
2050        }
2051    }
2052
2053    mNumWrites++;
2054    mInWrite = false;
2055    mStandby = false;
2056    return bytesWritten;
2057}
2058
2059void AudioFlinger::PlaybackThread::threadLoop_drain()
2060{
2061    if (mOutput->stream->drain) {
2062        ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2063        if (mUseAsyncWrite) {
2064            ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2065            mDrainSequence |= 1;
2066            ALOG_ASSERT(mCallbackThread != 0);
2067            mCallbackThread->setDraining(mDrainSequence);
2068        }
2069        mOutput->stream->drain(mOutput->stream,
2070            (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2071                                                : AUDIO_DRAIN_ALL);
2072    }
2073}
2074
2075void AudioFlinger::PlaybackThread::threadLoop_exit()
2076{
2077    // Default implementation has nothing to do
2078}
2079
2080/*
2081The derived values that are cached:
2082 - mSinkBufferSize from frame count * frame size
2083 - activeSleepTime from activeSleepTimeUs()
2084 - idleSleepTime from idleSleepTimeUs()
2085 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2086 - maxPeriod from frame count and sample rate (MIXER only)
2087
2088The parameters that affect these derived values are:
2089 - frame count
2090 - frame size
2091 - sample rate
2092 - device type: A2DP or not
2093 - device latency
2094 - format: PCM or not
2095 - active sleep time
2096 - idle sleep time
2097*/
2098
2099void AudioFlinger::PlaybackThread::cacheParameters_l()
2100{
2101    mSinkBufferSize = mNormalFrameCount * mFrameSize;
2102    activeSleepTime = activeSleepTimeUs();
2103    idleSleepTime = idleSleepTimeUs();
2104}
2105
2106void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2107{
2108    ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2109            this,  streamType, mTracks.size());
2110    Mutex::Autolock _l(mLock);
2111
2112    size_t size = mTracks.size();
2113    for (size_t i = 0; i < size; i++) {
2114        sp<Track> t = mTracks[i];
2115        if (t->streamType() == streamType) {
2116            t->invalidate();
2117        }
2118    }
2119}
2120
2121status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2122{
2123    int session = chain->sessionId();
2124    int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2125            ? mEffectBuffer : mSinkBuffer);
2126    bool ownsBuffer = false;
2127
2128    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2129    if (session > 0) {
2130        // Only one effect chain can be present in direct output thread and it uses
2131        // the sink buffer as input
2132        if (mType != DIRECT) {
2133            size_t numSamples = mNormalFrameCount * mChannelCount;
2134            buffer = new int16_t[numSamples];
2135            memset(buffer, 0, numSamples * sizeof(int16_t));
2136            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2137            ownsBuffer = true;
2138        }
2139
2140        // Attach all tracks with same session ID to this chain.
2141        for (size_t i = 0; i < mTracks.size(); ++i) {
2142            sp<Track> track = mTracks[i];
2143            if (session == track->sessionId()) {
2144                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2145                        buffer);
2146                track->setMainBuffer(buffer);
2147                chain->incTrackCnt();
2148            }
2149        }
2150
2151        // indicate all active tracks in the chain
2152        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2153            sp<Track> track = mActiveTracks[i].promote();
2154            if (track == 0) {
2155                continue;
2156            }
2157            if (session == track->sessionId()) {
2158                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2159                chain->incActiveTrackCnt();
2160            }
2161        }
2162    }
2163
2164    chain->setInBuffer(buffer, ownsBuffer);
2165    chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2166            ? mEffectBuffer : mSinkBuffer));
2167    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2168    // chains list in order to be processed last as it contains output stage effects
2169    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2170    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2171    // after track specific effects and before output stage
2172    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2173    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2174    // Effect chain for other sessions are inserted at beginning of effect
2175    // chains list to be processed before output mix effects. Relative order between other
2176    // sessions is not important
2177    size_t size = mEffectChains.size();
2178    size_t i = 0;
2179    for (i = 0; i < size; i++) {
2180        if (mEffectChains[i]->sessionId() < session) {
2181            break;
2182        }
2183    }
2184    mEffectChains.insertAt(chain, i);
2185    checkSuspendOnAddEffectChain_l(chain);
2186
2187    return NO_ERROR;
2188}
2189
2190size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2191{
2192    int session = chain->sessionId();
2193
2194    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2195
2196    for (size_t i = 0; i < mEffectChains.size(); i++) {
2197        if (chain == mEffectChains[i]) {
2198            mEffectChains.removeAt(i);
2199            // detach all active tracks from the chain
2200            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2201                sp<Track> track = mActiveTracks[i].promote();
2202                if (track == 0) {
2203                    continue;
2204                }
2205                if (session == track->sessionId()) {
2206                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2207                            chain.get(), session);
2208                    chain->decActiveTrackCnt();
2209                }
2210            }
2211
2212            // detach all tracks with same session ID from this chain
2213            for (size_t i = 0; i < mTracks.size(); ++i) {
2214                sp<Track> track = mTracks[i];
2215                if (session == track->sessionId()) {
2216                    track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
2217                    chain->decTrackCnt();
2218                }
2219            }
2220            break;
2221        }
2222    }
2223    return mEffectChains.size();
2224}
2225
2226status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2227        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2228{
2229    Mutex::Autolock _l(mLock);
2230    return attachAuxEffect_l(track, EffectId);
2231}
2232
2233status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2234        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2235{
2236    status_t status = NO_ERROR;
2237
2238    if (EffectId == 0) {
2239        track->setAuxBuffer(0, NULL);
2240    } else {
2241        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2242        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2243        if (effect != 0) {
2244            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2245                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2246            } else {
2247                status = INVALID_OPERATION;
2248            }
2249        } else {
2250            status = BAD_VALUE;
2251        }
2252    }
2253    return status;
2254}
2255
2256void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2257{
2258    for (size_t i = 0; i < mTracks.size(); ++i) {
2259        sp<Track> track = mTracks[i];
2260        if (track->auxEffectId() == effectId) {
2261            attachAuxEffect_l(track, 0);
2262        }
2263    }
2264}
2265
2266bool AudioFlinger::PlaybackThread::threadLoop()
2267{
2268    Vector< sp<Track> > tracksToRemove;
2269
2270    standbyTime = systemTime();
2271
2272    // MIXER
2273    nsecs_t lastWarning = 0;
2274
2275    // DUPLICATING
2276    // FIXME could this be made local to while loop?
2277    writeFrames = 0;
2278
2279    int lastGeneration = 0;
2280
2281    cacheParameters_l();
2282    sleepTime = idleSleepTime;
2283
2284    if (mType == MIXER) {
2285        sleepTimeShift = 0;
2286    }
2287
2288    CpuStats cpuStats;
2289    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2290
2291    acquireWakeLock();
2292
2293    // mNBLogWriter->log can only be called while thread mutex mLock is held.
2294    // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2295    // and then that string will be logged at the next convenient opportunity.
2296    const char *logString = NULL;
2297
2298    checkSilentMode_l();
2299
2300    while (!exitPending())
2301    {
2302        cpuStats.sample(myName);
2303
2304        Vector< sp<EffectChain> > effectChains;
2305
2306        processConfigEvents();
2307
2308        { // scope for mLock
2309
2310            Mutex::Autolock _l(mLock);
2311
2312            if (logString != NULL) {
2313                mNBLogWriter->logTimestamp();
2314                mNBLogWriter->log(logString);
2315                logString = NULL;
2316            }
2317
2318            if (mLatchDValid) {
2319                mLatchQ = mLatchD;
2320                mLatchDValid = false;
2321                mLatchQValid = true;
2322            }
2323
2324            if (checkForNewParameters_l()) {
2325                cacheParameters_l();
2326            }
2327
2328            saveOutputTracks();
2329            if (mSignalPending) {
2330                // A signal was raised while we were unlocked
2331                mSignalPending = false;
2332            } else if (waitingAsyncCallback_l()) {
2333                if (exitPending()) {
2334                    break;
2335                }
2336                releaseWakeLock_l();
2337                mWakeLockUids.clear();
2338                mActiveTracksGeneration++;
2339                ALOGV("wait async completion");
2340                mWaitWorkCV.wait(mLock);
2341                ALOGV("async completion/wake");
2342                acquireWakeLock_l();
2343                standbyTime = systemTime() + standbyDelay;
2344                sleepTime = 0;
2345
2346                continue;
2347            }
2348            if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
2349                                   isSuspended()) {
2350                // put audio hardware into standby after short delay
2351                if (shouldStandby_l()) {
2352
2353                    threadLoop_standby();
2354
2355                    mStandby = true;
2356                }
2357
2358                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2359                    // we're about to wait, flush the binder command buffer
2360                    IPCThreadState::self()->flushCommands();
2361
2362                    clearOutputTracks();
2363
2364                    if (exitPending()) {
2365                        break;
2366                    }
2367
2368                    releaseWakeLock_l();
2369                    mWakeLockUids.clear();
2370                    mActiveTracksGeneration++;
2371                    // wait until we have something to do...
2372                    ALOGV("%s going to sleep", myName.string());
2373                    mWaitWorkCV.wait(mLock);
2374                    ALOGV("%s waking up", myName.string());
2375                    acquireWakeLock_l();
2376
2377                    mMixerStatus = MIXER_IDLE;
2378                    mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2379                    mBytesWritten = 0;
2380                    mBytesRemaining = 0;
2381                    checkSilentMode_l();
2382
2383                    standbyTime = systemTime() + standbyDelay;
2384                    sleepTime = idleSleepTime;
2385                    if (mType == MIXER) {
2386                        sleepTimeShift = 0;
2387                    }
2388
2389                    continue;
2390                }
2391            }
2392            // mMixerStatusIgnoringFastTracks is also updated internally
2393            mMixerStatus = prepareTracks_l(&tracksToRemove);
2394
2395            // compare with previously applied list
2396            if (lastGeneration != mActiveTracksGeneration) {
2397                // update wakelock
2398                updateWakeLockUids_l(mWakeLockUids);
2399                lastGeneration = mActiveTracksGeneration;
2400            }
2401
2402            // prevent any changes in effect chain list and in each effect chain
2403            // during mixing and effect process as the audio buffers could be deleted
2404            // or modified if an effect is created or deleted
2405            lockEffectChains_l(effectChains);
2406        } // mLock scope ends
2407
2408        if (mBytesRemaining == 0) {
2409            mCurrentWriteLength = 0;
2410            if (mMixerStatus == MIXER_TRACKS_READY) {
2411                // threadLoop_mix() sets mCurrentWriteLength
2412                threadLoop_mix();
2413            } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2414                        && (mMixerStatus != MIXER_DRAIN_ALL)) {
2415                // threadLoop_sleepTime sets sleepTime to 0 if data
2416                // must be written to HAL
2417                threadLoop_sleepTime();
2418                if (sleepTime == 0) {
2419                    mCurrentWriteLength = mSinkBufferSize;
2420                }
2421            }
2422            // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2423            // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2424            // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2425            // or mSinkBuffer (if there are no effects).
2426            //
2427            // This is done pre-effects computation; if effects change to
2428            // support higher precision, this needs to move.
2429            //
2430            // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2431            // TODO use sleepTime == 0 as an additional condition.
2432            if (mMixerBufferValid) {
2433                void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2434                audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2435
2436                memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2437                        mNormalFrameCount * mChannelCount);
2438            }
2439
2440            mBytesRemaining = mCurrentWriteLength;
2441            if (isSuspended()) {
2442                sleepTime = suspendSleepTimeUs();
2443                // simulate write to HAL when suspended
2444                mBytesWritten += mSinkBufferSize;
2445                mBytesRemaining = 0;
2446            }
2447
2448            // only process effects if we're going to write
2449            if (sleepTime == 0 && mType != OFFLOAD) {
2450                for (size_t i = 0; i < effectChains.size(); i ++) {
2451                    effectChains[i]->process_l();
2452                }
2453            }
2454        }
2455        // Process effect chains for offloaded thread even if no audio
2456        // was read from audio track: process only updates effect state
2457        // and thus does have to be synchronized with audio writes but may have
2458        // to be called while waiting for async write callback
2459        if (mType == OFFLOAD) {
2460            for (size_t i = 0; i < effectChains.size(); i ++) {
2461                effectChains[i]->process_l();
2462            }
2463        }
2464
2465        // Only if the Effects buffer is enabled and there is data in the
2466        // Effects buffer (buffer valid), we need to
2467        // copy into the sink buffer.
2468        // TODO use sleepTime == 0 as an additional condition.
2469        if (mEffectBufferValid) {
2470            //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2471            memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2472                    mNormalFrameCount * mChannelCount);
2473        }
2474
2475        // enable changes in effect chain
2476        unlockEffectChains(effectChains);
2477
2478        if (!waitingAsyncCallback()) {
2479            // sleepTime == 0 means we must write to audio hardware
2480            if (sleepTime == 0) {
2481                if (mBytesRemaining) {
2482                    ssize_t ret = threadLoop_write();
2483                    if (ret < 0) {
2484                        mBytesRemaining = 0;
2485                    } else {
2486                        mBytesWritten += ret;
2487                        mBytesRemaining -= ret;
2488                    }
2489                } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2490                        (mMixerStatus == MIXER_DRAIN_ALL)) {
2491                    threadLoop_drain();
2492                }
2493                if (mType == MIXER) {
2494                    // write blocked detection
2495                    nsecs_t now = systemTime();
2496                    nsecs_t delta = now - mLastWriteTime;
2497                    if (!mStandby && delta > maxPeriod) {
2498                        mNumDelayedWrites++;
2499                        if ((now - lastWarning) > kWarningThrottleNs) {
2500                            ATRACE_NAME("underrun");
2501                            ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2502                                    ns2ms(delta), mNumDelayedWrites, this);
2503                            lastWarning = now;
2504                        }
2505                    }
2506                }
2507
2508            } else {
2509                usleep(sleepTime);
2510            }
2511        }
2512
2513        // Finally let go of removed track(s), without the lock held
2514        // since we can't guarantee the destructors won't acquire that
2515        // same lock.  This will also mutate and push a new fast mixer state.
2516        threadLoop_removeTracks(tracksToRemove);
2517        tracksToRemove.clear();
2518
2519        // FIXME I don't understand the need for this here;
2520        //       it was in the original code but maybe the
2521        //       assignment in saveOutputTracks() makes this unnecessary?
2522        clearOutputTracks();
2523
2524        // Effect chains will be actually deleted here if they were removed from
2525        // mEffectChains list during mixing or effects processing
2526        effectChains.clear();
2527
2528        // FIXME Note that the above .clear() is no longer necessary since effectChains
2529        // is now local to this block, but will keep it for now (at least until merge done).
2530    }
2531
2532    threadLoop_exit();
2533
2534    // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2535    if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) {
2536        // put output stream into standby mode
2537        if (!mStandby) {
2538            mOutput->stream->common.standby(&mOutput->stream->common);
2539        }
2540    }
2541
2542    releaseWakeLock();
2543    mWakeLockUids.clear();
2544    mActiveTracksGeneration++;
2545
2546    ALOGV("Thread %p type %d exiting", this, mType);
2547    return false;
2548}
2549
2550// removeTracks_l() must be called with ThreadBase::mLock held
2551void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2552{
2553    size_t count = tracksToRemove.size();
2554    if (count > 0) {
2555        for (size_t i=0 ; i<count ; i++) {
2556            const sp<Track>& track = tracksToRemove.itemAt(i);
2557            mActiveTracks.remove(track);
2558            mWakeLockUids.remove(track->uid());
2559            mActiveTracksGeneration++;
2560            ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2561            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2562            if (chain != 0) {
2563                ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2564                        track->sessionId());
2565                chain->decActiveTrackCnt();
2566            }
2567            if (track->isTerminated()) {
2568                removeTrack_l(track);
2569            }
2570        }
2571    }
2572
2573}
2574
2575status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2576{
2577    if (mNormalSink != 0) {
2578        return mNormalSink->getTimestamp(timestamp);
2579    }
2580    if (mType == OFFLOAD && mOutput->stream->get_presentation_position) {
2581        uint64_t position64;
2582        int ret = mOutput->stream->get_presentation_position(
2583                                                mOutput->stream, &position64, &timestamp.mTime);
2584        if (ret == 0) {
2585            timestamp.mPosition = (uint32_t)position64;
2586            return NO_ERROR;
2587        }
2588    }
2589    return INVALID_OPERATION;
2590}
2591// ----------------------------------------------------------------------------
2592
2593AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2594        audio_io_handle_t id, audio_devices_t device, type_t type)
2595    :   PlaybackThread(audioFlinger, output, id, device, type),
2596        // mAudioMixer below
2597        // mFastMixer below
2598        mFastMixerFutex(0)
2599        // mOutputSink below
2600        // mPipeSink below
2601        // mNormalSink below
2602{
2603    ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
2604    ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
2605            "mFrameCount=%d, mNormalFrameCount=%d",
2606            mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2607            mNormalFrameCount);
2608    mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2609
2610    // FIXME - Current mixer implementation only supports stereo output
2611    if (mChannelCount != FCC_2) {
2612        ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2613    }
2614
2615    // create an NBAIO sink for the HAL output stream, and negotiate
2616    mOutputSink = new AudioStreamOutSink(output->stream);
2617    size_t numCounterOffers = 0;
2618    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
2619    ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2620    ALOG_ASSERT(index == 0);
2621
2622    // initialize fast mixer depending on configuration
2623    bool initFastMixer;
2624    switch (kUseFastMixer) {
2625    case FastMixer_Never:
2626        initFastMixer = false;
2627        break;
2628    case FastMixer_Always:
2629        initFastMixer = true;
2630        break;
2631    case FastMixer_Static:
2632    case FastMixer_Dynamic:
2633        initFastMixer = mFrameCount < mNormalFrameCount;
2634        break;
2635    }
2636    if (initFastMixer) {
2637
2638        // create a MonoPipe to connect our submix to FastMixer
2639        NBAIO_Format format = mOutputSink->format();
2640        // This pipe depth compensates for scheduling latency of the normal mixer thread.
2641        // When it wakes up after a maximum latency, it runs a few cycles quickly before
2642        // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
2643        MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2644        const NBAIO_Format offers[1] = {format};
2645        size_t numCounterOffers = 0;
2646        ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2647        ALOG_ASSERT(index == 0);
2648        monoPipe->setAvgFrames((mScreenState & 1) ?
2649                (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2650        mPipeSink = monoPipe;
2651
2652#ifdef TEE_SINK
2653        if (mTeeSinkOutputEnabled) {
2654            // create a Pipe to archive a copy of FastMixer's output for dumpsys
2655            Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format);
2656            numCounterOffers = 0;
2657            index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2658            ALOG_ASSERT(index == 0);
2659            mTeeSink = teeSink;
2660            PipeReader *teeSource = new PipeReader(*teeSink);
2661            numCounterOffers = 0;
2662            index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2663            ALOG_ASSERT(index == 0);
2664            mTeeSource = teeSource;
2665        }
2666#endif
2667
2668        // create fast mixer and configure it initially with just one fast track for our submix
2669        mFastMixer = new FastMixer();
2670        FastMixerStateQueue *sq = mFastMixer->sq();
2671#ifdef STATE_QUEUE_DUMP
2672        sq->setObserverDump(&mStateQueueObserverDump);
2673        sq->setMutatorDump(&mStateQueueMutatorDump);
2674#endif
2675        FastMixerState *state = sq->begin();
2676        FastTrack *fastTrack = &state->mFastTracks[0];
2677        // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2678        fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2679        fastTrack->mVolumeProvider = NULL;
2680        fastTrack->mGeneration++;
2681        state->mFastTracksGen++;
2682        state->mTrackMask = 1;
2683        // fast mixer will use the HAL output sink
2684        state->mOutputSink = mOutputSink.get();
2685        state->mOutputSinkGen++;
2686        state->mFrameCount = mFrameCount;
2687        state->mCommand = FastMixerState::COLD_IDLE;
2688        // already done in constructor initialization list
2689        //mFastMixerFutex = 0;
2690        state->mColdFutexAddr = &mFastMixerFutex;
2691        state->mColdGen++;
2692        state->mDumpState = &mFastMixerDumpState;
2693#ifdef TEE_SINK
2694        state->mTeeSink = mTeeSink.get();
2695#endif
2696        mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
2697        state->mNBLogWriter = mFastMixerNBLogWriter.get();
2698        sq->end();
2699        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2700
2701        // start the fast mixer
2702        mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2703        pid_t tid = mFastMixer->getTid();
2704        int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2705        if (err != 0) {
2706            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2707                    kPriorityFastMixer, getpid_cached, tid, err);
2708        }
2709
2710#ifdef AUDIO_WATCHDOG
2711        // create and start the watchdog
2712        mAudioWatchdog = new AudioWatchdog();
2713        mAudioWatchdog->setDump(&mAudioWatchdogDump);
2714        mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2715        tid = mAudioWatchdog->getTid();
2716        err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2717        if (err != 0) {
2718            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2719                    kPriorityFastMixer, getpid_cached, tid, err);
2720        }
2721#endif
2722
2723    } else {
2724        mFastMixer = NULL;
2725    }
2726
2727    switch (kUseFastMixer) {
2728    case FastMixer_Never:
2729    case FastMixer_Dynamic:
2730        mNormalSink = mOutputSink;
2731        break;
2732    case FastMixer_Always:
2733        mNormalSink = mPipeSink;
2734        break;
2735    case FastMixer_Static:
2736        mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2737        break;
2738    }
2739}
2740
2741AudioFlinger::MixerThread::~MixerThread()
2742{
2743    if (mFastMixer != NULL) {
2744        FastMixerStateQueue *sq = mFastMixer->sq();
2745        FastMixerState *state = sq->begin();
2746        if (state->mCommand == FastMixerState::COLD_IDLE) {
2747            int32_t old = android_atomic_inc(&mFastMixerFutex);
2748            if (old == -1) {
2749                __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2750            }
2751        }
2752        state->mCommand = FastMixerState::EXIT;
2753        sq->end();
2754        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2755        mFastMixer->join();
2756        // Though the fast mixer thread has exited, it's state queue is still valid.
2757        // We'll use that extract the final state which contains one remaining fast track
2758        // corresponding to our sub-mix.
2759        state = sq->begin();
2760        ALOG_ASSERT(state->mTrackMask == 1);
2761        FastTrack *fastTrack = &state->mFastTracks[0];
2762        ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2763        delete fastTrack->mBufferProvider;
2764        sq->end(false /*didModify*/);
2765        delete mFastMixer;
2766#ifdef AUDIO_WATCHDOG
2767        if (mAudioWatchdog != 0) {
2768            mAudioWatchdog->requestExit();
2769            mAudioWatchdog->requestExitAndWait();
2770            mAudioWatchdog.clear();
2771        }
2772#endif
2773    }
2774    mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
2775    delete mAudioMixer;
2776}
2777
2778
2779uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
2780{
2781    if (mFastMixer != NULL) {
2782        MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2783        latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
2784    }
2785    return latency;
2786}
2787
2788
2789void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2790{
2791    PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2792}
2793
2794ssize_t AudioFlinger::MixerThread::threadLoop_write()
2795{
2796    // FIXME we should only do one push per cycle; confirm this is true
2797    // Start the fast mixer if it's not already running
2798    if (mFastMixer != NULL) {
2799        FastMixerStateQueue *sq = mFastMixer->sq();
2800        FastMixerState *state = sq->begin();
2801        if (state->mCommand != FastMixerState::MIX_WRITE &&
2802                (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2803            if (state->mCommand == FastMixerState::COLD_IDLE) {
2804                int32_t old = android_atomic_inc(&mFastMixerFutex);
2805                if (old == -1) {
2806                    __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2807                }
2808#ifdef AUDIO_WATCHDOG
2809                if (mAudioWatchdog != 0) {
2810                    mAudioWatchdog->resume();
2811                }
2812#endif
2813            }
2814            state->mCommand = FastMixerState::MIX_WRITE;
2815            mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
2816                    FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN);
2817            sq->end();
2818            sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2819            if (kUseFastMixer == FastMixer_Dynamic) {
2820                mNormalSink = mPipeSink;
2821            }
2822        } else {
2823            sq->end(false /*didModify*/);
2824        }
2825    }
2826    return PlaybackThread::threadLoop_write();
2827}
2828
2829void AudioFlinger::MixerThread::threadLoop_standby()
2830{
2831    // Idle the fast mixer if it's currently running
2832    if (mFastMixer != NULL) {
2833        FastMixerStateQueue *sq = mFastMixer->sq();
2834        FastMixerState *state = sq->begin();
2835        if (!(state->mCommand & FastMixerState::IDLE)) {
2836            state->mCommand = FastMixerState::COLD_IDLE;
2837            state->mColdFutexAddr = &mFastMixerFutex;
2838            state->mColdGen++;
2839            mFastMixerFutex = 0;
2840            sq->end();
2841            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2842            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2843            if (kUseFastMixer == FastMixer_Dynamic) {
2844                mNormalSink = mOutputSink;
2845            }
2846#ifdef AUDIO_WATCHDOG
2847            if (mAudioWatchdog != 0) {
2848                mAudioWatchdog->pause();
2849            }
2850#endif
2851        } else {
2852            sq->end(false /*didModify*/);
2853        }
2854    }
2855    PlaybackThread::threadLoop_standby();
2856}
2857
2858bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
2859{
2860    return false;
2861}
2862
2863bool AudioFlinger::PlaybackThread::shouldStandby_l()
2864{
2865    return !mStandby;
2866}
2867
2868bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
2869{
2870    Mutex::Autolock _l(mLock);
2871    return waitingAsyncCallback_l();
2872}
2873
2874// shared by MIXER and DIRECT, overridden by DUPLICATING
2875void AudioFlinger::PlaybackThread::threadLoop_standby()
2876{
2877    ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2878    mOutput->stream->common.standby(&mOutput->stream->common);
2879    if (mUseAsyncWrite != 0) {
2880        // discard any pending drain or write ack by incrementing sequence
2881        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
2882        mDrainSequence = (mDrainSequence + 2) & ~1;
2883        ALOG_ASSERT(mCallbackThread != 0);
2884        mCallbackThread->setWriteBlocked(mWriteAckSequence);
2885        mCallbackThread->setDraining(mDrainSequence);
2886    }
2887}
2888
2889void AudioFlinger::PlaybackThread::onAddNewTrack_l()
2890{
2891    ALOGV("signal playback thread");
2892    broadcast_l();
2893}
2894
2895void AudioFlinger::MixerThread::threadLoop_mix()
2896{
2897    // obtain the presentation timestamp of the next output buffer
2898    int64_t pts;
2899    status_t status = INVALID_OPERATION;
2900
2901    if (mNormalSink != 0) {
2902        status = mNormalSink->getNextWriteTimestamp(&pts);
2903    } else {
2904        status = mOutputSink->getNextWriteTimestamp(&pts);
2905    }
2906
2907    if (status != NO_ERROR) {
2908        pts = AudioBufferProvider::kInvalidPTS;
2909    }
2910
2911    // mix buffers...
2912    mAudioMixer->process(pts);
2913    mCurrentWriteLength = mSinkBufferSize;
2914    // increase sleep time progressively when application underrun condition clears.
2915    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2916    // that a steady state of alternating ready/not ready conditions keeps the sleep time
2917    // such that we would underrun the audio HAL.
2918    if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2919        sleepTimeShift--;
2920    }
2921    sleepTime = 0;
2922    standbyTime = systemTime() + standbyDelay;
2923    //TODO: delay standby when effects have a tail
2924}
2925
2926void AudioFlinger::MixerThread::threadLoop_sleepTime()
2927{
2928    // If no tracks are ready, sleep once for the duration of an output
2929    // buffer size, then write 0s to the output
2930    if (sleepTime == 0) {
2931        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2932            sleepTime = activeSleepTime >> sleepTimeShift;
2933            if (sleepTime < kMinThreadSleepTimeUs) {
2934                sleepTime = kMinThreadSleepTimeUs;
2935            }
2936            // reduce sleep time in case of consecutive application underruns to avoid
2937            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2938            // duration we would end up writing less data than needed by the audio HAL if
2939            // the condition persists.
2940            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2941                sleepTimeShift++;
2942            }
2943        } else {
2944            sleepTime = idleSleepTime;
2945        }
2946    } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2947        // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
2948        // before effects processing or output.
2949        if (mMixerBufferValid) {
2950            memset(mMixerBuffer, 0, mMixerBufferSize);
2951        } else {
2952            memset(mSinkBuffer, 0, mSinkBufferSize);
2953        }
2954        sleepTime = 0;
2955        ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
2956                "anticipated start");
2957    }
2958    // TODO add standby time extension fct of effect tail
2959}
2960
2961// prepareTracks_l() must be called with ThreadBase::mLock held
2962AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2963        Vector< sp<Track> > *tracksToRemove)
2964{
2965
2966    mixer_state mixerStatus = MIXER_IDLE;
2967    // find out which tracks need to be processed
2968    size_t count = mActiveTracks.size();
2969    size_t mixedTracks = 0;
2970    size_t tracksWithEffect = 0;
2971    // counts only _active_ fast tracks
2972    size_t fastTracks = 0;
2973    uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2974
2975    float masterVolume = mMasterVolume;
2976    bool masterMute = mMasterMute;
2977
2978    if (masterMute) {
2979        masterVolume = 0;
2980    }
2981    // Delegate master volume control to effect in output mix effect chain if needed
2982    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2983    if (chain != 0) {
2984        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2985        chain->setVolume_l(&v, &v);
2986        masterVolume = (float)((v + (1 << 23)) >> 24);
2987        chain.clear();
2988    }
2989
2990    // prepare a new state to push
2991    FastMixerStateQueue *sq = NULL;
2992    FastMixerState *state = NULL;
2993    bool didModify = false;
2994    FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2995    if (mFastMixer != NULL) {
2996        sq = mFastMixer->sq();
2997        state = sq->begin();
2998    }
2999
3000    mMixerBufferValid = false;  // mMixerBuffer has no valid data until appropriate tracks found.
3001    mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
3002
3003    for (size_t i=0 ; i<count ; i++) {
3004        const sp<Track> t = mActiveTracks[i].promote();
3005        if (t == 0) {
3006            continue;
3007        }
3008
3009        // this const just means the local variable doesn't change
3010        Track* const track = t.get();
3011
3012        // process fast tracks
3013        if (track->isFastTrack()) {
3014
3015            // It's theoretically possible (though unlikely) for a fast track to be created
3016            // and then removed within the same normal mix cycle.  This is not a problem, as
3017            // the track never becomes active so it's fast mixer slot is never touched.
3018            // The converse, of removing an (active) track and then creating a new track
3019            // at the identical fast mixer slot within the same normal mix cycle,
3020            // is impossible because the slot isn't marked available until the end of each cycle.
3021            int j = track->mFastIndex;
3022            ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3023            ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3024            FastTrack *fastTrack = &state->mFastTracks[j];
3025
3026            // Determine whether the track is currently in underrun condition,
3027            // and whether it had a recent underrun.
3028            FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3029            FastTrackUnderruns underruns = ftDump->mUnderruns;
3030            uint32_t recentFull = (underruns.mBitFields.mFull -
3031                    track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3032            uint32_t recentPartial = (underruns.mBitFields.mPartial -
3033                    track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3034            uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3035                    track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3036            uint32_t recentUnderruns = recentPartial + recentEmpty;
3037            track->mObservedUnderruns = underruns;
3038            // don't count underruns that occur while stopping or pausing
3039            // or stopped which can occur when flush() is called while active
3040            if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3041                    recentUnderruns > 0) {
3042                // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3043                track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
3044            }
3045
3046            // This is similar to the state machine for normal tracks,
3047            // with a few modifications for fast tracks.
3048            bool isActive = true;
3049            switch (track->mState) {
3050            case TrackBase::STOPPING_1:
3051                // track stays active in STOPPING_1 state until first underrun
3052                if (recentUnderruns > 0 || track->isTerminated()) {
3053                    track->mState = TrackBase::STOPPING_2;
3054                }
3055                break;
3056            case TrackBase::PAUSING:
3057                // ramp down is not yet implemented
3058                track->setPaused();
3059                break;
3060            case TrackBase::RESUMING:
3061                // ramp up is not yet implemented
3062                track->mState = TrackBase::ACTIVE;
3063                break;
3064            case TrackBase::ACTIVE:
3065                if (recentFull > 0 || recentPartial > 0) {
3066                    // track has provided at least some frames recently: reset retry count
3067                    track->mRetryCount = kMaxTrackRetries;
3068                }
3069                if (recentUnderruns == 0) {
3070                    // no recent underruns: stay active
3071                    break;
3072                }
3073                // there has recently been an underrun of some kind
3074                if (track->sharedBuffer() == 0) {
3075                    // were any of the recent underruns "empty" (no frames available)?
3076                    if (recentEmpty == 0) {
3077                        // no, then ignore the partial underruns as they are allowed indefinitely
3078                        break;
3079                    }
3080                    // there has recently been an "empty" underrun: decrement the retry counter
3081                    if (--(track->mRetryCount) > 0) {
3082                        break;
3083                    }
3084                    // indicate to client process that the track was disabled because of underrun;
3085                    // it will then automatically call start() when data is available
3086                    android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
3087                    // remove from active list, but state remains ACTIVE [confusing but true]
3088                    isActive = false;
3089                    break;
3090                }
3091                // fall through
3092            case TrackBase::STOPPING_2:
3093            case TrackBase::PAUSED:
3094            case TrackBase::STOPPED:
3095            case TrackBase::FLUSHED:   // flush() while active
3096                // Check for presentation complete if track is inactive
3097                // We have consumed all the buffers of this track.
3098                // This would be incomplete if we auto-paused on underrun
3099                {
3100                    size_t audioHALFrames =
3101                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3102                    size_t framesWritten = mBytesWritten / mFrameSize;
3103                    if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3104                        // track stays in active list until presentation is complete
3105                        break;
3106                    }
3107                }
3108                if (track->isStopping_2()) {
3109                    track->mState = TrackBase::STOPPED;
3110                }
3111                if (track->isStopped()) {
3112                    // Can't reset directly, as fast mixer is still polling this track
3113                    //   track->reset();
3114                    // So instead mark this track as needing to be reset after push with ack
3115                    resetMask |= 1 << i;
3116                }
3117                isActive = false;
3118                break;
3119            case TrackBase::IDLE:
3120            default:
3121                LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
3122            }
3123
3124            if (isActive) {
3125                // was it previously inactive?
3126                if (!(state->mTrackMask & (1 << j))) {
3127                    ExtendedAudioBufferProvider *eabp = track;
3128                    VolumeProvider *vp = track;
3129                    fastTrack->mBufferProvider = eabp;
3130                    fastTrack->mVolumeProvider = vp;
3131                    fastTrack->mChannelMask = track->mChannelMask;
3132                    fastTrack->mGeneration++;
3133                    state->mTrackMask |= 1 << j;
3134                    didModify = true;
3135                    // no acknowledgement required for newly active tracks
3136                }
3137                // cache the combined master volume and stream type volume for fast mixer; this
3138                // lacks any synchronization or barrier so VolumeProvider may read a stale value
3139                track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
3140                ++fastTracks;
3141            } else {
3142                // was it previously active?
3143                if (state->mTrackMask & (1 << j)) {
3144                    fastTrack->mBufferProvider = NULL;
3145                    fastTrack->mGeneration++;
3146                    state->mTrackMask &= ~(1 << j);
3147                    didModify = true;
3148                    // If any fast tracks were removed, we must wait for acknowledgement
3149                    // because we're about to decrement the last sp<> on those tracks.
3150                    block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3151                } else {
3152                    LOG_ALWAYS_FATAL("fast track %d should have been active", j);
3153                }
3154                tracksToRemove->add(track);
3155                // Avoids a misleading display in dumpsys
3156                track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3157            }
3158            continue;
3159        }
3160
3161        {   // local variable scope to avoid goto warning
3162
3163        audio_track_cblk_t* cblk = track->cblk();
3164
3165        // The first time a track is added we wait
3166        // for all its buffers to be filled before processing it
3167        int name = track->name();
3168        // make sure that we have enough frames to mix one full buffer.
3169        // enforce this condition only once to enable draining the buffer in case the client
3170        // app does not call stop() and relies on underrun to stop:
3171        // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3172        // during last round
3173        size_t desiredFrames;
3174        uint32_t sr = track->sampleRate();
3175        if (sr == mSampleRate) {
3176            desiredFrames = mNormalFrameCount;
3177        } else {
3178            // +1 for rounding and +1 for additional sample needed for interpolation
3179            desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1;
3180            // add frames already consumed but not yet released by the resampler
3181            // because mAudioTrackServerProxy->framesReady() will include these frames
3182            desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3183#if 0
3184            // the minimum track buffer size is normally twice the number of frames necessary
3185            // to fill one buffer and the resampler should not leave more than one buffer worth
3186            // of unreleased frames after each pass, but just in case...
3187            ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
3188#endif
3189        }
3190        uint32_t minFrames = 1;
3191        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3192                (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
3193            minFrames = desiredFrames;
3194        }
3195
3196        size_t framesReady = track->framesReady();
3197        if ((framesReady >= minFrames) && track->isReady() &&
3198                !track->isPaused() && !track->isTerminated())
3199        {
3200            ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
3201
3202            mixedTracks++;
3203
3204            // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3205            // there is an effect chain connected to the track
3206            chain.clear();
3207            if (track->mainBuffer() != mSinkBuffer &&
3208                    track->mainBuffer() != mMixerBuffer) {
3209                if (mEffectBufferEnabled) {
3210                    mEffectBufferValid = true; // Later can set directly.
3211                }
3212                chain = getEffectChain_l(track->sessionId());
3213                // Delegate volume control to effect in track effect chain if needed
3214                if (chain != 0) {
3215                    tracksWithEffect++;
3216                } else {
3217                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3218                            "session %d",
3219                            name, track->sessionId());
3220                }
3221            }
3222
3223
3224            int param = AudioMixer::VOLUME;
3225            if (track->mFillingUpStatus == Track::FS_FILLED) {
3226                // no ramp for the first volume setting
3227                track->mFillingUpStatus = Track::FS_ACTIVE;
3228                if (track->mState == TrackBase::RESUMING) {
3229                    track->mState = TrackBase::ACTIVE;
3230                    param = AudioMixer::RAMP_VOLUME;
3231                }
3232                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
3233            // FIXME should not make a decision based on mServer
3234            } else if (cblk->mServer != 0) {
3235                // If the track is stopped before the first frame was mixed,
3236                // do not apply ramp
3237                param = AudioMixer::RAMP_VOLUME;
3238            }
3239
3240            // compute volume for this track
3241            uint32_t vl, vr, va;
3242            if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
3243                vl = vr = va = 0;
3244                if (track->isPausing()) {
3245                    track->setPaused();
3246                }
3247            } else {
3248
3249                // read original volumes with volume control
3250                float typeVolume = mStreamTypes[track->streamType()].volume;
3251                float v = masterVolume * typeVolume;
3252                AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3253                uint32_t vlr = proxy->getVolumeLR();
3254                vl = vlr & 0xFFFF;
3255                vr = vlr >> 16;
3256                // track volumes come from shared memory, so can't be trusted and must be clamped
3257                if (vl > MAX_GAIN_INT) {
3258                    ALOGV("Track left volume out of range: %04X", vl);
3259                    vl = MAX_GAIN_INT;
3260                }
3261                if (vr > MAX_GAIN_INT) {
3262                    ALOGV("Track right volume out of range: %04X", vr);
3263                    vr = MAX_GAIN_INT;
3264                }
3265                // now apply the master volume and stream type volume
3266                vl = (uint32_t)(v * vl) << 12;
3267                vr = (uint32_t)(v * vr) << 12;
3268                // assuming master volume and stream type volume each go up to 1.0,
3269                // vl and vr are now in 8.24 format
3270
3271                uint16_t sendLevel = proxy->getSendLevel_U4_12();
3272                // send level comes from shared memory and so may be corrupt
3273                if (sendLevel > MAX_GAIN_INT) {
3274                    ALOGV("Track send level out of range: %04X", sendLevel);
3275                    sendLevel = MAX_GAIN_INT;
3276                }
3277                va = (uint32_t)(v * sendLevel);
3278            }
3279
3280            // Delegate volume control to effect in track effect chain if needed
3281            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3282                // Do not ramp volume if volume is controlled by effect
3283                param = AudioMixer::VOLUME;
3284                track->mHasVolumeController = true;
3285            } else {
3286                // force no volume ramp when volume controller was just disabled or removed
3287                // from effect chain to avoid volume spike
3288                if (track->mHasVolumeController) {
3289                    param = AudioMixer::VOLUME;
3290                }
3291                track->mHasVolumeController = false;
3292            }
3293
3294            // Convert volumes from 8.24 to 4.12 format
3295            // This additional clamping is needed in case chain->setVolume_l() overshot
3296            vl = (vl + (1 << 11)) >> 12;
3297            if (vl > MAX_GAIN_INT) {
3298                vl = MAX_GAIN_INT;
3299            }
3300            vr = (vr + (1 << 11)) >> 12;
3301            if (vr > MAX_GAIN_INT) {
3302                vr = MAX_GAIN_INT;
3303            }
3304
3305            if (va > MAX_GAIN_INT) {
3306                va = MAX_GAIN_INT;   // va is uint32_t, so no need to check for -
3307            }
3308
3309            // XXX: these things DON'T need to be done each time
3310            mAudioMixer->setBufferProvider(name, track);
3311            mAudioMixer->enable(name);
3312
3313            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
3314            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
3315            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
3316            mAudioMixer->setParameter(
3317                name,
3318                AudioMixer::TRACK,
3319                AudioMixer::FORMAT, (void *)track->format());
3320            mAudioMixer->setParameter(
3321                name,
3322                AudioMixer::TRACK,
3323                AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
3324            // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3325            uint32_t maxSampleRate = mSampleRate * 2;
3326            uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
3327            if (reqSampleRate == 0) {
3328                reqSampleRate = mSampleRate;
3329            } else if (reqSampleRate > maxSampleRate) {
3330                reqSampleRate = maxSampleRate;
3331            }
3332            mAudioMixer->setParameter(
3333                name,
3334                AudioMixer::RESAMPLE,
3335                AudioMixer::SAMPLE_RATE,
3336                (void *)(uintptr_t)reqSampleRate);
3337            /*
3338             * Select the appropriate output buffer for the track.
3339             *
3340             * Tracks with effects go into their own effects chain buffer
3341             * and from there into either mEffectBuffer or mSinkBuffer.
3342             *
3343             * Other tracks can use mMixerBuffer for higher precision
3344             * channel accumulation.  If this buffer is enabled
3345             * (mMixerBufferEnabled true), then selected tracks will accumulate
3346             * into it.
3347             *
3348             */
3349            if (mMixerBufferEnabled
3350                    && (track->mainBuffer() == mSinkBuffer
3351                            || track->mainBuffer() == mMixerBuffer)) {
3352                mAudioMixer->setParameter(
3353                        name,
3354                        AudioMixer::TRACK,
3355                        AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
3356                mAudioMixer->setParameter(
3357                        name,
3358                        AudioMixer::TRACK,
3359                        AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3360                // TODO: override track->mainBuffer()?
3361                mMixerBufferValid = true;
3362            } else {
3363                mAudioMixer->setParameter(
3364                        name,
3365                        AudioMixer::TRACK,
3366                        AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
3367                mAudioMixer->setParameter(
3368                        name,
3369                        AudioMixer::TRACK,
3370                        AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3371            }
3372            mAudioMixer->setParameter(
3373                name,
3374                AudioMixer::TRACK,
3375                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3376
3377            // reset retry count
3378            track->mRetryCount = kMaxTrackRetries;
3379
3380            // If one track is ready, set the mixer ready if:
3381            //  - the mixer was not ready during previous round OR
3382            //  - no other track is not ready
3383            if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3384                    mixerStatus != MIXER_TRACKS_ENABLED) {
3385                mixerStatus = MIXER_TRACKS_READY;
3386            }
3387        } else {
3388            if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
3389                track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
3390            }
3391            // clear effect chain input buffer if an active track underruns to avoid sending
3392            // previous audio buffer again to effects
3393            chain = getEffectChain_l(track->sessionId());
3394            if (chain != 0) {
3395                chain->clearInputBuffer();
3396            }
3397
3398            ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
3399            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3400                    track->isStopped() || track->isPaused()) {
3401                // We have consumed all the buffers of this track.
3402                // Remove it from the list of active tracks.
3403                // TODO: use actual buffer filling status instead of latency when available from
3404                // audio HAL
3405                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3406                size_t framesWritten = mBytesWritten / mFrameSize;
3407                if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3408                    if (track->isStopped()) {
3409                        track->reset();
3410                    }
3411                    tracksToRemove->add(track);
3412                }
3413            } else {
3414                // No buffers for this track. Give it a few chances to
3415                // fill a buffer, then remove it from active list.
3416                if (--(track->mRetryCount) <= 0) {
3417                    ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
3418                    tracksToRemove->add(track);
3419                    // indicate to client process that the track was disabled because of underrun;
3420                    // it will then automatically call start() when data is available
3421                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
3422                // If one track is not ready, mark the mixer also not ready if:
3423                //  - the mixer was ready during previous round OR
3424                //  - no other track is ready
3425                } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3426                                mixerStatus != MIXER_TRACKS_READY) {
3427                    mixerStatus = MIXER_TRACKS_ENABLED;
3428                }
3429            }
3430            mAudioMixer->disable(name);
3431        }
3432
3433        }   // local variable scope to avoid goto warning
3434track_is_ready: ;
3435
3436    }
3437
3438    // Push the new FastMixer state if necessary
3439    bool pauseAudioWatchdog = false;
3440    if (didModify) {
3441        state->mFastTracksGen++;
3442        // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3443        if (kUseFastMixer == FastMixer_Dynamic &&
3444                state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3445            state->mCommand = FastMixerState::COLD_IDLE;
3446            state->mColdFutexAddr = &mFastMixerFutex;
3447            state->mColdGen++;
3448            mFastMixerFutex = 0;
3449            if (kUseFastMixer == FastMixer_Dynamic) {
3450                mNormalSink = mOutputSink;
3451            }
3452            // If we go into cold idle, need to wait for acknowledgement
3453            // so that fast mixer stops doing I/O.
3454            block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3455            pauseAudioWatchdog = true;
3456        }
3457    }
3458    if (sq != NULL) {
3459        sq->end(didModify);
3460        sq->push(block);
3461    }
3462#ifdef AUDIO_WATCHDOG
3463    if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3464        mAudioWatchdog->pause();
3465    }
3466#endif
3467
3468    // Now perform the deferred reset on fast tracks that have stopped
3469    while (resetMask != 0) {
3470        size_t i = __builtin_ctz(resetMask);
3471        ALOG_ASSERT(i < count);
3472        resetMask &= ~(1 << i);
3473        sp<Track> t = mActiveTracks[i].promote();
3474        if (t == 0) {
3475            continue;
3476        }
3477        Track* track = t.get();
3478        ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3479        track->reset();
3480    }
3481
3482    // remove all the tracks that need to be...
3483    removeTracks_l(*tracksToRemove);
3484
3485    // sink or mix buffer must be cleared if all tracks are connected to an
3486    // effect chain as in this case the mixer will not write to the sink or mix buffer
3487    // and track effects will accumulate into it
3488    if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3489            (mixedTracks == 0 && fastTracks > 0))) {
3490        // FIXME as a performance optimization, should remember previous zero status
3491        if (mMixerBufferValid) {
3492            memset(mMixerBuffer, 0, mMixerBufferSize);
3493            // TODO: In testing, mSinkBuffer below need not be cleared because
3494            // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3495            // after mixing.
3496            //
3497            // To enforce this guarantee:
3498            // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3499            // (mixedTracks == 0 && fastTracks > 0))
3500            // must imply MIXER_TRACKS_READY.
3501            // Later, we may clear buffers regardless, and skip much of this logic.
3502        }
3503        // TODO - either mEffectBuffer or mSinkBuffer needs to be cleared.
3504        if (mEffectBufferValid) {
3505            memset(mEffectBuffer, 0, mEffectBufferSize);
3506        }
3507        // FIXME as a performance optimization, should remember previous zero status
3508        memset(mSinkBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3509    }
3510
3511    // if any fast tracks, then status is ready
3512    mMixerStatusIgnoringFastTracks = mixerStatus;
3513    if (fastTracks > 0) {
3514        mixerStatus = MIXER_TRACKS_READY;
3515    }
3516    return mixerStatus;
3517}
3518
3519// getTrackName_l() must be called with ThreadBase::mLock held
3520int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
3521{
3522    return mAudioMixer->getTrackName(channelMask, sessionId);
3523}
3524
3525// deleteTrackName_l() must be called with ThreadBase::mLock held
3526void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3527{
3528    ALOGV("remove track (%d) and delete from mixer", name);
3529    mAudioMixer->deleteTrackName(name);
3530}
3531
3532// checkForNewParameters_l() must be called with ThreadBase::mLock held
3533bool AudioFlinger::MixerThread::checkForNewParameters_l()
3534{
3535    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3536    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3537    bool reconfig = false;
3538
3539    while (!mNewParameters.isEmpty()) {
3540
3541        if (mFastMixer != NULL) {
3542            FastMixerStateQueue *sq = mFastMixer->sq();
3543            FastMixerState *state = sq->begin();
3544            if (!(state->mCommand & FastMixerState::IDLE)) {
3545                previousCommand = state->mCommand;
3546                state->mCommand = FastMixerState::HOT_IDLE;
3547                sq->end();
3548                sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3549            } else {
3550                sq->end(false /*didModify*/);
3551            }
3552        }
3553
3554        status_t status = NO_ERROR;
3555        String8 keyValuePair = mNewParameters[0];
3556        AudioParameter param = AudioParameter(keyValuePair);
3557        int value;
3558
3559        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3560            reconfig = true;
3561        }
3562        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3563            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3564                status = BAD_VALUE;
3565            } else {
3566                // no need to save value, since it's constant
3567                reconfig = true;
3568            }
3569        }
3570        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3571            if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) {
3572                status = BAD_VALUE;
3573            } else {
3574                // no need to save value, since it's constant
3575                reconfig = true;
3576            }
3577        }
3578        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3579            // do not accept frame count changes if tracks are open as the track buffer
3580            // size depends on frame count and correct behavior would not be guaranteed
3581            // if frame count is changed after track creation
3582            if (!mTracks.isEmpty()) {
3583                status = INVALID_OPERATION;
3584            } else {
3585                reconfig = true;
3586            }
3587        }
3588        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3589#ifdef ADD_BATTERY_DATA
3590            // when changing the audio output device, call addBatteryData to notify
3591            // the change
3592            if (mOutDevice != value) {
3593                uint32_t params = 0;
3594                // check whether speaker is on
3595                if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3596                    params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3597                }
3598
3599                audio_devices_t deviceWithoutSpeaker
3600                    = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3601                // check if any other device (except speaker) is on
3602                if (value & deviceWithoutSpeaker ) {
3603                    params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3604                }
3605
3606                if (params != 0) {
3607                    addBatteryData(params);
3608                }
3609            }
3610#endif
3611
3612            // forward device change to effects that have requested to be
3613            // aware of attached audio device.
3614            if (value != AUDIO_DEVICE_NONE) {
3615                mOutDevice = value;
3616                for (size_t i = 0; i < mEffectChains.size(); i++) {
3617                    mEffectChains[i]->setDevice_l(mOutDevice);
3618                }
3619            }
3620        }
3621
3622        if (status == NO_ERROR) {
3623            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3624                                                    keyValuePair.string());
3625            if (!mStandby && status == INVALID_OPERATION) {
3626                mOutput->stream->common.standby(&mOutput->stream->common);
3627                mStandby = true;
3628                mBytesWritten = 0;
3629                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3630                                                       keyValuePair.string());
3631            }
3632            if (status == NO_ERROR && reconfig) {
3633                readOutputParameters_l();
3634                delete mAudioMixer;
3635                mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3636                for (size_t i = 0; i < mTracks.size() ; i++) {
3637                    int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
3638                    if (name < 0) {
3639                        break;
3640                    }
3641                    mTracks[i]->mName = name;
3642                }
3643                sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3644            }
3645        }
3646
3647        mNewParameters.removeAt(0);
3648
3649        mParamStatus = status;
3650        mParamCond.signal();
3651        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3652        // already timed out waiting for the status and will never signal the condition.
3653        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3654    }
3655
3656    if (!(previousCommand & FastMixerState::IDLE)) {
3657        ALOG_ASSERT(mFastMixer != NULL);
3658        FastMixerStateQueue *sq = mFastMixer->sq();
3659        FastMixerState *state = sq->begin();
3660        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3661        state->mCommand = previousCommand;
3662        sq->end();
3663        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3664    }
3665
3666    return reconfig;
3667}
3668
3669
3670void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3671{
3672    const size_t SIZE = 256;
3673    char buffer[SIZE];
3674    String8 result;
3675
3676    PlaybackThread::dumpInternals(fd, args);
3677
3678    fdprintf(fd, "  AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
3679
3680    // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3681    const FastMixerDumpState copy(mFastMixerDumpState);
3682    copy.dump(fd);
3683
3684#ifdef STATE_QUEUE_DUMP
3685    // Similar for state queue
3686    StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3687    observerCopy.dump(fd);
3688    StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3689    mutatorCopy.dump(fd);
3690#endif
3691
3692#ifdef TEE_SINK
3693    // Write the tee output to a .wav file
3694    dumpTee(fd, mTeeSource, mId);
3695#endif
3696
3697#ifdef AUDIO_WATCHDOG
3698    if (mAudioWatchdog != 0) {
3699        // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3700        AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3701        wdCopy.dump(fd);
3702    }
3703#endif
3704}
3705
3706uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3707{
3708    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3709}
3710
3711uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3712{
3713    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3714}
3715
3716void AudioFlinger::MixerThread::cacheParameters_l()
3717{
3718    PlaybackThread::cacheParameters_l();
3719
3720    // FIXME: Relaxed timing because of a certain device that can't meet latency
3721    // Should be reduced to 2x after the vendor fixes the driver issue
3722    // increase threshold again due to low power audio mode. The way this warning
3723    // threshold is calculated and its usefulness should be reconsidered anyway.
3724    maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3725}
3726
3727// ----------------------------------------------------------------------------
3728
3729AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3730        AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3731    :   PlaybackThread(audioFlinger, output, id, device, DIRECT)
3732        // mLeftVolFloat, mRightVolFloat
3733{
3734}
3735
3736AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3737        AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
3738        ThreadBase::type_t type)
3739    :   PlaybackThread(audioFlinger, output, id, device, type)
3740        // mLeftVolFloat, mRightVolFloat
3741{
3742}
3743
3744AudioFlinger::DirectOutputThread::~DirectOutputThread()
3745{
3746}
3747
3748void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
3749{
3750    audio_track_cblk_t* cblk = track->cblk();
3751    float left, right;
3752
3753    if (mMasterMute || mStreamTypes[track->streamType()].mute) {
3754        left = right = 0;
3755    } else {
3756        float typeVolume = mStreamTypes[track->streamType()].volume;
3757        float v = mMasterVolume * typeVolume;
3758        AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3759        uint32_t vlr = proxy->getVolumeLR();
3760        float v_clamped = v * (vlr & 0xFFFF);
3761        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3762        left = v_clamped/MAX_GAIN;
3763        v_clamped = v * (vlr >> 16);
3764        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3765        right = v_clamped/MAX_GAIN;
3766    }
3767
3768    if (lastTrack) {
3769        if (left != mLeftVolFloat || right != mRightVolFloat) {
3770            mLeftVolFloat = left;
3771            mRightVolFloat = right;
3772
3773            // Convert volumes from float to 8.24
3774            uint32_t vl = (uint32_t)(left * (1 << 24));
3775            uint32_t vr = (uint32_t)(right * (1 << 24));
3776
3777            // Delegate volume control to effect in track effect chain if needed
3778            // only one effect chain can be present on DirectOutputThread, so if
3779            // there is one, the track is connected to it
3780            if (!mEffectChains.isEmpty()) {
3781                mEffectChains[0]->setVolume_l(&vl, &vr);
3782                left = (float)vl / (1 << 24);
3783                right = (float)vr / (1 << 24);
3784            }
3785            if (mOutput->stream->set_volume) {
3786                mOutput->stream->set_volume(mOutput->stream, left, right);
3787            }
3788        }
3789    }
3790}
3791
3792
3793AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3794    Vector< sp<Track> > *tracksToRemove
3795)
3796{
3797    size_t count = mActiveTracks.size();
3798    mixer_state mixerStatus = MIXER_IDLE;
3799
3800    // find out which tracks need to be processed
3801    for (size_t i = 0; i < count; i++) {
3802        sp<Track> t = mActiveTracks[i].promote();
3803        // The track died recently
3804        if (t == 0) {
3805            continue;
3806        }
3807
3808        Track* const track = t.get();
3809        audio_track_cblk_t* cblk = track->cblk();
3810        // Only consider last track started for volume and mixer state control.
3811        // In theory an older track could underrun and restart after the new one starts
3812        // but as we only care about the transition phase between two tracks on a
3813        // direct output, it is not a problem to ignore the underrun case.
3814        sp<Track> l = mLatestActiveTrack.promote();
3815        bool last = l.get() == track;
3816
3817        // The first time a track is added we wait
3818        // for all its buffers to be filled before processing it
3819        uint32_t minFrames;
3820        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3821            minFrames = mNormalFrameCount;
3822        } else {
3823            minFrames = 1;
3824        }
3825
3826        if ((track->framesReady() >= minFrames) && track->isReady() &&
3827                !track->isPaused() && !track->isTerminated())
3828        {
3829            ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
3830
3831            if (track->mFillingUpStatus == Track::FS_FILLED) {
3832                track->mFillingUpStatus = Track::FS_ACTIVE;
3833                // make sure processVolume_l() will apply new volume even if 0
3834                mLeftVolFloat = mRightVolFloat = -1.0;
3835                if (track->mState == TrackBase::RESUMING) {
3836                    track->mState = TrackBase::ACTIVE;
3837                }
3838            }
3839
3840            // compute volume for this track
3841            processVolume_l(track, last);
3842            if (last) {
3843                // reset retry count
3844                track->mRetryCount = kMaxTrackRetriesDirect;
3845                mActiveTrack = t;
3846                mixerStatus = MIXER_TRACKS_READY;
3847            }
3848        } else {
3849            // clear effect chain input buffer if the last active track started underruns
3850            // to avoid sending previous audio buffer again to effects
3851            if (!mEffectChains.isEmpty() && last) {
3852                mEffectChains[0]->clearInputBuffer();
3853            }
3854
3855            ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
3856            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3857                    track->isStopped() || track->isPaused()) {
3858                // We have consumed all the buffers of this track.
3859                // Remove it from the list of active tracks.
3860                // TODO: implement behavior for compressed audio
3861                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3862                size_t framesWritten = mBytesWritten / mFrameSize;
3863                if (mStandby || !last ||
3864                        track->presentationComplete(framesWritten, audioHALFrames)) {
3865                    if (track->isStopped()) {
3866                        track->reset();
3867                    }
3868                    tracksToRemove->add(track);
3869                }
3870            } else {
3871                // No buffers for this track. Give it a few chances to
3872                // fill a buffer, then remove it from active list.
3873                // Only consider last track started for mixer state control
3874                if (--(track->mRetryCount) <= 0) {
3875                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3876                    tracksToRemove->add(track);
3877                    // indicate to client process that the track was disabled because of underrun;
3878                    // it will then automatically call start() when data is available
3879                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
3880                } else if (last) {
3881                    mixerStatus = MIXER_TRACKS_ENABLED;
3882                }
3883            }
3884        }
3885    }
3886
3887    // remove all the tracks that need to be...
3888    removeTracks_l(*tracksToRemove);
3889
3890    return mixerStatus;
3891}
3892
3893void AudioFlinger::DirectOutputThread::threadLoop_mix()
3894{
3895    size_t frameCount = mFrameCount;
3896    int8_t *curBuf = (int8_t *)mSinkBuffer;
3897    // output audio to hardware
3898    while (frameCount) {
3899        AudioBufferProvider::Buffer buffer;
3900        buffer.frameCount = frameCount;
3901        mActiveTrack->getNextBuffer(&buffer);
3902        if (buffer.raw == NULL) {
3903            memset(curBuf, 0, frameCount * mFrameSize);
3904            break;
3905        }
3906        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3907        frameCount -= buffer.frameCount;
3908        curBuf += buffer.frameCount * mFrameSize;
3909        mActiveTrack->releaseBuffer(&buffer);
3910    }
3911    mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
3912    sleepTime = 0;
3913    standbyTime = systemTime() + standbyDelay;
3914    mActiveTrack.clear();
3915}
3916
3917void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3918{
3919    if (sleepTime == 0) {
3920        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3921            sleepTime = activeSleepTime;
3922        } else {
3923            sleepTime = idleSleepTime;
3924        }
3925    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3926        memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
3927        sleepTime = 0;
3928    }
3929}
3930
3931// getTrackName_l() must be called with ThreadBase::mLock held
3932int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
3933        int sessionId __unused)
3934{
3935    return 0;
3936}
3937
3938// deleteTrackName_l() must be called with ThreadBase::mLock held
3939void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
3940{
3941}
3942
3943// checkForNewParameters_l() must be called with ThreadBase::mLock held
3944bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3945{
3946    bool reconfig = false;
3947
3948    while (!mNewParameters.isEmpty()) {
3949        status_t status = NO_ERROR;
3950        String8 keyValuePair = mNewParameters[0];
3951        AudioParameter param = AudioParameter(keyValuePair);
3952        int value;
3953
3954        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3955            // forward device change to effects that have requested to be
3956            // aware of attached audio device.
3957            if (value != AUDIO_DEVICE_NONE) {
3958                mOutDevice = value;
3959                for (size_t i = 0; i < mEffectChains.size(); i++) {
3960                    mEffectChains[i]->setDevice_l(mOutDevice);
3961                }
3962            }
3963        }
3964        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3965            // do not accept frame count changes if tracks are open as the track buffer
3966            // size depends on frame count and correct behavior would not be garantied
3967            // if frame count is changed after track creation
3968            if (!mTracks.isEmpty()) {
3969                status = INVALID_OPERATION;
3970            } else {
3971                reconfig = true;
3972            }
3973        }
3974        if (status == NO_ERROR) {
3975            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3976                                                    keyValuePair.string());
3977            if (!mStandby && status == INVALID_OPERATION) {
3978                mOutput->stream->common.standby(&mOutput->stream->common);
3979                mStandby = true;
3980                mBytesWritten = 0;
3981                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3982                                                       keyValuePair.string());
3983            }
3984            if (status == NO_ERROR && reconfig) {
3985                readOutputParameters_l();
3986                sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3987            }
3988        }
3989
3990        mNewParameters.removeAt(0);
3991
3992        mParamStatus = status;
3993        mParamCond.signal();
3994        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3995        // already timed out waiting for the status and will never signal the condition.
3996        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3997    }
3998    return reconfig;
3999}
4000
4001uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4002{
4003    uint32_t time;
4004    if (audio_is_linear_pcm(mFormat)) {
4005        time = PlaybackThread::activeSleepTimeUs();
4006    } else {
4007        time = 10000;
4008    }
4009    return time;
4010}
4011
4012uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4013{
4014    uint32_t time;
4015    if (audio_is_linear_pcm(mFormat)) {
4016        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4017    } else {
4018        time = 10000;
4019    }
4020    return time;
4021}
4022
4023uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4024{
4025    uint32_t time;
4026    if (audio_is_linear_pcm(mFormat)) {
4027        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4028    } else {
4029        time = 10000;
4030    }
4031    return time;
4032}
4033
4034void AudioFlinger::DirectOutputThread::cacheParameters_l()
4035{
4036    PlaybackThread::cacheParameters_l();
4037
4038    // use shorter standby delay as on normal output to release
4039    // hardware resources as soon as possible
4040    if (audio_is_linear_pcm(mFormat)) {
4041        standbyDelay = microseconds(activeSleepTime*2);
4042    } else {
4043        standbyDelay = kOffloadStandbyDelayNs;
4044    }
4045}
4046
4047// ----------------------------------------------------------------------------
4048
4049AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
4050        const wp<AudioFlinger::PlaybackThread>& playbackThread)
4051    :   Thread(false /*canCallJava*/),
4052        mPlaybackThread(playbackThread),
4053        mWriteAckSequence(0),
4054        mDrainSequence(0)
4055{
4056}
4057
4058AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4059{
4060}
4061
4062void AudioFlinger::AsyncCallbackThread::onFirstRef()
4063{
4064    run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4065}
4066
4067bool AudioFlinger::AsyncCallbackThread::threadLoop()
4068{
4069    while (!exitPending()) {
4070        uint32_t writeAckSequence;
4071        uint32_t drainSequence;
4072
4073        {
4074            Mutex::Autolock _l(mLock);
4075            while (!((mWriteAckSequence & 1) ||
4076                     (mDrainSequence & 1) ||
4077                     exitPending())) {
4078                mWaitWorkCV.wait(mLock);
4079            }
4080
4081            if (exitPending()) {
4082                break;
4083            }
4084            ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4085                  mWriteAckSequence, mDrainSequence);
4086            writeAckSequence = mWriteAckSequence;
4087            mWriteAckSequence &= ~1;
4088            drainSequence = mDrainSequence;
4089            mDrainSequence &= ~1;
4090        }
4091        {
4092            sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4093            if (playbackThread != 0) {
4094                if (writeAckSequence & 1) {
4095                    playbackThread->resetWriteBlocked(writeAckSequence >> 1);
4096                }
4097                if (drainSequence & 1) {
4098                    playbackThread->resetDraining(drainSequence >> 1);
4099                }
4100            }
4101        }
4102    }
4103    return false;
4104}
4105
4106void AudioFlinger::AsyncCallbackThread::exit()
4107{
4108    ALOGV("AsyncCallbackThread::exit");
4109    Mutex::Autolock _l(mLock);
4110    requestExit();
4111    mWaitWorkCV.broadcast();
4112}
4113
4114void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
4115{
4116    Mutex::Autolock _l(mLock);
4117    // bit 0 is cleared
4118    mWriteAckSequence = sequence << 1;
4119}
4120
4121void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4122{
4123    Mutex::Autolock _l(mLock);
4124    // ignore unexpected callbacks
4125    if (mWriteAckSequence & 2) {
4126        mWriteAckSequence |= 1;
4127        mWaitWorkCV.signal();
4128    }
4129}
4130
4131void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
4132{
4133    Mutex::Autolock _l(mLock);
4134    // bit 0 is cleared
4135    mDrainSequence = sequence << 1;
4136}
4137
4138void AudioFlinger::AsyncCallbackThread::resetDraining()
4139{
4140    Mutex::Autolock _l(mLock);
4141    // ignore unexpected callbacks
4142    if (mDrainSequence & 2) {
4143        mDrainSequence |= 1;
4144        mWaitWorkCV.signal();
4145    }
4146}
4147
4148
4149// ----------------------------------------------------------------------------
4150AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4151        AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4152    :   DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4153        mHwPaused(false),
4154        mFlushPending(false),
4155        mPausedBytesRemaining(0)
4156{
4157    //FIXME: mStandby should be set to true by ThreadBase constructor
4158    mStandby = true;
4159}
4160
4161void AudioFlinger::OffloadThread::threadLoop_exit()
4162{
4163    if (mFlushPending || mHwPaused) {
4164        // If a flush is pending or track was paused, just discard buffered data
4165        flushHw_l();
4166    } else {
4167        mMixerStatus = MIXER_DRAIN_ALL;
4168        threadLoop_drain();
4169    }
4170    mCallbackThread->exit();
4171    PlaybackThread::threadLoop_exit();
4172}
4173
4174AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4175    Vector< sp<Track> > *tracksToRemove
4176)
4177{
4178    size_t count = mActiveTracks.size();
4179
4180    mixer_state mixerStatus = MIXER_IDLE;
4181    bool doHwPause = false;
4182    bool doHwResume = false;
4183
4184    ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4185
4186    // find out which tracks need to be processed
4187    for (size_t i = 0; i < count; i++) {
4188        sp<Track> t = mActiveTracks[i].promote();
4189        // The track died recently
4190        if (t == 0) {
4191            continue;
4192        }
4193        Track* const track = t.get();
4194        audio_track_cblk_t* cblk = track->cblk();
4195        // Only consider last track started for volume and mixer state control.
4196        // In theory an older track could underrun and restart after the new one starts
4197        // but as we only care about the transition phase between two tracks on a
4198        // direct output, it is not a problem to ignore the underrun case.
4199        sp<Track> l = mLatestActiveTrack.promote();
4200        bool last = l.get() == track;
4201
4202        if (track->isInvalid()) {
4203            ALOGW("An invalidated track shouldn't be in active list");
4204            tracksToRemove->add(track);
4205            continue;
4206        }
4207
4208        if (track->mState == TrackBase::IDLE) {
4209            ALOGW("An idle track shouldn't be in active list");
4210            continue;
4211        }
4212
4213        if (track->isPausing()) {
4214            track->setPaused();
4215            if (last) {
4216                if (!mHwPaused) {
4217                    doHwPause = true;
4218                    mHwPaused = true;
4219                }
4220                // If we were part way through writing the mixbuffer to
4221                // the HAL we must save this until we resume
4222                // BUG - this will be wrong if a different track is made active,
4223                // in that case we want to discard the pending data in the
4224                // mixbuffer and tell the client to present it again when the
4225                // track is resumed
4226                mPausedWriteLength = mCurrentWriteLength;
4227                mPausedBytesRemaining = mBytesRemaining;
4228                mBytesRemaining = 0;    // stop writing
4229            }
4230            tracksToRemove->add(track);
4231        } else if (track->isFlushPending()) {
4232            track->flushAck();
4233            if (last) {
4234                mFlushPending = true;
4235            }
4236        } else if (track->isResumePending()){
4237            track->resumeAck();
4238            if (last) {
4239                if (mPausedBytesRemaining) {
4240                    // Need to continue write that was interrupted
4241                    mCurrentWriteLength = mPausedWriteLength;
4242                    mBytesRemaining = mPausedBytesRemaining;
4243                    mPausedBytesRemaining = 0;
4244                }
4245                if (mHwPaused) {
4246                    doHwResume = true;
4247                    mHwPaused = false;
4248                    // threadLoop_mix() will handle the case that we need to
4249                    // resume an interrupted write
4250                }
4251                // enable write to audio HAL
4252                sleepTime = 0;
4253
4254                // Do not handle new data in this iteration even if track->framesReady()
4255                mixerStatus = MIXER_TRACKS_ENABLED;
4256            }
4257        }  else if (track->framesReady() && track->isReady() &&
4258                !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
4259            ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
4260            if (track->mFillingUpStatus == Track::FS_FILLED) {
4261                track->mFillingUpStatus = Track::FS_ACTIVE;
4262                // make sure processVolume_l() will apply new volume even if 0
4263                mLeftVolFloat = mRightVolFloat = -1.0;
4264            }
4265
4266            if (last) {
4267                sp<Track> previousTrack = mPreviousTrack.promote();
4268                if (previousTrack != 0) {
4269                    if (track != previousTrack.get()) {
4270                        // Flush any data still being written from last track
4271                        mBytesRemaining = 0;
4272                        if (mPausedBytesRemaining) {
4273                            // Last track was paused so we also need to flush saved
4274                            // mixbuffer state and invalidate track so that it will
4275                            // re-submit that unwritten data when it is next resumed
4276                            mPausedBytesRemaining = 0;
4277                            // Invalidate is a bit drastic - would be more efficient
4278                            // to have a flag to tell client that some of the
4279                            // previously written data was lost
4280                            previousTrack->invalidate();
4281                        }
4282                        // flush data already sent to the DSP if changing audio session as audio
4283                        // comes from a different source. Also invalidate previous track to force a
4284                        // seek when resuming.
4285                        if (previousTrack->sessionId() != track->sessionId()) {
4286                            previousTrack->invalidate();
4287                        }
4288                    }
4289                }
4290                mPreviousTrack = track;
4291                // reset retry count
4292                track->mRetryCount = kMaxTrackRetriesOffload;
4293                mActiveTrack = t;
4294                mixerStatus = MIXER_TRACKS_READY;
4295            }
4296        } else {
4297            ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
4298            if (track->isStopping_1()) {
4299                // Hardware buffer can hold a large amount of audio so we must
4300                // wait for all current track's data to drain before we say
4301                // that the track is stopped.
4302                if (mBytesRemaining == 0) {
4303                    // Only start draining when all data in mixbuffer
4304                    // has been written
4305                    ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4306                    track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
4307                    // do not drain if no data was ever sent to HAL (mStandby == true)
4308                    if (last && !mStandby) {
4309                        // do not modify drain sequence if we are already draining. This happens
4310                        // when resuming from pause after drain.
4311                        if ((mDrainSequence & 1) == 0) {
4312                            sleepTime = 0;
4313                            standbyTime = systemTime() + standbyDelay;
4314                            mixerStatus = MIXER_DRAIN_TRACK;
4315                            mDrainSequence += 2;
4316                        }
4317                        if (mHwPaused) {
4318                            // It is possible to move from PAUSED to STOPPING_1 without
4319                            // a resume so we must ensure hardware is running
4320                            doHwResume = true;
4321                            mHwPaused = false;
4322                        }
4323                    }
4324                }
4325            } else if (track->isStopping_2()) {
4326                // Drain has completed or we are in standby, signal presentation complete
4327                if (!(mDrainSequence & 1) || !last || mStandby) {
4328                    track->mState = TrackBase::STOPPED;
4329                    size_t audioHALFrames =
4330                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4331                    size_t framesWritten =
4332                            mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
4333                    track->presentationComplete(framesWritten, audioHALFrames);
4334                    track->reset();
4335                    tracksToRemove->add(track);
4336                }
4337            } else {
4338                // No buffers for this track. Give it a few chances to
4339                // fill a buffer, then remove it from active list.
4340                if (--(track->mRetryCount) <= 0) {
4341                    ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4342                          track->name());
4343                    tracksToRemove->add(track);
4344                    // indicate to client process that the track was disabled because of underrun;
4345                    // it will then automatically call start() when data is available
4346                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
4347                } else if (last){
4348                    mixerStatus = MIXER_TRACKS_ENABLED;
4349                }
4350            }
4351        }
4352        // compute volume for this track
4353        processVolume_l(track, last);
4354    }
4355
4356    // make sure the pause/flush/resume sequence is executed in the right order.
4357    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4358    // before flush and then resume HW. This can happen in case of pause/flush/resume
4359    // if resume is received before pause is executed.
4360    if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
4361        mOutput->stream->pause(mOutput->stream);
4362    }
4363    if (mFlushPending) {
4364        flushHw_l();
4365        mFlushPending = false;
4366    }
4367    if (!mStandby && doHwResume) {
4368        mOutput->stream->resume(mOutput->stream);
4369    }
4370
4371    // remove all the tracks that need to be...
4372    removeTracks_l(*tracksToRemove);
4373
4374    return mixerStatus;
4375}
4376
4377// must be called with thread mutex locked
4378bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4379{
4380    ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4381          mWriteAckSequence, mDrainSequence);
4382    if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
4383        return true;
4384    }
4385    return false;
4386}
4387
4388// must be called with thread mutex locked
4389bool AudioFlinger::OffloadThread::shouldStandby_l()
4390{
4391    bool trackPaused = false;
4392
4393    // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4394    // after a timeout and we will enter standby then.
4395    if (mTracks.size() > 0) {
4396        trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4397    }
4398
4399    return !mStandby && !trackPaused;
4400}
4401
4402
4403bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4404{
4405    Mutex::Autolock _l(mLock);
4406    return waitingAsyncCallback_l();
4407}
4408
4409void AudioFlinger::OffloadThread::flushHw_l()
4410{
4411    mOutput->stream->flush(mOutput->stream);
4412    // Flush anything still waiting in the mixbuffer
4413    mCurrentWriteLength = 0;
4414    mBytesRemaining = 0;
4415    mPausedWriteLength = 0;
4416    mPausedBytesRemaining = 0;
4417    mHwPaused = false;
4418
4419    if (mUseAsyncWrite) {
4420        // discard any pending drain or write ack by incrementing sequence
4421        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4422        mDrainSequence = (mDrainSequence + 2) & ~1;
4423        ALOG_ASSERT(mCallbackThread != 0);
4424        mCallbackThread->setWriteBlocked(mWriteAckSequence);
4425        mCallbackThread->setDraining(mDrainSequence);
4426    }
4427}
4428
4429void AudioFlinger::OffloadThread::onAddNewTrack_l()
4430{
4431    sp<Track> previousTrack = mPreviousTrack.promote();
4432    sp<Track> latestTrack = mLatestActiveTrack.promote();
4433
4434    if (previousTrack != 0 && latestTrack != 0 &&
4435        (previousTrack->sessionId() != latestTrack->sessionId())) {
4436        mFlushPending = true;
4437    }
4438    PlaybackThread::onAddNewTrack_l();
4439}
4440
4441// ----------------------------------------------------------------------------
4442
4443AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4444        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4445    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4446                DUPLICATING),
4447        mWaitTimeMs(UINT_MAX)
4448{
4449    addOutputTrack(mainThread);
4450}
4451
4452AudioFlinger::DuplicatingThread::~DuplicatingThread()
4453{
4454    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4455        mOutputTracks[i]->destroy();
4456    }
4457}
4458
4459void AudioFlinger::DuplicatingThread::threadLoop_mix()
4460{
4461    // mix buffers...
4462    if (outputsReady(outputTracks)) {
4463        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4464    } else {
4465        memset(mSinkBuffer, 0, mSinkBufferSize);
4466    }
4467    sleepTime = 0;
4468    writeFrames = mNormalFrameCount;
4469    mCurrentWriteLength = mSinkBufferSize;
4470    standbyTime = systemTime() + standbyDelay;
4471}
4472
4473void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4474{
4475    if (sleepTime == 0) {
4476        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4477            sleepTime = activeSleepTime;
4478        } else {
4479            sleepTime = idleSleepTime;
4480        }
4481    } else if (mBytesWritten != 0) {
4482        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4483            writeFrames = mNormalFrameCount;
4484            memset(mSinkBuffer, 0, mSinkBufferSize);
4485        } else {
4486            // flush remaining overflow buffers in output tracks
4487            writeFrames = 0;
4488        }
4489        sleepTime = 0;
4490    }
4491}
4492
4493ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
4494{
4495    for (size_t i = 0; i < outputTracks.size(); i++) {
4496        // We convert the duplicating thread format to AUDIO_FORMAT_PCM_16_BIT
4497        // for delivery downstream as needed. This in-place conversion is safe as
4498        // AUDIO_FORMAT_PCM_16_BIT is smaller than any other supported format
4499        // (AUDIO_FORMAT_PCM_8_BIT is not allowed here).
4500        if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4501            memcpy_by_audio_format(mSinkBuffer, AUDIO_FORMAT_PCM_16_BIT,
4502                    mSinkBuffer, mFormat, writeFrames * mChannelCount);
4503        }
4504        outputTracks[i]->write(reinterpret_cast<int16_t*>(mSinkBuffer), writeFrames);
4505    }
4506    mStandby = false;
4507    return (ssize_t)mSinkBufferSize;
4508}
4509
4510void AudioFlinger::DuplicatingThread::threadLoop_standby()
4511{
4512    // DuplicatingThread implements standby by stopping all tracks
4513    for (size_t i = 0; i < outputTracks.size(); i++) {
4514        outputTracks[i]->stop();
4515    }
4516}
4517
4518void AudioFlinger::DuplicatingThread::saveOutputTracks()
4519{
4520    outputTracks = mOutputTracks;
4521}
4522
4523void AudioFlinger::DuplicatingThread::clearOutputTracks()
4524{
4525    outputTracks.clear();
4526}
4527
4528void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4529{
4530    Mutex::Autolock _l(mLock);
4531    // FIXME explain this formula
4532    size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
4533    // OutputTrack is forced to AUDIO_FORMAT_PCM_16_BIT regardless of mFormat
4534    // due to current usage case and restrictions on the AudioBufferProvider.
4535    // Actual buffer conversion is done in threadLoop_write().
4536    //
4537    // TODO: This may change in the future, depending on multichannel
4538    // (and non int16_t*) support on AF::PlaybackThread::OutputTrack
4539    OutputTrack *outputTrack = new OutputTrack(thread,
4540                                            this,
4541                                            mSampleRate,
4542                                            AUDIO_FORMAT_PCM_16_BIT,
4543                                            mChannelMask,
4544                                            frameCount,
4545                                            IPCThreadState::self()->getCallingUid());
4546    if (outputTrack->cblk() != NULL) {
4547        thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
4548        mOutputTracks.add(outputTrack);
4549        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
4550        updateWaitTime_l();
4551    }
4552}
4553
4554void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4555{
4556    Mutex::Autolock _l(mLock);
4557    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4558        if (mOutputTracks[i]->thread() == thread) {
4559            mOutputTracks[i]->destroy();
4560            mOutputTracks.removeAt(i);
4561            updateWaitTime_l();
4562            return;
4563        }
4564    }
4565    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4566}
4567
4568// caller must hold mLock
4569void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4570{
4571    mWaitTimeMs = UINT_MAX;
4572    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4573        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4574        if (strong != 0) {
4575            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4576            if (waitTimeMs < mWaitTimeMs) {
4577                mWaitTimeMs = waitTimeMs;
4578            }
4579        }
4580    }
4581}
4582
4583
4584bool AudioFlinger::DuplicatingThread::outputsReady(
4585        const SortedVector< sp<OutputTrack> > &outputTracks)
4586{
4587    for (size_t i = 0; i < outputTracks.size(); i++) {
4588        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4589        if (thread == 0) {
4590            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4591                    outputTracks[i].get());
4592            return false;
4593        }
4594        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4595        // see note at standby() declaration
4596        if (playbackThread->standby() && !playbackThread->isSuspended()) {
4597            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4598                    thread.get());
4599            return false;
4600        }
4601    }
4602    return true;
4603}
4604
4605uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4606{
4607    return (mWaitTimeMs * 1000) / 2;
4608}
4609
4610void AudioFlinger::DuplicatingThread::cacheParameters_l()
4611{
4612    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4613    updateWaitTime_l();
4614
4615    MixerThread::cacheParameters_l();
4616}
4617
4618// ----------------------------------------------------------------------------
4619//      Record
4620// ----------------------------------------------------------------------------
4621
4622AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4623                                         AudioStreamIn *input,
4624                                         audio_io_handle_t id,
4625                                         audio_devices_t outDevice,
4626                                         audio_devices_t inDevice
4627#ifdef TEE_SINK
4628                                         , const sp<NBAIO_Sink>& teeSink
4629#endif
4630                                         ) :
4631    ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
4632    mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
4633    // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
4634    mRsmpInRear(0)
4635#ifdef TEE_SINK
4636    , mTeeSink(teeSink)
4637#endif
4638{
4639    snprintf(mName, kNameLength, "AudioIn_%X", id);
4640    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
4641
4642    readInputParameters_l();
4643}
4644
4645
4646AudioFlinger::RecordThread::~RecordThread()
4647{
4648    mAudioFlinger->unregisterWriter(mNBLogWriter);
4649    delete[] mRsmpInBuffer;
4650}
4651
4652void AudioFlinger::RecordThread::onFirstRef()
4653{
4654    run(mName, PRIORITY_URGENT_AUDIO);
4655}
4656
4657bool AudioFlinger::RecordThread::threadLoop()
4658{
4659    nsecs_t lastWarning = 0;
4660
4661    inputStandBy();
4662
4663reacquire_wakelock:
4664    sp<RecordTrack> activeTrack;
4665    int activeTracksGen;
4666    {
4667        Mutex::Autolock _l(mLock);
4668        size_t size = mActiveTracks.size();
4669        activeTracksGen = mActiveTracksGen;
4670        if (size > 0) {
4671            // FIXME an arbitrary choice
4672            activeTrack = mActiveTracks[0];
4673            acquireWakeLock_l(activeTrack->uid());
4674            if (size > 1) {
4675                SortedVector<int> tmp;
4676                for (size_t i = 0; i < size; i++) {
4677                    tmp.add(mActiveTracks[i]->uid());
4678                }
4679                updateWakeLockUids_l(tmp);
4680            }
4681        } else {
4682            acquireWakeLock_l(-1);
4683        }
4684    }
4685
4686    // used to request a deferred sleep, to be executed later while mutex is unlocked
4687    uint32_t sleepUs = 0;
4688
4689    // loop while there is work to do
4690    for (;;) {
4691        Vector< sp<EffectChain> > effectChains;
4692
4693        // sleep with mutex unlocked
4694        if (sleepUs > 0) {
4695            usleep(sleepUs);
4696            sleepUs = 0;
4697        }
4698
4699        // activeTracks accumulates a copy of a subset of mActiveTracks
4700        Vector< sp<RecordTrack> > activeTracks;
4701
4702        { // scope for mLock
4703            Mutex::Autolock _l(mLock);
4704
4705            processConfigEvents_l();
4706            // return value 'reconfig' is currently unused
4707            bool reconfig = checkForNewParameters_l();
4708
4709            // check exitPending here because checkForNewParameters_l() and
4710            // checkForNewParameters_l() can temporarily release mLock
4711            if (exitPending()) {
4712                break;
4713            }
4714
4715            // if no active track(s), then standby and release wakelock
4716            size_t size = mActiveTracks.size();
4717            if (size == 0) {
4718                standbyIfNotAlreadyInStandby();
4719                // exitPending() can't become true here
4720                releaseWakeLock_l();
4721                ALOGV("RecordThread: loop stopping");
4722                // go to sleep
4723                mWaitWorkCV.wait(mLock);
4724                ALOGV("RecordThread: loop starting");
4725                goto reacquire_wakelock;
4726            }
4727
4728            if (mActiveTracksGen != activeTracksGen) {
4729                activeTracksGen = mActiveTracksGen;
4730                SortedVector<int> tmp;
4731                for (size_t i = 0; i < size; i++) {
4732                    tmp.add(mActiveTracks[i]->uid());
4733                }
4734                updateWakeLockUids_l(tmp);
4735            }
4736
4737            bool doBroadcast = false;
4738            for (size_t i = 0; i < size; ) {
4739
4740                activeTrack = mActiveTracks[i];
4741                if (activeTrack->isTerminated()) {
4742                    removeTrack_l(activeTrack);
4743                    mActiveTracks.remove(activeTrack);
4744                    mActiveTracksGen++;
4745                    size--;
4746                    continue;
4747                }
4748
4749                TrackBase::track_state activeTrackState = activeTrack->mState;
4750                switch (activeTrackState) {
4751
4752                case TrackBase::PAUSING:
4753                    mActiveTracks.remove(activeTrack);
4754                    mActiveTracksGen++;
4755                    doBroadcast = true;
4756                    size--;
4757                    continue;
4758
4759                case TrackBase::STARTING_1:
4760                    sleepUs = 10000;
4761                    i++;
4762                    continue;
4763
4764                case TrackBase::STARTING_2:
4765                    doBroadcast = true;
4766                    mStandby = false;
4767                    activeTrack->mState = TrackBase::ACTIVE;
4768                    break;
4769
4770                case TrackBase::ACTIVE:
4771                    break;
4772
4773                case TrackBase::IDLE:
4774                    i++;
4775                    continue;
4776
4777                default:
4778                    LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
4779                }
4780
4781                activeTracks.add(activeTrack);
4782                i++;
4783
4784            }
4785            if (doBroadcast) {
4786                mStartStopCond.broadcast();
4787            }
4788
4789            // sleep if there are no active tracks to process
4790            if (activeTracks.size() == 0) {
4791                if (sleepUs == 0) {
4792                    sleepUs = kRecordThreadSleepUs;
4793                }
4794                continue;
4795            }
4796            sleepUs = 0;
4797
4798            lockEffectChains_l(effectChains);
4799        }
4800
4801        // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
4802
4803        size_t size = effectChains.size();
4804        for (size_t i = 0; i < size; i++) {
4805            // thread mutex is not locked, but effect chain is locked
4806            effectChains[i]->process_l();
4807        }
4808
4809        // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
4810        // Only the client(s) that are too slow will overrun. But if even the fastest client is too
4811        // slow, then this RecordThread will overrun by not calling HAL read often enough.
4812        // If destination is non-contiguous, first read past the nominal end of buffer, then
4813        // copy to the right place.  Permitted because mRsmpInBuffer was over-allocated.
4814
4815        int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
4816        ssize_t bytesRead = mInput->stream->read(mInput->stream,
4817                &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
4818        if (bytesRead <= 0) {
4819            ALOGE("read failed: bytesRead=%d < %u", bytesRead, mBufferSize);
4820            // Force input into standby so that it tries to recover at next read attempt
4821            inputStandBy();
4822            sleepUs = kRecordThreadSleepUs;
4823            continue;
4824        }
4825        ALOG_ASSERT((size_t) bytesRead <= mBufferSize);
4826        size_t framesRead = bytesRead / mFrameSize;
4827        ALOG_ASSERT(framesRead > 0);
4828        if (mTeeSink != 0) {
4829            (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
4830        }
4831        // If destination is non-contiguous, we now correct for reading past end of buffer.
4832        size_t part1 = mRsmpInFramesP2 - rear;
4833        if (framesRead > part1) {
4834            memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
4835                    (framesRead - part1) * mFrameSize);
4836        }
4837        rear = mRsmpInRear += framesRead;
4838
4839        size = activeTracks.size();
4840        // loop over each active track
4841        for (size_t i = 0; i < size; i++) {
4842            activeTrack = activeTracks[i];
4843
4844            enum {
4845                OVERRUN_UNKNOWN,
4846                OVERRUN_TRUE,
4847                OVERRUN_FALSE
4848            } overrun = OVERRUN_UNKNOWN;
4849
4850            // loop over getNextBuffer to handle circular sink
4851            for (;;) {
4852
4853                activeTrack->mSink.frameCount = ~0;
4854                status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
4855                size_t framesOut = activeTrack->mSink.frameCount;
4856                LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
4857
4858                int32_t front = activeTrack->mRsmpInFront;
4859                ssize_t filled = rear - front;
4860                size_t framesIn;
4861
4862                if (filled < 0) {
4863                    // should not happen, but treat like a massive overrun and re-sync
4864                    framesIn = 0;
4865                    activeTrack->mRsmpInFront = rear;
4866                    overrun = OVERRUN_TRUE;
4867                } else if ((size_t) filled <= mRsmpInFrames) {
4868                    framesIn = (size_t) filled;
4869                } else {
4870                    // client is not keeping up with server, but give it latest data
4871                    framesIn = mRsmpInFrames;
4872                    activeTrack->mRsmpInFront = front = rear - framesIn;
4873                    overrun = OVERRUN_TRUE;
4874                }
4875
4876                if (framesOut == 0 || framesIn == 0) {
4877                    break;
4878                }
4879
4880                if (activeTrack->mResampler == NULL) {
4881                    // no resampling
4882                    if (framesIn > framesOut) {
4883                        framesIn = framesOut;
4884                    } else {
4885                        framesOut = framesIn;
4886                    }
4887                    int8_t *dst = activeTrack->mSink.i8;
4888                    while (framesIn > 0) {
4889                        front &= mRsmpInFramesP2 - 1;
4890                        size_t part1 = mRsmpInFramesP2 - front;
4891                        if (part1 > framesIn) {
4892                            part1 = framesIn;
4893                        }
4894                        int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
4895                        if (mChannelCount == activeTrack->mChannelCount) {
4896                            memcpy(dst, src, part1 * mFrameSize);
4897                        } else if (mChannelCount == 1) {
4898                            upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (int16_t *)src,
4899                                    part1);
4900                        } else {
4901                            downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, (int16_t *)src,
4902                                    part1);
4903                        }
4904                        dst += part1 * activeTrack->mFrameSize;
4905                        front += part1;
4906                        framesIn -= part1;
4907                    }
4908                    activeTrack->mRsmpInFront += framesOut;
4909
4910                } else {
4911                    // resampling
4912                    // FIXME framesInNeeded should really be part of resampler API, and should
4913                    //       depend on the SRC ratio
4914                    //       to keep mRsmpInBuffer full so resampler always has sufficient input
4915                    size_t framesInNeeded;
4916                    // FIXME only re-calculate when it changes, and optimize for common ratios
4917                    double inOverOut = (double) mSampleRate / activeTrack->mSampleRate;
4918                    double outOverIn = (double) activeTrack->mSampleRate / mSampleRate;
4919                    framesInNeeded = ceil(framesOut * inOverOut) + 1;
4920                    ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
4921                                framesInNeeded, framesOut, inOverOut);
4922                    // Although we theoretically have framesIn in circular buffer, some of those are
4923                    // unreleased frames, and thus must be discounted for purpose of budgeting.
4924                    size_t unreleased = activeTrack->mRsmpInUnrel;
4925                    framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
4926                    if (framesIn < framesInNeeded) {
4927                        ALOGV("not enough to resample: have %u frames in but need %u in to "
4928                                "produce %u out given in/out ratio of %.4g",
4929                                framesIn, framesInNeeded, framesOut, inOverOut);
4930                        size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * outOverIn) : 0;
4931                        LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
4932                        if (newFramesOut == 0) {
4933                            break;
4934                        }
4935                        framesInNeeded = ceil(newFramesOut * inOverOut) + 1;
4936                        ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
4937                                framesInNeeded, newFramesOut, outOverIn);
4938                        LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
4939                        ALOGV("success 2: have %u frames in and need %u in to produce %u out "
4940                              "given in/out ratio of %.4g",
4941                              framesIn, framesInNeeded, newFramesOut, inOverOut);
4942                        framesOut = newFramesOut;
4943                    } else {
4944                        ALOGV("success 1: have %u in and need %u in to produce %u out "
4945                            "given in/out ratio of %.4g",
4946                            framesIn, framesInNeeded, framesOut, inOverOut);
4947                    }
4948
4949                    // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
4950                    if (activeTrack->mRsmpOutFrameCount < framesOut) {
4951                        // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
4952                        delete[] activeTrack->mRsmpOutBuffer;
4953                        // resampler always outputs stereo
4954                        activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
4955                        activeTrack->mRsmpOutFrameCount = framesOut;
4956                    }
4957
4958                    // resampler accumulates, but we only have one source track
4959                    memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
4960                    activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
4961                            // FIXME how about having activeTrack implement this interface itself?
4962                            activeTrack->mResamplerBufferProvider
4963                            /*this*/ /* AudioBufferProvider* */);
4964                    // ditherAndClamp() works as long as all buffers returned by
4965                    // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
4966                    if (activeTrack->mChannelCount == 1) {
4967                        // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
4968                        ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
4969                                framesOut);
4970                        // the resampler always outputs stereo samples:
4971                        // do post stereo to mono conversion
4972                        downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
4973                                (int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
4974                    } else {
4975                        ditherAndClamp((int32_t *)activeTrack->mSink.raw,
4976                                activeTrack->mRsmpOutBuffer, framesOut);
4977                    }
4978                    // now done with mRsmpOutBuffer
4979
4980                }
4981
4982                if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
4983                    overrun = OVERRUN_FALSE;
4984                }
4985
4986                if (activeTrack->mFramesToDrop == 0) {
4987                    if (framesOut > 0) {
4988                        activeTrack->mSink.frameCount = framesOut;
4989                        activeTrack->releaseBuffer(&activeTrack->mSink);
4990                    }
4991                } else {
4992                    // FIXME could do a partial drop of framesOut
4993                    if (activeTrack->mFramesToDrop > 0) {
4994                        activeTrack->mFramesToDrop -= framesOut;
4995                        if (activeTrack->mFramesToDrop <= 0) {
4996                            activeTrack->clearSyncStartEvent();
4997                        }
4998                    } else {
4999                        activeTrack->mFramesToDrop += framesOut;
5000                        if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5001                                activeTrack->mSyncStartEvent->isCancelled()) {
5002                            ALOGW("Synced record %s, session %d, trigger session %d",
5003                                  (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5004                                  activeTrack->sessionId(),
5005                                  (activeTrack->mSyncStartEvent != 0) ?
5006                                          activeTrack->mSyncStartEvent->triggerSession() : 0);
5007                            activeTrack->clearSyncStartEvent();
5008                        }
5009                    }
5010                }
5011
5012                if (framesOut == 0) {
5013                    break;
5014                }
5015            }
5016
5017            switch (overrun) {
5018            case OVERRUN_TRUE:
5019                // client isn't retrieving buffers fast enough
5020                if (!activeTrack->setOverflow()) {
5021                    nsecs_t now = systemTime();
5022                    // FIXME should lastWarning per track?
5023                    if ((now - lastWarning) > kWarningThrottleNs) {
5024                        ALOGW("RecordThread: buffer overflow");
5025                        lastWarning = now;
5026                    }
5027                }
5028                break;
5029            case OVERRUN_FALSE:
5030                activeTrack->clearOverflow();
5031                break;
5032            case OVERRUN_UNKNOWN:
5033                break;
5034            }
5035
5036        }
5037
5038        // enable changes in effect chain
5039        unlockEffectChains(effectChains);
5040        // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
5041    }
5042
5043    standbyIfNotAlreadyInStandby();
5044
5045    {
5046        Mutex::Autolock _l(mLock);
5047        for (size_t i = 0; i < mTracks.size(); i++) {
5048            sp<RecordTrack> track = mTracks[i];
5049            track->invalidate();
5050        }
5051        mActiveTracks.clear();
5052        mActiveTracksGen++;
5053        mStartStopCond.broadcast();
5054    }
5055
5056    releaseWakeLock();
5057
5058    ALOGV("RecordThread %p exiting", this);
5059    return false;
5060}
5061
5062void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
5063{
5064    if (!mStandby) {
5065        inputStandBy();
5066        mStandby = true;
5067    }
5068}
5069
5070void AudioFlinger::RecordThread::inputStandBy()
5071{
5072    mInput->stream->common.standby(&mInput->stream->common);
5073}
5074
5075// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
5076sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5077        const sp<AudioFlinger::Client>& client,
5078        uint32_t sampleRate,
5079        audio_format_t format,
5080        audio_channel_mask_t channelMask,
5081        size_t *pFrameCount,
5082        int sessionId,
5083        int uid,
5084        IAudioFlinger::track_flags_t *flags,
5085        pid_t tid,
5086        status_t *status)
5087{
5088    size_t frameCount = *pFrameCount;
5089    sp<RecordTrack> track;
5090    status_t lStatus;
5091
5092    // client expresses a preference for FAST, but we get the final say
5093    if (*flags & IAudioFlinger::TRACK_FAST) {
5094      if (
5095            // use case: callback handler and frame count is default or at least as large as HAL
5096            (
5097                (tid != -1) &&
5098                ((frameCount == 0) ||
5099                // FIXME not necessarily true, should be native frame count for native SR!
5100                (frameCount >= mFrameCount))
5101            ) &&
5102            // PCM data
5103            audio_is_linear_pcm(format) &&
5104            // mono or stereo
5105            ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
5106              (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
5107            // hardware sample rate
5108            // FIXME actually the native hardware sample rate
5109            (sampleRate == mSampleRate) &&
5110            // record thread has an associated fast capture
5111            hasFastCapture()
5112            // fast capture does not require slots
5113        ) {
5114        // if frameCount not specified, then it defaults to fast capture (HAL) frame count
5115        if (frameCount == 0) {
5116            // FIXME wrong mFrameCount
5117            frameCount = mFrameCount * kFastTrackMultiplier;
5118        }
5119        ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
5120                frameCount, mFrameCount);
5121      } else {
5122        ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d "
5123                "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
5124                "hasFastCapture=%d tid=%d",
5125                frameCount, mFrameCount, format,
5126                audio_is_linear_pcm(format),
5127                channelMask, sampleRate, mSampleRate, hasFastCapture(), tid);
5128        *flags &= ~IAudioFlinger::TRACK_FAST;
5129        // FIXME It's not clear that we need to enforce this any more, since we have a pipe.
5130        // For compatibility with AudioRecord calculation, buffer depth is forced
5131        // to be at least 2 x the record thread frame count and cover audio hardware latency.
5132        // This is probably too conservative, but legacy application code may depend on it.
5133        // If you change this calculation, also review the start threshold which is related.
5134        uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream);
5135        size_t mNormalFrameCount = 2048; // FIXME
5136        uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
5137        if (minBufCount < 2) {
5138            minBufCount = 2;
5139        }
5140        size_t minFrameCount = mNormalFrameCount * minBufCount;
5141        if (frameCount < minFrameCount) {
5142            frameCount = minFrameCount;
5143        }
5144      }
5145    }
5146    *pFrameCount = frameCount;
5147
5148    lStatus = initCheck();
5149    if (lStatus != NO_ERROR) {
5150        ALOGE("createRecordTrack_l() audio driver not initialized");
5151        goto Exit;
5152    }
5153
5154    { // scope for mLock
5155        Mutex::Autolock _l(mLock);
5156
5157        track = new RecordTrack(this, client, sampleRate,
5158                      format, channelMask, frameCount, sessionId, uid);
5159
5160        lStatus = track->initCheck();
5161        if (lStatus != NO_ERROR) {
5162            ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
5163            // track must be cleared from the caller as the caller has the AF lock
5164            goto Exit;
5165        }
5166        mTracks.add(track);
5167
5168        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5169        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5170                        mAudioFlinger->btNrecIsOff();
5171        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5172        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
5173
5174        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5175            pid_t callingPid = IPCThreadState::self()->getCallingPid();
5176            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5177            // so ask activity manager to do this on our behalf
5178            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5179        }
5180    }
5181
5182    lStatus = NO_ERROR;
5183
5184Exit:
5185    *status = lStatus;
5186    return track;
5187}
5188
5189status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5190                                           AudioSystem::sync_event_t event,
5191                                           int triggerSession)
5192{
5193    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5194    sp<ThreadBase> strongMe = this;
5195    status_t status = NO_ERROR;
5196
5197    if (event == AudioSystem::SYNC_EVENT_NONE) {
5198        recordTrack->clearSyncStartEvent();
5199    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5200        recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5201                                       triggerSession,
5202                                       recordTrack->sessionId(),
5203                                       syncStartEventCallback,
5204                                       recordTrack);
5205        // Sync event can be cancelled by the trigger session if the track is not in a
5206        // compatible state in which case we start record immediately
5207        if (recordTrack->mSyncStartEvent->isCancelled()) {
5208            recordTrack->clearSyncStartEvent();
5209        } else {
5210            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
5211            recordTrack->mFramesToDrop = -
5212                    ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
5213        }
5214    }
5215
5216    {
5217        // This section is a rendezvous between binder thread executing start() and RecordThread
5218        AutoMutex lock(mLock);
5219        if (mActiveTracks.indexOf(recordTrack) >= 0) {
5220            if (recordTrack->mState == TrackBase::PAUSING) {
5221                ALOGV("active record track PAUSING -> ACTIVE");
5222                recordTrack->mState = TrackBase::ACTIVE;
5223            } else {
5224                ALOGV("active record track state %d", recordTrack->mState);
5225            }
5226            return status;
5227        }
5228
5229        // TODO consider other ways of handling this, such as changing the state to :STARTING and
5230        //      adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5231        //      or using a separate command thread
5232        recordTrack->mState = TrackBase::STARTING_1;
5233        mActiveTracks.add(recordTrack);
5234        mActiveTracksGen++;
5235        mLock.unlock();
5236        status_t status = AudioSystem::startInput(mId);
5237        mLock.lock();
5238        // FIXME should verify that recordTrack is still in mActiveTracks
5239        if (status != NO_ERROR) {
5240            mActiveTracks.remove(recordTrack);
5241            mActiveTracksGen++;
5242            recordTrack->clearSyncStartEvent();
5243            return status;
5244        }
5245        // Catch up with current buffer indices if thread is already running.
5246        // This is what makes a new client discard all buffered data.  If the track's mRsmpInFront
5247        // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5248        // see previously buffered data before it called start(), but with greater risk of overrun.
5249
5250        recordTrack->mRsmpInFront = mRsmpInRear;
5251        recordTrack->mRsmpInUnrel = 0;
5252        // FIXME why reset?
5253        if (recordTrack->mResampler != NULL) {
5254            recordTrack->mResampler->reset();
5255        }
5256        recordTrack->mState = TrackBase::STARTING_2;
5257        // signal thread to start
5258        mWaitWorkCV.broadcast();
5259        if (mActiveTracks.indexOf(recordTrack) < 0) {
5260            ALOGV("Record failed to start");
5261            status = BAD_VALUE;
5262            goto startError;
5263        }
5264        return status;
5265    }
5266
5267startError:
5268    AudioSystem::stopInput(mId);
5269    recordTrack->clearSyncStartEvent();
5270    // FIXME I wonder why we do not reset the state here?
5271    return status;
5272}
5273
5274void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5275{
5276    sp<SyncEvent> strongEvent = event.promote();
5277
5278    if (strongEvent != 0) {
5279        sp<RefBase> ptr = strongEvent->cookie().promote();
5280        if (ptr != 0) {
5281            RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5282            recordTrack->handleSyncStartEvent(strongEvent);
5283        }
5284    }
5285}
5286
5287bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
5288    ALOGV("RecordThread::stop");
5289    AutoMutex _l(mLock);
5290    if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
5291        return false;
5292    }
5293    // note that threadLoop may still be processing the track at this point [without lock]
5294    recordTrack->mState = TrackBase::PAUSING;
5295    // do not wait for mStartStopCond if exiting
5296    if (exitPending()) {
5297        return true;
5298    }
5299    // FIXME incorrect usage of wait: no explicit predicate or loop
5300    mStartStopCond.wait(mLock);
5301    // if we have been restarted, recordTrack is in mActiveTracks here
5302    if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
5303        ALOGV("Record stopped OK");
5304        return true;
5305    }
5306    return false;
5307}
5308
5309bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
5310{
5311    return false;
5312}
5313
5314status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
5315{
5316#if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
5317    if (!isValidSyncEvent(event)) {
5318        return BAD_VALUE;
5319    }
5320
5321    int eventSession = event->triggerSession();
5322    status_t ret = NAME_NOT_FOUND;
5323
5324    Mutex::Autolock _l(mLock);
5325
5326    for (size_t i = 0; i < mTracks.size(); i++) {
5327        sp<RecordTrack> track = mTracks[i];
5328        if (eventSession == track->sessionId()) {
5329            (void) track->setSyncEvent(event);
5330            ret = NO_ERROR;
5331        }
5332    }
5333    return ret;
5334#else
5335    return BAD_VALUE;
5336#endif
5337}
5338
5339// destroyTrack_l() must be called with ThreadBase::mLock held
5340void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
5341{
5342    track->terminate();
5343    track->mState = TrackBase::STOPPED;
5344    // active tracks are removed by threadLoop()
5345    if (mActiveTracks.indexOf(track) < 0) {
5346        removeTrack_l(track);
5347    }
5348}
5349
5350void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
5351{
5352    mTracks.remove(track);
5353    // need anything related to effects here?
5354}
5355
5356void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5357{
5358    dumpInternals(fd, args);
5359    dumpTracks(fd, args);
5360    dumpEffectChains(fd, args);
5361}
5362
5363void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
5364{
5365    fdprintf(fd, "\nInput thread %p:\n", this);
5366
5367    if (mActiveTracks.size() > 0) {
5368        fdprintf(fd, "  Buffer size: %zu bytes\n", mBufferSize);
5369    } else {
5370        fdprintf(fd, "  No active record clients\n");
5371    }
5372
5373    dumpBase(fd, args);
5374}
5375
5376void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
5377{
5378    const size_t SIZE = 256;
5379    char buffer[SIZE];
5380    String8 result;
5381
5382    size_t numtracks = mTracks.size();
5383    size_t numactive = mActiveTracks.size();
5384    size_t numactiveseen = 0;
5385    fdprintf(fd, "  %d Tracks", numtracks);
5386    if (numtracks) {
5387        fdprintf(fd, " of which %d are active\n", numactive);
5388        RecordTrack::appendDumpHeader(result);
5389        for (size_t i = 0; i < numtracks ; ++i) {
5390            sp<RecordTrack> track = mTracks[i];
5391            if (track != 0) {
5392                bool active = mActiveTracks.indexOf(track) >= 0;
5393                if (active) {
5394                    numactiveseen++;
5395                }
5396                track->dump(buffer, SIZE, active);
5397                result.append(buffer);
5398            }
5399        }
5400    } else {
5401        fdprintf(fd, "\n");
5402    }
5403
5404    if (numactiveseen != numactive) {
5405        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
5406                " not in the track list\n");
5407        result.append(buffer);
5408        RecordTrack::appendDumpHeader(result);
5409        for (size_t i = 0; i < numactive; ++i) {
5410            sp<RecordTrack> track = mActiveTracks[i];
5411            if (mTracks.indexOf(track) < 0) {
5412                track->dump(buffer, SIZE, true);
5413                result.append(buffer);
5414            }
5415        }
5416
5417    }
5418    write(fd, result.string(), result.size());
5419}
5420
5421// AudioBufferProvider interface
5422status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
5423        AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
5424{
5425    RecordTrack *activeTrack = mRecordTrack;
5426    sp<ThreadBase> threadBase = activeTrack->mThread.promote();
5427    if (threadBase == 0) {
5428        buffer->frameCount = 0;
5429        buffer->raw = NULL;
5430        return NOT_ENOUGH_DATA;
5431    }
5432    RecordThread *recordThread = (RecordThread *) threadBase.get();
5433    int32_t rear = recordThread->mRsmpInRear;
5434    int32_t front = activeTrack->mRsmpInFront;
5435    ssize_t filled = rear - front;
5436    // FIXME should not be P2 (don't want to increase latency)
5437    // FIXME if client not keeping up, discard
5438    LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
5439    // 'filled' may be non-contiguous, so return only the first contiguous chunk
5440    front &= recordThread->mRsmpInFramesP2 - 1;
5441    size_t part1 = recordThread->mRsmpInFramesP2 - front;
5442    if (part1 > (size_t) filled) {
5443        part1 = filled;
5444    }
5445    size_t ask = buffer->frameCount;
5446    ALOG_ASSERT(ask > 0);
5447    if (part1 > ask) {
5448        part1 = ask;
5449    }
5450    if (part1 == 0) {
5451        // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
5452        LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
5453        buffer->raw = NULL;
5454        buffer->frameCount = 0;
5455        activeTrack->mRsmpInUnrel = 0;
5456        return NOT_ENOUGH_DATA;
5457    }
5458
5459    buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
5460    buffer->frameCount = part1;
5461    activeTrack->mRsmpInUnrel = part1;
5462    return NO_ERROR;
5463}
5464
5465// AudioBufferProvider interface
5466void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
5467        AudioBufferProvider::Buffer* buffer)
5468{
5469    RecordTrack *activeTrack = mRecordTrack;
5470    size_t stepCount = buffer->frameCount;
5471    if (stepCount == 0) {
5472        return;
5473    }
5474    ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
5475    activeTrack->mRsmpInUnrel -= stepCount;
5476    activeTrack->mRsmpInFront += stepCount;
5477    buffer->raw = NULL;
5478    buffer->frameCount = 0;
5479}
5480
5481bool AudioFlinger::RecordThread::checkForNewParameters_l()
5482{
5483    bool reconfig = false;
5484
5485    while (!mNewParameters.isEmpty()) {
5486        status_t status = NO_ERROR;
5487        String8 keyValuePair = mNewParameters[0];
5488        AudioParameter param = AudioParameter(keyValuePair);
5489        int value;
5490        audio_format_t reqFormat = mFormat;
5491        uint32_t samplingRate = mSampleRate;
5492        audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
5493
5494        // TODO Investigate when this code runs. Check with audio policy when a sample rate and
5495        //      channel count change can be requested. Do we mandate the first client defines the
5496        //      HAL sampling rate and channel count or do we allow changes on the fly?
5497        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5498            samplingRate = value;
5499            reconfig = true;
5500        }
5501        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5502            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
5503                status = BAD_VALUE;
5504            } else {
5505                reqFormat = (audio_format_t) value;
5506                reconfig = true;
5507            }
5508        }
5509        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
5510            audio_channel_mask_t mask = (audio_channel_mask_t) value;
5511            if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
5512                status = BAD_VALUE;
5513            } else {
5514                channelMask = mask;
5515                reconfig = true;
5516            }
5517        }
5518        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5519            // do not accept frame count changes if tracks are open as the track buffer
5520            // size depends on frame count and correct behavior would not be guaranteed
5521            // if frame count is changed after track creation
5522            if (mActiveTracks.size() > 0) {
5523                status = INVALID_OPERATION;
5524            } else {
5525                reconfig = true;
5526            }
5527        }
5528        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5529            // forward device change to effects that have requested to be
5530            // aware of attached audio device.
5531            for (size_t i = 0; i < mEffectChains.size(); i++) {
5532                mEffectChains[i]->setDevice_l(value);
5533            }
5534
5535            // store input device and output device but do not forward output device to audio HAL.
5536            // Note that status is ignored by the caller for output device
5537            // (see AudioFlinger::setParameters()
5538            if (audio_is_output_devices(value)) {
5539                mOutDevice = value;
5540                status = BAD_VALUE;
5541            } else {
5542                mInDevice = value;
5543                // disable AEC and NS if the device is a BT SCO headset supporting those
5544                // pre processings
5545                if (mTracks.size() > 0) {
5546                    bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5547                                        mAudioFlinger->btNrecIsOff();
5548                    for (size_t i = 0; i < mTracks.size(); i++) {
5549                        sp<RecordTrack> track = mTracks[i];
5550                        setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
5551                        setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
5552                    }
5553                }
5554            }
5555        }
5556        if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
5557                mAudioSource != (audio_source_t)value) {
5558            // forward device change to effects that have requested to be
5559            // aware of attached audio device.
5560            for (size_t i = 0; i < mEffectChains.size(); i++) {
5561                mEffectChains[i]->setAudioSource_l((audio_source_t)value);
5562            }
5563            mAudioSource = (audio_source_t)value;
5564        }
5565
5566        if (status == NO_ERROR) {
5567            status = mInput->stream->common.set_parameters(&mInput->stream->common,
5568                    keyValuePair.string());
5569            if (status == INVALID_OPERATION) {
5570                inputStandBy();
5571                status = mInput->stream->common.set_parameters(&mInput->stream->common,
5572                        keyValuePair.string());
5573            }
5574            if (reconfig) {
5575                if (status == BAD_VALUE &&
5576                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
5577                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
5578                    (mInput->stream->common.get_sample_rate(&mInput->stream->common)
5579                            <= (2 * samplingRate)) &&
5580                    popcount(mInput->stream->common.get_channels(&mInput->stream->common))
5581                            <= FCC_2 &&
5582                    (channelMask == AUDIO_CHANNEL_IN_MONO ||
5583                            channelMask == AUDIO_CHANNEL_IN_STEREO)) {
5584                    status = NO_ERROR;
5585                }
5586                if (status == NO_ERROR) {
5587                    readInputParameters_l();
5588                    sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5589                }
5590            }
5591        }
5592
5593        mNewParameters.removeAt(0);
5594
5595        mParamStatus = status;
5596        mParamCond.signal();
5597        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5598        // already timed out waiting for the status and will never signal the condition.
5599        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
5600    }
5601    return reconfig;
5602}
5603
5604String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5605{
5606    Mutex::Autolock _l(mLock);
5607    if (initCheck() != NO_ERROR) {
5608        return String8();
5609    }
5610
5611    char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
5612    const String8 out_s8(s);
5613    free(s);
5614    return out_s8;
5615}
5616
5617void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param __unused) {
5618    AudioSystem::OutputDescriptor desc;
5619    const void *param2 = NULL;
5620
5621    switch (event) {
5622    case AudioSystem::INPUT_OPENED:
5623    case AudioSystem::INPUT_CONFIG_CHANGED:
5624        desc.channelMask = mChannelMask;
5625        desc.samplingRate = mSampleRate;
5626        desc.format = mFormat;
5627        desc.frameCount = mFrameCount;
5628        desc.latency = 0;
5629        param2 = &desc;
5630        break;
5631
5632    case AudioSystem::INPUT_CLOSED:
5633    default:
5634        break;
5635    }
5636    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5637}
5638
5639void AudioFlinger::RecordThread::readInputParameters_l()
5640{
5641    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
5642    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5643    mChannelCount = popcount(mChannelMask);
5644    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
5645    if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
5646        ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
5647    }
5648    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
5649    mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
5650    mFrameCount = mBufferSize / mFrameSize;
5651    // This is the formula for calculating the temporary buffer size.
5652    // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
5653    // 1 full output buffer, regardless of the alignment of the available input.
5654    // The value is somewhat arbitrary, and could probably be even larger.
5655    // A larger value should allow more old data to be read after a track calls start(),
5656    // without increasing latency.
5657    mRsmpInFrames = mFrameCount * 7;
5658    mRsmpInFramesP2 = roundup(mRsmpInFrames);
5659    delete[] mRsmpInBuffer;
5660    // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
5661    mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
5662
5663    // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
5664    // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
5665}
5666
5667uint32_t AudioFlinger::RecordThread::getInputFramesLost()
5668{
5669    Mutex::Autolock _l(mLock);
5670    if (initCheck() != NO_ERROR) {
5671        return 0;
5672    }
5673
5674    return mInput->stream->get_input_frames_lost(mInput->stream);
5675}
5676
5677uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
5678{
5679    Mutex::Autolock _l(mLock);
5680    uint32_t result = 0;
5681    if (getEffectChain_l(sessionId) != 0) {
5682        result = EFFECT_SESSION;
5683    }
5684
5685    for (size_t i = 0; i < mTracks.size(); ++i) {
5686        if (sessionId == mTracks[i]->sessionId()) {
5687            result |= TRACK_SESSION;
5688            break;
5689        }
5690    }
5691
5692    return result;
5693}
5694
5695KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
5696{
5697    KeyedVector<int, bool> ids;
5698    Mutex::Autolock _l(mLock);
5699    for (size_t j = 0; j < mTracks.size(); ++j) {
5700        sp<RecordThread::RecordTrack> track = mTracks[j];
5701        int sessionId = track->sessionId();
5702        if (ids.indexOfKey(sessionId) < 0) {
5703            ids.add(sessionId, true);
5704        }
5705    }
5706    return ids;
5707}
5708
5709AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5710{
5711    Mutex::Autolock _l(mLock);
5712    AudioStreamIn *input = mInput;
5713    mInput = NULL;
5714    return input;
5715}
5716
5717// this method must always be called either with ThreadBase mLock held or inside the thread loop
5718audio_stream_t* AudioFlinger::RecordThread::stream() const
5719{
5720    if (mInput == NULL) {
5721        return NULL;
5722    }
5723    return &mInput->stream->common;
5724}
5725
5726status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5727{
5728    // only one chain per input thread
5729    if (mEffectChains.size() != 0) {
5730        return INVALID_OPERATION;
5731    }
5732    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5733
5734    chain->setInBuffer(NULL);
5735    chain->setOutBuffer(NULL);
5736
5737    checkSuspendOnAddEffectChain_l(chain);
5738
5739    mEffectChains.add(chain);
5740
5741    return NO_ERROR;
5742}
5743
5744size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5745{
5746    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5747    ALOGW_IF(mEffectChains.size() != 1,
5748            "removeEffectChain_l() %p invalid chain size %d on thread %p",
5749            chain.get(), mEffectChains.size(), this);
5750    if (mEffectChains.size() == 1) {
5751        mEffectChains.removeAt(0);
5752    }
5753    return 0;
5754}
5755
5756}; // namespace android
5757