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