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