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