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