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