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