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