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