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