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