Threads.cpp revision 8ce74c3c11458faa34395591a3424e90db856bfc
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(audio_io_config_event event)
588{
589    Mutex::Autolock _l(mLock);
590    sendIoConfigEvent_l(event);
591}
592
593// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
594void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event)
595{
596    sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event);
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            ioConfigChanged(data->mEvent);
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::ioConfigChanged(audio_io_config_event event) {
1925    sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
1926    ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
1927
1928    desc->mIoHandle = mId;
1929
1930    switch (event) {
1931    case AUDIO_OUTPUT_OPENED:
1932    case AUDIO_OUTPUT_CONFIG_CHANGED:
1933        desc->mChannelMask = mChannelMask;
1934        desc->mSamplingRate = mSampleRate;
1935        desc->mFormat = mFormat;
1936        desc->mFrameCount = mNormalFrameCount; // FIXME see
1937                                             // AudioFlinger::frameCount(audio_io_handle_t)
1938        desc->mLatency = latency_l();
1939        break;
1940
1941    case AUDIO_OUTPUT_CLOSED:
1942    default:
1943        break;
1944    }
1945    mAudioFlinger->ioConfigChanged(event, desc);
1946}
1947
1948void AudioFlinger::PlaybackThread::writeCallback()
1949{
1950    ALOG_ASSERT(mCallbackThread != 0);
1951    mCallbackThread->resetWriteBlocked();
1952}
1953
1954void AudioFlinger::PlaybackThread::drainCallback()
1955{
1956    ALOG_ASSERT(mCallbackThread != 0);
1957    mCallbackThread->resetDraining();
1958}
1959
1960void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
1961{
1962    Mutex::Autolock _l(mLock);
1963    // reject out of sequence requests
1964    if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1965        mWriteAckSequence &= ~1;
1966        mWaitWorkCV.signal();
1967    }
1968}
1969
1970void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
1971{
1972    Mutex::Autolock _l(mLock);
1973    // reject out of sequence requests
1974    if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1975        mDrainSequence &= ~1;
1976        mWaitWorkCV.signal();
1977    }
1978}
1979
1980// static
1981int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
1982                                                void *param __unused,
1983                                                void *cookie)
1984{
1985    AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1986    ALOGV("asyncCallback() event %d", event);
1987    switch (event) {
1988    case STREAM_CBK_EVENT_WRITE_READY:
1989        me->writeCallback();
1990        break;
1991    case STREAM_CBK_EVENT_DRAIN_READY:
1992        me->drainCallback();
1993        break;
1994    default:
1995        ALOGW("asyncCallback() unknown event %d", event);
1996        break;
1997    }
1998    return 0;
1999}
2000
2001void AudioFlinger::PlaybackThread::readOutputParameters_l()
2002{
2003    // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
2004    mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2005    mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2006    if (!audio_is_output_channel(mChannelMask)) {
2007        LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
2008    }
2009    if ((mType == MIXER || mType == DUPLICATING)
2010            && !isValidPcmSinkChannelMask(mChannelMask)) {
2011        LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2012                mChannelMask);
2013    }
2014    mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
2015    mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2016    mFormat = mHALFormat;
2017    if (!audio_is_valid_format(mFormat)) {
2018        LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
2019    }
2020    if ((mType == MIXER || mType == DUPLICATING)
2021            && !isValidPcmSinkFormat(mFormat)) {
2022        LOG_FATAL("HAL format %#x not supported for mixed output",
2023                mFormat);
2024    }
2025    mFrameSize = mOutput->getFrameSize();
2026    mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2027    mFrameCount = mBufferSize / mFrameSize;
2028    if (mFrameCount & 15) {
2029        ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2030                mFrameCount);
2031    }
2032
2033    if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2034            (mOutput->stream->set_callback != NULL)) {
2035        if (mOutput->stream->set_callback(mOutput->stream,
2036                                      AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2037            mUseAsyncWrite = true;
2038            mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
2039        }
2040    }
2041
2042    mHwSupportsPause = false;
2043    if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2044        if (mOutput->stream->pause != NULL) {
2045            if (mOutput->stream->resume != NULL) {
2046                mHwSupportsPause = true;
2047            } else {
2048                ALOGW("direct output implements pause but not resume");
2049            }
2050        } else if (mOutput->stream->resume != NULL) {
2051            ALOGW("direct output implements resume but not pause");
2052        }
2053    }
2054    if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2055        LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2056    }
2057
2058    if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2059        // For best precision, we use float instead of the associated output
2060        // device format (typically PCM 16 bit).
2061
2062        mFormat = AUDIO_FORMAT_PCM_FLOAT;
2063        mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2064        mBufferSize = mFrameSize * mFrameCount;
2065
2066        // TODO: We currently use the associated output device channel mask and sample rate.
2067        // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2068        // (if a valid mask) to avoid premature downmix.
2069        // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2070        // instead of the output device sample rate to avoid loss of high frequency information.
2071        // This may need to be updated as MixerThread/OutputTracks are added and not here.
2072    }
2073
2074    // Calculate size of normal sink buffer relative to the HAL output buffer size
2075    double multiplier = 1.0;
2076    if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2077            kUseFastMixer == FastMixer_Dynamic)) {
2078        size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2079        size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
2080        // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2081        minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2082        maxNormalFrameCount = maxNormalFrameCount & ~15;
2083        if (maxNormalFrameCount < minNormalFrameCount) {
2084            maxNormalFrameCount = minNormalFrameCount;
2085        }
2086        multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2087        if (multiplier <= 1.0) {
2088            multiplier = 1.0;
2089        } else if (multiplier <= 2.0) {
2090            if (2 * mFrameCount <= maxNormalFrameCount) {
2091                multiplier = 2.0;
2092            } else {
2093                multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2094            }
2095        } else {
2096            // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
2097            // SRC (it would be unusual for the normal sink buffer size to not be a multiple of fast
2098            // track, but we sometimes have to do this to satisfy the maximum frame count
2099            // constraint)
2100            // FIXME this rounding up should not be done if no HAL SRC
2101            uint32_t truncMult = (uint32_t) multiplier;
2102            if ((truncMult & 1)) {
2103                if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2104                    ++truncMult;
2105                }
2106            }
2107            multiplier = (double) truncMult;
2108        }
2109    }
2110    mNormalFrameCount = multiplier * mFrameCount;
2111    // round up to nearest 16 frames to satisfy AudioMixer
2112    if (mType == MIXER || mType == DUPLICATING) {
2113        mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2114    }
2115    ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
2116            mNormalFrameCount);
2117
2118    // mSinkBuffer is the sink buffer.  Size is always multiple-of-16 frames.
2119    // Originally this was int16_t[] array, need to remove legacy implications.
2120    free(mSinkBuffer);
2121    mSinkBuffer = NULL;
2122    // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2123    // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2124    const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
2125    (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
2126
2127    // We resize the mMixerBuffer according to the requirements of the sink buffer which
2128    // drives the output.
2129    free(mMixerBuffer);
2130    mMixerBuffer = NULL;
2131    if (mMixerBufferEnabled) {
2132        mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2133        mMixerBufferSize = mNormalFrameCount * mChannelCount
2134                * audio_bytes_per_sample(mMixerBufferFormat);
2135        (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2136    }
2137    free(mEffectBuffer);
2138    mEffectBuffer = NULL;
2139    if (mEffectBufferEnabled) {
2140        mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2141        mEffectBufferSize = mNormalFrameCount * mChannelCount
2142                * audio_bytes_per_sample(mEffectBufferFormat);
2143        (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2144    }
2145
2146    // force reconfiguration of effect chains and engines to take new buffer size and audio
2147    // parameters into account
2148    // Note that mLock is not held when readOutputParameters_l() is called from the constructor
2149    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2150    // matter.
2151    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2152    Vector< sp<EffectChain> > effectChains = mEffectChains;
2153    for (size_t i = 0; i < effectChains.size(); i ++) {
2154        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2155    }
2156}
2157
2158
2159status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2160{
2161    if (halFrames == NULL || dspFrames == NULL) {
2162        return BAD_VALUE;
2163    }
2164    Mutex::Autolock _l(mLock);
2165    if (initCheck() != NO_ERROR) {
2166        return INVALID_OPERATION;
2167    }
2168    size_t framesWritten = mBytesWritten / mFrameSize;
2169    *halFrames = framesWritten;
2170
2171    if (isSuspended()) {
2172        // return an estimation of rendered frames when the output is suspended
2173        size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2174        *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2175        return NO_ERROR;
2176    } else {
2177        status_t status;
2178        uint32_t frames;
2179        status = mOutput->getRenderPosition(&frames);
2180        *dspFrames = (size_t)frames;
2181        return status;
2182    }
2183}
2184
2185uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2186{
2187    Mutex::Autolock _l(mLock);
2188    uint32_t result = 0;
2189    if (getEffectChain_l(sessionId) != 0) {
2190        result = EFFECT_SESSION;
2191    }
2192
2193    for (size_t i = 0; i < mTracks.size(); ++i) {
2194        sp<Track> track = mTracks[i];
2195        if (sessionId == track->sessionId() && !track->isInvalid()) {
2196            result |= TRACK_SESSION;
2197            break;
2198        }
2199    }
2200
2201    return result;
2202}
2203
2204uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2205{
2206    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2207    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2208    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2209        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2210    }
2211    for (size_t i = 0; i < mTracks.size(); i++) {
2212        sp<Track> track = mTracks[i];
2213        if (sessionId == track->sessionId() && !track->isInvalid()) {
2214            return AudioSystem::getStrategyForStream(track->streamType());
2215        }
2216    }
2217    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2218}
2219
2220
2221AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2222{
2223    Mutex::Autolock _l(mLock);
2224    return mOutput;
2225}
2226
2227AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2228{
2229    Mutex::Autolock _l(mLock);
2230    AudioStreamOut *output = mOutput;
2231    mOutput = NULL;
2232    // FIXME FastMixer might also have a raw ptr to mOutputSink;
2233    //       must push a NULL and wait for ack
2234    mOutputSink.clear();
2235    mPipeSink.clear();
2236    mNormalSink.clear();
2237    return output;
2238}
2239
2240// this method must always be called either with ThreadBase mLock held or inside the thread loop
2241audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2242{
2243    if (mOutput == NULL) {
2244        return NULL;
2245    }
2246    return &mOutput->stream->common;
2247}
2248
2249uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2250{
2251    return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2252}
2253
2254status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2255{
2256    if (!isValidSyncEvent(event)) {
2257        return BAD_VALUE;
2258    }
2259
2260    Mutex::Autolock _l(mLock);
2261
2262    for (size_t i = 0; i < mTracks.size(); ++i) {
2263        sp<Track> track = mTracks[i];
2264        if (event->triggerSession() == track->sessionId()) {
2265            (void) track->setSyncEvent(event);
2266            return NO_ERROR;
2267        }
2268    }
2269
2270    return NAME_NOT_FOUND;
2271}
2272
2273bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2274{
2275    return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2276}
2277
2278void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2279        const Vector< sp<Track> >& tracksToRemove)
2280{
2281    size_t count = tracksToRemove.size();
2282    if (count > 0) {
2283        for (size_t i = 0 ; i < count ; i++) {
2284            const sp<Track>& track = tracksToRemove.itemAt(i);
2285            if (track->isExternalTrack()) {
2286                AudioSystem::stopOutput(mId, track->streamType(),
2287                                        (audio_session_t)track->sessionId());
2288#ifdef ADD_BATTERY_DATA
2289                // to track the speaker usage
2290                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2291#endif
2292                if (track->isTerminated()) {
2293                    AudioSystem::releaseOutput(mId, track->streamType(),
2294                                               (audio_session_t)track->sessionId());
2295                }
2296            }
2297        }
2298    }
2299}
2300
2301void AudioFlinger::PlaybackThread::checkSilentMode_l()
2302{
2303    if (!mMasterMute) {
2304        char value[PROPERTY_VALUE_MAX];
2305        if (property_get("ro.audio.silent", value, "0") > 0) {
2306            char *endptr;
2307            unsigned long ul = strtoul(value, &endptr, 0);
2308            if (*endptr == '\0' && ul != 0) {
2309                ALOGD("Silence is golden");
2310                // The setprop command will not allow a property to be changed after
2311                // the first time it is set, so we don't have to worry about un-muting.
2312                setMasterMute_l(true);
2313            }
2314        }
2315    }
2316}
2317
2318// shared by MIXER and DIRECT, overridden by DUPLICATING
2319ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
2320{
2321    // FIXME rewrite to reduce number of system calls
2322    mLastWriteTime = systemTime();
2323    mInWrite = true;
2324    ssize_t bytesWritten;
2325    const size_t offset = mCurrentWriteLength - mBytesRemaining;
2326
2327    // If an NBAIO sink is present, use it to write the normal mixer's submix
2328    if (mNormalSink != 0) {
2329
2330        const size_t count = mBytesRemaining / mFrameSize;
2331
2332        ATRACE_BEGIN("write");
2333        // update the setpoint when AudioFlinger::mScreenState changes
2334        uint32_t screenState = AudioFlinger::mScreenState;
2335        if (screenState != mScreenState) {
2336            mScreenState = screenState;
2337            MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2338            if (pipe != NULL) {
2339                pipe->setAvgFrames((mScreenState & 1) ?
2340                        (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2341            }
2342        }
2343        ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
2344        ATRACE_END();
2345        if (framesWritten > 0) {
2346            bytesWritten = framesWritten * mFrameSize;
2347        } else {
2348            bytesWritten = framesWritten;
2349        }
2350        mLatchDValid = false;
2351        status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
2352        if (status == NO_ERROR) {
2353            size_t totalFramesWritten = mNormalSink->framesWritten();
2354            if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2355                mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
2356                // mLatchD.mFramesReleased is set immediately before D is clocked into Q
2357                mLatchDValid = true;
2358            }
2359        }
2360    // otherwise use the HAL / AudioStreamOut directly
2361    } else {
2362        // Direct output and offload threads
2363
2364        if (mUseAsyncWrite) {
2365            ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2366            mWriteAckSequence += 2;
2367            mWriteAckSequence |= 1;
2368            ALOG_ASSERT(mCallbackThread != 0);
2369            mCallbackThread->setWriteBlocked(mWriteAckSequence);
2370        }
2371        // FIXME We should have an implementation of timestamps for direct output threads.
2372        // They are used e.g for multichannel PCM playback over HDMI.
2373        bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
2374        if (mUseAsyncWrite &&
2375                ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2376            // do not wait for async callback in case of error of full write
2377            mWriteAckSequence &= ~1;
2378            ALOG_ASSERT(mCallbackThread != 0);
2379            mCallbackThread->setWriteBlocked(mWriteAckSequence);
2380        }
2381    }
2382
2383    mNumWrites++;
2384    mInWrite = false;
2385    mStandby = false;
2386    return bytesWritten;
2387}
2388
2389void AudioFlinger::PlaybackThread::threadLoop_drain()
2390{
2391    if (mOutput->stream->drain) {
2392        ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2393        if (mUseAsyncWrite) {
2394            ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2395            mDrainSequence |= 1;
2396            ALOG_ASSERT(mCallbackThread != 0);
2397            mCallbackThread->setDraining(mDrainSequence);
2398        }
2399        mOutput->stream->drain(mOutput->stream,
2400            (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2401                                                : AUDIO_DRAIN_ALL);
2402    }
2403}
2404
2405void AudioFlinger::PlaybackThread::threadLoop_exit()
2406{
2407    {
2408        Mutex::Autolock _l(mLock);
2409        for (size_t i = 0; i < mTracks.size(); i++) {
2410            sp<Track> track = mTracks[i];
2411            track->invalidate();
2412        }
2413    }
2414}
2415
2416/*
2417The derived values that are cached:
2418 - mSinkBufferSize from frame count * frame size
2419 - activeSleepTime from activeSleepTimeUs()
2420 - idleSleepTime from idleSleepTimeUs()
2421 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2422 - maxPeriod from frame count and sample rate (MIXER only)
2423
2424The parameters that affect these derived values are:
2425 - frame count
2426 - frame size
2427 - sample rate
2428 - device type: A2DP or not
2429 - device latency
2430 - format: PCM or not
2431 - active sleep time
2432 - idle sleep time
2433*/
2434
2435void AudioFlinger::PlaybackThread::cacheParameters_l()
2436{
2437    mSinkBufferSize = mNormalFrameCount * mFrameSize;
2438    activeSleepTime = activeSleepTimeUs();
2439    idleSleepTime = idleSleepTimeUs();
2440}
2441
2442void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2443{
2444    ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2445            this,  streamType, mTracks.size());
2446    Mutex::Autolock _l(mLock);
2447
2448    size_t size = mTracks.size();
2449    for (size_t i = 0; i < size; i++) {
2450        sp<Track> t = mTracks[i];
2451        if (t->streamType() == streamType) {
2452            t->invalidate();
2453        }
2454    }
2455}
2456
2457status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2458{
2459    int session = chain->sessionId();
2460    int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2461            ? mEffectBuffer : mSinkBuffer);
2462    bool ownsBuffer = false;
2463
2464    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2465    if (session > 0) {
2466        // Only one effect chain can be present in direct output thread and it uses
2467        // the sink buffer as input
2468        if (mType != DIRECT) {
2469            size_t numSamples = mNormalFrameCount * mChannelCount;
2470            buffer = new int16_t[numSamples];
2471            memset(buffer, 0, numSamples * sizeof(int16_t));
2472            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2473            ownsBuffer = true;
2474        }
2475
2476        // Attach all tracks with same session ID to this chain.
2477        for (size_t i = 0; i < mTracks.size(); ++i) {
2478            sp<Track> track = mTracks[i];
2479            if (session == track->sessionId()) {
2480                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2481                        buffer);
2482                track->setMainBuffer(buffer);
2483                chain->incTrackCnt();
2484            }
2485        }
2486
2487        // indicate all active tracks in the chain
2488        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2489            sp<Track> track = mActiveTracks[i].promote();
2490            if (track == 0) {
2491                continue;
2492            }
2493            if (session == track->sessionId()) {
2494                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2495                chain->incActiveTrackCnt();
2496            }
2497        }
2498    }
2499    chain->setThread(this);
2500    chain->setInBuffer(buffer, ownsBuffer);
2501    chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2502            ? mEffectBuffer : mSinkBuffer));
2503    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2504    // chains list in order to be processed last as it contains output stage effects
2505    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2506    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2507    // after track specific effects and before output stage
2508    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2509    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2510    // Effect chain for other sessions are inserted at beginning of effect
2511    // chains list to be processed before output mix effects. Relative order between other
2512    // sessions is not important
2513    size_t size = mEffectChains.size();
2514    size_t i = 0;
2515    for (i = 0; i < size; i++) {
2516        if (mEffectChains[i]->sessionId() < session) {
2517            break;
2518        }
2519    }
2520    mEffectChains.insertAt(chain, i);
2521    checkSuspendOnAddEffectChain_l(chain);
2522
2523    return NO_ERROR;
2524}
2525
2526size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2527{
2528    int session = chain->sessionId();
2529
2530    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2531
2532    for (size_t i = 0; i < mEffectChains.size(); i++) {
2533        if (chain == mEffectChains[i]) {
2534            mEffectChains.removeAt(i);
2535            // detach all active tracks from the chain
2536            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2537                sp<Track> track = mActiveTracks[i].promote();
2538                if (track == 0) {
2539                    continue;
2540                }
2541                if (session == track->sessionId()) {
2542                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2543                            chain.get(), session);
2544                    chain->decActiveTrackCnt();
2545                }
2546            }
2547
2548            // detach all tracks with same session ID from this chain
2549            for (size_t i = 0; i < mTracks.size(); ++i) {
2550                sp<Track> track = mTracks[i];
2551                if (session == track->sessionId()) {
2552                    track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
2553                    chain->decTrackCnt();
2554                }
2555            }
2556            break;
2557        }
2558    }
2559    return mEffectChains.size();
2560}
2561
2562status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2563        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2564{
2565    Mutex::Autolock _l(mLock);
2566    return attachAuxEffect_l(track, EffectId);
2567}
2568
2569status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2570        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2571{
2572    status_t status = NO_ERROR;
2573
2574    if (EffectId == 0) {
2575        track->setAuxBuffer(0, NULL);
2576    } else {
2577        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2578        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2579        if (effect != 0) {
2580            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2581                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2582            } else {
2583                status = INVALID_OPERATION;
2584            }
2585        } else {
2586            status = BAD_VALUE;
2587        }
2588    }
2589    return status;
2590}
2591
2592void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2593{
2594    for (size_t i = 0; i < mTracks.size(); ++i) {
2595        sp<Track> track = mTracks[i];
2596        if (track->auxEffectId() == effectId) {
2597            attachAuxEffect_l(track, 0);
2598        }
2599    }
2600}
2601
2602bool AudioFlinger::PlaybackThread::threadLoop()
2603{
2604    Vector< sp<Track> > tracksToRemove;
2605
2606    standbyTime = systemTime();
2607
2608    // MIXER
2609    nsecs_t lastWarning = 0;
2610
2611    // DUPLICATING
2612    // FIXME could this be made local to while loop?
2613    writeFrames = 0;
2614
2615    int lastGeneration = 0;
2616
2617    cacheParameters_l();
2618    sleepTime = idleSleepTime;
2619
2620    if (mType == MIXER) {
2621        sleepTimeShift = 0;
2622    }
2623
2624    CpuStats cpuStats;
2625    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2626
2627    acquireWakeLock();
2628
2629    // mNBLogWriter->log can only be called while thread mutex mLock is held.
2630    // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2631    // and then that string will be logged at the next convenient opportunity.
2632    const char *logString = NULL;
2633
2634    checkSilentMode_l();
2635
2636    while (!exitPending())
2637    {
2638        cpuStats.sample(myName);
2639
2640        Vector< sp<EffectChain> > effectChains;
2641
2642        { // scope for mLock
2643
2644            Mutex::Autolock _l(mLock);
2645
2646            processConfigEvents_l();
2647
2648            if (logString != NULL) {
2649                mNBLogWriter->logTimestamp();
2650                mNBLogWriter->log(logString);
2651                logString = NULL;
2652            }
2653
2654            // Gather the framesReleased counters for all active tracks,
2655            // and latch them atomically with the timestamp.
2656            // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2657            mLatchD.mFramesReleased.clear();
2658            size_t size = mActiveTracks.size();
2659            for (size_t i = 0; i < size; i++) {
2660                sp<Track> t = mActiveTracks[i].promote();
2661                if (t != 0) {
2662                    mLatchD.mFramesReleased.add(t.get(),
2663                            t->mAudioTrackServerProxy->framesReleased());
2664                }
2665            }
2666            if (mLatchDValid) {
2667                mLatchQ = mLatchD;
2668                mLatchDValid = false;
2669                mLatchQValid = true;
2670            }
2671
2672            saveOutputTracks();
2673            if (mSignalPending) {
2674                // A signal was raised while we were unlocked
2675                mSignalPending = false;
2676            } else if (waitingAsyncCallback_l()) {
2677                if (exitPending()) {
2678                    break;
2679                }
2680                releaseWakeLock_l();
2681                mWakeLockUids.clear();
2682                mActiveTracksGeneration++;
2683                ALOGV("wait async completion");
2684                mWaitWorkCV.wait(mLock);
2685                ALOGV("async completion/wake");
2686                acquireWakeLock_l();
2687                standbyTime = systemTime() + standbyDelay;
2688                sleepTime = 0;
2689
2690                continue;
2691            }
2692            if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
2693                                   isSuspended()) {
2694                // put audio hardware into standby after short delay
2695                if (shouldStandby_l()) {
2696
2697                    threadLoop_standby();
2698
2699                    mStandby = true;
2700                }
2701
2702                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2703                    // we're about to wait, flush the binder command buffer
2704                    IPCThreadState::self()->flushCommands();
2705
2706                    clearOutputTracks();
2707
2708                    if (exitPending()) {
2709                        break;
2710                    }
2711
2712                    releaseWakeLock_l();
2713                    mWakeLockUids.clear();
2714                    mActiveTracksGeneration++;
2715                    // wait until we have something to do...
2716                    ALOGV("%s going to sleep", myName.string());
2717                    mWaitWorkCV.wait(mLock);
2718                    ALOGV("%s waking up", myName.string());
2719                    acquireWakeLock_l();
2720
2721                    mMixerStatus = MIXER_IDLE;
2722                    mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2723                    mBytesWritten = 0;
2724                    mBytesRemaining = 0;
2725                    checkSilentMode_l();
2726
2727                    standbyTime = systemTime() + standbyDelay;
2728                    sleepTime = idleSleepTime;
2729                    if (mType == MIXER) {
2730                        sleepTimeShift = 0;
2731                    }
2732
2733                    continue;
2734                }
2735            }
2736            // mMixerStatusIgnoringFastTracks is also updated internally
2737            mMixerStatus = prepareTracks_l(&tracksToRemove);
2738
2739            // compare with previously applied list
2740            if (lastGeneration != mActiveTracksGeneration) {
2741                // update wakelock
2742                updateWakeLockUids_l(mWakeLockUids);
2743                lastGeneration = mActiveTracksGeneration;
2744            }
2745
2746            // prevent any changes in effect chain list and in each effect chain
2747            // during mixing and effect process as the audio buffers could be deleted
2748            // or modified if an effect is created or deleted
2749            lockEffectChains_l(effectChains);
2750        } // mLock scope ends
2751
2752        if (mBytesRemaining == 0) {
2753            mCurrentWriteLength = 0;
2754            if (mMixerStatus == MIXER_TRACKS_READY) {
2755                // threadLoop_mix() sets mCurrentWriteLength
2756                threadLoop_mix();
2757            } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2758                        && (mMixerStatus != MIXER_DRAIN_ALL)) {
2759                // threadLoop_sleepTime sets sleepTime to 0 if data
2760                // must be written to HAL
2761                threadLoop_sleepTime();
2762                if (sleepTime == 0) {
2763                    mCurrentWriteLength = mSinkBufferSize;
2764                }
2765            }
2766            // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2767            // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2768            // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2769            // or mSinkBuffer (if there are no effects).
2770            //
2771            // This is done pre-effects computation; if effects change to
2772            // support higher precision, this needs to move.
2773            //
2774            // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2775            // TODO use sleepTime == 0 as an additional condition.
2776            if (mMixerBufferValid) {
2777                void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2778                audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2779
2780                memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2781                        mNormalFrameCount * mChannelCount);
2782            }
2783
2784            mBytesRemaining = mCurrentWriteLength;
2785            if (isSuspended()) {
2786                sleepTime = suspendSleepTimeUs();
2787                // simulate write to HAL when suspended
2788                mBytesWritten += mSinkBufferSize;
2789                mBytesRemaining = 0;
2790            }
2791
2792            // only process effects if we're going to write
2793            if (sleepTime == 0 && mType != OFFLOAD) {
2794                for (size_t i = 0; i < effectChains.size(); i ++) {
2795                    effectChains[i]->process_l();
2796                }
2797            }
2798        }
2799        // Process effect chains for offloaded thread even if no audio
2800        // was read from audio track: process only updates effect state
2801        // and thus does have to be synchronized with audio writes but may have
2802        // to be called while waiting for async write callback
2803        if (mType == OFFLOAD) {
2804            for (size_t i = 0; i < effectChains.size(); i ++) {
2805                effectChains[i]->process_l();
2806            }
2807        }
2808
2809        // Only if the Effects buffer is enabled and there is data in the
2810        // Effects buffer (buffer valid), we need to
2811        // copy into the sink buffer.
2812        // TODO use sleepTime == 0 as an additional condition.
2813        if (mEffectBufferValid) {
2814            //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2815            memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2816                    mNormalFrameCount * mChannelCount);
2817        }
2818
2819        // enable changes in effect chain
2820        unlockEffectChains(effectChains);
2821
2822        if (!waitingAsyncCallback()) {
2823            // sleepTime == 0 means we must write to audio hardware
2824            if (sleepTime == 0) {
2825                if (mBytesRemaining) {
2826                    ssize_t ret = threadLoop_write();
2827                    if (ret < 0) {
2828                        mBytesRemaining = 0;
2829                    } else {
2830                        mBytesWritten += ret;
2831                        mBytesRemaining -= ret;
2832                    }
2833                } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2834                        (mMixerStatus == MIXER_DRAIN_ALL)) {
2835                    threadLoop_drain();
2836                }
2837                if (mType == MIXER) {
2838                    // write blocked detection
2839                    nsecs_t now = systemTime();
2840                    nsecs_t delta = now - mLastWriteTime;
2841                    if (!mStandby && delta > maxPeriod) {
2842                        mNumDelayedWrites++;
2843                        if ((now - lastWarning) > kWarningThrottleNs) {
2844                            ATRACE_NAME("underrun");
2845                            ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2846                                    ns2ms(delta), mNumDelayedWrites, this);
2847                            lastWarning = now;
2848                        }
2849                    }
2850                }
2851
2852            } else {
2853                ATRACE_BEGIN("sleep");
2854                usleep(sleepTime);
2855                ATRACE_END();
2856            }
2857        }
2858
2859        // Finally let go of removed track(s), without the lock held
2860        // since we can't guarantee the destructors won't acquire that
2861        // same lock.  This will also mutate and push a new fast mixer state.
2862        threadLoop_removeTracks(tracksToRemove);
2863        tracksToRemove.clear();
2864
2865        // FIXME I don't understand the need for this here;
2866        //       it was in the original code but maybe the
2867        //       assignment in saveOutputTracks() makes this unnecessary?
2868        clearOutputTracks();
2869
2870        // Effect chains will be actually deleted here if they were removed from
2871        // mEffectChains list during mixing or effects processing
2872        effectChains.clear();
2873
2874        // FIXME Note that the above .clear() is no longer necessary since effectChains
2875        // is now local to this block, but will keep it for now (at least until merge done).
2876    }
2877
2878    threadLoop_exit();
2879
2880    if (!mStandby) {
2881        threadLoop_standby();
2882        mStandby = true;
2883    }
2884
2885    releaseWakeLock();
2886    mWakeLockUids.clear();
2887    mActiveTracksGeneration++;
2888
2889    ALOGV("Thread %p type %d exiting", this, mType);
2890    return false;
2891}
2892
2893// removeTracks_l() must be called with ThreadBase::mLock held
2894void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2895{
2896    size_t count = tracksToRemove.size();
2897    if (count > 0) {
2898        for (size_t i=0 ; i<count ; i++) {
2899            const sp<Track>& track = tracksToRemove.itemAt(i);
2900            mActiveTracks.remove(track);
2901            mWakeLockUids.remove(track->uid());
2902            mActiveTracksGeneration++;
2903            ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2904            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2905            if (chain != 0) {
2906                ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2907                        track->sessionId());
2908                chain->decActiveTrackCnt();
2909            }
2910            if (track->isTerminated()) {
2911                removeTrack_l(track);
2912            }
2913        }
2914    }
2915
2916}
2917
2918status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2919{
2920    if (mNormalSink != 0) {
2921        return mNormalSink->getTimestamp(timestamp);
2922    }
2923    if ((mType == OFFLOAD || mType == DIRECT)
2924            && mOutput != NULL && mOutput->stream->get_presentation_position) {
2925        uint64_t position64;
2926        int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
2927        if (ret == 0) {
2928            timestamp.mPosition = (uint32_t)position64;
2929            return NO_ERROR;
2930        }
2931    }
2932    return INVALID_OPERATION;
2933}
2934
2935status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
2936                                                          audio_patch_handle_t *handle)
2937{
2938    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
2939    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
2940    if (mFastMixer != 0) {
2941        FastMixerStateQueue *sq = mFastMixer->sq();
2942        FastMixerState *state = sq->begin();
2943        if (!(state->mCommand & FastMixerState::IDLE)) {
2944            previousCommand = state->mCommand;
2945            state->mCommand = FastMixerState::HOT_IDLE;
2946            sq->end();
2947            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2948        } else {
2949            sq->end(false /*didModify*/);
2950        }
2951    }
2952    status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
2953
2954    if (!(previousCommand & FastMixerState::IDLE)) {
2955        ALOG_ASSERT(mFastMixer != 0);
2956        FastMixerStateQueue *sq = mFastMixer->sq();
2957        FastMixerState *state = sq->begin();
2958        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
2959        state->mCommand = previousCommand;
2960        sq->end();
2961        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2962    }
2963
2964    return status;
2965}
2966
2967status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2968                                                          audio_patch_handle_t *handle)
2969{
2970    status_t status = NO_ERROR;
2971
2972    // store new device and send to effects
2973    audio_devices_t type = AUDIO_DEVICE_NONE;
2974    for (unsigned int i = 0; i < patch->num_sinks; i++) {
2975        type |= patch->sinks[i].ext.device.type;
2976    }
2977
2978#ifdef ADD_BATTERY_DATA
2979    // when changing the audio output device, call addBatteryData to notify
2980    // the change
2981    if (mOutDevice != type) {
2982        uint32_t params = 0;
2983        // check whether speaker is on
2984        if (type & AUDIO_DEVICE_OUT_SPEAKER) {
2985            params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2986        }
2987
2988        audio_devices_t deviceWithoutSpeaker
2989            = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
2990        // check if any other device (except speaker) is on
2991        if (type & deviceWithoutSpeaker) {
2992            params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2993        }
2994
2995        if (params != 0) {
2996            addBatteryData(params);
2997        }
2998    }
2999#endif
3000
3001    for (size_t i = 0; i < mEffectChains.size(); i++) {
3002        mEffectChains[i]->setDevice_l(type);
3003    }
3004    mOutDevice = type;
3005
3006    if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3007        audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3008        status = hwDevice->create_audio_patch(hwDevice,
3009                                               patch->num_sources,
3010                                               patch->sources,
3011                                               patch->num_sinks,
3012                                               patch->sinks,
3013                                               handle);
3014    } else {
3015        char *address;
3016        if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3017            //FIXME: we only support address on first sink with HAL version < 3.0
3018            address = audio_device_address_to_parameter(
3019                                                        patch->sinks[0].ext.device.type,
3020                                                        patch->sinks[0].ext.device.address);
3021        } else {
3022            address = (char *)calloc(1, 1);
3023        }
3024        AudioParameter param = AudioParameter(String8(address));
3025        free(address);
3026        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3027        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3028                param.toString().string());
3029        *handle = AUDIO_PATCH_HANDLE_NONE;
3030    }
3031    return status;
3032}
3033
3034status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3035{
3036    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3037    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3038    if (mFastMixer != 0) {
3039        FastMixerStateQueue *sq = mFastMixer->sq();
3040        FastMixerState *state = sq->begin();
3041        if (!(state->mCommand & FastMixerState::IDLE)) {
3042            previousCommand = state->mCommand;
3043            state->mCommand = FastMixerState::HOT_IDLE;
3044            sq->end();
3045            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3046        } else {
3047            sq->end(false /*didModify*/);
3048        }
3049    }
3050
3051    status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3052
3053    if (!(previousCommand & FastMixerState::IDLE)) {
3054        ALOG_ASSERT(mFastMixer != 0);
3055        FastMixerStateQueue *sq = mFastMixer->sq();
3056        FastMixerState *state = sq->begin();
3057        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3058        state->mCommand = previousCommand;
3059        sq->end();
3060        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3061    }
3062
3063    return status;
3064}
3065
3066status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3067{
3068    status_t status = NO_ERROR;
3069
3070    mOutDevice = AUDIO_DEVICE_NONE;
3071
3072    if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3073        audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3074        status = hwDevice->release_audio_patch(hwDevice, handle);
3075    } else {
3076        AudioParameter param;
3077        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3078        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3079                param.toString().string());
3080    }
3081    return status;
3082}
3083
3084void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3085{
3086    Mutex::Autolock _l(mLock);
3087    mTracks.add(track);
3088}
3089
3090void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3091{
3092    Mutex::Autolock _l(mLock);
3093    destroyTrack_l(track);
3094}
3095
3096void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3097{
3098    ThreadBase::getAudioPortConfig(config);
3099    config->role = AUDIO_PORT_ROLE_SOURCE;
3100    config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3101    config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3102}
3103
3104// ----------------------------------------------------------------------------
3105
3106AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
3107        audio_io_handle_t id, audio_devices_t device, type_t type)
3108    :   PlaybackThread(audioFlinger, output, id, device, type),
3109        // mAudioMixer below
3110        // mFastMixer below
3111        mFastMixerFutex(0)
3112        // mOutputSink below
3113        // mPipeSink below
3114        // mNormalSink below
3115{
3116    ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
3117    ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
3118            "mFrameCount=%d, mNormalFrameCount=%d",
3119            mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3120            mNormalFrameCount);
3121    mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3122
3123    if (type == DUPLICATING) {
3124        // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3125        // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3126        // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3127        return;
3128    }
3129    // create an NBAIO sink for the HAL output stream, and negotiate
3130    mOutputSink = new AudioStreamOutSink(output->stream);
3131    size_t numCounterOffers = 0;
3132    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
3133    ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3134    ALOG_ASSERT(index == 0);
3135
3136    // initialize fast mixer depending on configuration
3137    bool initFastMixer;
3138    switch (kUseFastMixer) {
3139    case FastMixer_Never:
3140        initFastMixer = false;
3141        break;
3142    case FastMixer_Always:
3143        initFastMixer = true;
3144        break;
3145    case FastMixer_Static:
3146    case FastMixer_Dynamic:
3147        initFastMixer = mFrameCount < mNormalFrameCount;
3148        break;
3149    }
3150    if (initFastMixer) {
3151        audio_format_t fastMixerFormat;
3152        if (mMixerBufferEnabled && mEffectBufferEnabled) {
3153            fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3154        } else {
3155            fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3156        }
3157        if (mFormat != fastMixerFormat) {
3158            // change our Sink format to accept our intermediate precision
3159            mFormat = fastMixerFormat;
3160            free(mSinkBuffer);
3161            mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3162            const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3163            (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3164        }
3165
3166        // create a MonoPipe to connect our submix to FastMixer
3167        NBAIO_Format format = mOutputSink->format();
3168        NBAIO_Format origformat = format;
3169        // adjust format to match that of the Fast Mixer
3170        ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
3171        format.mFormat = fastMixerFormat;
3172        format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3173
3174        // This pipe depth compensates for scheduling latency of the normal mixer thread.
3175        // When it wakes up after a maximum latency, it runs a few cycles quickly before
3176        // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
3177        MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3178        const NBAIO_Format offers[1] = {format};
3179        size_t numCounterOffers = 0;
3180        ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3181        ALOG_ASSERT(index == 0);
3182        monoPipe->setAvgFrames((mScreenState & 1) ?
3183                (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3184        mPipeSink = monoPipe;
3185
3186#ifdef TEE_SINK
3187        if (mTeeSinkOutputEnabled) {
3188            // create a Pipe to archive a copy of FastMixer's output for dumpsys
3189            Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3190            const NBAIO_Format offers2[1] = {origformat};
3191            numCounterOffers = 0;
3192            index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
3193            ALOG_ASSERT(index == 0);
3194            mTeeSink = teeSink;
3195            PipeReader *teeSource = new PipeReader(*teeSink);
3196            numCounterOffers = 0;
3197            index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
3198            ALOG_ASSERT(index == 0);
3199            mTeeSource = teeSource;
3200        }
3201#endif
3202
3203        // create fast mixer and configure it initially with just one fast track for our submix
3204        mFastMixer = new FastMixer();
3205        FastMixerStateQueue *sq = mFastMixer->sq();
3206#ifdef STATE_QUEUE_DUMP
3207        sq->setObserverDump(&mStateQueueObserverDump);
3208        sq->setMutatorDump(&mStateQueueMutatorDump);
3209#endif
3210        FastMixerState *state = sq->begin();
3211        FastTrack *fastTrack = &state->mFastTracks[0];
3212        // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3213        fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3214        fastTrack->mVolumeProvider = NULL;
3215        fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3216        fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
3217        fastTrack->mGeneration++;
3218        state->mFastTracksGen++;
3219        state->mTrackMask = 1;
3220        // fast mixer will use the HAL output sink
3221        state->mOutputSink = mOutputSink.get();
3222        state->mOutputSinkGen++;
3223        state->mFrameCount = mFrameCount;
3224        state->mCommand = FastMixerState::COLD_IDLE;
3225        // already done in constructor initialization list
3226        //mFastMixerFutex = 0;
3227        state->mColdFutexAddr = &mFastMixerFutex;
3228        state->mColdGen++;
3229        state->mDumpState = &mFastMixerDumpState;
3230#ifdef TEE_SINK
3231        state->mTeeSink = mTeeSink.get();
3232#endif
3233        mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3234        state->mNBLogWriter = mFastMixerNBLogWriter.get();
3235        sq->end();
3236        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3237
3238        // start the fast mixer
3239        mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3240        pid_t tid = mFastMixer->getTid();
3241        int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3242        if (err != 0) {
3243            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3244                    kPriorityFastMixer, getpid_cached, tid, err);
3245        }
3246
3247#ifdef AUDIO_WATCHDOG
3248        // create and start the watchdog
3249        mAudioWatchdog = new AudioWatchdog();
3250        mAudioWatchdog->setDump(&mAudioWatchdogDump);
3251        mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3252        tid = mAudioWatchdog->getTid();
3253        err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3254        if (err != 0) {
3255            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3256                    kPriorityFastMixer, getpid_cached, tid, err);
3257        }
3258#endif
3259
3260    }
3261
3262    switch (kUseFastMixer) {
3263    case FastMixer_Never:
3264    case FastMixer_Dynamic:
3265        mNormalSink = mOutputSink;
3266        break;
3267    case FastMixer_Always:
3268        mNormalSink = mPipeSink;
3269        break;
3270    case FastMixer_Static:
3271        mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3272        break;
3273    }
3274}
3275
3276AudioFlinger::MixerThread::~MixerThread()
3277{
3278    if (mFastMixer != 0) {
3279        FastMixerStateQueue *sq = mFastMixer->sq();
3280        FastMixerState *state = sq->begin();
3281        if (state->mCommand == FastMixerState::COLD_IDLE) {
3282            int32_t old = android_atomic_inc(&mFastMixerFutex);
3283            if (old == -1) {
3284                (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3285            }
3286        }
3287        state->mCommand = FastMixerState::EXIT;
3288        sq->end();
3289        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3290        mFastMixer->join();
3291        // Though the fast mixer thread has exited, it's state queue is still valid.
3292        // We'll use that extract the final state which contains one remaining fast track
3293        // corresponding to our sub-mix.
3294        state = sq->begin();
3295        ALOG_ASSERT(state->mTrackMask == 1);
3296        FastTrack *fastTrack = &state->mFastTracks[0];
3297        ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3298        delete fastTrack->mBufferProvider;
3299        sq->end(false /*didModify*/);
3300        mFastMixer.clear();
3301#ifdef AUDIO_WATCHDOG
3302        if (mAudioWatchdog != 0) {
3303            mAudioWatchdog->requestExit();
3304            mAudioWatchdog->requestExitAndWait();
3305            mAudioWatchdog.clear();
3306        }
3307#endif
3308    }
3309    mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
3310    delete mAudioMixer;
3311}
3312
3313
3314uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3315{
3316    if (mFastMixer != 0) {
3317        MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3318        latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3319    }
3320    return latency;
3321}
3322
3323
3324void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3325{
3326    PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3327}
3328
3329ssize_t AudioFlinger::MixerThread::threadLoop_write()
3330{
3331    // FIXME we should only do one push per cycle; confirm this is true
3332    // Start the fast mixer if it's not already running
3333    if (mFastMixer != 0) {
3334        FastMixerStateQueue *sq = mFastMixer->sq();
3335        FastMixerState *state = sq->begin();
3336        if (state->mCommand != FastMixerState::MIX_WRITE &&
3337                (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3338            if (state->mCommand == FastMixerState::COLD_IDLE) {
3339                int32_t old = android_atomic_inc(&mFastMixerFutex);
3340                if (old == -1) {
3341                    (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
3342                }
3343#ifdef AUDIO_WATCHDOG
3344                if (mAudioWatchdog != 0) {
3345                    mAudioWatchdog->resume();
3346                }
3347#endif
3348            }
3349            state->mCommand = FastMixerState::MIX_WRITE;
3350#ifdef FAST_THREAD_STATISTICS
3351            mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
3352                FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
3353#endif
3354            sq->end();
3355            sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3356            if (kUseFastMixer == FastMixer_Dynamic) {
3357                mNormalSink = mPipeSink;
3358            }
3359        } else {
3360            sq->end(false /*didModify*/);
3361        }
3362    }
3363    return PlaybackThread::threadLoop_write();
3364}
3365
3366void AudioFlinger::MixerThread::threadLoop_standby()
3367{
3368    // Idle the fast mixer if it's currently running
3369    if (mFastMixer != 0) {
3370        FastMixerStateQueue *sq = mFastMixer->sq();
3371        FastMixerState *state = sq->begin();
3372        if (!(state->mCommand & FastMixerState::IDLE)) {
3373            state->mCommand = FastMixerState::COLD_IDLE;
3374            state->mColdFutexAddr = &mFastMixerFutex;
3375            state->mColdGen++;
3376            mFastMixerFutex = 0;
3377            sq->end();
3378            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3379            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3380            if (kUseFastMixer == FastMixer_Dynamic) {
3381                mNormalSink = mOutputSink;
3382            }
3383#ifdef AUDIO_WATCHDOG
3384            if (mAudioWatchdog != 0) {
3385                mAudioWatchdog->pause();
3386            }
3387#endif
3388        } else {
3389            sq->end(false /*didModify*/);
3390        }
3391    }
3392    PlaybackThread::threadLoop_standby();
3393}
3394
3395bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3396{
3397    return false;
3398}
3399
3400bool AudioFlinger::PlaybackThread::shouldStandby_l()
3401{
3402    return !mStandby;
3403}
3404
3405bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3406{
3407    Mutex::Autolock _l(mLock);
3408    return waitingAsyncCallback_l();
3409}
3410
3411// shared by MIXER and DIRECT, overridden by DUPLICATING
3412void AudioFlinger::PlaybackThread::threadLoop_standby()
3413{
3414    ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3415    mOutput->standby();
3416    if (mUseAsyncWrite != 0) {
3417        // discard any pending drain or write ack by incrementing sequence
3418        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3419        mDrainSequence = (mDrainSequence + 2) & ~1;
3420        ALOG_ASSERT(mCallbackThread != 0);
3421        mCallbackThread->setWriteBlocked(mWriteAckSequence);
3422        mCallbackThread->setDraining(mDrainSequence);
3423    }
3424    mHwPaused = false;
3425}
3426
3427void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3428{
3429    ALOGV("signal playback thread");
3430    broadcast_l();
3431}
3432
3433void AudioFlinger::MixerThread::threadLoop_mix()
3434{
3435    // obtain the presentation timestamp of the next output buffer
3436    int64_t pts;
3437    status_t status = INVALID_OPERATION;
3438
3439    if (mNormalSink != 0) {
3440        status = mNormalSink->getNextWriteTimestamp(&pts);
3441    } else {
3442        status = mOutputSink->getNextWriteTimestamp(&pts);
3443    }
3444
3445    if (status != NO_ERROR) {
3446        pts = AudioBufferProvider::kInvalidPTS;
3447    }
3448
3449    // mix buffers...
3450    mAudioMixer->process(pts);
3451    mCurrentWriteLength = mSinkBufferSize;
3452    // increase sleep time progressively when application underrun condition clears.
3453    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3454    // that a steady state of alternating ready/not ready conditions keeps the sleep time
3455    // such that we would underrun the audio HAL.
3456    if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3457        sleepTimeShift--;
3458    }
3459    sleepTime = 0;
3460    standbyTime = systemTime() + standbyDelay;
3461    //TODO: delay standby when effects have a tail
3462
3463}
3464
3465void AudioFlinger::MixerThread::threadLoop_sleepTime()
3466{
3467    // If no tracks are ready, sleep once for the duration of an output
3468    // buffer size, then write 0s to the output
3469    if (sleepTime == 0) {
3470        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3471            sleepTime = activeSleepTime >> sleepTimeShift;
3472            if (sleepTime < kMinThreadSleepTimeUs) {
3473                sleepTime = kMinThreadSleepTimeUs;
3474            }
3475            // reduce sleep time in case of consecutive application underruns to avoid
3476            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3477            // duration we would end up writing less data than needed by the audio HAL if
3478            // the condition persists.
3479            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3480                sleepTimeShift++;
3481            }
3482        } else {
3483            sleepTime = idleSleepTime;
3484        }
3485    } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
3486        // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3487        // before effects processing or output.
3488        if (mMixerBufferValid) {
3489            memset(mMixerBuffer, 0, mMixerBufferSize);
3490        } else {
3491            memset(mSinkBuffer, 0, mSinkBufferSize);
3492        }
3493        sleepTime = 0;
3494        ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3495                "anticipated start");
3496    }
3497    // TODO add standby time extension fct of effect tail
3498}
3499
3500// prepareTracks_l() must be called with ThreadBase::mLock held
3501AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3502        Vector< sp<Track> > *tracksToRemove)
3503{
3504
3505    mixer_state mixerStatus = MIXER_IDLE;
3506    // find out which tracks need to be processed
3507    size_t count = mActiveTracks.size();
3508    size_t mixedTracks = 0;
3509    size_t tracksWithEffect = 0;
3510    // counts only _active_ fast tracks
3511    size_t fastTracks = 0;
3512    uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3513
3514    float masterVolume = mMasterVolume;
3515    bool masterMute = mMasterMute;
3516
3517    if (masterMute) {
3518        masterVolume = 0;
3519    }
3520    // Delegate master volume control to effect in output mix effect chain if needed
3521    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3522    if (chain != 0) {
3523        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3524        chain->setVolume_l(&v, &v);
3525        masterVolume = (float)((v + (1 << 23)) >> 24);
3526        chain.clear();
3527    }
3528
3529    // prepare a new state to push
3530    FastMixerStateQueue *sq = NULL;
3531    FastMixerState *state = NULL;
3532    bool didModify = false;
3533    FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
3534    if (mFastMixer != 0) {
3535        sq = mFastMixer->sq();
3536        state = sq->begin();
3537    }
3538
3539    mMixerBufferValid = false;  // mMixerBuffer has no valid data until appropriate tracks found.
3540    mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
3541
3542    for (size_t i=0 ; i<count ; i++) {
3543        const sp<Track> t = mActiveTracks[i].promote();
3544        if (t == 0) {
3545            continue;
3546        }
3547
3548        // this const just means the local variable doesn't change
3549        Track* const track = t.get();
3550
3551        // process fast tracks
3552        if (track->isFastTrack()) {
3553
3554            // It's theoretically possible (though unlikely) for a fast track to be created
3555            // and then removed within the same normal mix cycle.  This is not a problem, as
3556            // the track never becomes active so it's fast mixer slot is never touched.
3557            // The converse, of removing an (active) track and then creating a new track
3558            // at the identical fast mixer slot within the same normal mix cycle,
3559            // is impossible because the slot isn't marked available until the end of each cycle.
3560            int j = track->mFastIndex;
3561            ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3562            ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3563            FastTrack *fastTrack = &state->mFastTracks[j];
3564
3565            // Determine whether the track is currently in underrun condition,
3566            // and whether it had a recent underrun.
3567            FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3568            FastTrackUnderruns underruns = ftDump->mUnderruns;
3569            uint32_t recentFull = (underruns.mBitFields.mFull -
3570                    track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3571            uint32_t recentPartial = (underruns.mBitFields.mPartial -
3572                    track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3573            uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3574                    track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3575            uint32_t recentUnderruns = recentPartial + recentEmpty;
3576            track->mObservedUnderruns = underruns;
3577            // don't count underruns that occur while stopping or pausing
3578            // or stopped which can occur when flush() is called while active
3579            if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3580                    recentUnderruns > 0) {
3581                // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3582                track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
3583            }
3584
3585            // This is similar to the state machine for normal tracks,
3586            // with a few modifications for fast tracks.
3587            bool isActive = true;
3588            switch (track->mState) {
3589            case TrackBase::STOPPING_1:
3590                // track stays active in STOPPING_1 state until first underrun
3591                if (recentUnderruns > 0 || track->isTerminated()) {
3592                    track->mState = TrackBase::STOPPING_2;
3593                }
3594                break;
3595            case TrackBase::PAUSING:
3596                // ramp down is not yet implemented
3597                track->setPaused();
3598                break;
3599            case TrackBase::RESUMING:
3600                // ramp up is not yet implemented
3601                track->mState = TrackBase::ACTIVE;
3602                break;
3603            case TrackBase::ACTIVE:
3604                if (recentFull > 0 || recentPartial > 0) {
3605                    // track has provided at least some frames recently: reset retry count
3606                    track->mRetryCount = kMaxTrackRetries;
3607                }
3608                if (recentUnderruns == 0) {
3609                    // no recent underruns: stay active
3610                    break;
3611                }
3612                // there has recently been an underrun of some kind
3613                if (track->sharedBuffer() == 0) {
3614                    // were any of the recent underruns "empty" (no frames available)?
3615                    if (recentEmpty == 0) {
3616                        // no, then ignore the partial underruns as they are allowed indefinitely
3617                        break;
3618                    }
3619                    // there has recently been an "empty" underrun: decrement the retry counter
3620                    if (--(track->mRetryCount) > 0) {
3621                        break;
3622                    }
3623                    // indicate to client process that the track was disabled because of underrun;
3624                    // it will then automatically call start() when data is available
3625                    android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
3626                    // remove from active list, but state remains ACTIVE [confusing but true]
3627                    isActive = false;
3628                    break;
3629                }
3630                // fall through
3631            case TrackBase::STOPPING_2:
3632            case TrackBase::PAUSED:
3633            case TrackBase::STOPPED:
3634            case TrackBase::FLUSHED:   // flush() while active
3635                // Check for presentation complete if track is inactive
3636                // We have consumed all the buffers of this track.
3637                // This would be incomplete if we auto-paused on underrun
3638                {
3639                    size_t audioHALFrames =
3640                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3641                    size_t framesWritten = mBytesWritten / mFrameSize;
3642                    if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3643                        // track stays in active list until presentation is complete
3644                        break;
3645                    }
3646                }
3647                if (track->isStopping_2()) {
3648                    track->mState = TrackBase::STOPPED;
3649                }
3650                if (track->isStopped()) {
3651                    // Can't reset directly, as fast mixer is still polling this track
3652                    //   track->reset();
3653                    // So instead mark this track as needing to be reset after push with ack
3654                    resetMask |= 1 << i;
3655                }
3656                isActive = false;
3657                break;
3658            case TrackBase::IDLE:
3659            default:
3660                LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
3661            }
3662
3663            if (isActive) {
3664                // was it previously inactive?
3665                if (!(state->mTrackMask & (1 << j))) {
3666                    ExtendedAudioBufferProvider *eabp = track;
3667                    VolumeProvider *vp = track;
3668                    fastTrack->mBufferProvider = eabp;
3669                    fastTrack->mVolumeProvider = vp;
3670                    fastTrack->mChannelMask = track->mChannelMask;
3671                    fastTrack->mFormat = track->mFormat;
3672                    fastTrack->mGeneration++;
3673                    state->mTrackMask |= 1 << j;
3674                    didModify = true;
3675                    // no acknowledgement required for newly active tracks
3676                }
3677                // cache the combined master volume and stream type volume for fast mixer; this
3678                // lacks any synchronization or barrier so VolumeProvider may read a stale value
3679                track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
3680                ++fastTracks;
3681            } else {
3682                // was it previously active?
3683                if (state->mTrackMask & (1 << j)) {
3684                    fastTrack->mBufferProvider = NULL;
3685                    fastTrack->mGeneration++;
3686                    state->mTrackMask &= ~(1 << j);
3687                    didModify = true;
3688                    // If any fast tracks were removed, we must wait for acknowledgement
3689                    // because we're about to decrement the last sp<> on those tracks.
3690                    block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3691                } else {
3692                    LOG_ALWAYS_FATAL("fast track %d should have been active", j);
3693                }
3694                tracksToRemove->add(track);
3695                // Avoids a misleading display in dumpsys
3696                track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3697            }
3698            continue;
3699        }
3700
3701        {   // local variable scope to avoid goto warning
3702
3703        audio_track_cblk_t* cblk = track->cblk();
3704
3705        // The first time a track is added we wait
3706        // for all its buffers to be filled before processing it
3707        int name = track->name();
3708        // make sure that we have enough frames to mix one full buffer.
3709        // enforce this condition only once to enable draining the buffer in case the client
3710        // app does not call stop() and relies on underrun to stop:
3711        // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3712        // during last round
3713        size_t desiredFrames;
3714        const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
3715        AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
3716
3717        desiredFrames = sourceFramesNeededWithTimestretch(
3718                sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
3719        // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3720        // add frames already consumed but not yet released by the resampler
3721        // because mAudioTrackServerProxy->framesReady() will include these frames
3722        desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3723
3724        uint32_t minFrames = 1;
3725        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3726                (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
3727            minFrames = desiredFrames;
3728        }
3729
3730        size_t framesReady = track->framesReady();
3731        if (ATRACE_ENABLED()) {
3732            // I wish we had formatted trace names
3733            char traceName[16];
3734            strcpy(traceName, "nRdy");
3735            int name = track->name();
3736            if (AudioMixer::TRACK0 <= name &&
3737                    name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3738                name -= AudioMixer::TRACK0;
3739                traceName[4] = (name / 10) + '0';
3740                traceName[5] = (name % 10) + '0';
3741            } else {
3742                traceName[4] = '?';
3743                traceName[5] = '?';
3744            }
3745            traceName[6] = '\0';
3746            ATRACE_INT(traceName, framesReady);
3747        }
3748        if ((framesReady >= minFrames) && track->isReady() &&
3749                !track->isPaused() && !track->isTerminated())
3750        {
3751            ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
3752
3753            mixedTracks++;
3754
3755            // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3756            // there is an effect chain connected to the track
3757            chain.clear();
3758            if (track->mainBuffer() != mSinkBuffer &&
3759                    track->mainBuffer() != mMixerBuffer) {
3760                if (mEffectBufferEnabled) {
3761                    mEffectBufferValid = true; // Later can set directly.
3762                }
3763                chain = getEffectChain_l(track->sessionId());
3764                // Delegate volume control to effect in track effect chain if needed
3765                if (chain != 0) {
3766                    tracksWithEffect++;
3767                } else {
3768                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3769                            "session %d",
3770                            name, track->sessionId());
3771                }
3772            }
3773
3774
3775            int param = AudioMixer::VOLUME;
3776            if (track->mFillingUpStatus == Track::FS_FILLED) {
3777                // no ramp for the first volume setting
3778                track->mFillingUpStatus = Track::FS_ACTIVE;
3779                if (track->mState == TrackBase::RESUMING) {
3780                    track->mState = TrackBase::ACTIVE;
3781                    param = AudioMixer::RAMP_VOLUME;
3782                }
3783                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
3784            // FIXME should not make a decision based on mServer
3785            } else if (cblk->mServer != 0) {
3786                // If the track is stopped before the first frame was mixed,
3787                // do not apply ramp
3788                param = AudioMixer::RAMP_VOLUME;
3789            }
3790
3791            // compute volume for this track
3792            uint32_t vl, vr;       // in U8.24 integer format
3793            float vlf, vrf, vaf;   // in [0.0, 1.0] float format
3794            if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
3795                vl = vr = 0;
3796                vlf = vrf = vaf = 0.;
3797                if (track->isPausing()) {
3798                    track->setPaused();
3799                }
3800            } else {
3801
3802                // read original volumes with volume control
3803                float typeVolume = mStreamTypes[track->streamType()].volume;
3804                float v = masterVolume * typeVolume;
3805                AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
3806                gain_minifloat_packed_t vlr = proxy->getVolumeLR();
3807                vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3808                vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
3809                // track volumes come from shared memory, so can't be trusted and must be clamped
3810                if (vlf > GAIN_FLOAT_UNITY) {
3811                    ALOGV("Track left volume out of range: %.3g", vlf);
3812                    vlf = GAIN_FLOAT_UNITY;
3813                }
3814                if (vrf > GAIN_FLOAT_UNITY) {
3815                    ALOGV("Track right volume out of range: %.3g", vrf);
3816                    vrf = GAIN_FLOAT_UNITY;
3817                }
3818                // now apply the master volume and stream type volume
3819                vlf *= v;
3820                vrf *= v;
3821                // assuming master volume and stream type volume each go up to 1.0,
3822                // then derive vl and vr as U8.24 versions for the effect chain
3823                const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3824                vl = (uint32_t) (scaleto8_24 * vlf);
3825                vr = (uint32_t) (scaleto8_24 * vrf);
3826                // vl and vr are now in U8.24 format
3827                uint16_t sendLevel = proxy->getSendLevel_U4_12();
3828                // send level comes from shared memory and so may be corrupt
3829                if (sendLevel > MAX_GAIN_INT) {
3830                    ALOGV("Track send level out of range: %04X", sendLevel);
3831                    sendLevel = MAX_GAIN_INT;
3832                }
3833                // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3834                vaf = v * sendLevel * (1. / MAX_GAIN_INT);
3835            }
3836
3837            // Delegate volume control to effect in track effect chain if needed
3838            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3839                // Do not ramp volume if volume is controlled by effect
3840                param = AudioMixer::VOLUME;
3841                // Update remaining floating point volume levels
3842                vlf = (float)vl / (1 << 24);
3843                vrf = (float)vr / (1 << 24);
3844                track->mHasVolumeController = true;
3845            } else {
3846                // force no volume ramp when volume controller was just disabled or removed
3847                // from effect chain to avoid volume spike
3848                if (track->mHasVolumeController) {
3849                    param = AudioMixer::VOLUME;
3850                }
3851                track->mHasVolumeController = false;
3852            }
3853
3854            // XXX: these things DON'T need to be done each time
3855            mAudioMixer->setBufferProvider(name, track);
3856            mAudioMixer->enable(name);
3857
3858            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3859            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3860            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
3861            mAudioMixer->setParameter(
3862                name,
3863                AudioMixer::TRACK,
3864                AudioMixer::FORMAT, (void *)track->format());
3865            mAudioMixer->setParameter(
3866                name,
3867                AudioMixer::TRACK,
3868                AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
3869            mAudioMixer->setParameter(
3870                name,
3871                AudioMixer::TRACK,
3872                AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
3873            // limit track sample rate to 2 x output sample rate, which changes at re-configuration
3874            uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
3875            uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
3876            if (reqSampleRate == 0) {
3877                reqSampleRate = mSampleRate;
3878            } else if (reqSampleRate > maxSampleRate) {
3879                reqSampleRate = maxSampleRate;
3880            }
3881            mAudioMixer->setParameter(
3882                name,
3883                AudioMixer::RESAMPLE,
3884                AudioMixer::SAMPLE_RATE,
3885                (void *)(uintptr_t)reqSampleRate);
3886
3887            AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
3888            mAudioMixer->setParameter(
3889                name,
3890                AudioMixer::TIMESTRETCH,
3891                AudioMixer::PLAYBACK_RATE,
3892                &playbackRate);
3893
3894            /*
3895             * Select the appropriate output buffer for the track.
3896             *
3897             * Tracks with effects go into their own effects chain buffer
3898             * and from there into either mEffectBuffer or mSinkBuffer.
3899             *
3900             * Other tracks can use mMixerBuffer for higher precision
3901             * channel accumulation.  If this buffer is enabled
3902             * (mMixerBufferEnabled true), then selected tracks will accumulate
3903             * into it.
3904             *
3905             */
3906            if (mMixerBufferEnabled
3907                    && (track->mainBuffer() == mSinkBuffer
3908                            || track->mainBuffer() == mMixerBuffer)) {
3909                mAudioMixer->setParameter(
3910                        name,
3911                        AudioMixer::TRACK,
3912                        AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
3913                mAudioMixer->setParameter(
3914                        name,
3915                        AudioMixer::TRACK,
3916                        AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3917                // TODO: override track->mainBuffer()?
3918                mMixerBufferValid = true;
3919            } else {
3920                mAudioMixer->setParameter(
3921                        name,
3922                        AudioMixer::TRACK,
3923                        AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
3924                mAudioMixer->setParameter(
3925                        name,
3926                        AudioMixer::TRACK,
3927                        AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3928            }
3929            mAudioMixer->setParameter(
3930                name,
3931                AudioMixer::TRACK,
3932                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3933
3934            // reset retry count
3935            track->mRetryCount = kMaxTrackRetries;
3936
3937            // If one track is ready, set the mixer ready if:
3938            //  - the mixer was not ready during previous round OR
3939            //  - no other track is not ready
3940            if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3941                    mixerStatus != MIXER_TRACKS_ENABLED) {
3942                mixerStatus = MIXER_TRACKS_READY;
3943            }
3944        } else {
3945            if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
3946                track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
3947            }
3948            // clear effect chain input buffer if an active track underruns to avoid sending
3949            // previous audio buffer again to effects
3950            chain = getEffectChain_l(track->sessionId());
3951            if (chain != 0) {
3952                chain->clearInputBuffer();
3953            }
3954
3955            ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
3956            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3957                    track->isStopped() || track->isPaused()) {
3958                // We have consumed all the buffers of this track.
3959                // Remove it from the list of active tracks.
3960                // TODO: use actual buffer filling status instead of latency when available from
3961                // audio HAL
3962                size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3963                size_t framesWritten = mBytesWritten / mFrameSize;
3964                if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3965                    if (track->isStopped()) {
3966                        track->reset();
3967                    }
3968                    tracksToRemove->add(track);
3969                }
3970            } else {
3971                // No buffers for this track. Give it a few chances to
3972                // fill a buffer, then remove it from active list.
3973                if (--(track->mRetryCount) <= 0) {
3974                    ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
3975                    tracksToRemove->add(track);
3976                    // indicate to client process that the track was disabled because of underrun;
3977                    // it will then automatically call start() when data is available
3978                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
3979                // If one track is not ready, mark the mixer also not ready if:
3980                //  - the mixer was ready during previous round OR
3981                //  - no other track is ready
3982                } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3983                                mixerStatus != MIXER_TRACKS_READY) {
3984                    mixerStatus = MIXER_TRACKS_ENABLED;
3985                }
3986            }
3987            mAudioMixer->disable(name);
3988        }
3989
3990        }   // local variable scope to avoid goto warning
3991track_is_ready: ;
3992
3993    }
3994
3995    // Push the new FastMixer state if necessary
3996    bool pauseAudioWatchdog = false;
3997    if (didModify) {
3998        state->mFastTracksGen++;
3999        // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4000        if (kUseFastMixer == FastMixer_Dynamic &&
4001                state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4002            state->mCommand = FastMixerState::COLD_IDLE;
4003            state->mColdFutexAddr = &mFastMixerFutex;
4004            state->mColdGen++;
4005            mFastMixerFutex = 0;
4006            if (kUseFastMixer == FastMixer_Dynamic) {
4007                mNormalSink = mOutputSink;
4008            }
4009            // If we go into cold idle, need to wait for acknowledgement
4010            // so that fast mixer stops doing I/O.
4011            block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4012            pauseAudioWatchdog = true;
4013        }
4014    }
4015    if (sq != NULL) {
4016        sq->end(didModify);
4017        sq->push(block);
4018    }
4019#ifdef AUDIO_WATCHDOG
4020    if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4021        mAudioWatchdog->pause();
4022    }
4023#endif
4024
4025    // Now perform the deferred reset on fast tracks that have stopped
4026    while (resetMask != 0) {
4027        size_t i = __builtin_ctz(resetMask);
4028        ALOG_ASSERT(i < count);
4029        resetMask &= ~(1 << i);
4030        sp<Track> t = mActiveTracks[i].promote();
4031        if (t == 0) {
4032            continue;
4033        }
4034        Track* track = t.get();
4035        ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4036        track->reset();
4037    }
4038
4039    // remove all the tracks that need to be...
4040    removeTracks_l(*tracksToRemove);
4041
4042    if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4043        mEffectBufferValid = true;
4044    }
4045
4046    if (mEffectBufferValid) {
4047        // as long as there are effects we should clear the effects buffer, to avoid
4048        // passing a non-clean buffer to the effect chain
4049        memset(mEffectBuffer, 0, mEffectBufferSize);
4050    }
4051    // sink or mix buffer must be cleared if all tracks are connected to an
4052    // effect chain as in this case the mixer will not write to the sink or mix buffer
4053    // and track effects will accumulate into it
4054    if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4055            (mixedTracks == 0 && fastTracks > 0))) {
4056        // FIXME as a performance optimization, should remember previous zero status
4057        if (mMixerBufferValid) {
4058            memset(mMixerBuffer, 0, mMixerBufferSize);
4059            // TODO: In testing, mSinkBuffer below need not be cleared because
4060            // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4061            // after mixing.
4062            //
4063            // To enforce this guarantee:
4064            // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4065            // (mixedTracks == 0 && fastTracks > 0))
4066            // must imply MIXER_TRACKS_READY.
4067            // Later, we may clear buffers regardless, and skip much of this logic.
4068        }
4069        // FIXME as a performance optimization, should remember previous zero status
4070        memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
4071    }
4072
4073    // if any fast tracks, then status is ready
4074    mMixerStatusIgnoringFastTracks = mixerStatus;
4075    if (fastTracks > 0) {
4076        mixerStatus = MIXER_TRACKS_READY;
4077    }
4078    return mixerStatus;
4079}
4080
4081// getTrackName_l() must be called with ThreadBase::mLock held
4082int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4083        audio_format_t format, int sessionId)
4084{
4085    return mAudioMixer->getTrackName(channelMask, format, sessionId);
4086}
4087
4088// deleteTrackName_l() must be called with ThreadBase::mLock held
4089void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4090{
4091    ALOGV("remove track (%d) and delete from mixer", name);
4092    mAudioMixer->deleteTrackName(name);
4093}
4094
4095// checkForNewParameter_l() must be called with ThreadBase::mLock held
4096bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4097                                                       status_t& status)
4098{
4099    bool reconfig = false;
4100
4101    status = NO_ERROR;
4102
4103    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4104    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
4105    if (mFastMixer != 0) {
4106        FastMixerStateQueue *sq = mFastMixer->sq();
4107        FastMixerState *state = sq->begin();
4108        if (!(state->mCommand & FastMixerState::IDLE)) {
4109            previousCommand = state->mCommand;
4110            state->mCommand = FastMixerState::HOT_IDLE;
4111            sq->end();
4112            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4113        } else {
4114            sq->end(false /*didModify*/);
4115        }
4116    }
4117
4118    AudioParameter param = AudioParameter(keyValuePair);
4119    int value;
4120    if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4121        reconfig = true;
4122    }
4123    if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4124        if (!isValidPcmSinkFormat((audio_format_t) value)) {
4125            status = BAD_VALUE;
4126        } else {
4127            // no need to save value, since it's constant
4128            reconfig = true;
4129        }
4130    }
4131    if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4132        if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
4133            status = BAD_VALUE;
4134        } else {
4135            // no need to save value, since it's constant
4136            reconfig = true;
4137        }
4138    }
4139    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4140        // do not accept frame count changes if tracks are open as the track buffer
4141        // size depends on frame count and correct behavior would not be guaranteed
4142        // if frame count is changed after track creation
4143        if (!mTracks.isEmpty()) {
4144            status = INVALID_OPERATION;
4145        } else {
4146            reconfig = true;
4147        }
4148    }
4149    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4150#ifdef ADD_BATTERY_DATA
4151        // when changing the audio output device, call addBatteryData to notify
4152        // the change
4153        if (mOutDevice != value) {
4154            uint32_t params = 0;
4155            // check whether speaker is on
4156            if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4157                params |= IMediaPlayerService::kBatteryDataSpeakerOn;
4158            }
4159
4160            audio_devices_t deviceWithoutSpeaker
4161                = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4162            // check if any other device (except speaker) is on
4163            if (value & deviceWithoutSpeaker) {
4164                params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4165            }
4166
4167            if (params != 0) {
4168                addBatteryData(params);
4169            }
4170        }
4171#endif
4172
4173        // forward device change to effects that have requested to be
4174        // aware of attached audio device.
4175        if (value != AUDIO_DEVICE_NONE) {
4176            mOutDevice = value;
4177            for (size_t i = 0; i < mEffectChains.size(); i++) {
4178                mEffectChains[i]->setDevice_l(mOutDevice);
4179            }
4180        }
4181    }
4182
4183    if (status == NO_ERROR) {
4184        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4185                                                keyValuePair.string());
4186        if (!mStandby && status == INVALID_OPERATION) {
4187            mOutput->standby();
4188            mStandby = true;
4189            mBytesWritten = 0;
4190            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4191                                                   keyValuePair.string());
4192        }
4193        if (status == NO_ERROR && reconfig) {
4194            readOutputParameters_l();
4195            delete mAudioMixer;
4196            mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4197            for (size_t i = 0; i < mTracks.size() ; i++) {
4198                int name = getTrackName_l(mTracks[i]->mChannelMask,
4199                        mTracks[i]->mFormat, mTracks[i]->mSessionId);
4200                if (name < 0) {
4201                    break;
4202                }
4203                mTracks[i]->mName = name;
4204            }
4205            sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4206        }
4207    }
4208
4209    if (!(previousCommand & FastMixerState::IDLE)) {
4210        ALOG_ASSERT(mFastMixer != 0);
4211        FastMixerStateQueue *sq = mFastMixer->sq();
4212        FastMixerState *state = sq->begin();
4213        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4214        state->mCommand = previousCommand;
4215        sq->end();
4216        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4217    }
4218
4219    return reconfig;
4220}
4221
4222
4223void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4224{
4225    const size_t SIZE = 256;
4226    char buffer[SIZE];
4227    String8 result;
4228
4229    PlaybackThread::dumpInternals(fd, args);
4230
4231    dprintf(fd, "  AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
4232
4233    // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4234    const FastMixerDumpState copy(mFastMixerDumpState);
4235    copy.dump(fd);
4236
4237#ifdef STATE_QUEUE_DUMP
4238    // Similar for state queue
4239    StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4240    observerCopy.dump(fd);
4241    StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4242    mutatorCopy.dump(fd);
4243#endif
4244
4245#ifdef TEE_SINK
4246    // Write the tee output to a .wav file
4247    dumpTee(fd, mTeeSource, mId);
4248#endif
4249
4250#ifdef AUDIO_WATCHDOG
4251    if (mAudioWatchdog != 0) {
4252        // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4253        AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4254        wdCopy.dump(fd);
4255    }
4256#endif
4257}
4258
4259uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4260{
4261    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4262}
4263
4264uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4265{
4266    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4267}
4268
4269void AudioFlinger::MixerThread::cacheParameters_l()
4270{
4271    PlaybackThread::cacheParameters_l();
4272
4273    // FIXME: Relaxed timing because of a certain device that can't meet latency
4274    // Should be reduced to 2x after the vendor fixes the driver issue
4275    // increase threshold again due to low power audio mode. The way this warning
4276    // threshold is calculated and its usefulness should be reconsidered anyway.
4277    maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4278}
4279
4280// ----------------------------------------------------------------------------
4281
4282AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4283        AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4284    :   PlaybackThread(audioFlinger, output, id, device, DIRECT)
4285        // mLeftVolFloat, mRightVolFloat
4286{
4287}
4288
4289AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4290        AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4291        ThreadBase::type_t type)
4292    :   PlaybackThread(audioFlinger, output, id, device, type)
4293        // mLeftVolFloat, mRightVolFloat
4294{
4295}
4296
4297AudioFlinger::DirectOutputThread::~DirectOutputThread()
4298{
4299}
4300
4301void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4302{
4303    audio_track_cblk_t* cblk = track->cblk();
4304    float left, right;
4305
4306    if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4307        left = right = 0;
4308    } else {
4309        float typeVolume = mStreamTypes[track->streamType()].volume;
4310        float v = mMasterVolume * typeVolume;
4311        AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
4312        gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4313        left = float_from_gain(gain_minifloat_unpack_left(vlr));
4314        if (left > GAIN_FLOAT_UNITY) {
4315            left = GAIN_FLOAT_UNITY;
4316        }
4317        left *= v;
4318        right = float_from_gain(gain_minifloat_unpack_right(vlr));
4319        if (right > GAIN_FLOAT_UNITY) {
4320            right = GAIN_FLOAT_UNITY;
4321        }
4322        right *= v;
4323    }
4324
4325    if (lastTrack) {
4326        if (left != mLeftVolFloat || right != mRightVolFloat) {
4327            mLeftVolFloat = left;
4328            mRightVolFloat = right;
4329
4330            // Convert volumes from float to 8.24
4331            uint32_t vl = (uint32_t)(left * (1 << 24));
4332            uint32_t vr = (uint32_t)(right * (1 << 24));
4333
4334            // Delegate volume control to effect in track effect chain if needed
4335            // only one effect chain can be present on DirectOutputThread, so if
4336            // there is one, the track is connected to it
4337            if (!mEffectChains.isEmpty()) {
4338                mEffectChains[0]->setVolume_l(&vl, &vr);
4339                left = (float)vl / (1 << 24);
4340                right = (float)vr / (1 << 24);
4341            }
4342            if (mOutput->stream->set_volume) {
4343                mOutput->stream->set_volume(mOutput->stream, left, right);
4344            }
4345        }
4346    }
4347}
4348
4349
4350AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4351    Vector< sp<Track> > *tracksToRemove
4352)
4353{
4354    size_t count = mActiveTracks.size();
4355    mixer_state mixerStatus = MIXER_IDLE;
4356    bool doHwPause = false;
4357    bool doHwResume = false;
4358    bool flushPending = false;
4359
4360    // find out which tracks need to be processed
4361    for (size_t i = 0; i < count; i++) {
4362        sp<Track> t = mActiveTracks[i].promote();
4363        // The track died recently
4364        if (t == 0) {
4365            continue;
4366        }
4367
4368        Track* const track = t.get();
4369        audio_track_cblk_t* cblk = track->cblk();
4370        // Only consider last track started for volume and mixer state control.
4371        // In theory an older track could underrun and restart after the new one starts
4372        // but as we only care about the transition phase between two tracks on a
4373        // direct output, it is not a problem to ignore the underrun case.
4374        sp<Track> l = mLatestActiveTrack.promote();
4375        bool last = l.get() == track;
4376
4377        if (track->isPausing()) {
4378            track->setPaused();
4379            if (mHwSupportsPause && last && !mHwPaused) {
4380                doHwPause = true;
4381                mHwPaused = true;
4382            }
4383            tracksToRemove->add(track);
4384        } else if (track->isFlushPending()) {
4385            track->flushAck();
4386            if (last) {
4387                flushPending = true;
4388            }
4389        } else if (track->isResumePending()) {
4390            track->resumeAck();
4391            if (last && mHwPaused) {
4392                doHwResume = true;
4393                mHwPaused = false;
4394            }
4395        }
4396
4397        // The first time a track is added we wait
4398        // for all its buffers to be filled before processing it.
4399        // Allow draining the buffer in case the client
4400        // app does not call stop() and relies on underrun to stop:
4401        // hence the test on (track->mRetryCount > 1).
4402        // If retryCount<=1 then track is about to underrun and be removed.
4403        uint32_t minFrames;
4404        if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4405            && (track->mRetryCount > 1)) {
4406            minFrames = mNormalFrameCount;
4407        } else {
4408            minFrames = 1;
4409        }
4410
4411        if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4412                !track->isStopping_2() && !track->isStopped())
4413        {
4414            ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
4415
4416            if (track->mFillingUpStatus == Track::FS_FILLED) {
4417                track->mFillingUpStatus = Track::FS_ACTIVE;
4418                // make sure processVolume_l() will apply new volume even if 0
4419                mLeftVolFloat = mRightVolFloat = -1.0;
4420                if (!mHwSupportsPause) {
4421                    track->resumeAck();
4422                }
4423            }
4424
4425            // compute volume for this track
4426            processVolume_l(track, last);
4427            if (last) {
4428                // reset retry count
4429                track->mRetryCount = kMaxTrackRetriesDirect;
4430                mActiveTrack = t;
4431                mixerStatus = MIXER_TRACKS_READY;
4432                if (usesHwAvSync() && mHwPaused) {
4433                    doHwResume = true;
4434                    mHwPaused = false;
4435                }
4436            }
4437        } else {
4438            // clear effect chain input buffer if the last active track started underruns
4439            // to avoid sending previous audio buffer again to effects
4440            if (!mEffectChains.isEmpty() && last) {
4441                mEffectChains[0]->clearInputBuffer();
4442            }
4443            if (track->isStopping_1()) {
4444                track->mState = TrackBase::STOPPING_2;
4445                if (last && mHwPaused) {
4446                     doHwResume = true;
4447                     mHwPaused = false;
4448                 }
4449            }
4450            if ((track->sharedBuffer() != 0) || track->isStopped() ||
4451                    track->isStopping_2() || track->isPaused()) {
4452                // We have consumed all the buffers of this track.
4453                // Remove it from the list of active tracks.
4454                size_t audioHALFrames;
4455                if (audio_is_linear_pcm(mFormat)) {
4456                    audioHALFrames = (latency_l() * mSampleRate) / 1000;
4457                } else {
4458                    audioHALFrames = 0;
4459                }
4460
4461                size_t framesWritten = mBytesWritten / mFrameSize;
4462                if (mStandby || !last ||
4463                        track->presentationComplete(framesWritten, audioHALFrames)) {
4464                    if (track->isStopping_2()) {
4465                        track->mState = TrackBase::STOPPED;
4466                    }
4467                    if (track->isStopped()) {
4468                        track->reset();
4469                    }
4470                    tracksToRemove->add(track);
4471                }
4472            } else {
4473                // No buffers for this track. Give it a few chances to
4474                // fill a buffer, then remove it from active list.
4475                // Only consider last track started for mixer state control
4476                if (--(track->mRetryCount) <= 0) {
4477                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
4478                    tracksToRemove->add(track);
4479                    // indicate to client process that the track was disabled because of underrun;
4480                    // it will then automatically call start() when data is available
4481                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
4482                } else if (last) {
4483                    mixerStatus = MIXER_TRACKS_ENABLED;
4484                    if (usesHwAvSync() && !mHwPaused && !mStandby) {
4485                        doHwPause = true;
4486                        mHwPaused = true;
4487                    }
4488                }
4489            }
4490        }
4491    }
4492
4493    // if an active track did not command a flush, check for pending flush on stopped tracks
4494    if (!flushPending) {
4495        for (size_t i = 0; i < mTracks.size(); i++) {
4496            if (mTracks[i]->isFlushPending()) {
4497                mTracks[i]->flushAck();
4498                flushPending = true;
4499            }
4500        }
4501    }
4502
4503    // make sure the pause/flush/resume sequence is executed in the right order.
4504    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4505    // before flush and then resume HW. This can happen in case of pause/flush/resume
4506    // if resume is received before pause is executed.
4507    if (mHwSupportsPause && !mStandby &&
4508            (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4509        mOutput->stream->pause(mOutput->stream);
4510    }
4511    if (flushPending) {
4512        flushHw_l();
4513    }
4514    if (mHwSupportsPause && !mStandby && doHwResume) {
4515        mOutput->stream->resume(mOutput->stream);
4516    }
4517    // remove all the tracks that need to be...
4518    removeTracks_l(*tracksToRemove);
4519
4520    return mixerStatus;
4521}
4522
4523void AudioFlinger::DirectOutputThread::threadLoop_mix()
4524{
4525    size_t frameCount = mFrameCount;
4526    int8_t *curBuf = (int8_t *)mSinkBuffer;
4527    // output audio to hardware
4528    while (frameCount) {
4529        AudioBufferProvider::Buffer buffer;
4530        buffer.frameCount = frameCount;
4531        status_t status = mActiveTrack->getNextBuffer(&buffer);
4532        if (status != NO_ERROR || buffer.raw == NULL) {
4533            memset(curBuf, 0, frameCount * mFrameSize);
4534            break;
4535        }
4536        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4537        frameCount -= buffer.frameCount;
4538        curBuf += buffer.frameCount * mFrameSize;
4539        mActiveTrack->releaseBuffer(&buffer);
4540    }
4541    mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
4542    sleepTime = 0;
4543    standbyTime = systemTime() + standbyDelay;
4544    mActiveTrack.clear();
4545}
4546
4547void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4548{
4549    // do not write to HAL when paused
4550    if (mHwPaused || (usesHwAvSync() && mStandby)) {
4551        sleepTime = idleSleepTime;
4552        return;
4553    }
4554    if (sleepTime == 0) {
4555        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4556            sleepTime = activeSleepTime;
4557        } else {
4558            sleepTime = idleSleepTime;
4559        }
4560    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
4561        memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
4562        sleepTime = 0;
4563    }
4564}
4565
4566void AudioFlinger::DirectOutputThread::threadLoop_exit()
4567{
4568    {
4569        Mutex::Autolock _l(mLock);
4570        bool flushPending = false;
4571        for (size_t i = 0; i < mTracks.size(); i++) {
4572            if (mTracks[i]->isFlushPending()) {
4573                mTracks[i]->flushAck();
4574                flushPending = true;
4575            }
4576        }
4577        if (flushPending) {
4578            flushHw_l();
4579        }
4580    }
4581    PlaybackThread::threadLoop_exit();
4582}
4583
4584// must be called with thread mutex locked
4585bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4586{
4587    bool trackPaused = false;
4588    bool trackStopped = false;
4589
4590    // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4591    // after a timeout and we will enter standby then.
4592    if (mTracks.size() > 0) {
4593        trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4594        trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4595                           mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
4596    }
4597
4598    return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
4599}
4600
4601// getTrackName_l() must be called with ThreadBase::mLock held
4602int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
4603        audio_format_t format __unused, int sessionId __unused)
4604{
4605    return 0;
4606}
4607
4608// deleteTrackName_l() must be called with ThreadBase::mLock held
4609void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
4610{
4611}
4612
4613// checkForNewParameter_l() must be called with ThreadBase::mLock held
4614bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4615                                                              status_t& status)
4616{
4617    bool reconfig = false;
4618
4619    status = NO_ERROR;
4620
4621    AudioParameter param = AudioParameter(keyValuePair);
4622    int value;
4623    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4624        // forward device change to effects that have requested to be
4625        // aware of attached audio device.
4626        if (value != AUDIO_DEVICE_NONE) {
4627            mOutDevice = value;
4628            for (size_t i = 0; i < mEffectChains.size(); i++) {
4629                mEffectChains[i]->setDevice_l(mOutDevice);
4630            }
4631        }
4632    }
4633    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4634        // do not accept frame count changes if tracks are open as the track buffer
4635        // size depends on frame count and correct behavior would not be garantied
4636        // if frame count is changed after track creation
4637        if (!mTracks.isEmpty()) {
4638            status = INVALID_OPERATION;
4639        } else {
4640            reconfig = true;
4641        }
4642    }
4643    if (status == NO_ERROR) {
4644        status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4645                                                keyValuePair.string());
4646        if (!mStandby && status == INVALID_OPERATION) {
4647            mOutput->standby();
4648            mStandby = true;
4649            mBytesWritten = 0;
4650            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4651                                                   keyValuePair.string());
4652        }
4653        if (status == NO_ERROR && reconfig) {
4654            readOutputParameters_l();
4655            sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4656        }
4657    }
4658
4659    return reconfig;
4660}
4661
4662uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4663{
4664    uint32_t time;
4665    if (audio_is_linear_pcm(mFormat)) {
4666        time = PlaybackThread::activeSleepTimeUs();
4667    } else {
4668        time = 10000;
4669    }
4670    return time;
4671}
4672
4673uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4674{
4675    uint32_t time;
4676    if (audio_is_linear_pcm(mFormat)) {
4677        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4678    } else {
4679        time = 10000;
4680    }
4681    return time;
4682}
4683
4684uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4685{
4686    uint32_t time;
4687    if (audio_is_linear_pcm(mFormat)) {
4688        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4689    } else {
4690        time = 10000;
4691    }
4692    return time;
4693}
4694
4695void AudioFlinger::DirectOutputThread::cacheParameters_l()
4696{
4697    PlaybackThread::cacheParameters_l();
4698
4699    // use shorter standby delay as on normal output to release
4700    // hardware resources as soon as possible
4701    // no delay on outputs with HW A/V sync
4702    if (usesHwAvSync()) {
4703        standbyDelay = 0;
4704    } else if (audio_is_linear_pcm(mFormat)) {
4705        standbyDelay = microseconds(activeSleepTime*2);
4706    } else {
4707        standbyDelay = kOffloadStandbyDelayNs;
4708    }
4709}
4710
4711void AudioFlinger::DirectOutputThread::flushHw_l()
4712{
4713    mOutput->flush();
4714    mHwPaused = false;
4715}
4716
4717// ----------------------------------------------------------------------------
4718
4719AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
4720        const wp<AudioFlinger::PlaybackThread>& playbackThread)
4721    :   Thread(false /*canCallJava*/),
4722        mPlaybackThread(playbackThread),
4723        mWriteAckSequence(0),
4724        mDrainSequence(0)
4725{
4726}
4727
4728AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4729{
4730}
4731
4732void AudioFlinger::AsyncCallbackThread::onFirstRef()
4733{
4734    run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4735}
4736
4737bool AudioFlinger::AsyncCallbackThread::threadLoop()
4738{
4739    while (!exitPending()) {
4740        uint32_t writeAckSequence;
4741        uint32_t drainSequence;
4742
4743        {
4744            Mutex::Autolock _l(mLock);
4745            while (!((mWriteAckSequence & 1) ||
4746                     (mDrainSequence & 1) ||
4747                     exitPending())) {
4748                mWaitWorkCV.wait(mLock);
4749            }
4750
4751            if (exitPending()) {
4752                break;
4753            }
4754            ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4755                  mWriteAckSequence, mDrainSequence);
4756            writeAckSequence = mWriteAckSequence;
4757            mWriteAckSequence &= ~1;
4758            drainSequence = mDrainSequence;
4759            mDrainSequence &= ~1;
4760        }
4761        {
4762            sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4763            if (playbackThread != 0) {
4764                if (writeAckSequence & 1) {
4765                    playbackThread->resetWriteBlocked(writeAckSequence >> 1);
4766                }
4767                if (drainSequence & 1) {
4768                    playbackThread->resetDraining(drainSequence >> 1);
4769                }
4770            }
4771        }
4772    }
4773    return false;
4774}
4775
4776void AudioFlinger::AsyncCallbackThread::exit()
4777{
4778    ALOGV("AsyncCallbackThread::exit");
4779    Mutex::Autolock _l(mLock);
4780    requestExit();
4781    mWaitWorkCV.broadcast();
4782}
4783
4784void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
4785{
4786    Mutex::Autolock _l(mLock);
4787    // bit 0 is cleared
4788    mWriteAckSequence = sequence << 1;
4789}
4790
4791void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4792{
4793    Mutex::Autolock _l(mLock);
4794    // ignore unexpected callbacks
4795    if (mWriteAckSequence & 2) {
4796        mWriteAckSequence |= 1;
4797        mWaitWorkCV.signal();
4798    }
4799}
4800
4801void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
4802{
4803    Mutex::Autolock _l(mLock);
4804    // bit 0 is cleared
4805    mDrainSequence = sequence << 1;
4806}
4807
4808void AudioFlinger::AsyncCallbackThread::resetDraining()
4809{
4810    Mutex::Autolock _l(mLock);
4811    // ignore unexpected callbacks
4812    if (mDrainSequence & 2) {
4813        mDrainSequence |= 1;
4814        mWaitWorkCV.signal();
4815    }
4816}
4817
4818
4819// ----------------------------------------------------------------------------
4820AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4821        AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4822    :   DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
4823        mPausedBytesRemaining(0)
4824{
4825    //FIXME: mStandby should be set to true by ThreadBase constructor
4826    mStandby = true;
4827}
4828
4829void AudioFlinger::OffloadThread::threadLoop_exit()
4830{
4831    if (mFlushPending || mHwPaused) {
4832        // If a flush is pending or track was paused, just discard buffered data
4833        flushHw_l();
4834    } else {
4835        mMixerStatus = MIXER_DRAIN_ALL;
4836        threadLoop_drain();
4837    }
4838    if (mUseAsyncWrite) {
4839        ALOG_ASSERT(mCallbackThread != 0);
4840        mCallbackThread->exit();
4841    }
4842    PlaybackThread::threadLoop_exit();
4843}
4844
4845AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4846    Vector< sp<Track> > *tracksToRemove
4847)
4848{
4849    size_t count = mActiveTracks.size();
4850
4851    mixer_state mixerStatus = MIXER_IDLE;
4852    bool doHwPause = false;
4853    bool doHwResume = false;
4854
4855    ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4856
4857    // find out which tracks need to be processed
4858    for (size_t i = 0; i < count; i++) {
4859        sp<Track> t = mActiveTracks[i].promote();
4860        // The track died recently
4861        if (t == 0) {
4862            continue;
4863        }
4864        Track* const track = t.get();
4865        audio_track_cblk_t* cblk = track->cblk();
4866        // Only consider last track started for volume and mixer state control.
4867        // In theory an older track could underrun and restart after the new one starts
4868        // but as we only care about the transition phase between two tracks on a
4869        // direct output, it is not a problem to ignore the underrun case.
4870        sp<Track> l = mLatestActiveTrack.promote();
4871        bool last = l.get() == track;
4872
4873        if (track->isInvalid()) {
4874            ALOGW("An invalidated track shouldn't be in active list");
4875            tracksToRemove->add(track);
4876            continue;
4877        }
4878
4879        if (track->mState == TrackBase::IDLE) {
4880            ALOGW("An idle track shouldn't be in active list");
4881            continue;
4882        }
4883
4884        if (track->isPausing()) {
4885            track->setPaused();
4886            if (last) {
4887                if (!mHwPaused) {
4888                    doHwPause = true;
4889                    mHwPaused = true;
4890                }
4891                // If we were part way through writing the mixbuffer to
4892                // the HAL we must save this until we resume
4893                // BUG - this will be wrong if a different track is made active,
4894                // in that case we want to discard the pending data in the
4895                // mixbuffer and tell the client to present it again when the
4896                // track is resumed
4897                mPausedWriteLength = mCurrentWriteLength;
4898                mPausedBytesRemaining = mBytesRemaining;
4899                mBytesRemaining = 0;    // stop writing
4900            }
4901            tracksToRemove->add(track);
4902        } else if (track->isFlushPending()) {
4903            track->flushAck();
4904            if (last) {
4905                mFlushPending = true;
4906            }
4907        } else if (track->isResumePending()){
4908            track->resumeAck();
4909            if (last) {
4910                if (mPausedBytesRemaining) {
4911                    // Need to continue write that was interrupted
4912                    mCurrentWriteLength = mPausedWriteLength;
4913                    mBytesRemaining = mPausedBytesRemaining;
4914                    mPausedBytesRemaining = 0;
4915                }
4916                if (mHwPaused) {
4917                    doHwResume = true;
4918                    mHwPaused = false;
4919                    // threadLoop_mix() will handle the case that we need to
4920                    // resume an interrupted write
4921                }
4922                // enable write to audio HAL
4923                sleepTime = 0;
4924
4925                // Do not handle new data in this iteration even if track->framesReady()
4926                mixerStatus = MIXER_TRACKS_ENABLED;
4927            }
4928        }  else if (track->framesReady() && track->isReady() &&
4929                !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
4930            ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
4931            if (track->mFillingUpStatus == Track::FS_FILLED) {
4932                track->mFillingUpStatus = Track::FS_ACTIVE;
4933                // make sure processVolume_l() will apply new volume even if 0
4934                mLeftVolFloat = mRightVolFloat = -1.0;
4935            }
4936
4937            if (last) {
4938                sp<Track> previousTrack = mPreviousTrack.promote();
4939                if (previousTrack != 0) {
4940                    if (track != previousTrack.get()) {
4941                        // Flush any data still being written from last track
4942                        mBytesRemaining = 0;
4943                        if (mPausedBytesRemaining) {
4944                            // Last track was paused so we also need to flush saved
4945                            // mixbuffer state and invalidate track so that it will
4946                            // re-submit that unwritten data when it is next resumed
4947                            mPausedBytesRemaining = 0;
4948                            // Invalidate is a bit drastic - would be more efficient
4949                            // to have a flag to tell client that some of the
4950                            // previously written data was lost
4951                            previousTrack->invalidate();
4952                        }
4953                        // flush data already sent to the DSP if changing audio session as audio
4954                        // comes from a different source. Also invalidate previous track to force a
4955                        // seek when resuming.
4956                        if (previousTrack->sessionId() != track->sessionId()) {
4957                            previousTrack->invalidate();
4958                        }
4959                    }
4960                }
4961                mPreviousTrack = track;
4962                // reset retry count
4963                track->mRetryCount = kMaxTrackRetriesOffload;
4964                mActiveTrack = t;
4965                mixerStatus = MIXER_TRACKS_READY;
4966            }
4967        } else {
4968            ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
4969            if (track->isStopping_1()) {
4970                // Hardware buffer can hold a large amount of audio so we must
4971                // wait for all current track's data to drain before we say
4972                // that the track is stopped.
4973                if (mBytesRemaining == 0) {
4974                    // Only start draining when all data in mixbuffer
4975                    // has been written
4976                    ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4977                    track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
4978                    // do not drain if no data was ever sent to HAL (mStandby == true)
4979                    if (last && !mStandby) {
4980                        // do not modify drain sequence if we are already draining. This happens
4981                        // when resuming from pause after drain.
4982                        if ((mDrainSequence & 1) == 0) {
4983                            sleepTime = 0;
4984                            standbyTime = systemTime() + standbyDelay;
4985                            mixerStatus = MIXER_DRAIN_TRACK;
4986                            mDrainSequence += 2;
4987                        }
4988                        if (mHwPaused) {
4989                            // It is possible to move from PAUSED to STOPPING_1 without
4990                            // a resume so we must ensure hardware is running
4991                            doHwResume = true;
4992                            mHwPaused = false;
4993                        }
4994                    }
4995                }
4996            } else if (track->isStopping_2()) {
4997                // Drain has completed or we are in standby, signal presentation complete
4998                if (!(mDrainSequence & 1) || !last || mStandby) {
4999                    track->mState = TrackBase::STOPPED;
5000                    size_t audioHALFrames =
5001                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5002                    size_t framesWritten =
5003                            mBytesWritten / mOutput->getFrameSize();
5004                    track->presentationComplete(framesWritten, audioHALFrames);
5005                    track->reset();
5006                    tracksToRemove->add(track);
5007                }
5008            } else {
5009                // No buffers for this track. Give it a few chances to
5010                // fill a buffer, then remove it from active list.
5011                if (--(track->mRetryCount) <= 0) {
5012                    ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5013                          track->name());
5014                    tracksToRemove->add(track);
5015                    // indicate to client process that the track was disabled because of underrun;
5016                    // it will then automatically call start() when data is available
5017                    android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
5018                } else if (last){
5019                    mixerStatus = MIXER_TRACKS_ENABLED;
5020                }
5021            }
5022        }
5023        // compute volume for this track
5024        processVolume_l(track, last);
5025    }
5026
5027    // make sure the pause/flush/resume sequence is executed in the right order.
5028    // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5029    // before flush and then resume HW. This can happen in case of pause/flush/resume
5030    // if resume is received before pause is executed.
5031    if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
5032        mOutput->stream->pause(mOutput->stream);
5033    }
5034    if (mFlushPending) {
5035        flushHw_l();
5036        mFlushPending = false;
5037    }
5038    if (!mStandby && doHwResume) {
5039        mOutput->stream->resume(mOutput->stream);
5040    }
5041
5042    // remove all the tracks that need to be...
5043    removeTracks_l(*tracksToRemove);
5044
5045    return mixerStatus;
5046}
5047
5048// must be called with thread mutex locked
5049bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5050{
5051    ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5052          mWriteAckSequence, mDrainSequence);
5053    if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
5054        return true;
5055    }
5056    return false;
5057}
5058
5059bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5060{
5061    Mutex::Autolock _l(mLock);
5062    return waitingAsyncCallback_l();
5063}
5064
5065void AudioFlinger::OffloadThread::flushHw_l()
5066{
5067    DirectOutputThread::flushHw_l();
5068    // Flush anything still waiting in the mixbuffer
5069    mCurrentWriteLength = 0;
5070    mBytesRemaining = 0;
5071    mPausedWriteLength = 0;
5072    mPausedBytesRemaining = 0;
5073
5074    if (mUseAsyncWrite) {
5075        // discard any pending drain or write ack by incrementing sequence
5076        mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5077        mDrainSequence = (mDrainSequence + 2) & ~1;
5078        ALOG_ASSERT(mCallbackThread != 0);
5079        mCallbackThread->setWriteBlocked(mWriteAckSequence);
5080        mCallbackThread->setDraining(mDrainSequence);
5081    }
5082}
5083
5084void AudioFlinger::OffloadThread::onAddNewTrack_l()
5085{
5086    sp<Track> previousTrack = mPreviousTrack.promote();
5087    sp<Track> latestTrack = mLatestActiveTrack.promote();
5088
5089    if (previousTrack != 0 && latestTrack != 0 &&
5090        (previousTrack->sessionId() != latestTrack->sessionId())) {
5091        mFlushPending = true;
5092    }
5093    PlaybackThread::onAddNewTrack_l();
5094}
5095
5096// ----------------------------------------------------------------------------
5097
5098AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
5099        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
5100    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
5101                DUPLICATING),
5102        mWaitTimeMs(UINT_MAX)
5103{
5104    addOutputTrack(mainThread);
5105}
5106
5107AudioFlinger::DuplicatingThread::~DuplicatingThread()
5108{
5109    for (size_t i = 0; i < mOutputTracks.size(); i++) {
5110        mOutputTracks[i]->destroy();
5111    }
5112}
5113
5114void AudioFlinger::DuplicatingThread::threadLoop_mix()
5115{
5116    // mix buffers...
5117    if (outputsReady(outputTracks)) {
5118        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5119    } else {
5120        if (mMixerBufferValid) {
5121            memset(mMixerBuffer, 0, mMixerBufferSize);
5122        } else {
5123            memset(mSinkBuffer, 0, mSinkBufferSize);
5124        }
5125    }
5126    sleepTime = 0;
5127    writeFrames = mNormalFrameCount;
5128    mCurrentWriteLength = mSinkBufferSize;
5129    standbyTime = systemTime() + standbyDelay;
5130}
5131
5132void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5133{
5134    if (sleepTime == 0) {
5135        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5136            sleepTime = activeSleepTime;
5137        } else {
5138            sleepTime = idleSleepTime;
5139        }
5140    } else if (mBytesWritten != 0) {
5141        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5142            writeFrames = mNormalFrameCount;
5143            memset(mSinkBuffer, 0, mSinkBufferSize);
5144        } else {
5145            // flush remaining overflow buffers in output tracks
5146            writeFrames = 0;
5147        }
5148        sleepTime = 0;
5149    }
5150}
5151
5152ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
5153{
5154    for (size_t i = 0; i < outputTracks.size(); i++) {
5155        outputTracks[i]->write(mSinkBuffer, writeFrames);
5156    }
5157    mStandby = false;
5158    return (ssize_t)mSinkBufferSize;
5159}
5160
5161void AudioFlinger::DuplicatingThread::threadLoop_standby()
5162{
5163    // DuplicatingThread implements standby by stopping all tracks
5164    for (size_t i = 0; i < outputTracks.size(); i++) {
5165        outputTracks[i]->stop();
5166    }
5167}
5168
5169void AudioFlinger::DuplicatingThread::saveOutputTracks()
5170{
5171    outputTracks = mOutputTracks;
5172}
5173
5174void AudioFlinger::DuplicatingThread::clearOutputTracks()
5175{
5176    outputTracks.clear();
5177}
5178
5179void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5180{
5181    Mutex::Autolock _l(mLock);
5182    // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5183    // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5184    // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5185    const size_t frameCount =
5186            3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5187    // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5188    // from different OutputTracks and their associated MixerThreads (e.g. one may
5189    // nearly empty and the other may be dropping data).
5190
5191    sp<OutputTrack> outputTrack = new OutputTrack(thread,
5192                                            this,
5193                                            mSampleRate,
5194                                            mFormat,
5195                                            mChannelMask,
5196                                            frameCount,
5197                                            IPCThreadState::self()->getCallingUid());
5198    if (outputTrack->cblk() != NULL) {
5199        thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5200        mOutputTracks.add(outputTrack);
5201        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5202        updateWaitTime_l();
5203    }
5204}
5205
5206void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5207{
5208    Mutex::Autolock _l(mLock);
5209    for (size_t i = 0; i < mOutputTracks.size(); i++) {
5210        if (mOutputTracks[i]->thread() == thread) {
5211            mOutputTracks[i]->destroy();
5212            mOutputTracks.removeAt(i);
5213            updateWaitTime_l();
5214            return;
5215        }
5216    }
5217    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5218}
5219
5220// caller must hold mLock
5221void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5222{
5223    mWaitTimeMs = UINT_MAX;
5224    for (size_t i = 0; i < mOutputTracks.size(); i++) {
5225        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5226        if (strong != 0) {
5227            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5228            if (waitTimeMs < mWaitTimeMs) {
5229                mWaitTimeMs = waitTimeMs;
5230            }
5231        }
5232    }
5233}
5234
5235
5236bool AudioFlinger::DuplicatingThread::outputsReady(
5237        const SortedVector< sp<OutputTrack> > &outputTracks)
5238{
5239    for (size_t i = 0; i < outputTracks.size(); i++) {
5240        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5241        if (thread == 0) {
5242            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5243                    outputTracks[i].get());
5244            return false;
5245        }
5246        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5247        // see note at standby() declaration
5248        if (playbackThread->standby() && !playbackThread->isSuspended()) {
5249            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5250                    thread.get());
5251            return false;
5252        }
5253    }
5254    return true;
5255}
5256
5257uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5258{
5259    return (mWaitTimeMs * 1000) / 2;
5260}
5261
5262void AudioFlinger::DuplicatingThread::cacheParameters_l()
5263{
5264    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5265    updateWaitTime_l();
5266
5267    MixerThread::cacheParameters_l();
5268}
5269
5270// ----------------------------------------------------------------------------
5271//      Record
5272// ----------------------------------------------------------------------------
5273
5274AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5275                                         AudioStreamIn *input,
5276                                         audio_io_handle_t id,
5277                                         audio_devices_t outDevice,
5278                                         audio_devices_t inDevice
5279#ifdef TEE_SINK
5280                                         , const sp<NBAIO_Sink>& teeSink
5281#endif
5282                                         ) :
5283    ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
5284    mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
5285    // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
5286    mRsmpInRear(0)
5287#ifdef TEE_SINK
5288    , mTeeSink(teeSink)
5289#endif
5290    , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5291            "RecordThreadRO", MemoryHeapBase::READ_ONLY))
5292    // mFastCapture below
5293    , mFastCaptureFutex(0)
5294    // mInputSource
5295    // mPipeSink
5296    // mPipeSource
5297    , mPipeFramesP2(0)
5298    // mPipeMemory
5299    // mFastCaptureNBLogWriter
5300    , mFastTrackAvail(false)
5301{
5302    snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5303    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
5304
5305    readInputParameters_l();
5306
5307    // create an NBAIO source for the HAL input stream, and negotiate
5308    mInputSource = new AudioStreamInSource(input->stream);
5309    size_t numCounterOffers = 0;
5310    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5311    ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5312    ALOG_ASSERT(index == 0);
5313
5314    // initialize fast capture depending on configuration
5315    bool initFastCapture;
5316    switch (kUseFastCapture) {
5317    case FastCapture_Never:
5318        initFastCapture = false;
5319        break;
5320    case FastCapture_Always:
5321        initFastCapture = true;
5322        break;
5323    case FastCapture_Static:
5324        uint32_t primaryOutputSampleRate;
5325        {
5326            AutoMutex _l(audioFlinger->mHardwareLock);
5327            primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5328        }
5329        initFastCapture =
5330                // either capture sample rate is same as (a reasonable) primary output sample rate
5331                (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5332                    (mSampleRate == primaryOutputSampleRate)) ||
5333                // or primary output sample rate is unknown, and capture sample rate is reasonable
5334                ((primaryOutputSampleRate == 0) &&
5335                    ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
5336                // and the buffer size is < 12 ms
5337                (mFrameCount * 1000) / mSampleRate < 12;
5338        break;
5339    // case FastCapture_Dynamic:
5340    }
5341
5342    if (initFastCapture) {
5343        // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
5344        NBAIO_Format format = mInputSource->format();
5345        size_t pipeFramesP2 = roundup(mSampleRate / 25);    // double-buffering of 20 ms each
5346        size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5347        void *pipeBuffer;
5348        const sp<MemoryDealer> roHeap(readOnlyHeap());
5349        sp<IMemory> pipeMemory;
5350        if ((roHeap == 0) ||
5351                (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5352                (pipeBuffer = pipeMemory->pointer()) == NULL) {
5353            ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5354            goto failed;
5355        }
5356        // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5357        memset(pipeBuffer, 0, pipeSize);
5358        Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5359        const NBAIO_Format offers[1] = {format};
5360        size_t numCounterOffers = 0;
5361        ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5362        ALOG_ASSERT(index == 0);
5363        mPipeSink = pipe;
5364        PipeReader *pipeReader = new PipeReader(*pipe);
5365        numCounterOffers = 0;
5366        index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5367        ALOG_ASSERT(index == 0);
5368        mPipeSource = pipeReader;
5369        mPipeFramesP2 = pipeFramesP2;
5370        mPipeMemory = pipeMemory;
5371
5372        // create fast capture
5373        mFastCapture = new FastCapture();
5374        FastCaptureStateQueue *sq = mFastCapture->sq();
5375#ifdef STATE_QUEUE_DUMP
5376        // FIXME
5377#endif
5378        FastCaptureState *state = sq->begin();
5379        state->mCblk = NULL;
5380        state->mInputSource = mInputSource.get();
5381        state->mInputSourceGen++;
5382        state->mPipeSink = pipe;
5383        state->mPipeSinkGen++;
5384        state->mFrameCount = mFrameCount;
5385        state->mCommand = FastCaptureState::COLD_IDLE;
5386        // already done in constructor initialization list
5387        //mFastCaptureFutex = 0;
5388        state->mColdFutexAddr = &mFastCaptureFutex;
5389        state->mColdGen++;
5390        state->mDumpState = &mFastCaptureDumpState;
5391#ifdef TEE_SINK
5392        // FIXME
5393#endif
5394        mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5395        state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5396        sq->end();
5397        sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5398
5399        // start the fast capture
5400        mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5401        pid_t tid = mFastCapture->getTid();
5402        int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5403        if (err != 0) {
5404            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5405                    kPriorityFastCapture, getpid_cached, tid, err);
5406        }
5407
5408#ifdef AUDIO_WATCHDOG
5409        // FIXME
5410#endif
5411
5412        mFastTrackAvail = true;
5413    }
5414failed: ;
5415
5416    // FIXME mNormalSource
5417}
5418
5419AudioFlinger::RecordThread::~RecordThread()
5420{
5421    if (mFastCapture != 0) {
5422        FastCaptureStateQueue *sq = mFastCapture->sq();
5423        FastCaptureState *state = sq->begin();
5424        if (state->mCommand == FastCaptureState::COLD_IDLE) {
5425            int32_t old = android_atomic_inc(&mFastCaptureFutex);
5426            if (old == -1) {
5427                (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5428            }
5429        }
5430        state->mCommand = FastCaptureState::EXIT;
5431        sq->end();
5432        sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5433        mFastCapture->join();
5434        mFastCapture.clear();
5435    }
5436    mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
5437    mAudioFlinger->unregisterWriter(mNBLogWriter);
5438    free(mRsmpInBuffer);
5439}
5440
5441void AudioFlinger::RecordThread::onFirstRef()
5442{
5443    run(mThreadName, PRIORITY_URGENT_AUDIO);
5444}
5445
5446bool AudioFlinger::RecordThread::threadLoop()
5447{
5448    nsecs_t lastWarning = 0;
5449
5450    inputStandBy();
5451
5452reacquire_wakelock:
5453    sp<RecordTrack> activeTrack;
5454    int activeTracksGen;
5455    {
5456        Mutex::Autolock _l(mLock);
5457        size_t size = mActiveTracks.size();
5458        activeTracksGen = mActiveTracksGen;
5459        if (size > 0) {
5460            // FIXME an arbitrary choice
5461            activeTrack = mActiveTracks[0];
5462            acquireWakeLock_l(activeTrack->uid());
5463            if (size > 1) {
5464                SortedVector<int> tmp;
5465                for (size_t i = 0; i < size; i++) {
5466                    tmp.add(mActiveTracks[i]->uid());
5467                }
5468                updateWakeLockUids_l(tmp);
5469            }
5470        } else {
5471            acquireWakeLock_l(-1);
5472        }
5473    }
5474
5475    // used to request a deferred sleep, to be executed later while mutex is unlocked
5476    uint32_t sleepUs = 0;
5477
5478    // loop while there is work to do
5479    for (;;) {
5480        Vector< sp<EffectChain> > effectChains;
5481
5482        // sleep with mutex unlocked
5483        if (sleepUs > 0) {
5484            ATRACE_BEGIN("sleep");
5485            usleep(sleepUs);
5486            ATRACE_END();
5487            sleepUs = 0;
5488        }
5489
5490        // activeTracks accumulates a copy of a subset of mActiveTracks
5491        Vector< sp<RecordTrack> > activeTracks;
5492
5493        // reference to the (first and only) active fast track
5494        sp<RecordTrack> fastTrack;
5495
5496        // reference to a fast track which is about to be removed
5497        sp<RecordTrack> fastTrackToRemove;
5498
5499        { // scope for mLock
5500            Mutex::Autolock _l(mLock);
5501
5502            processConfigEvents_l();
5503
5504            // check exitPending here because checkForNewParameters_l() and
5505            // checkForNewParameters_l() can temporarily release mLock
5506            if (exitPending()) {
5507                break;
5508            }
5509
5510            // if no active track(s), then standby and release wakelock
5511            size_t size = mActiveTracks.size();
5512            if (size == 0) {
5513                standbyIfNotAlreadyInStandby();
5514                // exitPending() can't become true here
5515                releaseWakeLock_l();
5516                ALOGV("RecordThread: loop stopping");
5517                // go to sleep
5518                mWaitWorkCV.wait(mLock);
5519                ALOGV("RecordThread: loop starting");
5520                goto reacquire_wakelock;
5521            }
5522
5523            if (mActiveTracksGen != activeTracksGen) {
5524                activeTracksGen = mActiveTracksGen;
5525                SortedVector<int> tmp;
5526                for (size_t i = 0; i < size; i++) {
5527                    tmp.add(mActiveTracks[i]->uid());
5528                }
5529                updateWakeLockUids_l(tmp);
5530            }
5531
5532            bool doBroadcast = false;
5533            for (size_t i = 0; i < size; ) {
5534
5535                activeTrack = mActiveTracks[i];
5536                if (activeTrack->isTerminated()) {
5537                    if (activeTrack->isFastTrack()) {
5538                        ALOG_ASSERT(fastTrackToRemove == 0);
5539                        fastTrackToRemove = activeTrack;
5540                    }
5541                    removeTrack_l(activeTrack);
5542                    mActiveTracks.remove(activeTrack);
5543                    mActiveTracksGen++;
5544                    size--;
5545                    continue;
5546                }
5547
5548                TrackBase::track_state activeTrackState = activeTrack->mState;
5549                switch (activeTrackState) {
5550
5551                case TrackBase::PAUSING:
5552                    mActiveTracks.remove(activeTrack);
5553                    mActiveTracksGen++;
5554                    doBroadcast = true;
5555                    size--;
5556                    continue;
5557
5558                case TrackBase::STARTING_1:
5559                    sleepUs = 10000;
5560                    i++;
5561                    continue;
5562
5563                case TrackBase::STARTING_2:
5564                    doBroadcast = true;
5565                    mStandby = false;
5566                    activeTrack->mState = TrackBase::ACTIVE;
5567                    break;
5568
5569                case TrackBase::ACTIVE:
5570                    break;
5571
5572                case TrackBase::IDLE:
5573                    i++;
5574                    continue;
5575
5576                default:
5577                    LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
5578                }
5579
5580                activeTracks.add(activeTrack);
5581                i++;
5582
5583                if (activeTrack->isFastTrack()) {
5584                    ALOG_ASSERT(!mFastTrackAvail);
5585                    ALOG_ASSERT(fastTrack == 0);
5586                    fastTrack = activeTrack;
5587                }
5588            }
5589            if (doBroadcast) {
5590                mStartStopCond.broadcast();
5591            }
5592
5593            // sleep if there are no active tracks to process
5594            if (activeTracks.size() == 0) {
5595                if (sleepUs == 0) {
5596                    sleepUs = kRecordThreadSleepUs;
5597                }
5598                continue;
5599            }
5600            sleepUs = 0;
5601
5602            lockEffectChains_l(effectChains);
5603        }
5604
5605        // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
5606
5607        size_t size = effectChains.size();
5608        for (size_t i = 0; i < size; i++) {
5609            // thread mutex is not locked, but effect chain is locked
5610            effectChains[i]->process_l();
5611        }
5612
5613        // Push a new fast capture state if fast capture is not already running, or cblk change
5614        if (mFastCapture != 0) {
5615            FastCaptureStateQueue *sq = mFastCapture->sq();
5616            FastCaptureState *state = sq->begin();
5617            bool didModify = false;
5618            FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
5619            if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5620                    (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5621                if (state->mCommand == FastCaptureState::COLD_IDLE) {
5622                    int32_t old = android_atomic_inc(&mFastCaptureFutex);
5623                    if (old == -1) {
5624                        (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5625                    }
5626                }
5627                state->mCommand = FastCaptureState::READ_WRITE;
5628#if 0   // FIXME
5629                mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
5630                        FastThreadDumpState::kSamplingNforLowRamDevice :
5631                        FastThreadDumpState::kSamplingN);
5632#endif
5633                didModify = true;
5634            }
5635            audio_track_cblk_t *cblkOld = state->mCblk;
5636            audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5637            if (cblkNew != cblkOld) {
5638                state->mCblk = cblkNew;
5639                // block until acked if removing a fast track
5640                if (cblkOld != NULL) {
5641                    block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5642                }
5643                didModify = true;
5644            }
5645            sq->end(didModify);
5646            if (didModify) {
5647                sq->push(block);
5648#if 0
5649                if (kUseFastCapture == FastCapture_Dynamic) {
5650                    mNormalSource = mPipeSource;
5651                }
5652#endif
5653            }
5654        }
5655
5656        // now run the fast track destructor with thread mutex unlocked
5657        fastTrackToRemove.clear();
5658
5659        // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5660        // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5661        // slow, then this RecordThread will overrun by not calling HAL read often enough.
5662        // If destination is non-contiguous, first read past the nominal end of buffer, then
5663        // copy to the right place.  Permitted because mRsmpInBuffer was over-allocated.
5664
5665        int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
5666        ssize_t framesRead;
5667
5668        // If an NBAIO source is present, use it to read the normal capture's data
5669        if (mPipeSource != 0) {
5670            size_t framesToRead = mBufferSize / mFrameSize;
5671            framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
5672                    framesToRead, AudioBufferProvider::kInvalidPTS);
5673            if (framesRead == 0) {
5674                // since pipe is non-blocking, simulate blocking input
5675                sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5676            }
5677        // otherwise use the HAL / AudioStreamIn directly
5678        } else {
5679            ssize_t bytesRead = mInput->stream->read(mInput->stream,
5680                    (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
5681            if (bytesRead < 0) {
5682                framesRead = bytesRead;
5683            } else {
5684                framesRead = bytesRead / mFrameSize;
5685            }
5686        }
5687
5688        if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5689            ALOGE("read failed: framesRead=%d", framesRead);
5690            // Force input into standby so that it tries to recover at next read attempt
5691            inputStandBy();
5692            sleepUs = kRecordThreadSleepUs;
5693        }
5694        if (framesRead <= 0) {
5695            goto unlock;
5696        }
5697        ALOG_ASSERT(framesRead > 0);
5698
5699        if (mTeeSink != 0) {
5700            (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
5701        }
5702        // If destination is non-contiguous, we now correct for reading past end of buffer.
5703        {
5704            size_t part1 = mRsmpInFramesP2 - rear;
5705            if ((size_t) framesRead > part1) {
5706                memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
5707                        (framesRead - part1) * mFrameSize);
5708            }
5709        }
5710        rear = mRsmpInRear += framesRead;
5711
5712        size = activeTracks.size();
5713        // loop over each active track
5714        for (size_t i = 0; i < size; i++) {
5715            activeTrack = activeTracks[i];
5716
5717            // skip fast tracks, as those are handled directly by FastCapture
5718            if (activeTrack->isFastTrack()) {
5719                continue;
5720            }
5721
5722            // TODO: This code probably should be moved to RecordTrack.
5723            // TODO: Update the activeTrack buffer converter in case of reconfigure.
5724
5725            enum {
5726                OVERRUN_UNKNOWN,
5727                OVERRUN_TRUE,
5728                OVERRUN_FALSE
5729            } overrun = OVERRUN_UNKNOWN;
5730
5731            // loop over getNextBuffer to handle circular sink
5732            for (;;) {
5733
5734                activeTrack->mSink.frameCount = ~0;
5735                status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5736                size_t framesOut = activeTrack->mSink.frameCount;
5737                LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5738
5739                // check available frames and handle overrun conditions
5740                // if the record track isn't draining fast enough.
5741                bool hasOverrun;
5742                size_t framesIn;
5743                activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5744                if (hasOverrun) {
5745                    overrun = OVERRUN_TRUE;
5746                }
5747                if (framesOut == 0 || framesIn == 0) {
5748                    break;
5749                }
5750
5751                // Don't allow framesOut to be larger than what is possible with resampling
5752                // from framesIn.
5753                // This isn't strictly necessary but helps limit buffer resizing in
5754                // RecordBufferConverter.  TODO: remove when no longer needed.
5755                framesOut = min(framesOut,
5756                        destinationFramesPossible(
5757                                framesIn, mSampleRate, activeTrack->mSampleRate));
5758                // process frames from the RecordThread buffer provider to the RecordTrack buffer
5759                framesOut = activeTrack->mRecordBufferConverter->convert(
5760                        activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
5761
5762                if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5763                    overrun = OVERRUN_FALSE;
5764                }
5765
5766                if (activeTrack->mFramesToDrop == 0) {
5767                    if (framesOut > 0) {
5768                        activeTrack->mSink.frameCount = framesOut;
5769                        activeTrack->releaseBuffer(&activeTrack->mSink);
5770                    }
5771                } else {
5772                    // FIXME could do a partial drop of framesOut
5773                    if (activeTrack->mFramesToDrop > 0) {
5774                        activeTrack->mFramesToDrop -= framesOut;
5775                        if (activeTrack->mFramesToDrop <= 0) {
5776                            activeTrack->clearSyncStartEvent();
5777                        }
5778                    } else {
5779                        activeTrack->mFramesToDrop += framesOut;
5780                        if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5781                                activeTrack->mSyncStartEvent->isCancelled()) {
5782                            ALOGW("Synced record %s, session %d, trigger session %d",
5783                                  (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5784                                  activeTrack->sessionId(),
5785                                  (activeTrack->mSyncStartEvent != 0) ?
5786                                          activeTrack->mSyncStartEvent->triggerSession() : 0);
5787                            activeTrack->clearSyncStartEvent();
5788                        }
5789                    }
5790                }
5791
5792                if (framesOut == 0) {
5793                    break;
5794                }
5795            }
5796
5797            switch (overrun) {
5798            case OVERRUN_TRUE:
5799                // client isn't retrieving buffers fast enough
5800                if (!activeTrack->setOverflow()) {
5801                    nsecs_t now = systemTime();
5802                    // FIXME should lastWarning per track?
5803                    if ((now - lastWarning) > kWarningThrottleNs) {
5804                        ALOGW("RecordThread: buffer overflow");
5805                        lastWarning = now;
5806                    }
5807                }
5808                break;
5809            case OVERRUN_FALSE:
5810                activeTrack->clearOverflow();
5811                break;
5812            case OVERRUN_UNKNOWN:
5813                break;
5814            }
5815
5816        }
5817
5818unlock:
5819        // enable changes in effect chain
5820        unlockEffectChains(effectChains);
5821        // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
5822    }
5823
5824    standbyIfNotAlreadyInStandby();
5825
5826    {
5827        Mutex::Autolock _l(mLock);
5828        for (size_t i = 0; i < mTracks.size(); i++) {
5829            sp<RecordTrack> track = mTracks[i];
5830            track->invalidate();
5831        }
5832        mActiveTracks.clear();
5833        mActiveTracksGen++;
5834        mStartStopCond.broadcast();
5835    }
5836
5837    releaseWakeLock();
5838
5839    ALOGV("RecordThread %p exiting", this);
5840    return false;
5841}
5842
5843void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
5844{
5845    if (!mStandby) {
5846        inputStandBy();
5847        mStandby = true;
5848    }
5849}
5850
5851void AudioFlinger::RecordThread::inputStandBy()
5852{
5853    // Idle the fast capture if it's currently running
5854    if (mFastCapture != 0) {
5855        FastCaptureStateQueue *sq = mFastCapture->sq();
5856        FastCaptureState *state = sq->begin();
5857        if (!(state->mCommand & FastCaptureState::IDLE)) {
5858            state->mCommand = FastCaptureState::COLD_IDLE;
5859            state->mColdFutexAddr = &mFastCaptureFutex;
5860            state->mColdGen++;
5861            mFastCaptureFutex = 0;
5862            sq->end();
5863            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5864            sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5865#if 0
5866            if (kUseFastCapture == FastCapture_Dynamic) {
5867                // FIXME
5868            }
5869#endif
5870#ifdef AUDIO_WATCHDOG
5871            // FIXME
5872#endif
5873        } else {
5874            sq->end(false /*didModify*/);
5875        }
5876    }
5877    mInput->stream->common.standby(&mInput->stream->common);
5878}
5879
5880// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
5881sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5882        const sp<AudioFlinger::Client>& client,
5883        uint32_t sampleRate,
5884        audio_format_t format,
5885        audio_channel_mask_t channelMask,
5886        size_t *pFrameCount,
5887        int sessionId,
5888        size_t *notificationFrames,
5889        int uid,
5890        IAudioFlinger::track_flags_t *flags,
5891        pid_t tid,
5892        status_t *status)
5893{
5894    size_t frameCount = *pFrameCount;
5895    sp<RecordTrack> track;
5896    status_t lStatus;
5897
5898    // client expresses a preference for FAST, but we get the final say
5899    if (*flags & IAudioFlinger::TRACK_FAST) {
5900      if (
5901            // we formerly checked for a callback handler (non-0 tid),
5902            // but that is no longer required for TRANSFER_OBTAIN mode
5903            //
5904            // frame count is not specified, or is exactly the pipe depth
5905            ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
5906            // PCM data
5907            audio_is_linear_pcm(format) &&
5908            // native format
5909            (format == mFormat) &&
5910            // native channel mask
5911            (channelMask == mChannelMask) &&
5912            // native hardware sample rate
5913            (sampleRate == mSampleRate) &&
5914            // record thread has an associated fast capture
5915            hasFastCapture() &&
5916            // there are sufficient fast track slots available
5917            mFastTrackAvail
5918        ) {
5919        ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
5920                frameCount, mFrameCount);
5921      } else {
5922        ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5923                "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
5924                "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
5925                frameCount, mFrameCount, mPipeFramesP2,
5926                format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5927                hasFastCapture(), tid, mFastTrackAvail);
5928        *flags &= ~IAudioFlinger::TRACK_FAST;
5929      }
5930    }
5931
5932    // compute track buffer size in frames, and suggest the notification frame count
5933    if (*flags & IAudioFlinger::TRACK_FAST) {
5934        // fast track: frame count is exactly the pipe depth
5935        frameCount = mPipeFramesP2;
5936        // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5937        *notificationFrames = mFrameCount;
5938    } else {
5939        // not fast track: max notification period is resampled equivalent of one HAL buffer time
5940        //                 or 20 ms if there is a fast capture
5941        // TODO This could be a roundupRatio inline, and const
5942        size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5943                * sampleRate + mSampleRate - 1) / mSampleRate;
5944        // minimum number of notification periods is at least kMinNotifications,
5945        // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5946        static const size_t kMinNotifications = 3;
5947        static const uint32_t kMinMs = 30;
5948        // TODO This could be a roundupRatio inline
5949        const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5950        // TODO This could be a roundupRatio inline
5951        const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5952                maxNotificationFrames;
5953        const size_t minFrameCount = maxNotificationFrames *
5954                max(kMinNotifications, minNotificationsByMs);
5955        frameCount = max(frameCount, minFrameCount);
5956        if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5957            *notificationFrames = maxNotificationFrames;
5958        }
5959    }
5960    *pFrameCount = frameCount;
5961
5962    lStatus = initCheck();
5963    if (lStatus != NO_ERROR) {
5964        ALOGE("createRecordTrack_l() audio driver not initialized");
5965        goto Exit;
5966    }
5967
5968    { // scope for mLock
5969        Mutex::Autolock _l(mLock);
5970
5971        track = new RecordTrack(this, client, sampleRate,
5972                      format, channelMask, frameCount, NULL, sessionId, uid,
5973                      *flags, TrackBase::TYPE_DEFAULT);
5974
5975        lStatus = track->initCheck();
5976        if (lStatus != NO_ERROR) {
5977            ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
5978            // track must be cleared from the caller as the caller has the AF lock
5979            goto Exit;
5980        }
5981        mTracks.add(track);
5982
5983        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5984        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5985                        mAudioFlinger->btNrecIsOff();
5986        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5987        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
5988
5989        if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5990            pid_t callingPid = IPCThreadState::self()->getCallingPid();
5991            // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5992            // so ask activity manager to do this on our behalf
5993            sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5994        }
5995    }
5996
5997    lStatus = NO_ERROR;
5998
5999Exit:
6000    *status = lStatus;
6001    return track;
6002}
6003
6004status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6005                                           AudioSystem::sync_event_t event,
6006                                           int triggerSession)
6007{
6008    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6009    sp<ThreadBase> strongMe = this;
6010    status_t status = NO_ERROR;
6011
6012    if (event == AudioSystem::SYNC_EVENT_NONE) {
6013        recordTrack->clearSyncStartEvent();
6014    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6015        recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6016                                       triggerSession,
6017                                       recordTrack->sessionId(),
6018                                       syncStartEventCallback,
6019                                       recordTrack);
6020        // Sync event can be cancelled by the trigger session if the track is not in a
6021        // compatible state in which case we start record immediately
6022        if (recordTrack->mSyncStartEvent->isCancelled()) {
6023            recordTrack->clearSyncStartEvent();
6024        } else {
6025            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6026            recordTrack->mFramesToDrop = -
6027                    ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
6028        }
6029    }
6030
6031    {
6032        // This section is a rendezvous between binder thread executing start() and RecordThread
6033        AutoMutex lock(mLock);
6034        if (mActiveTracks.indexOf(recordTrack) >= 0) {
6035            if (recordTrack->mState == TrackBase::PAUSING) {
6036                ALOGV("active record track PAUSING -> ACTIVE");
6037                recordTrack->mState = TrackBase::ACTIVE;
6038            } else {
6039                ALOGV("active record track state %d", recordTrack->mState);
6040            }
6041            return status;
6042        }
6043
6044        // TODO consider other ways of handling this, such as changing the state to :STARTING and
6045        //      adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6046        //      or using a separate command thread
6047        recordTrack->mState = TrackBase::STARTING_1;
6048        mActiveTracks.add(recordTrack);
6049        mActiveTracksGen++;
6050        status_t status = NO_ERROR;
6051        if (recordTrack->isExternalTrack()) {
6052            mLock.unlock();
6053            status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
6054            mLock.lock();
6055            // FIXME should verify that recordTrack is still in mActiveTracks
6056            if (status != NO_ERROR) {
6057                mActiveTracks.remove(recordTrack);
6058                mActiveTracksGen++;
6059                recordTrack->clearSyncStartEvent();
6060                ALOGV("RecordThread::start error %d", status);
6061                return status;
6062            }
6063        }
6064        // Catch up with current buffer indices if thread is already running.
6065        // This is what makes a new client discard all buffered data.  If the track's mRsmpInFront
6066        // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6067        // see previously buffered data before it called start(), but with greater risk of overrun.
6068
6069        recordTrack->mResamplerBufferProvider->reset();
6070        // clear any converter state as new data will be discontinuous
6071        recordTrack->mRecordBufferConverter->reset();
6072        recordTrack->mState = TrackBase::STARTING_2;
6073        // signal thread to start
6074        mWaitWorkCV.broadcast();
6075        if (mActiveTracks.indexOf(recordTrack) < 0) {
6076            ALOGV("Record failed to start");
6077            status = BAD_VALUE;
6078            goto startError;
6079        }
6080        return status;
6081    }
6082
6083startError:
6084    if (recordTrack->isExternalTrack()) {
6085        AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
6086    }
6087    recordTrack->clearSyncStartEvent();
6088    // FIXME I wonder why we do not reset the state here?
6089    return status;
6090}
6091
6092void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6093{
6094    sp<SyncEvent> strongEvent = event.promote();
6095
6096    if (strongEvent != 0) {
6097        sp<RefBase> ptr = strongEvent->cookie().promote();
6098        if (ptr != 0) {
6099            RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6100            recordTrack->handleSyncStartEvent(strongEvent);
6101        }
6102    }
6103}
6104
6105bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
6106    ALOGV("RecordThread::stop");
6107    AutoMutex _l(mLock);
6108    if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
6109        return false;
6110    }
6111    // note that threadLoop may still be processing the track at this point [without lock]
6112    recordTrack->mState = TrackBase::PAUSING;
6113    // do not wait for mStartStopCond if exiting
6114    if (exitPending()) {
6115        return true;
6116    }
6117    // FIXME incorrect usage of wait: no explicit predicate or loop
6118    mStartStopCond.wait(mLock);
6119    // if we have been restarted, recordTrack is in mActiveTracks here
6120    if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
6121        ALOGV("Record stopped OK");
6122        return true;
6123    }
6124    return false;
6125}
6126
6127bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
6128{
6129    return false;
6130}
6131
6132status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
6133{
6134#if 0   // This branch is currently dead code, but is preserved in case it will be needed in future
6135    if (!isValidSyncEvent(event)) {
6136        return BAD_VALUE;
6137    }
6138
6139    int eventSession = event->triggerSession();
6140    status_t ret = NAME_NOT_FOUND;
6141
6142    Mutex::Autolock _l(mLock);
6143
6144    for (size_t i = 0; i < mTracks.size(); i++) {
6145        sp<RecordTrack> track = mTracks[i];
6146        if (eventSession == track->sessionId()) {
6147            (void) track->setSyncEvent(event);
6148            ret = NO_ERROR;
6149        }
6150    }
6151    return ret;
6152#else
6153    return BAD_VALUE;
6154#endif
6155}
6156
6157// destroyTrack_l() must be called with ThreadBase::mLock held
6158void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6159{
6160    track->terminate();
6161    track->mState = TrackBase::STOPPED;
6162    // active tracks are removed by threadLoop()
6163    if (mActiveTracks.indexOf(track) < 0) {
6164        removeTrack_l(track);
6165    }
6166}
6167
6168void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6169{
6170    mTracks.remove(track);
6171    // need anything related to effects here?
6172    if (track->isFastTrack()) {
6173        ALOG_ASSERT(!mFastTrackAvail);
6174        mFastTrackAvail = true;
6175    }
6176}
6177
6178void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6179{
6180    dumpInternals(fd, args);
6181    dumpTracks(fd, args);
6182    dumpEffectChains(fd, args);
6183}
6184
6185void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6186{
6187    dprintf(fd, "\nInput thread %p:\n", this);
6188
6189    dumpBase(fd, args);
6190
6191    if (mActiveTracks.size() == 0) {
6192        dprintf(fd, "  No active record clients\n");
6193    }
6194    dprintf(fd, "  Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
6195    dprintf(fd, "  Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
6196
6197    //  Make a non-atomic copy of fast capture dump state so it won't change underneath us
6198    const FastCaptureDumpState copy(mFastCaptureDumpState);
6199    copy.dump(fd);
6200}
6201
6202void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
6203{
6204    const size_t SIZE = 256;
6205    char buffer[SIZE];
6206    String8 result;
6207
6208    size_t numtracks = mTracks.size();
6209    size_t numactive = mActiveTracks.size();
6210    size_t numactiveseen = 0;
6211    dprintf(fd, "  %d Tracks", numtracks);
6212    if (numtracks) {
6213        dprintf(fd, " of which %d are active\n", numactive);
6214        RecordTrack::appendDumpHeader(result);
6215        for (size_t i = 0; i < numtracks ; ++i) {
6216            sp<RecordTrack> track = mTracks[i];
6217            if (track != 0) {
6218                bool active = mActiveTracks.indexOf(track) >= 0;
6219                if (active) {
6220                    numactiveseen++;
6221                }
6222                track->dump(buffer, SIZE, active);
6223                result.append(buffer);
6224            }
6225        }
6226    } else {
6227        dprintf(fd, "\n");
6228    }
6229
6230    if (numactiveseen != numactive) {
6231        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
6232                " not in the track list\n");
6233        result.append(buffer);
6234        RecordTrack::appendDumpHeader(result);
6235        for (size_t i = 0; i < numactive; ++i) {
6236            sp<RecordTrack> track = mActiveTracks[i];
6237            if (mTracks.indexOf(track) < 0) {
6238                track->dump(buffer, SIZE, true);
6239                result.append(buffer);
6240            }
6241        }
6242
6243    }
6244    write(fd, result.string(), result.size());
6245}
6246
6247
6248void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6249{
6250    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6251    RecordThread *recordThread = (RecordThread *) threadBase.get();
6252    mRsmpInFront = recordThread->mRsmpInRear;
6253    mRsmpInUnrel = 0;
6254}
6255
6256void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6257        size_t *framesAvailable, bool *hasOverrun)
6258{
6259    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6260    RecordThread *recordThread = (RecordThread *) threadBase.get();
6261    const int32_t rear = recordThread->mRsmpInRear;
6262    const int32_t front = mRsmpInFront;
6263    const ssize_t filled = rear - front;
6264
6265    size_t framesIn;
6266    bool overrun = false;
6267    if (filled < 0) {
6268        // should not happen, but treat like a massive overrun and re-sync
6269        framesIn = 0;
6270        mRsmpInFront = rear;
6271        overrun = true;
6272    } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6273        framesIn = (size_t) filled;
6274    } else {
6275        // client is not keeping up with server, but give it latest data
6276        framesIn = recordThread->mRsmpInFrames;
6277        mRsmpInFront = /* front = */ rear - framesIn;
6278        overrun = true;
6279    }
6280    if (framesAvailable != NULL) {
6281        *framesAvailable = framesIn;
6282    }
6283    if (hasOverrun != NULL) {
6284        *hasOverrun = overrun;
6285    }
6286}
6287
6288// AudioBufferProvider interface
6289status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6290        AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
6291{
6292    sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6293    if (threadBase == 0) {
6294        buffer->frameCount = 0;
6295        buffer->raw = NULL;
6296        return NOT_ENOUGH_DATA;
6297    }
6298    RecordThread *recordThread = (RecordThread *) threadBase.get();
6299    int32_t rear = recordThread->mRsmpInRear;
6300    int32_t front = mRsmpInFront;
6301    ssize_t filled = rear - front;
6302    // FIXME should not be P2 (don't want to increase latency)
6303    // FIXME if client not keeping up, discard
6304    LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
6305    // 'filled' may be non-contiguous, so return only the first contiguous chunk
6306    front &= recordThread->mRsmpInFramesP2 - 1;
6307    size_t part1 = recordThread->mRsmpInFramesP2 - front;
6308    if (part1 > (size_t) filled) {
6309        part1 = filled;
6310    }
6311    size_t ask = buffer->frameCount;
6312    ALOG_ASSERT(ask > 0);
6313    if (part1 > ask) {
6314        part1 = ask;
6315    }
6316    if (part1 == 0) {
6317        // out of data is fine since the resampler will return a short-count.
6318        buffer->raw = NULL;
6319        buffer->frameCount = 0;
6320        mRsmpInUnrel = 0;
6321        return NOT_ENOUGH_DATA;
6322    }
6323
6324    buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
6325    buffer->frameCount = part1;
6326    mRsmpInUnrel = part1;
6327    return NO_ERROR;
6328}
6329
6330// AudioBufferProvider interface
6331void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6332        AudioBufferProvider::Buffer* buffer)
6333{
6334    size_t stepCount = buffer->frameCount;
6335    if (stepCount == 0) {
6336        return;
6337    }
6338    ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6339    mRsmpInUnrel -= stepCount;
6340    mRsmpInFront += stepCount;
6341    buffer->raw = NULL;
6342    buffer->frameCount = 0;
6343}
6344
6345AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6346        audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6347        uint32_t srcSampleRate,
6348        audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6349        uint32_t dstSampleRate) :
6350            mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6351            // mSrcFormat
6352            // mSrcSampleRate
6353            // mDstChannelMask
6354            // mDstFormat
6355            // mDstSampleRate
6356            // mSrcChannelCount
6357            // mDstChannelCount
6358            // mDstFrameSize
6359            mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
6360            mResampler(NULL),
6361            mIsLegacyDownmix(false),
6362            mIsLegacyUpmix(false),
6363            mRequiresFloat(false),
6364            mInputConverterProvider(NULL)
6365{
6366    (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6367            dstChannelMask, dstFormat, dstSampleRate);
6368}
6369
6370AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6371    free(mBuf);
6372    delete mResampler;
6373    delete mInputConverterProvider;
6374}
6375
6376size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6377        AudioBufferProvider *provider, size_t frames)
6378{
6379    if (mInputConverterProvider != NULL) {
6380        mInputConverterProvider->setBufferProvider(provider);
6381        provider = mInputConverterProvider;
6382    }
6383
6384    if (mResampler == NULL) {
6385        ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6386                mSrcSampleRate, mSrcFormat, mDstFormat);
6387
6388        AudioBufferProvider::Buffer buffer;
6389        for (size_t i = frames; i > 0; ) {
6390            buffer.frameCount = i;
6391            status_t status = provider->getNextBuffer(&buffer, 0);
6392            if (status != OK || buffer.frameCount == 0) {
6393                frames -= i; // cannot fill request.
6394                break;
6395            }
6396            // format convert to destination buffer
6397            convertNoResampler(dst, buffer.raw, buffer.frameCount);
6398
6399            dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6400            i -= buffer.frameCount;
6401            provider->releaseBuffer(&buffer);
6402        }
6403    } else {
6404         ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6405                 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6406
6407         // reallocate buffer if needed
6408         if (mBufFrameSize != 0 && mBufFrames < frames) {
6409             free(mBuf);
6410             mBufFrames = frames;
6411             (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6412         }
6413        // resampler accumulates, but we only have one source track
6414        memset(mBuf, 0, frames * mBufFrameSize);
6415        frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6416        // format convert to destination buffer
6417        convertResampler(dst, mBuf, frames);
6418    }
6419    return frames;
6420}
6421
6422status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6423        audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6424        uint32_t srcSampleRate,
6425        audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6426        uint32_t dstSampleRate)
6427{
6428    // quick evaluation if there is any change.
6429    if (mSrcFormat == srcFormat
6430            && mSrcChannelMask == srcChannelMask
6431            && mSrcSampleRate == srcSampleRate
6432            && mDstFormat == dstFormat
6433            && mDstChannelMask == dstChannelMask
6434            && mDstSampleRate == dstSampleRate) {
6435        return NO_ERROR;
6436    }
6437
6438    const bool valid =
6439            audio_is_input_channel(srcChannelMask)
6440            && audio_is_input_channel(dstChannelMask)
6441            && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6442            && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6443            && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6444            ; // no upsampling checks for now
6445    if (!valid) {
6446        return BAD_VALUE;
6447    }
6448
6449    mSrcFormat = srcFormat;
6450    mSrcChannelMask = srcChannelMask;
6451    mSrcSampleRate = srcSampleRate;
6452    mDstFormat = dstFormat;
6453    mDstChannelMask = dstChannelMask;
6454    mDstSampleRate = dstSampleRate;
6455
6456    // compute derived parameters
6457    mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6458    mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6459    mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6460
6461    // do we need to resample?
6462    delete mResampler;
6463    mResampler = NULL;
6464    if (mSrcSampleRate != mDstSampleRate) {
6465        mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6466                mSrcChannelCount, mDstSampleRate);
6467        mResampler->setSampleRate(mSrcSampleRate);
6468        mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6469    }
6470
6471    // are we running legacy channel conversion modes?
6472    mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6473                            || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6474                   && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6475    mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6476                   && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6477                            || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6478
6479    // do we need to process in float?
6480    mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6481
6482    // do we need a staging buffer to convert for destination (we can still optimize this)?
6483    // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6484    if (mResampler != NULL) {
6485        mBufFrameSize = max(mSrcChannelCount, FCC_2)
6486                * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6487    } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6488        mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6489    } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
6490        mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6491    } else {
6492        mBufFrameSize = 0;
6493    }
6494    mBufFrames = 0; // force the buffer to be resized.
6495
6496    // do we need an input converter buffer provider to give us float?
6497    delete mInputConverterProvider;
6498    mInputConverterProvider = NULL;
6499    if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6500        mInputConverterProvider = new ReformatBufferProvider(
6501                audio_channel_count_from_in_mask(mSrcChannelMask),
6502                mSrcFormat,
6503                AUDIO_FORMAT_PCM_FLOAT,
6504                256 /* provider buffer frame count */);
6505    }
6506
6507    // do we need a remixer to do channel mask conversion
6508    if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6509        (void) memcpy_by_index_array_initialization_from_channel_mask(
6510                mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
6511    }
6512    return NO_ERROR;
6513}
6514
6515void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6516        void *dst, const void *src, size_t frames)
6517{
6518    // src is native type unless there is legacy upmix or downmix, whereupon it is float.
6519    if (mBufFrameSize != 0 && mBufFrames < frames) {
6520        free(mBuf);
6521        mBufFrames = frames;
6522        (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6523    }
6524    // do we need to do legacy upmix and downmix?
6525    if (mIsLegacyUpmix || mIsLegacyDownmix) {
6526        void *dstBuf = mBuf != NULL ? mBuf : dst;
6527        if (mIsLegacyUpmix) {
6528            upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6529                    (const float *)src, frames);
6530        } else /*mIsLegacyDownmix */ {
6531            downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6532                    (const float *)src, frames);
6533        }
6534        if (mBuf != NULL) {
6535            memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6536                    frames * mDstChannelCount);
6537        }
6538        return;
6539    }
6540    // do we need to do channel mask conversion?
6541    if (mSrcChannelMask != mDstChannelMask) {
6542        void *dstBuf = mBuf != NULL ? mBuf : dst;
6543        memcpy_by_index_array(dstBuf, mDstChannelCount,
6544                src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6545        if (dstBuf == dst) {
6546            return; // format is the same
6547        }
6548    }
6549    // convert to destination buffer
6550    const void *convertBuf = mBuf != NULL ? mBuf : src;
6551    memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6552            frames * mDstChannelCount);
6553}
6554
6555void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6556        void *dst, /*not-a-const*/ void *src, size_t frames)
6557{
6558    // src buffer format is ALWAYS float when entering this routine
6559    if (mIsLegacyUpmix) {
6560        ; // mono to stereo already handled by resampler
6561    } else if (mIsLegacyDownmix
6562            || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6563        // the resampler outputs stereo for mono input channel (a feature?)
6564        // must convert to mono
6565        downmix_to_mono_float_from_stereo_float((float *)src,
6566                (const float *)src, frames);
6567    } else if (mSrcChannelMask != mDstChannelMask) {
6568        // convert to mono channel again for channel mask conversion (could be skipped
6569        // with further optimization).
6570        if (mSrcChannelCount == 1) {
6571            downmix_to_mono_float_from_stereo_float((float *)src,
6572                (const float *)src, frames);
6573        }
6574        // convert to destination format (in place, OK as float is larger than other types)
6575        if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6576            memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6577                    frames * mSrcChannelCount);
6578        }
6579        // channel convert and save to dst
6580        memcpy_by_index_array(dst, mDstChannelCount,
6581                src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6582        return;
6583    }
6584    // convert to destination format and save to dst
6585    memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6586            frames * mDstChannelCount);
6587}
6588
6589bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6590                                                        status_t& status)
6591{
6592    bool reconfig = false;
6593
6594    status = NO_ERROR;
6595
6596    audio_format_t reqFormat = mFormat;
6597    uint32_t samplingRate = mSampleRate;
6598    audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6599    // possible that we are > 2 channels, use channel index mask
6600    if (channelMask == AUDIO_CHANNEL_INVALID && mChannelCount <= FCC_8) {
6601        audio_channel_mask_for_index_assignment_from_count(mChannelCount);
6602    }
6603
6604    AudioParameter param = AudioParameter(keyValuePair);
6605    int value;
6606    // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6607    //      channel count change can be requested. Do we mandate the first client defines the
6608    //      HAL sampling rate and channel count or do we allow changes on the fly?
6609    if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6610        samplingRate = value;
6611        reconfig = true;
6612    }
6613    if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6614        if (!audio_is_linear_pcm((audio_format_t) value)) {
6615            status = BAD_VALUE;
6616        } else {
6617            reqFormat = (audio_format_t) value;
6618            reconfig = true;
6619        }
6620    }
6621    if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6622        audio_channel_mask_t mask = (audio_channel_mask_t) value;
6623        if (!audio_is_input_channel(mask) ||
6624                audio_channel_count_from_in_mask(mask) > FCC_8) {
6625            status = BAD_VALUE;
6626        } else {
6627            channelMask = mask;
6628            reconfig = true;
6629        }
6630    }
6631    if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6632        // do not accept frame count changes if tracks are open as the track buffer
6633        // size depends on frame count and correct behavior would not be guaranteed
6634        // if frame count is changed after track creation
6635        if (mActiveTracks.size() > 0) {
6636            status = INVALID_OPERATION;
6637        } else {
6638            reconfig = true;
6639        }
6640    }
6641    if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6642        // forward device change to effects that have requested to be
6643        // aware of attached audio device.
6644        for (size_t i = 0; i < mEffectChains.size(); i++) {
6645            mEffectChains[i]->setDevice_l(value);
6646        }
6647
6648        // store input device and output device but do not forward output device to audio HAL.
6649        // Note that status is ignored by the caller for output device
6650        // (see AudioFlinger::setParameters()
6651        if (audio_is_output_devices(value)) {
6652            mOutDevice = value;
6653            status = BAD_VALUE;
6654        } else {
6655            mInDevice = value;
6656            // disable AEC and NS if the device is a BT SCO headset supporting those
6657            // pre processings
6658            if (mTracks.size() > 0) {
6659                bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6660                                    mAudioFlinger->btNrecIsOff();
6661                for (size_t i = 0; i < mTracks.size(); i++) {
6662                    sp<RecordTrack> track = mTracks[i];
6663                    setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6664                    setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6665                }
6666            }
6667        }
6668    }
6669    if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6670            mAudioSource != (audio_source_t)value) {
6671        // forward device change to effects that have requested to be
6672        // aware of attached audio device.
6673        for (size_t i = 0; i < mEffectChains.size(); i++) {
6674            mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6675        }
6676        mAudioSource = (audio_source_t)value;
6677    }
6678
6679    if (status == NO_ERROR) {
6680        status = mInput->stream->common.set_parameters(&mInput->stream->common,
6681                keyValuePair.string());
6682        if (status == INVALID_OPERATION) {
6683            inputStandBy();
6684            status = mInput->stream->common.set_parameters(&mInput->stream->common,
6685                    keyValuePair.string());
6686        }
6687        if (reconfig) {
6688            if (status == BAD_VALUE &&
6689                audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6690                audio_is_linear_pcm(reqFormat) &&
6691                (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6692                        <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
6693                audio_channel_count_from_in_mask(
6694                        mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6695                (channelMask == AUDIO_CHANNEL_IN_MONO ||
6696                        channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6697                status = NO_ERROR;
6698            }
6699            if (status == NO_ERROR) {
6700                readInputParameters_l();
6701                sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
6702            }
6703        }
6704    }
6705
6706    return reconfig;
6707}
6708
6709String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6710{
6711    Mutex::Autolock _l(mLock);
6712    if (initCheck() != NO_ERROR) {
6713        return String8();
6714    }
6715
6716    char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6717    const String8 out_s8(s);
6718    free(s);
6719    return out_s8;
6720}
6721
6722void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6723    sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6724
6725    desc->mIoHandle = mId;
6726
6727    switch (event) {
6728    case AUDIO_INPUT_OPENED:
6729    case AUDIO_INPUT_CONFIG_CHANGED:
6730        desc->mChannelMask = mChannelMask;
6731        desc->mSamplingRate = mSampleRate;
6732        desc->mFormat = mFormat;
6733        desc->mFrameCount = mFrameCount;
6734        desc->mLatency = 0;
6735        break;
6736
6737    case AUDIO_INPUT_CLOSED:
6738    default:
6739        break;
6740    }
6741    mAudioFlinger->ioConfigChanged(event, desc);
6742}
6743
6744void AudioFlinger::RecordThread::readInputParameters_l()
6745{
6746    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6747    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6748    mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
6749    if (mChannelCount > FCC_8) {
6750        ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6751    }
6752    mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6753    mFormat = mHALFormat;
6754    if (!audio_is_linear_pcm(mFormat)) {
6755        ALOGE("HAL format %#x is not linear pcm", mFormat);
6756    }
6757    mFrameSize = audio_stream_in_frame_size(mInput->stream);
6758    mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6759    mFrameCount = mBufferSize / mFrameSize;
6760    // This is the formula for calculating the temporary buffer size.
6761    // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
6762    // 1 full output buffer, regardless of the alignment of the available input.
6763    // The value is somewhat arbitrary, and could probably be even larger.
6764    // A larger value should allow more old data to be read after a track calls start(),
6765    // without increasing latency.
6766    //
6767    // Note this is independent of the maximum downsampling ratio permitted for capture.
6768    mRsmpInFrames = mFrameCount * 7;
6769    mRsmpInFramesP2 = roundup(mRsmpInFrames);
6770    free(mRsmpInBuffer);
6771
6772    // TODO optimize audio capture buffer sizes ...
6773    // Here we calculate the size of the sliding buffer used as a source
6774    // for resampling.  mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6775    // For current HAL frame counts, this is usually 2048 = 40 ms.  It would
6776    // be better to have it derived from the pipe depth in the long term.
6777    // The current value is higher than necessary.  However it should not add to latency.
6778
6779    // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6780    (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
6781
6782    // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6783    // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
6784}
6785
6786uint32_t AudioFlinger::RecordThread::getInputFramesLost()
6787{
6788    Mutex::Autolock _l(mLock);
6789    if (initCheck() != NO_ERROR) {
6790        return 0;
6791    }
6792
6793    return mInput->stream->get_input_frames_lost(mInput->stream);
6794}
6795
6796uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6797{
6798    Mutex::Autolock _l(mLock);
6799    uint32_t result = 0;
6800    if (getEffectChain_l(sessionId) != 0) {
6801        result = EFFECT_SESSION;
6802    }
6803
6804    for (size_t i = 0; i < mTracks.size(); ++i) {
6805        if (sessionId == mTracks[i]->sessionId()) {
6806            result |= TRACK_SESSION;
6807            break;
6808        }
6809    }
6810
6811    return result;
6812}
6813
6814KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6815{
6816    KeyedVector<int, bool> ids;
6817    Mutex::Autolock _l(mLock);
6818    for (size_t j = 0; j < mTracks.size(); ++j) {
6819        sp<RecordThread::RecordTrack> track = mTracks[j];
6820        int sessionId = track->sessionId();
6821        if (ids.indexOfKey(sessionId) < 0) {
6822            ids.add(sessionId, true);
6823        }
6824    }
6825    return ids;
6826}
6827
6828AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6829{
6830    Mutex::Autolock _l(mLock);
6831    AudioStreamIn *input = mInput;
6832    mInput = NULL;
6833    return input;
6834}
6835
6836// this method must always be called either with ThreadBase mLock held or inside the thread loop
6837audio_stream_t* AudioFlinger::RecordThread::stream() const
6838{
6839    if (mInput == NULL) {
6840        return NULL;
6841    }
6842    return &mInput->stream->common;
6843}
6844
6845status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6846{
6847    // only one chain per input thread
6848    if (mEffectChains.size() != 0) {
6849        ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
6850        return INVALID_OPERATION;
6851    }
6852    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6853    chain->setThread(this);
6854    chain->setInBuffer(NULL);
6855    chain->setOutBuffer(NULL);
6856
6857    checkSuspendOnAddEffectChain_l(chain);
6858
6859    // make sure enabled pre processing effects state is communicated to the HAL as we
6860    // just moved them to a new input stream.
6861    chain->syncHalEffectsState();
6862
6863    mEffectChains.add(chain);
6864
6865    return NO_ERROR;
6866}
6867
6868size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6869{
6870    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6871    ALOGW_IF(mEffectChains.size() != 1,
6872            "removeEffectChain_l() %p invalid chain size %d on thread %p",
6873            chain.get(), mEffectChains.size(), this);
6874    if (mEffectChains.size() == 1) {
6875        mEffectChains.removeAt(0);
6876    }
6877    return 0;
6878}
6879
6880status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6881                                                          audio_patch_handle_t *handle)
6882{
6883    status_t status = NO_ERROR;
6884
6885    // store new device and send to effects
6886    mInDevice = patch->sources[0].ext.device.type;
6887    for (size_t i = 0; i < mEffectChains.size(); i++) {
6888        mEffectChains[i]->setDevice_l(mInDevice);
6889    }
6890
6891    // disable AEC and NS if the device is a BT SCO headset supporting those
6892    // pre processings
6893    if (mTracks.size() > 0) {
6894        bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6895                            mAudioFlinger->btNrecIsOff();
6896        for (size_t i = 0; i < mTracks.size(); i++) {
6897            sp<RecordTrack> track = mTracks[i];
6898            setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6899            setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6900        }
6901    }
6902
6903    // store new source and send to effects
6904    if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6905        mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6906        for (size_t i = 0; i < mEffectChains.size(); i++) {
6907            mEffectChains[i]->setAudioSource_l(mAudioSource);
6908        }
6909    }
6910
6911    if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6912        audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6913        status = hwDevice->create_audio_patch(hwDevice,
6914                                               patch->num_sources,
6915                                               patch->sources,
6916                                               patch->num_sinks,
6917                                               patch->sinks,
6918                                               handle);
6919    } else {
6920        char *address;
6921        if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
6922            address = audio_device_address_to_parameter(
6923                                                patch->sources[0].ext.device.type,
6924                                                patch->sources[0].ext.device.address);
6925        } else {
6926            address = (char *)calloc(1, 1);
6927        }
6928        AudioParameter param = AudioParameter(String8(address));
6929        free(address);
6930        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
6931                     (int)patch->sources[0].ext.device.type);
6932        param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
6933                                         (int)patch->sinks[0].ext.mix.usecase.source);
6934        status = mInput->stream->common.set_parameters(&mInput->stream->common,
6935                param.toString().string());
6936        *handle = AUDIO_PATCH_HANDLE_NONE;
6937    }
6938
6939    return status;
6940}
6941
6942status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6943{
6944    status_t status = NO_ERROR;
6945
6946    mInDevice = AUDIO_DEVICE_NONE;
6947
6948    if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6949        audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6950        status = hwDevice->release_audio_patch(hwDevice, handle);
6951    } else {
6952        AudioParameter param;
6953        param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
6954        status = mInput->stream->common.set_parameters(&mInput->stream->common,
6955                param.toString().string());
6956    }
6957    return status;
6958}
6959
6960void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6961{
6962    Mutex::Autolock _l(mLock);
6963    mTracks.add(record);
6964}
6965
6966void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6967{
6968    Mutex::Autolock _l(mLock);
6969    destroyTrack_l(record);
6970}
6971
6972void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6973{
6974    ThreadBase::getAudioPortConfig(config);
6975    config->role = AUDIO_PORT_ROLE_SINK;
6976    config->ext.mix.hw_module = mInput->audioHwDev->handle();
6977    config->ext.mix.usecase.source = mAudioSource;
6978}
6979
6980} // namespace android
6981