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