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