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