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