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