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