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