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