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