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