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