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