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