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