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