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