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