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