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