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