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