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