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