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