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