AudioFlinger.cpp revision bb4350d3b9e9485ae59e084de270f86aecef8066
1/*
2**
3** Copyright 2007, 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
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
27#include <binder/IPCThreadState.h>
28#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <utils/Trace.h>
31#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
35#include <utils/Atomic.h>
36
37#include <cutils/bitops.h>
38#include <cutils/properties.h>
39#include <cutils/compiler.h>
40
41#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
44#include <media/IMediaPlayerService.h>
45#include <media/IMediaDeathNotifier.h>
46#endif
47
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
50
51#include <system/audio.h>
52#include <hardware/audio.h>
53
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
56#include "ServiceUtilities.h"
57
58#include <media/EffectsFactoryApi.h>
59#include <audio_effects/effect_visualizer.h>
60#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
62
63#include <audio_utils/primitives.h>
64
65#include <powermanager/PowerManager.h>
66
67// #define DEBUG_CPU_USAGE 10  // log statistics every n wall clock seconds
68#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
72
73#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
76#include "FastMixer.h"
77
78// NBAIO implementations
79#include "AudioStreamOutSink.h"
80#include "MonoPipe.h"
81#include "MonoPipeReader.h"
82#include "Pipe.h"
83#include "PipeReader.h"
84#include "SourceAudioBufferProvider.h"
85
86#include "SchedulingPolicyService.h"
87
88// ----------------------------------------------------------------------------
89
90// Note: the following macro is used for extremely verbose logging message.  In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well.  Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on.  Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
102
103namespace android {
104
105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
106static const char kHardwareLockedString[] = "Hardware lock is taken\n";
107
108static const float MAX_GAIN = 4096.0f;
109static const uint32_t MAX_GAIN_INT = 0x1000;
110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
119
120static const int kDumpLockRetries = 50;
121static const int kDumpLockSleepUs = 20000;
122
123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
125
126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
128
129// maximum time to wait for setParameters to complete
130static const nsecs_t kSetParametersTimeoutNs = seconds(2);
131
132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
137// minimum normal mix buffer size, expressed in milliseconds rather than frames
138static const uint32_t kMinNormalMixBufferSizeMs = 20;
139// maximum normal mix buffer size
140static const uint32_t kMaxNormalMixBufferSizeMs = 24;
141
142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
143
144// Whether to use fast mixer
145static const enum {
146    FastMixer_Never,    // never initialize or use: for debugging only
147    FastMixer_Always,   // always initialize and use, even if not needed: for debugging only
148                        // normal mixer multiplier is 1
149    FastMixer_Static,   // initialize if needed, then use all the time if initialized,
150                        // multiplier is calculated based on min & max normal mixer buffer size
151    FastMixer_Dynamic,  // initialize if needed, then use dynamically depending on track load,
152                        // multiplier is calculated based on min & max normal mixer buffer size
153    // FIXME for FastMixer_Dynamic:
154    //  Supporting this option will require fixing HALs that can't handle large writes.
155    //  For example, one HAL implementation returns an error from a large write,
156    //  and another HAL implementation corrupts memory, possibly in the sample rate converter.
157    //  We could either fix the HAL implementations, or provide a wrapper that breaks
158    //  up large writes into smaller ones, and the wrapper would need to deal with scheduler.
159} kUseFastMixer = FastMixer_Static;
160
161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
162                              // AudioFlinger::setParameters() updates, other threads read w/o lock
163
164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
167
168// ----------------------------------------------------------------------------
169
170#ifdef ADD_BATTERY_DATA
171// To collect the amplifier usage
172static void addBatteryData(uint32_t params) {
173    sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
174    if (service == NULL) {
175        // it already logged
176        return;
177    }
178
179    service->addBatteryData(params);
180}
181#endif
182
183static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
184{
185    const hw_module_t *mod;
186    int rc;
187
188    rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
189    ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
190                 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
191    if (rc) {
192        goto out;
193    }
194    rc = audio_hw_device_open(mod, dev);
195    ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
196                 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
197    if (rc) {
198        goto out;
199    }
200    if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
201        ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
202        rc = BAD_VALUE;
203        goto out;
204    }
205    return 0;
206
207out:
208    *dev = NULL;
209    return rc;
210}
211
212// ----------------------------------------------------------------------------
213
214AudioFlinger::AudioFlinger()
215    : BnAudioFlinger(),
216      mPrimaryHardwareDev(NULL),
217      mHardwareStatus(AUDIO_HW_IDLE),
218      mMasterVolume(1.0f),
219      mMasterVolumeSW(1.0f),
220      mMasterVolumeSupportLvl(MVS_NONE),
221      mMasterMute(false),
222      mNextUniqueId(1),
223      mMode(AUDIO_MODE_INVALID),
224      mBtNrecIsOff(false)
225{
226}
227
228void AudioFlinger::onFirstRef()
229{
230    int rc = 0;
231
232    Mutex::Autolock _l(mLock);
233
234    /* TODO: move all this work into an Init() function */
235    char val_str[PROPERTY_VALUE_MAX] = { 0 };
236    if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
237        uint32_t int_val;
238        if (1 == sscanf(val_str, "%u", &int_val)) {
239            mStandbyTimeInNsecs = milliseconds(int_val);
240            ALOGI("Using %u mSec as standby time.", int_val);
241        } else {
242            mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
243            ALOGI("Using default %u mSec as standby time.",
244                    (uint32_t)(mStandbyTimeInNsecs / 1000000));
245        }
246    }
247
248    mMode = AUDIO_MODE_NORMAL;
249}
250
251AudioFlinger::~AudioFlinger()
252{
253    while (!mRecordThreads.isEmpty()) {
254        // closeInput() will remove first entry from mRecordThreads
255        closeInput_nonvirtual(mRecordThreads.keyAt(0));
256    }
257    while (!mPlaybackThreads.isEmpty()) {
258        // closeOutput() will remove first entry from mPlaybackThreads
259        closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
260    }
261
262    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
263        // no mHardwareLock needed, as there are no other references to this
264        audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
265        delete mAudioHwDevs.valueAt(i);
266    }
267}
268
269static const char * const audio_interfaces[] = {
270    AUDIO_HARDWARE_MODULE_ID_PRIMARY,
271    AUDIO_HARDWARE_MODULE_ID_A2DP,
272    AUDIO_HARDWARE_MODULE_ID_USB,
273};
274#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
275
276audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, audio_devices_t devices)
277{
278    // if module is 0, the request comes from an old policy manager and we should load
279    // well known modules
280    if (module == 0) {
281        ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
282        for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
283            loadHwModule_l(audio_interfaces[i]);
284        }
285    } else {
286        // check a match for the requested module handle
287        AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
288        if (audioHwdevice != NULL) {
289            return audioHwdevice->hwDevice();
290        }
291    }
292    // then try to find a module supporting the requested device.
293    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
294        audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
295        if ((dev->get_supported_devices(dev) & devices) == devices)
296            return dev;
297    }
298
299    return NULL;
300}
301
302status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
303{
304    const size_t SIZE = 256;
305    char buffer[SIZE];
306    String8 result;
307
308    result.append("Clients:\n");
309    for (size_t i = 0; i < mClients.size(); ++i) {
310        sp<Client> client = mClients.valueAt(i).promote();
311        if (client != 0) {
312            snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
313            result.append(buffer);
314        }
315    }
316
317    result.append("Global session refs:\n");
318    result.append(" session pid count\n");
319    for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
320        AudioSessionRef *r = mAudioSessionRefs[i];
321        snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
322        result.append(buffer);
323    }
324    write(fd, result.string(), result.size());
325    return NO_ERROR;
326}
327
328
329status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
330{
331    const size_t SIZE = 256;
332    char buffer[SIZE];
333    String8 result;
334    hardware_call_state hardwareStatus = mHardwareStatus;
335
336    snprintf(buffer, SIZE, "Hardware status: %d\n"
337                           "Standby Time mSec: %u\n",
338                            hardwareStatus,
339                            (uint32_t)(mStandbyTimeInNsecs / 1000000));
340    result.append(buffer);
341    write(fd, result.string(), result.size());
342    return NO_ERROR;
343}
344
345status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
346{
347    const size_t SIZE = 256;
348    char buffer[SIZE];
349    String8 result;
350    snprintf(buffer, SIZE, "Permission Denial: "
351            "can't dump AudioFlinger from pid=%d, uid=%d\n",
352            IPCThreadState::self()->getCallingPid(),
353            IPCThreadState::self()->getCallingUid());
354    result.append(buffer);
355    write(fd, result.string(), result.size());
356    return NO_ERROR;
357}
358
359static bool tryLock(Mutex& mutex)
360{
361    bool locked = false;
362    for (int i = 0; i < kDumpLockRetries; ++i) {
363        if (mutex.tryLock() == NO_ERROR) {
364            locked = true;
365            break;
366        }
367        usleep(kDumpLockSleepUs);
368    }
369    return locked;
370}
371
372status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
373{
374    if (!dumpAllowed()) {
375        dumpPermissionDenial(fd, args);
376    } else {
377        // get state of hardware lock
378        bool hardwareLocked = tryLock(mHardwareLock);
379        if (!hardwareLocked) {
380            String8 result(kHardwareLockedString);
381            write(fd, result.string(), result.size());
382        } else {
383            mHardwareLock.unlock();
384        }
385
386        bool locked = tryLock(mLock);
387
388        // failed to lock - AudioFlinger is probably deadlocked
389        if (!locked) {
390            String8 result(kDeadlockedString);
391            write(fd, result.string(), result.size());
392        }
393
394        dumpClients(fd, args);
395        dumpInternals(fd, args);
396
397        // dump playback threads
398        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
399            mPlaybackThreads.valueAt(i)->dump(fd, args);
400        }
401
402        // dump record threads
403        for (size_t i = 0; i < mRecordThreads.size(); i++) {
404            mRecordThreads.valueAt(i)->dump(fd, args);
405        }
406
407        // dump all hardware devs
408        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
409            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
410            dev->dump(dev, fd);
411        }
412        if (locked) mLock.unlock();
413    }
414    return NO_ERROR;
415}
416
417sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
418{
419    // If pid is already in the mClients wp<> map, then use that entry
420    // (for which promote() is always != 0), otherwise create a new entry and Client.
421    sp<Client> client = mClients.valueFor(pid).promote();
422    if (client == 0) {
423        client = new Client(this, pid);
424        mClients.add(pid, client);
425    }
426
427    return client;
428}
429
430// IAudioFlinger interface
431
432
433sp<IAudioTrack> AudioFlinger::createTrack(
434        pid_t pid,
435        audio_stream_type_t streamType,
436        uint32_t sampleRate,
437        audio_format_t format,
438        audio_channel_mask_t channelMask,
439        int frameCount,
440        IAudioFlinger::track_flags_t flags,
441        const sp<IMemory>& sharedBuffer,
442        audio_io_handle_t output,
443        pid_t tid,
444        int *sessionId,
445        status_t *status)
446{
447    sp<PlaybackThread::Track> track;
448    sp<TrackHandle> trackHandle;
449    sp<Client> client;
450    status_t lStatus;
451    int lSessionId;
452
453    // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
454    // but if someone uses binder directly they could bypass that and cause us to crash
455    if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
456        ALOGE("createTrack() invalid stream type %d", streamType);
457        lStatus = BAD_VALUE;
458        goto Exit;
459    }
460
461    {
462        Mutex::Autolock _l(mLock);
463        PlaybackThread *thread = checkPlaybackThread_l(output);
464        PlaybackThread *effectThread = NULL;
465        if (thread == NULL) {
466            ALOGE("unknown output thread");
467            lStatus = BAD_VALUE;
468            goto Exit;
469        }
470
471        client = registerPid_l(pid);
472
473        ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
474        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
475            // check if an effect chain with the same session ID is present on another
476            // output thread and move it here.
477            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
478                sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
479                if (mPlaybackThreads.keyAt(i) != output) {
480                    uint32_t sessions = t->hasAudioSession(*sessionId);
481                    if (sessions & PlaybackThread::EFFECT_SESSION) {
482                        effectThread = t.get();
483                        break;
484                    }
485                }
486            }
487            lSessionId = *sessionId;
488        } else {
489            // if no audio session id is provided, create one here
490            lSessionId = nextUniqueId();
491            if (sessionId != NULL) {
492                *sessionId = lSessionId;
493            }
494        }
495        ALOGV("createTrack() lSessionId: %d", lSessionId);
496
497        track = thread->createTrack_l(client, streamType, sampleRate, format,
498                channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
499
500        // move effect chain to this output thread if an effect on same session was waiting
501        // for a track to be created
502        if (lStatus == NO_ERROR && effectThread != NULL) {
503            Mutex::Autolock _dl(thread->mLock);
504            Mutex::Autolock _sl(effectThread->mLock);
505            moveEffectChain_l(lSessionId, effectThread, thread, true);
506        }
507
508        // Look for sync events awaiting for a session to be used.
509        for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
510            if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
511                if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
512                    if (lStatus == NO_ERROR) {
513                        track->setSyncEvent(mPendingSyncEvents[i]);
514                    } else {
515                        mPendingSyncEvents[i]->cancel();
516                    }
517                    mPendingSyncEvents.removeAt(i);
518                    i--;
519                }
520            }
521        }
522    }
523    if (lStatus == NO_ERROR) {
524        trackHandle = new TrackHandle(track);
525    } else {
526        // remove local strong reference to Client before deleting the Track so that the Client
527        // destructor is called by the TrackBase destructor with mLock held
528        client.clear();
529        track.clear();
530    }
531
532Exit:
533    if (status != NULL) {
534        *status = lStatus;
535    }
536    return trackHandle;
537}
538
539uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
540{
541    Mutex::Autolock _l(mLock);
542    PlaybackThread *thread = checkPlaybackThread_l(output);
543    if (thread == NULL) {
544        ALOGW("sampleRate() unknown thread %d", output);
545        return 0;
546    }
547    return thread->sampleRate();
548}
549
550int AudioFlinger::channelCount(audio_io_handle_t output) const
551{
552    Mutex::Autolock _l(mLock);
553    PlaybackThread *thread = checkPlaybackThread_l(output);
554    if (thread == NULL) {
555        ALOGW("channelCount() unknown thread %d", output);
556        return 0;
557    }
558    return thread->channelCount();
559}
560
561audio_format_t AudioFlinger::format(audio_io_handle_t output) const
562{
563    Mutex::Autolock _l(mLock);
564    PlaybackThread *thread = checkPlaybackThread_l(output);
565    if (thread == NULL) {
566        ALOGW("format() unknown thread %d", output);
567        return AUDIO_FORMAT_INVALID;
568    }
569    return thread->format();
570}
571
572size_t AudioFlinger::frameCount(audio_io_handle_t output) const
573{
574    Mutex::Autolock _l(mLock);
575    PlaybackThread *thread = checkPlaybackThread_l(output);
576    if (thread == NULL) {
577        ALOGW("frameCount() unknown thread %d", output);
578        return 0;
579    }
580    // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
581    //       should examine all callers and fix them to handle smaller counts
582    return thread->frameCount();
583}
584
585uint32_t AudioFlinger::latency(audio_io_handle_t output) const
586{
587    Mutex::Autolock _l(mLock);
588    PlaybackThread *thread = checkPlaybackThread_l(output);
589    if (thread == NULL) {
590        ALOGW("latency() unknown thread %d", output);
591        return 0;
592    }
593    return thread->latency();
594}
595
596status_t AudioFlinger::setMasterVolume(float value)
597{
598    status_t ret = initCheck();
599    if (ret != NO_ERROR) {
600        return ret;
601    }
602
603    // check calling permissions
604    if (!settingsAllowed()) {
605        return PERMISSION_DENIED;
606    }
607
608    float swmv = value;
609
610    Mutex::Autolock _l(mLock);
611
612    // when hw supports master volume, don't scale in sw mixer
613    if (MVS_NONE != mMasterVolumeSupportLvl) {
614        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
615            AutoMutex lock(mHardwareLock);
616            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
617
618            mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
619            if (NULL != dev->set_master_volume) {
620                dev->set_master_volume(dev, value);
621            }
622            mHardwareStatus = AUDIO_HW_IDLE;
623        }
624
625        swmv = 1.0;
626    }
627
628    mMasterVolume   = value;
629    mMasterVolumeSW = swmv;
630    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
631        mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
632
633    return NO_ERROR;
634}
635
636status_t AudioFlinger::setMode(audio_mode_t mode)
637{
638    status_t ret = initCheck();
639    if (ret != NO_ERROR) {
640        return ret;
641    }
642
643    // check calling permissions
644    if (!settingsAllowed()) {
645        return PERMISSION_DENIED;
646    }
647    if (uint32_t(mode) >= AUDIO_MODE_CNT) {
648        ALOGW("Illegal value: setMode(%d)", mode);
649        return BAD_VALUE;
650    }
651
652    { // scope for the lock
653        AutoMutex lock(mHardwareLock);
654        mHardwareStatus = AUDIO_HW_SET_MODE;
655        ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
656        mHardwareStatus = AUDIO_HW_IDLE;
657    }
658
659    if (NO_ERROR == ret) {
660        Mutex::Autolock _l(mLock);
661        mMode = mode;
662        for (size_t i = 0; i < mPlaybackThreads.size(); i++)
663            mPlaybackThreads.valueAt(i)->setMode(mode);
664    }
665
666    return ret;
667}
668
669status_t AudioFlinger::setMicMute(bool state)
670{
671    status_t ret = initCheck();
672    if (ret != NO_ERROR) {
673        return ret;
674    }
675
676    // check calling permissions
677    if (!settingsAllowed()) {
678        return PERMISSION_DENIED;
679    }
680
681    AutoMutex lock(mHardwareLock);
682    mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
683    ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
684    mHardwareStatus = AUDIO_HW_IDLE;
685    return ret;
686}
687
688bool AudioFlinger::getMicMute() const
689{
690    status_t ret = initCheck();
691    if (ret != NO_ERROR) {
692        return false;
693    }
694
695    bool state = AUDIO_MODE_INVALID;
696    AutoMutex lock(mHardwareLock);
697    mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
698    mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
699    mHardwareStatus = AUDIO_HW_IDLE;
700    return state;
701}
702
703status_t AudioFlinger::setMasterMute(bool muted)
704{
705    // check calling permissions
706    if (!settingsAllowed()) {
707        return PERMISSION_DENIED;
708    }
709
710    Mutex::Autolock _l(mLock);
711    // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
712    mMasterMute = muted;
713    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
714        mPlaybackThreads.valueAt(i)->setMasterMute(muted);
715
716    return NO_ERROR;
717}
718
719float AudioFlinger::masterVolume() const
720{
721    Mutex::Autolock _l(mLock);
722    return masterVolume_l();
723}
724
725float AudioFlinger::masterVolumeSW() const
726{
727    Mutex::Autolock _l(mLock);
728    return masterVolumeSW_l();
729}
730
731bool AudioFlinger::masterMute() const
732{
733    Mutex::Autolock _l(mLock);
734    return masterMute_l();
735}
736
737float AudioFlinger::masterVolume_l() const
738{
739    if (MVS_FULL == mMasterVolumeSupportLvl) {
740        float ret_val;
741        AutoMutex lock(mHardwareLock);
742
743        mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
744        ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
745                    (NULL != mPrimaryHardwareDev->get_master_volume),
746                "can't get master volume");
747
748        mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
749        mHardwareStatus = AUDIO_HW_IDLE;
750        return ret_val;
751    }
752
753    return mMasterVolume;
754}
755
756status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
757        audio_io_handle_t output)
758{
759    // check calling permissions
760    if (!settingsAllowed()) {
761        return PERMISSION_DENIED;
762    }
763
764    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
765        ALOGE("setStreamVolume() invalid stream %d", stream);
766        return BAD_VALUE;
767    }
768
769    AutoMutex lock(mLock);
770    PlaybackThread *thread = NULL;
771    if (output) {
772        thread = checkPlaybackThread_l(output);
773        if (thread == NULL) {
774            return BAD_VALUE;
775        }
776    }
777
778    mStreamTypes[stream].volume = value;
779
780    if (thread == NULL) {
781        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
782            mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
783        }
784    } else {
785        thread->setStreamVolume(stream, value);
786    }
787
788    return NO_ERROR;
789}
790
791status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
792{
793    // check calling permissions
794    if (!settingsAllowed()) {
795        return PERMISSION_DENIED;
796    }
797
798    if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
799        uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
800        ALOGE("setStreamMute() invalid stream %d", stream);
801        return BAD_VALUE;
802    }
803
804    AutoMutex lock(mLock);
805    mStreamTypes[stream].mute = muted;
806    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
807        mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
808
809    return NO_ERROR;
810}
811
812float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
813{
814    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
815        return 0.0f;
816    }
817
818    AutoMutex lock(mLock);
819    float volume;
820    if (output) {
821        PlaybackThread *thread = checkPlaybackThread_l(output);
822        if (thread == NULL) {
823            return 0.0f;
824        }
825        volume = thread->streamVolume(stream);
826    } else {
827        volume = streamVolume_l(stream);
828    }
829
830    return volume;
831}
832
833bool AudioFlinger::streamMute(audio_stream_type_t stream) const
834{
835    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
836        return true;
837    }
838
839    AutoMutex lock(mLock);
840    return streamMute_l(stream);
841}
842
843status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
844{
845    ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
846            ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
847    // check calling permissions
848    if (!settingsAllowed()) {
849        return PERMISSION_DENIED;
850    }
851
852    // ioHandle == 0 means the parameters are global to the audio hardware interface
853    if (ioHandle == 0) {
854        Mutex::Autolock _l(mLock);
855        status_t final_result = NO_ERROR;
856        {
857            AutoMutex lock(mHardwareLock);
858            mHardwareStatus = AUDIO_HW_SET_PARAMETER;
859            for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
860                audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
861                status_t result = dev->set_parameters(dev, keyValuePairs.string());
862                final_result = result ?: final_result;
863            }
864            mHardwareStatus = AUDIO_HW_IDLE;
865        }
866        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
867        AudioParameter param = AudioParameter(keyValuePairs);
868        String8 value;
869        if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
870            bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
871            if (mBtNrecIsOff != btNrecIsOff) {
872                for (size_t i = 0; i < mRecordThreads.size(); i++) {
873                    sp<RecordThread> thread = mRecordThreads.valueAt(i);
874                    RecordThread::RecordTrack *track = thread->track();
875                    if (track != NULL) {
876                        audio_devices_t device = thread->device() & AUDIO_DEVICE_IN_ALL;
877                        bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
878                        thread->setEffectSuspended(FX_IID_AEC,
879                                                   suspend,
880                                                   track->sessionId());
881                        thread->setEffectSuspended(FX_IID_NS,
882                                                   suspend,
883                                                   track->sessionId());
884                    }
885                }
886                mBtNrecIsOff = btNrecIsOff;
887            }
888        }
889        String8 screenState;
890        if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
891            bool isOff = screenState == "off";
892            if (isOff != (gScreenState & 1)) {
893                gScreenState = ((gScreenState & ~1) + 2) | isOff;
894            }
895        }
896        return final_result;
897    }
898
899    // hold a strong ref on thread in case closeOutput() or closeInput() is called
900    // and the thread is exited once the lock is released
901    sp<ThreadBase> thread;
902    {
903        Mutex::Autolock _l(mLock);
904        thread = checkPlaybackThread_l(ioHandle);
905        if (thread == 0) {
906            thread = checkRecordThread_l(ioHandle);
907        } else if (thread == primaryPlaybackThread_l()) {
908            // indicate output device change to all input threads for pre processing
909            AudioParameter param = AudioParameter(keyValuePairs);
910            int value;
911            if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
912                    (value != 0)) {
913                for (size_t i = 0; i < mRecordThreads.size(); i++) {
914                    mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
915                }
916            }
917        }
918    }
919    if (thread != 0) {
920        return thread->setParameters(keyValuePairs);
921    }
922    return BAD_VALUE;
923}
924
925String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
926{
927//    ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
928//            ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
929
930    Mutex::Autolock _l(mLock);
931
932    if (ioHandle == 0) {
933        String8 out_s8;
934
935        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
936            char *s;
937            {
938            AutoMutex lock(mHardwareLock);
939            mHardwareStatus = AUDIO_HW_GET_PARAMETER;
940            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
941            s = dev->get_parameters(dev, keys.string());
942            mHardwareStatus = AUDIO_HW_IDLE;
943            }
944            out_s8 += String8(s ? s : "");
945            free(s);
946        }
947        return out_s8;
948    }
949
950    PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
951    if (playbackThread != NULL) {
952        return playbackThread->getParameters(keys);
953    }
954    RecordThread *recordThread = checkRecordThread_l(ioHandle);
955    if (recordThread != NULL) {
956        return recordThread->getParameters(keys);
957    }
958    return String8("");
959}
960
961size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
962        audio_channel_mask_t channelMask) const
963{
964    status_t ret = initCheck();
965    if (ret != NO_ERROR) {
966        return 0;
967    }
968
969    AutoMutex lock(mHardwareLock);
970    mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
971    struct audio_config config = {
972        sample_rate: sampleRate,
973        channel_mask: channelMask,
974        format: format,
975    };
976    size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
977    mHardwareStatus = AUDIO_HW_IDLE;
978    return size;
979}
980
981unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
982{
983    Mutex::Autolock _l(mLock);
984
985    RecordThread *recordThread = checkRecordThread_l(ioHandle);
986    if (recordThread != NULL) {
987        return recordThread->getInputFramesLost();
988    }
989    return 0;
990}
991
992status_t AudioFlinger::setVoiceVolume(float value)
993{
994    status_t ret = initCheck();
995    if (ret != NO_ERROR) {
996        return ret;
997    }
998
999    // check calling permissions
1000    if (!settingsAllowed()) {
1001        return PERMISSION_DENIED;
1002    }
1003
1004    AutoMutex lock(mHardwareLock);
1005    mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
1006    ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
1007    mHardwareStatus = AUDIO_HW_IDLE;
1008
1009    return ret;
1010}
1011
1012status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1013        audio_io_handle_t output) const
1014{
1015    status_t status;
1016
1017    Mutex::Autolock _l(mLock);
1018
1019    PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1020    if (playbackThread != NULL) {
1021        return playbackThread->getRenderPosition(halFrames, dspFrames);
1022    }
1023
1024    return BAD_VALUE;
1025}
1026
1027void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1028{
1029
1030    Mutex::Autolock _l(mLock);
1031
1032    pid_t pid = IPCThreadState::self()->getCallingPid();
1033    if (mNotificationClients.indexOfKey(pid) < 0) {
1034        sp<NotificationClient> notificationClient = new NotificationClient(this,
1035                                                                            client,
1036                                                                            pid);
1037        ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
1038
1039        mNotificationClients.add(pid, notificationClient);
1040
1041        sp<IBinder> binder = client->asBinder();
1042        binder->linkToDeath(notificationClient);
1043
1044        // the config change is always sent from playback or record threads to avoid deadlock
1045        // with AudioSystem::gLock
1046        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1047            mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1048        }
1049
1050        for (size_t i = 0; i < mRecordThreads.size(); i++) {
1051            mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1052        }
1053    }
1054}
1055
1056void AudioFlinger::removeNotificationClient(pid_t pid)
1057{
1058    Mutex::Autolock _l(mLock);
1059
1060    mNotificationClients.removeItem(pid);
1061
1062    ALOGV("%d died, releasing its sessions", pid);
1063    size_t num = mAudioSessionRefs.size();
1064    bool removed = false;
1065    for (size_t i = 0; i< num; ) {
1066        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1067        ALOGV(" pid %d @ %d", ref->mPid, i);
1068        if (ref->mPid == pid) {
1069            ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1070            mAudioSessionRefs.removeAt(i);
1071            delete ref;
1072            removed = true;
1073            num--;
1074        } else {
1075            i++;
1076        }
1077    }
1078    if (removed) {
1079        purgeStaleEffects_l();
1080    }
1081}
1082
1083// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1084void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
1085{
1086    size_t size = mNotificationClients.size();
1087    for (size_t i = 0; i < size; i++) {
1088        mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1089                                                                               param2);
1090    }
1091}
1092
1093// removeClient_l() must be called with AudioFlinger::mLock held
1094void AudioFlinger::removeClient_l(pid_t pid)
1095{
1096    ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
1097    mClients.removeItem(pid);
1098}
1099
1100// getEffectThread_l() must be called with AudioFlinger::mLock held
1101sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1102{
1103    sp<PlaybackThread> thread;
1104
1105    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1106        if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1107            ALOG_ASSERT(thread == 0);
1108            thread = mPlaybackThreads.valueAt(i);
1109        }
1110    }
1111
1112    return thread;
1113}
1114
1115// ----------------------------------------------------------------------------
1116
1117AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1118        audio_devices_t device, type_t type)
1119    :   Thread(false),
1120        mType(type),
1121        mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
1122        // mChannelMask
1123        mChannelCount(0),
1124        mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1125        mParamStatus(NO_ERROR),
1126        mStandby(false), mDevice((audio_devices_t) device), mId(id),
1127        mDeathRecipient(new PMDeathRecipient(this))
1128{
1129}
1130
1131AudioFlinger::ThreadBase::~ThreadBase()
1132{
1133    mParamCond.broadcast();
1134    // do not lock the mutex in destructor
1135    releaseWakeLock_l();
1136    if (mPowerManager != 0) {
1137        sp<IBinder> binder = mPowerManager->asBinder();
1138        binder->unlinkToDeath(mDeathRecipient);
1139    }
1140}
1141
1142void AudioFlinger::ThreadBase::exit()
1143{
1144    ALOGV("ThreadBase::exit");
1145    {
1146        // This lock prevents the following race in thread (uniprocessor for illustration):
1147        //  if (!exitPending()) {
1148        //      // context switch from here to exit()
1149        //      // exit() calls requestExit(), what exitPending() observes
1150        //      // exit() calls signal(), which is dropped since no waiters
1151        //      // context switch back from exit() to here
1152        //      mWaitWorkCV.wait(...);
1153        //      // now thread is hung
1154        //  }
1155        AutoMutex lock(mLock);
1156        requestExit();
1157        mWaitWorkCV.signal();
1158    }
1159    // When Thread::requestExitAndWait is made virtual and this method is renamed to
1160    // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
1161    requestExitAndWait();
1162}
1163
1164status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1165{
1166    status_t status;
1167
1168    ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1169    Mutex::Autolock _l(mLock);
1170
1171    mNewParameters.add(keyValuePairs);
1172    mWaitWorkCV.signal();
1173    // wait condition with timeout in case the thread loop has exited
1174    // before the request could be processed
1175    if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
1176        status = mParamStatus;
1177        mWaitWorkCV.signal();
1178    } else {
1179        status = TIMED_OUT;
1180    }
1181    return status;
1182}
1183
1184void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1185{
1186    Mutex::Autolock _l(mLock);
1187    sendConfigEvent_l(event, param);
1188}
1189
1190// sendConfigEvent_l() must be called with ThreadBase::mLock held
1191void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1192{
1193    ConfigEvent configEvent;
1194    configEvent.mEvent = event;
1195    configEvent.mParam = param;
1196    mConfigEvents.add(configEvent);
1197    ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1198    mWaitWorkCV.signal();
1199}
1200
1201void AudioFlinger::ThreadBase::processConfigEvents()
1202{
1203    mLock.lock();
1204    while (!mConfigEvents.isEmpty()) {
1205        ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1206        ConfigEvent configEvent = mConfigEvents[0];
1207        mConfigEvents.removeAt(0);
1208        // release mLock before locking AudioFlinger mLock: lock order is always
1209        // AudioFlinger then ThreadBase to avoid cross deadlock
1210        mLock.unlock();
1211        mAudioFlinger->mLock.lock();
1212        audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
1213        mAudioFlinger->mLock.unlock();
1214        mLock.lock();
1215    }
1216    mLock.unlock();
1217}
1218
1219status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1220{
1221    const size_t SIZE = 256;
1222    char buffer[SIZE];
1223    String8 result;
1224
1225    bool locked = tryLock(mLock);
1226    if (!locked) {
1227        snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1228        write(fd, buffer, strlen(buffer));
1229    }
1230
1231    snprintf(buffer, SIZE, "io handle: %d\n", mId);
1232    result.append(buffer);
1233    snprintf(buffer, SIZE, "TID: %d\n", getTid());
1234    result.append(buffer);
1235    snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1236    result.append(buffer);
1237    snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1238    result.append(buffer);
1239    snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1240    result.append(buffer);
1241    snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
1242    result.append(buffer);
1243    snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1244    result.append(buffer);
1245    snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1246    result.append(buffer);
1247    snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1248    result.append(buffer);
1249    snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
1250    result.append(buffer);
1251
1252    snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1253    result.append(buffer);
1254    result.append(" Index Command");
1255    for (size_t i = 0; i < mNewParameters.size(); ++i) {
1256        snprintf(buffer, SIZE, "\n %02d    ", i);
1257        result.append(buffer);
1258        result.append(mNewParameters[i]);
1259    }
1260
1261    snprintf(buffer, SIZE, "\n\nPending config events: \n");
1262    result.append(buffer);
1263    snprintf(buffer, SIZE, " Index event param\n");
1264    result.append(buffer);
1265    for (size_t i = 0; i < mConfigEvents.size(); i++) {
1266        snprintf(buffer, SIZE, " %02d    %02d    %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
1267        result.append(buffer);
1268    }
1269    result.append("\n");
1270
1271    write(fd, result.string(), result.size());
1272
1273    if (locked) {
1274        mLock.unlock();
1275    }
1276    return NO_ERROR;
1277}
1278
1279status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1280{
1281    const size_t SIZE = 256;
1282    char buffer[SIZE];
1283    String8 result;
1284
1285    snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1286    write(fd, buffer, strlen(buffer));
1287
1288    for (size_t i = 0; i < mEffectChains.size(); ++i) {
1289        sp<EffectChain> chain = mEffectChains[i];
1290        if (chain != 0) {
1291            chain->dump(fd, args);
1292        }
1293    }
1294    return NO_ERROR;
1295}
1296
1297void AudioFlinger::ThreadBase::acquireWakeLock()
1298{
1299    Mutex::Autolock _l(mLock);
1300    acquireWakeLock_l();
1301}
1302
1303void AudioFlinger::ThreadBase::acquireWakeLock_l()
1304{
1305    if (mPowerManager == 0) {
1306        // use checkService() to avoid blocking if power service is not up yet
1307        sp<IBinder> binder =
1308            defaultServiceManager()->checkService(String16("power"));
1309        if (binder == 0) {
1310            ALOGW("Thread %s cannot connect to the power manager service", mName);
1311        } else {
1312            mPowerManager = interface_cast<IPowerManager>(binder);
1313            binder->linkToDeath(mDeathRecipient);
1314        }
1315    }
1316    if (mPowerManager != 0) {
1317        sp<IBinder> binder = new BBinder();
1318        status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1319                                                         binder,
1320                                                         String16(mName));
1321        if (status == NO_ERROR) {
1322            mWakeLockToken = binder;
1323        }
1324        ALOGV("acquireWakeLock_l() %s status %d", mName, status);
1325    }
1326}
1327
1328void AudioFlinger::ThreadBase::releaseWakeLock()
1329{
1330    Mutex::Autolock _l(mLock);
1331    releaseWakeLock_l();
1332}
1333
1334void AudioFlinger::ThreadBase::releaseWakeLock_l()
1335{
1336    if (mWakeLockToken != 0) {
1337        ALOGV("releaseWakeLock_l() %s", mName);
1338        if (mPowerManager != 0) {
1339            mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1340        }
1341        mWakeLockToken.clear();
1342    }
1343}
1344
1345void AudioFlinger::ThreadBase::clearPowerManager()
1346{
1347    Mutex::Autolock _l(mLock);
1348    releaseWakeLock_l();
1349    mPowerManager.clear();
1350}
1351
1352void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1353{
1354    sp<ThreadBase> thread = mThread.promote();
1355    if (thread != 0) {
1356        thread->clearPowerManager();
1357    }
1358    ALOGW("power manager service died !!!");
1359}
1360
1361void AudioFlinger::ThreadBase::setEffectSuspended(
1362        const effect_uuid_t *type, bool suspend, int sessionId)
1363{
1364    Mutex::Autolock _l(mLock);
1365    setEffectSuspended_l(type, suspend, sessionId);
1366}
1367
1368void AudioFlinger::ThreadBase::setEffectSuspended_l(
1369        const effect_uuid_t *type, bool suspend, int sessionId)
1370{
1371    sp<EffectChain> chain = getEffectChain_l(sessionId);
1372    if (chain != 0) {
1373        if (type != NULL) {
1374            chain->setEffectSuspended_l(type, suspend);
1375        } else {
1376            chain->setEffectSuspendedAll_l(suspend);
1377        }
1378    }
1379
1380    updateSuspendedSessions_l(type, suspend, sessionId);
1381}
1382
1383void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1384{
1385    ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1386    if (index < 0) {
1387        return;
1388    }
1389
1390    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1391            mSuspendedSessions.editValueAt(index);
1392
1393    for (size_t i = 0; i < sessionEffects.size(); i++) {
1394        sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1395        for (int j = 0; j < desc->mRefCount; j++) {
1396            if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1397                chain->setEffectSuspendedAll_l(true);
1398            } else {
1399                ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1400                    desc->mType.timeLow);
1401                chain->setEffectSuspended_l(&desc->mType, true);
1402            }
1403        }
1404    }
1405}
1406
1407void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1408                                                         bool suspend,
1409                                                         int sessionId)
1410{
1411    ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1412
1413    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1414
1415    if (suspend) {
1416        if (index >= 0) {
1417            sessionEffects = mSuspendedSessions.editValueAt(index);
1418        } else {
1419            mSuspendedSessions.add(sessionId, sessionEffects);
1420        }
1421    } else {
1422        if (index < 0) {
1423            return;
1424        }
1425        sessionEffects = mSuspendedSessions.editValueAt(index);
1426    }
1427
1428
1429    int key = EffectChain::kKeyForSuspendAll;
1430    if (type != NULL) {
1431        key = type->timeLow;
1432    }
1433    index = sessionEffects.indexOfKey(key);
1434
1435    sp<SuspendedSessionDesc> desc;
1436    if (suspend) {
1437        if (index >= 0) {
1438            desc = sessionEffects.valueAt(index);
1439        } else {
1440            desc = new SuspendedSessionDesc();
1441            if (type != NULL) {
1442                desc->mType = *type;
1443            }
1444            sessionEffects.add(key, desc);
1445            ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1446        }
1447        desc->mRefCount++;
1448    } else {
1449        if (index < 0) {
1450            return;
1451        }
1452        desc = sessionEffects.valueAt(index);
1453        if (--desc->mRefCount == 0) {
1454            ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1455            sessionEffects.removeItemsAt(index);
1456            if (sessionEffects.isEmpty()) {
1457                ALOGV("updateSuspendedSessions_l() restore removing session %d",
1458                                 sessionId);
1459                mSuspendedSessions.removeItem(sessionId);
1460            }
1461        }
1462    }
1463    if (!sessionEffects.isEmpty()) {
1464        mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1465    }
1466}
1467
1468void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1469                                                            bool enabled,
1470                                                            int sessionId)
1471{
1472    Mutex::Autolock _l(mLock);
1473    checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1474}
1475
1476void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1477                                                            bool enabled,
1478                                                            int sessionId)
1479{
1480    if (mType != RECORD) {
1481        // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1482        // another session. This gives the priority to well behaved effect control panels
1483        // and applications not using global effects.
1484        // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1485        // global effects
1486        if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1487            setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1488        }
1489    }
1490
1491    sp<EffectChain> chain = getEffectChain_l(sessionId);
1492    if (chain != 0) {
1493        chain->checkSuspendOnEffectEnabled(effect, enabled);
1494    }
1495}
1496
1497// ----------------------------------------------------------------------------
1498
1499AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1500                                             AudioStreamOut* output,
1501                                             audio_io_handle_t id,
1502                                             audio_devices_t device,
1503                                             type_t type)
1504    :   ThreadBase(audioFlinger, id, device, type),
1505        mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1506        // Assumes constructor is called by AudioFlinger with it's mLock held,
1507        // but it would be safer to explicitly pass initial masterMute as parameter
1508        mMasterMute(audioFlinger->masterMute_l()),
1509        // mStreamTypes[] initialized in constructor body
1510        mOutput(output),
1511        // Assumes constructor is called by AudioFlinger with it's mLock held,
1512        // but it would be safer to explicitly pass initial masterVolume as parameter
1513        mMasterVolume(audioFlinger->masterVolumeSW_l()),
1514        mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1515        mMixerStatus(MIXER_IDLE),
1516        mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1517        standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
1518        mScreenState(gScreenState),
1519        // index 0 is reserved for normal mixer's submix
1520        mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
1521{
1522    snprintf(mName, kNameLength, "AudioOut_%X", id);
1523
1524    readOutputParameters();
1525
1526    // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1527    // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1528    for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1529            stream = (audio_stream_type_t) (stream + 1)) {
1530        mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1531        mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1532    }
1533    // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1534    // because mAudioFlinger doesn't have one to copy from
1535}
1536
1537AudioFlinger::PlaybackThread::~PlaybackThread()
1538{
1539    delete [] mMixBuffer;
1540}
1541
1542status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1543{
1544    dumpInternals(fd, args);
1545    dumpTracks(fd, args);
1546    dumpEffectChains(fd, args);
1547    return NO_ERROR;
1548}
1549
1550status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1551{
1552    const size_t SIZE = 256;
1553    char buffer[SIZE];
1554    String8 result;
1555
1556    result.appendFormat("Output thread %p stream volumes in dB:\n    ", this);
1557    for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1558        const stream_type_t *st = &mStreamTypes[i];
1559        if (i > 0) {
1560            result.appendFormat(", ");
1561        }
1562        result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1563        if (st->mute) {
1564            result.append("M");
1565        }
1566    }
1567    result.append("\n");
1568    write(fd, result.string(), result.length());
1569    result.clear();
1570
1571    snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1572    result.append(buffer);
1573    Track::appendDumpHeader(result);
1574    for (size_t i = 0; i < mTracks.size(); ++i) {
1575        sp<Track> track = mTracks[i];
1576        if (track != 0) {
1577            track->dump(buffer, SIZE);
1578            result.append(buffer);
1579        }
1580    }
1581
1582    snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1583    result.append(buffer);
1584    Track::appendDumpHeader(result);
1585    for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1586        sp<Track> track = mActiveTracks[i].promote();
1587        if (track != 0) {
1588            track->dump(buffer, SIZE);
1589            result.append(buffer);
1590        }
1591    }
1592    write(fd, result.string(), result.size());
1593
1594    // These values are "raw"; they will wrap around.  See prepareTracks_l() for a better way.
1595    FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1596    fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1597            underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
1598
1599    return NO_ERROR;
1600}
1601
1602status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1603{
1604    const size_t SIZE = 256;
1605    char buffer[SIZE];
1606    String8 result;
1607
1608    snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1609    result.append(buffer);
1610    snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1611    result.append(buffer);
1612    snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1613    result.append(buffer);
1614    snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1615    result.append(buffer);
1616    snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1617    result.append(buffer);
1618    snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1619    result.append(buffer);
1620    snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1621    result.append(buffer);
1622    write(fd, result.string(), result.size());
1623    fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
1624
1625    dumpBase(fd, args);
1626
1627    return NO_ERROR;
1628}
1629
1630// Thread virtuals
1631status_t AudioFlinger::PlaybackThread::readyToRun()
1632{
1633    status_t status = initCheck();
1634    if (status == NO_ERROR) {
1635        ALOGI("AudioFlinger's thread %p ready to run", this);
1636    } else {
1637        ALOGE("No working audio driver found.");
1638    }
1639    return status;
1640}
1641
1642void AudioFlinger::PlaybackThread::onFirstRef()
1643{
1644    run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1645}
1646
1647// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1648sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1649        const sp<AudioFlinger::Client>& client,
1650        audio_stream_type_t streamType,
1651        uint32_t sampleRate,
1652        audio_format_t format,
1653        audio_channel_mask_t channelMask,
1654        int frameCount,
1655        const sp<IMemory>& sharedBuffer,
1656        int sessionId,
1657        IAudioFlinger::track_flags_t flags,
1658        pid_t tid,
1659        status_t *status)
1660{
1661    sp<Track> track;
1662    status_t lStatus;
1663
1664    bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1665
1666    // client expresses a preference for FAST, but we get the final say
1667    if (flags & IAudioFlinger::TRACK_FAST) {
1668      if (
1669            // not timed
1670            (!isTimed) &&
1671            // either of these use cases:
1672            (
1673              // use case 1: shared buffer with any frame count
1674              (
1675                (sharedBuffer != 0)
1676              ) ||
1677              // use case 2: callback handler and frame count is default or at least as large as HAL
1678              (
1679                (tid != -1) &&
1680                ((frameCount == 0) ||
1681                (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
1682              )
1683            ) &&
1684            // PCM data
1685            audio_is_linear_pcm(format) &&
1686            // mono or stereo
1687            ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1688              (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
1689#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
1690            // hardware sample rate
1691            (sampleRate == mSampleRate) &&
1692#endif
1693            // normal mixer has an associated fast mixer
1694            hasFastMixer() &&
1695            // there are sufficient fast track slots available
1696            (mFastTrackAvailMask != 0)
1697            // FIXME test that MixerThread for this fast track has a capable output HAL
1698            // FIXME add a permission test also?
1699        ) {
1700        // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1701        if (frameCount == 0) {
1702            frameCount = mFrameCount * 2;   // FIXME * 2 is due to SRC jitter, should be computed
1703        }
1704        ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1705                frameCount, mFrameCount);
1706      } else {
1707        ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1708                "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
1709                "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1710                isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1711                audio_is_linear_pcm(format),
1712                channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1713        flags &= ~IAudioFlinger::TRACK_FAST;
1714        // For compatibility with AudioTrack calculation, buffer depth is forced
1715        // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1716        // This is probably too conservative, but legacy application code may depend on it.
1717        // If you change this calculation, also review the start threshold which is related.
1718        uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1719        uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1720        if (minBufCount < 2) {
1721            minBufCount = 2;
1722        }
1723        int minFrameCount = mNormalFrameCount * minBufCount;
1724        if (frameCount < minFrameCount) {
1725            frameCount = minFrameCount;
1726        }
1727      }
1728    }
1729
1730    if (mType == DIRECT) {
1731        if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1732            if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1733                ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1734                        "for output %p with format %d",
1735                        sampleRate, format, channelMask, mOutput, mFormat);
1736                lStatus = BAD_VALUE;
1737                goto Exit;
1738            }
1739        }
1740    } else {
1741        // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1742        if (sampleRate > mSampleRate*2) {
1743            ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1744            lStatus = BAD_VALUE;
1745            goto Exit;
1746        }
1747    }
1748
1749    lStatus = initCheck();
1750    if (lStatus != NO_ERROR) {
1751        ALOGE("Audio driver not initialized.");
1752        goto Exit;
1753    }
1754
1755    { // scope for mLock
1756        Mutex::Autolock _l(mLock);
1757
1758        // all tracks in same audio session must share the same routing strategy otherwise
1759        // conflicts will happen when tracks are moved from one output to another by audio policy
1760        // manager
1761        uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1762        for (size_t i = 0; i < mTracks.size(); ++i) {
1763            sp<Track> t = mTracks[i];
1764            if (t != 0 && !t->isOutputTrack()) {
1765                uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1766                if (sessionId == t->sessionId() && strategy != actual) {
1767                    ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1768                            strategy, actual);
1769                    lStatus = BAD_VALUE;
1770                    goto Exit;
1771                }
1772            }
1773        }
1774
1775        if (!isTimed) {
1776            track = new Track(this, client, streamType, sampleRate, format,
1777                    channelMask, frameCount, sharedBuffer, sessionId, flags);
1778        } else {
1779            track = TimedTrack::create(this, client, streamType, sampleRate, format,
1780                    channelMask, frameCount, sharedBuffer, sessionId);
1781        }
1782        if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
1783            lStatus = NO_MEMORY;
1784            goto Exit;
1785        }
1786        mTracks.add(track);
1787
1788        sp<EffectChain> chain = getEffectChain_l(sessionId);
1789        if (chain != 0) {
1790            ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1791            track->setMainBuffer(chain->inBuffer());
1792            chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1793            chain->incTrackCnt();
1794        }
1795    }
1796
1797    if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1798        pid_t callingPid = IPCThreadState::self()->getCallingPid();
1799        // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1800        // so ask activity manager to do this on our behalf
1801        int err = requestPriority(callingPid, tid, kPriorityAudioApp);
1802        if (err != 0) {
1803            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1804                    kPriorityAudioApp, callingPid, tid, err);
1805        }
1806    }
1807
1808    lStatus = NO_ERROR;
1809
1810Exit:
1811    if (status) {
1812        *status = lStatus;
1813    }
1814    return track;
1815}
1816
1817uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1818{
1819    if (mFastMixer != NULL) {
1820        MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1821        latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1822    }
1823    return latency;
1824}
1825
1826uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1827{
1828    return latency;
1829}
1830
1831uint32_t AudioFlinger::PlaybackThread::latency() const
1832{
1833    Mutex::Autolock _l(mLock);
1834    return latency_l();
1835}
1836uint32_t AudioFlinger::PlaybackThread::latency_l() const
1837{
1838    if (initCheck() == NO_ERROR) {
1839        return correctLatency(mOutput->stream->get_latency(mOutput->stream));
1840    } else {
1841        return 0;
1842    }
1843}
1844
1845void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1846{
1847    Mutex::Autolock _l(mLock);
1848    mMasterVolume = value;
1849}
1850
1851void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1852{
1853    Mutex::Autolock _l(mLock);
1854    setMasterMute_l(muted);
1855}
1856
1857void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1858{
1859    Mutex::Autolock _l(mLock);
1860    mStreamTypes[stream].volume = value;
1861}
1862
1863void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1864{
1865    Mutex::Autolock _l(mLock);
1866    mStreamTypes[stream].mute = muted;
1867}
1868
1869float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1870{
1871    Mutex::Autolock _l(mLock);
1872    return mStreamTypes[stream].volume;
1873}
1874
1875// addTrack_l() must be called with ThreadBase::mLock held
1876status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1877{
1878    status_t status = ALREADY_EXISTS;
1879
1880    // set retry count for buffer fill
1881    track->mRetryCount = kMaxTrackStartupRetries;
1882    if (mActiveTracks.indexOf(track) < 0) {
1883        // the track is newly added, make sure it fills up all its
1884        // buffers before playing. This is to ensure the client will
1885        // effectively get the latency it requested.
1886        track->mFillingUpStatus = Track::FS_FILLING;
1887        track->mResetDone = false;
1888        track->mPresentationCompleteFrames = 0;
1889        mActiveTracks.add(track);
1890        if (track->mainBuffer() != mMixBuffer) {
1891            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1892            if (chain != 0) {
1893                ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1894                chain->incActiveTrackCnt();
1895            }
1896        }
1897
1898        status = NO_ERROR;
1899    }
1900
1901    ALOGV("mWaitWorkCV.broadcast");
1902    mWaitWorkCV.broadcast();
1903
1904    return status;
1905}
1906
1907// destroyTrack_l() must be called with ThreadBase::mLock held
1908void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1909{
1910    track->mState = TrackBase::TERMINATED;
1911    // active tracks are removed by threadLoop()
1912    if (mActiveTracks.indexOf(track) < 0) {
1913        removeTrack_l(track);
1914    }
1915}
1916
1917void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1918{
1919    track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1920    mTracks.remove(track);
1921    deleteTrackName_l(track->name());
1922    // redundant as track is about to be destroyed, for dumpsys only
1923    track->mName = -1;
1924    if (track->isFastTrack()) {
1925        int index = track->mFastIndex;
1926        ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1927        ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1928        mFastTrackAvailMask |= 1 << index;
1929        // redundant as track is about to be destroyed, for dumpsys only
1930        track->mFastIndex = -1;
1931    }
1932    sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1933    if (chain != 0) {
1934        chain->decTrackCnt();
1935    }
1936}
1937
1938String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1939{
1940    String8 out_s8 = String8("");
1941    char *s;
1942
1943    Mutex::Autolock _l(mLock);
1944    if (initCheck() != NO_ERROR) {
1945        return out_s8;
1946    }
1947
1948    s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1949    out_s8 = String8(s);
1950    free(s);
1951    return out_s8;
1952}
1953
1954// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1955void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1956    AudioSystem::OutputDescriptor desc;
1957    void *param2 = NULL;
1958
1959    ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1960
1961    switch (event) {
1962    case AudioSystem::OUTPUT_OPENED:
1963    case AudioSystem::OUTPUT_CONFIG_CHANGED:
1964        desc.channels = mChannelMask;
1965        desc.samplingRate = mSampleRate;
1966        desc.format = mFormat;
1967        desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
1968        desc.latency = latency();
1969        param2 = &desc;
1970        break;
1971
1972    case AudioSystem::STREAM_CONFIG_CHANGED:
1973        param2 = &param;
1974    case AudioSystem::OUTPUT_CLOSED:
1975    default:
1976        break;
1977    }
1978    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1979}
1980
1981void AudioFlinger::PlaybackThread::readOutputParameters()
1982{
1983    mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1984    mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1985    mChannelCount = (uint16_t)popcount(mChannelMask);
1986    mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1987    mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1988    mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1989    if (mFrameCount & 15) {
1990        ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1991                mFrameCount);
1992    }
1993
1994    // Calculate size of normal mix buffer relative to the HAL output buffer size
1995    double multiplier = 1.0;
1996    if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
1997        size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1998        size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
1999        // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2000        minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2001        maxNormalFrameCount = maxNormalFrameCount & ~15;
2002        if (maxNormalFrameCount < minNormalFrameCount) {
2003            maxNormalFrameCount = minNormalFrameCount;
2004        }
2005        multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2006        if (multiplier <= 1.0) {
2007            multiplier = 1.0;
2008        } else if (multiplier <= 2.0) {
2009            if (2 * mFrameCount <= maxNormalFrameCount) {
2010                multiplier = 2.0;
2011            } else {
2012                multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2013            }
2014        } else {
2015            // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2016            // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2017            // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2018            // FIXME this rounding up should not be done if no HAL SRC
2019            uint32_t truncMult = (uint32_t) multiplier;
2020            if ((truncMult & 1)) {
2021                if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2022                    ++truncMult;
2023                }
2024            }
2025            multiplier = (double) truncMult;
2026        }
2027    }
2028    mNormalFrameCount = multiplier * mFrameCount;
2029    // round up to nearest 16 frames to satisfy AudioMixer
2030    mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2031    ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
2032
2033    delete[] mMixBuffer;
2034    mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2035    memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
2036
2037    // force reconfiguration of effect chains and engines to take new buffer size and audio
2038    // parameters into account
2039    // Note that mLock is not held when readOutputParameters() is called from the constructor
2040    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2041    // matter.
2042    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2043    Vector< sp<EffectChain> > effectChains = mEffectChains;
2044    for (size_t i = 0; i < effectChains.size(); i ++) {
2045        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2046    }
2047}
2048
2049
2050status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2051{
2052    if (halFrames == NULL || dspFrames == NULL) {
2053        return BAD_VALUE;
2054    }
2055    Mutex::Autolock _l(mLock);
2056    if (initCheck() != NO_ERROR) {
2057        return INVALID_OPERATION;
2058    }
2059    *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2060
2061    return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2062}
2063
2064uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
2065{
2066    Mutex::Autolock _l(mLock);
2067    uint32_t result = 0;
2068    if (getEffectChain_l(sessionId) != 0) {
2069        result = EFFECT_SESSION;
2070    }
2071
2072    for (size_t i = 0; i < mTracks.size(); ++i) {
2073        sp<Track> track = mTracks[i];
2074        if (sessionId == track->sessionId() &&
2075                !(track->mCblk->flags & CBLK_INVALID_MSK)) {
2076            result |= TRACK_SESSION;
2077            break;
2078        }
2079    }
2080
2081    return result;
2082}
2083
2084uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2085{
2086    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2087    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2088    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2089        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2090    }
2091    for (size_t i = 0; i < mTracks.size(); i++) {
2092        sp<Track> track = mTracks[i];
2093        if (sessionId == track->sessionId() &&
2094                !(track->mCblk->flags & CBLK_INVALID_MSK)) {
2095            return AudioSystem::getStrategyForStream(track->streamType());
2096        }
2097    }
2098    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2099}
2100
2101
2102AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2103{
2104    Mutex::Autolock _l(mLock);
2105    return mOutput;
2106}
2107
2108AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2109{
2110    Mutex::Autolock _l(mLock);
2111    AudioStreamOut *output = mOutput;
2112    mOutput = NULL;
2113    // FIXME FastMixer might also have a raw ptr to mOutputSink;
2114    //       must push a NULL and wait for ack
2115    mOutputSink.clear();
2116    mPipeSink.clear();
2117    mNormalSink.clear();
2118    return output;
2119}
2120
2121// this method must always be called either with ThreadBase mLock held or inside the thread loop
2122audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2123{
2124    if (mOutput == NULL) {
2125        return NULL;
2126    }
2127    return &mOutput->stream->common;
2128}
2129
2130uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2131{
2132    return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2133}
2134
2135status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2136{
2137    if (!isValidSyncEvent(event)) {
2138        return BAD_VALUE;
2139    }
2140
2141    Mutex::Autolock _l(mLock);
2142
2143    for (size_t i = 0; i < mTracks.size(); ++i) {
2144        sp<Track> track = mTracks[i];
2145        if (event->triggerSession() == track->sessionId()) {
2146            track->setSyncEvent(event);
2147            return NO_ERROR;
2148        }
2149    }
2150
2151    return NAME_NOT_FOUND;
2152}
2153
2154bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2155{
2156    switch (event->type()) {
2157    case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2158        return true;
2159    default:
2160        break;
2161    }
2162    return false;
2163}
2164
2165void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2166{
2167    size_t count = tracksToRemove.size();
2168    if (CC_UNLIKELY(count)) {
2169        for (size_t i = 0 ; i < count ; i++) {
2170            const sp<Track>& track = tracksToRemove.itemAt(i);
2171            if ((track->sharedBuffer() != 0) &&
2172                    (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2173                AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2174            }
2175        }
2176    }
2177
2178}
2179
2180// ----------------------------------------------------------------------------
2181
2182AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2183        audio_io_handle_t id, audio_devices_t device, type_t type)
2184    :   PlaybackThread(audioFlinger, output, id, device, type),
2185        // mAudioMixer below
2186        // mFastMixer below
2187        mFastMixerFutex(0)
2188        // mOutputSink below
2189        // mPipeSink below
2190        // mNormalSink below
2191{
2192    ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
2193    ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2194            "mFrameCount=%d, mNormalFrameCount=%d",
2195            mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2196            mNormalFrameCount);
2197    mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2198
2199    // FIXME - Current mixer implementation only supports stereo output
2200    if (mChannelCount != FCC_2) {
2201        ALOGE("Invalid audio hardware channel count %d", mChannelCount);
2202    }
2203
2204    // create an NBAIO sink for the HAL output stream, and negotiate
2205    mOutputSink = new AudioStreamOutSink(output->stream);
2206    size_t numCounterOffers = 0;
2207    const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2208    ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2209    ALOG_ASSERT(index == 0);
2210
2211    // initialize fast mixer depending on configuration
2212    bool initFastMixer;
2213    switch (kUseFastMixer) {
2214    case FastMixer_Never:
2215        initFastMixer = false;
2216        break;
2217    case FastMixer_Always:
2218        initFastMixer = true;
2219        break;
2220    case FastMixer_Static:
2221    case FastMixer_Dynamic:
2222        initFastMixer = mFrameCount < mNormalFrameCount;
2223        break;
2224    }
2225    if (initFastMixer) {
2226
2227        // create a MonoPipe to connect our submix to FastMixer
2228        NBAIO_Format format = mOutputSink->format();
2229        // This pipe depth compensates for scheduling latency of the normal mixer thread.
2230        // When it wakes up after a maximum latency, it runs a few cycles quickly before
2231        // finally blocking.  Note the pipe implementation rounds up the request to a power of 2.
2232        MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
2233        const NBAIO_Format offers[1] = {format};
2234        size_t numCounterOffers = 0;
2235        ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2236        ALOG_ASSERT(index == 0);
2237        monoPipe->setAvgFrames((mScreenState & 1) ?
2238                (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2239        mPipeSink = monoPipe;
2240
2241#ifdef TEE_SINK_FRAMES
2242        // create a Pipe to archive a copy of FastMixer's output for dumpsys
2243        Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2244        numCounterOffers = 0;
2245        index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2246        ALOG_ASSERT(index == 0);
2247        mTeeSink = teeSink;
2248        PipeReader *teeSource = new PipeReader(*teeSink);
2249        numCounterOffers = 0;
2250        index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2251        ALOG_ASSERT(index == 0);
2252        mTeeSource = teeSource;
2253#endif
2254
2255        // create fast mixer and configure it initially with just one fast track for our submix
2256        mFastMixer = new FastMixer();
2257        FastMixerStateQueue *sq = mFastMixer->sq();
2258#ifdef STATE_QUEUE_DUMP
2259        sq->setObserverDump(&mStateQueueObserverDump);
2260        sq->setMutatorDump(&mStateQueueMutatorDump);
2261#endif
2262        FastMixerState *state = sq->begin();
2263        FastTrack *fastTrack = &state->mFastTracks[0];
2264        // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2265        fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2266        fastTrack->mVolumeProvider = NULL;
2267        fastTrack->mGeneration++;
2268        state->mFastTracksGen++;
2269        state->mTrackMask = 1;
2270        // fast mixer will use the HAL output sink
2271        state->mOutputSink = mOutputSink.get();
2272        state->mOutputSinkGen++;
2273        state->mFrameCount = mFrameCount;
2274        state->mCommand = FastMixerState::COLD_IDLE;
2275        // already done in constructor initialization list
2276        //mFastMixerFutex = 0;
2277        state->mColdFutexAddr = &mFastMixerFutex;
2278        state->mColdGen++;
2279        state->mDumpState = &mFastMixerDumpState;
2280        state->mTeeSink = mTeeSink.get();
2281        sq->end();
2282        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2283
2284        // start the fast mixer
2285        mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2286        pid_t tid = mFastMixer->getTid();
2287        int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2288        if (err != 0) {
2289            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2290                    kPriorityFastMixer, getpid_cached, tid, err);
2291        }
2292
2293#ifdef AUDIO_WATCHDOG
2294        // create and start the watchdog
2295        mAudioWatchdog = new AudioWatchdog();
2296        mAudioWatchdog->setDump(&mAudioWatchdogDump);
2297        mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2298        tid = mAudioWatchdog->getTid();
2299        err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
2300        if (err != 0) {
2301            ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2302                    kPriorityFastMixer, getpid_cached, tid, err);
2303        }
2304#endif
2305
2306    } else {
2307        mFastMixer = NULL;
2308    }
2309
2310    switch (kUseFastMixer) {
2311    case FastMixer_Never:
2312    case FastMixer_Dynamic:
2313        mNormalSink = mOutputSink;
2314        break;
2315    case FastMixer_Always:
2316        mNormalSink = mPipeSink;
2317        break;
2318    case FastMixer_Static:
2319        mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2320        break;
2321    }
2322}
2323
2324AudioFlinger::MixerThread::~MixerThread()
2325{
2326    if (mFastMixer != NULL) {
2327        FastMixerStateQueue *sq = mFastMixer->sq();
2328        FastMixerState *state = sq->begin();
2329        if (state->mCommand == FastMixerState::COLD_IDLE) {
2330            int32_t old = android_atomic_inc(&mFastMixerFutex);
2331            if (old == -1) {
2332                __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2333            }
2334        }
2335        state->mCommand = FastMixerState::EXIT;
2336        sq->end();
2337        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2338        mFastMixer->join();
2339        // Though the fast mixer thread has exited, it's state queue is still valid.
2340        // We'll use that extract the final state which contains one remaining fast track
2341        // corresponding to our sub-mix.
2342        state = sq->begin();
2343        ALOG_ASSERT(state->mTrackMask == 1);
2344        FastTrack *fastTrack = &state->mFastTracks[0];
2345        ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2346        delete fastTrack->mBufferProvider;
2347        sq->end(false /*didModify*/);
2348        delete mFastMixer;
2349        if (mAudioWatchdog != 0) {
2350            mAudioWatchdog->requestExit();
2351            mAudioWatchdog->requestExitAndWait();
2352            mAudioWatchdog.clear();
2353        }
2354    }
2355    delete mAudioMixer;
2356}
2357
2358class CpuStats {
2359public:
2360    CpuStats();
2361    void sample(const String8 &title);
2362#ifdef DEBUG_CPU_USAGE
2363private:
2364    ThreadCpuUsage mCpuUsage;           // instantaneous thread CPU usage in wall clock ns
2365    CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2366
2367    CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2368
2369    int mCpuNum;                        // thread's current CPU number
2370    int mCpukHz;                        // frequency of thread's current CPU in kHz
2371#endif
2372};
2373
2374CpuStats::CpuStats()
2375#ifdef DEBUG_CPU_USAGE
2376    : mCpuNum(-1), mCpukHz(-1)
2377#endif
2378{
2379}
2380
2381void CpuStats::sample(const String8 &title) {
2382#ifdef DEBUG_CPU_USAGE
2383    // get current thread's delta CPU time in wall clock ns
2384    double wcNs;
2385    bool valid = mCpuUsage.sampleAndEnable(wcNs);
2386
2387    // record sample for wall clock statistics
2388    if (valid) {
2389        mWcStats.sample(wcNs);
2390    }
2391
2392    // get the current CPU number
2393    int cpuNum = sched_getcpu();
2394
2395    // get the current CPU frequency in kHz
2396    int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2397
2398    // check if either CPU number or frequency changed
2399    if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2400        mCpuNum = cpuNum;
2401        mCpukHz = cpukHz;
2402        // ignore sample for purposes of cycles
2403        valid = false;
2404    }
2405
2406    // if no change in CPU number or frequency, then record sample for cycle statistics
2407    if (valid && mCpukHz > 0) {
2408        double cycles = wcNs * cpukHz * 0.000001;
2409        mHzStats.sample(cycles);
2410    }
2411
2412    unsigned n = mWcStats.n();
2413    // mCpuUsage.elapsed() is expensive, so don't call it every loop
2414    if ((n & 127) == 1) {
2415        long long elapsed = mCpuUsage.elapsed();
2416        if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2417            double perLoop = elapsed / (double) n;
2418            double perLoop100 = perLoop * 0.01;
2419            double perLoop1k = perLoop * 0.001;
2420            double mean = mWcStats.mean();
2421            double stddev = mWcStats.stddev();
2422            double minimum = mWcStats.minimum();
2423            double maximum = mWcStats.maximum();
2424            double meanCycles = mHzStats.mean();
2425            double stddevCycles = mHzStats.stddev();
2426            double minCycles = mHzStats.minimum();
2427            double maxCycles = mHzStats.maximum();
2428            mCpuUsage.resetElapsed();
2429            mWcStats.reset();
2430            mHzStats.reset();
2431            ALOGD("CPU usage for %s over past %.1f secs\n"
2432                "  (%u mixer loops at %.1f mean ms per loop):\n"
2433                "  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2434                "  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2435                "  MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2436                    title.string(),
2437                    elapsed * .000000001, n, perLoop * .000001,
2438                    mean * .001,
2439                    stddev * .001,
2440                    minimum * .001,
2441                    maximum * .001,
2442                    mean / perLoop100,
2443                    stddev / perLoop100,
2444                    minimum / perLoop100,
2445                    maximum / perLoop100,
2446                    meanCycles / perLoop1k,
2447                    stddevCycles / perLoop1k,
2448                    minCycles / perLoop1k,
2449                    maxCycles / perLoop1k);
2450
2451        }
2452    }
2453#endif
2454};
2455
2456void AudioFlinger::PlaybackThread::checkSilentMode_l()
2457{
2458    if (!mMasterMute) {
2459        char value[PROPERTY_VALUE_MAX];
2460        if (property_get("ro.audio.silent", value, "0") > 0) {
2461            char *endptr;
2462            unsigned long ul = strtoul(value, &endptr, 0);
2463            if (*endptr == '\0' && ul != 0) {
2464                ALOGD("Silence is golden");
2465                // The setprop command will not allow a property to be changed after
2466                // the first time it is set, so we don't have to worry about un-muting.
2467                setMasterMute_l(true);
2468            }
2469        }
2470    }
2471}
2472
2473bool AudioFlinger::PlaybackThread::threadLoop()
2474{
2475    Vector< sp<Track> > tracksToRemove;
2476
2477    standbyTime = systemTime();
2478
2479    // MIXER
2480    nsecs_t lastWarning = 0;
2481
2482    // DUPLICATING
2483    // FIXME could this be made local to while loop?
2484    writeFrames = 0;
2485
2486    cacheParameters_l();
2487    sleepTime = idleSleepTime;
2488
2489    if (mType == MIXER) {
2490        sleepTimeShift = 0;
2491    }
2492
2493    CpuStats cpuStats;
2494    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2495
2496    acquireWakeLock();
2497
2498    while (!exitPending())
2499    {
2500        cpuStats.sample(myName);
2501
2502        Vector< sp<EffectChain> > effectChains;
2503
2504        processConfigEvents();
2505
2506        { // scope for mLock
2507
2508            Mutex::Autolock _l(mLock);
2509
2510            if (checkForNewParameters_l()) {
2511                cacheParameters_l();
2512            }
2513
2514            saveOutputTracks();
2515
2516            // put audio hardware into standby after short delay
2517            if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2518                        isSuspended())) {
2519                if (!mStandby) {
2520
2521                    threadLoop_standby();
2522
2523                    mStandby = true;
2524                    mBytesWritten = 0;
2525                }
2526
2527                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2528                    // we're about to wait, flush the binder command buffer
2529                    IPCThreadState::self()->flushCommands();
2530
2531                    clearOutputTracks();
2532
2533                    if (exitPending()) break;
2534
2535                    releaseWakeLock_l();
2536                    // wait until we have something to do...
2537                    ALOGV("%s going to sleep", myName.string());
2538                    mWaitWorkCV.wait(mLock);
2539                    ALOGV("%s waking up", myName.string());
2540                    acquireWakeLock_l();
2541
2542                    mMixerStatus = MIXER_IDLE;
2543                    mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2544
2545                    checkSilentMode_l();
2546
2547                    standbyTime = systemTime() + standbyDelay;
2548                    sleepTime = idleSleepTime;
2549                    if (mType == MIXER) {
2550                        sleepTimeShift = 0;
2551                    }
2552
2553                    continue;
2554                }
2555            }
2556
2557            // mMixerStatusIgnoringFastTracks is also updated internally
2558            mMixerStatus = prepareTracks_l(&tracksToRemove);
2559
2560            // prevent any changes in effect chain list and in each effect chain
2561            // during mixing and effect process as the audio buffers could be deleted
2562            // or modified if an effect is created or deleted
2563            lockEffectChains_l(effectChains);
2564        }
2565
2566        if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
2567            threadLoop_mix();
2568        } else {
2569            threadLoop_sleepTime();
2570        }
2571
2572        if (isSuspended()) {
2573            sleepTime = suspendSleepTimeUs();
2574        }
2575
2576        // only process effects if we're going to write
2577        if (sleepTime == 0) {
2578            for (size_t i = 0; i < effectChains.size(); i ++) {
2579                effectChains[i]->process_l();
2580            }
2581        }
2582
2583        // enable changes in effect chain
2584        unlockEffectChains(effectChains);
2585
2586        // sleepTime == 0 means we must write to audio hardware
2587        if (sleepTime == 0) {
2588
2589            threadLoop_write();
2590
2591if (mType == MIXER) {
2592            // write blocked detection
2593            nsecs_t now = systemTime();
2594            nsecs_t delta = now - mLastWriteTime;
2595            if (!mStandby && delta > maxPeriod) {
2596                mNumDelayedWrites++;
2597                if ((now - lastWarning) > kWarningThrottleNs) {
2598#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2599                    ScopedTrace st(ATRACE_TAG, "underrun");
2600#endif
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            mStandby = false;
2609        } else {
2610            usleep(sleepTime);
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    // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2633    if (mType == MIXER || mType == DIRECT) {
2634        // put output stream into standby mode
2635        if (!mStandby) {
2636            mOutput->stream->common.standby(&mOutput->stream->common);
2637        }
2638    }
2639
2640    releaseWakeLock();
2641
2642    ALOGV("Thread %p type %d exiting", this, mType);
2643    return false;
2644}
2645
2646void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2647{
2648    PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2649}
2650
2651void AudioFlinger::MixerThread::threadLoop_write()
2652{
2653    // FIXME we should only do one push per cycle; confirm this is true
2654    // Start the fast mixer if it's not already running
2655    if (mFastMixer != NULL) {
2656        FastMixerStateQueue *sq = mFastMixer->sq();
2657        FastMixerState *state = sq->begin();
2658        if (state->mCommand != FastMixerState::MIX_WRITE &&
2659                (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
2660            if (state->mCommand == FastMixerState::COLD_IDLE) {
2661                int32_t old = android_atomic_inc(&mFastMixerFutex);
2662                if (old == -1) {
2663                    __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2664                }
2665                if (mAudioWatchdog != 0) {
2666                    mAudioWatchdog->resume();
2667                }
2668            }
2669            state->mCommand = FastMixerState::MIX_WRITE;
2670            sq->end();
2671            sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2672            if (kUseFastMixer == FastMixer_Dynamic) {
2673                mNormalSink = mPipeSink;
2674            }
2675        } else {
2676            sq->end(false /*didModify*/);
2677        }
2678    }
2679    PlaybackThread::threadLoop_write();
2680}
2681
2682// shared by MIXER and DIRECT, overridden by DUPLICATING
2683void AudioFlinger::PlaybackThread::threadLoop_write()
2684{
2685    // FIXME rewrite to reduce number of system calls
2686    mLastWriteTime = systemTime();
2687    mInWrite = true;
2688    int bytesWritten;
2689
2690    // If an NBAIO sink is present, use it to write the normal mixer's submix
2691    if (mNormalSink != 0) {
2692#define mBitShift 2 // FIXME
2693        size_t count = mixBufferSize >> mBitShift;
2694#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2695        Tracer::traceBegin(ATRACE_TAG, "write");
2696#endif
2697        // update the setpoint when gScreenState changes
2698        uint32_t screenState = gScreenState;
2699        if (screenState != mScreenState) {
2700            mScreenState = screenState;
2701            MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2702            if (pipe != NULL) {
2703                pipe->setAvgFrames((mScreenState & 1) ?
2704                        (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2705            }
2706        }
2707        ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2708#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
2709        Tracer::traceEnd(ATRACE_TAG);
2710#endif
2711        if (framesWritten > 0) {
2712            bytesWritten = framesWritten << mBitShift;
2713        } else {
2714            bytesWritten = framesWritten;
2715        }
2716    // otherwise use the HAL / AudioStreamOut directly
2717    } else {
2718        // Direct output thread.
2719        bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2720    }
2721
2722    if (bytesWritten > 0) mBytesWritten += mixBufferSize;
2723    mNumWrites++;
2724    mInWrite = false;
2725}
2726
2727void AudioFlinger::MixerThread::threadLoop_standby()
2728{
2729    // Idle the fast mixer if it's currently running
2730    if (mFastMixer != NULL) {
2731        FastMixerStateQueue *sq = mFastMixer->sq();
2732        FastMixerState *state = sq->begin();
2733        if (!(state->mCommand & FastMixerState::IDLE)) {
2734            state->mCommand = FastMixerState::COLD_IDLE;
2735            state->mColdFutexAddr = &mFastMixerFutex;
2736            state->mColdGen++;
2737            mFastMixerFutex = 0;
2738            sq->end();
2739            // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2740            sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2741            if (kUseFastMixer == FastMixer_Dynamic) {
2742                mNormalSink = mOutputSink;
2743            }
2744            if (mAudioWatchdog != 0) {
2745                mAudioWatchdog->pause();
2746            }
2747        } else {
2748            sq->end(false /*didModify*/);
2749        }
2750    }
2751    PlaybackThread::threadLoop_standby();
2752}
2753
2754// shared by MIXER and DIRECT, overridden by DUPLICATING
2755void AudioFlinger::PlaybackThread::threadLoop_standby()
2756{
2757    ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
2758    mOutput->stream->common.standby(&mOutput->stream->common);
2759}
2760
2761void AudioFlinger::MixerThread::threadLoop_mix()
2762{
2763    // obtain the presentation timestamp of the next output buffer
2764    int64_t pts;
2765    status_t status = INVALID_OPERATION;
2766
2767    if (NULL != mOutput->stream->get_next_write_timestamp) {
2768        status = mOutput->stream->get_next_write_timestamp(
2769                mOutput->stream, &pts);
2770    }
2771
2772    if (status != NO_ERROR) {
2773        pts = AudioBufferProvider::kInvalidPTS;
2774    }
2775
2776    // mix buffers...
2777    mAudioMixer->process(pts);
2778    // increase sleep time progressively when application underrun condition clears.
2779    // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2780    // that a steady state of alternating ready/not ready conditions keeps the sleep time
2781    // such that we would underrun the audio HAL.
2782    if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2783        sleepTimeShift--;
2784    }
2785    sleepTime = 0;
2786    standbyTime = systemTime() + standbyDelay;
2787    //TODO: delay standby when effects have a tail
2788}
2789
2790void AudioFlinger::MixerThread::threadLoop_sleepTime()
2791{
2792    // If no tracks are ready, sleep once for the duration of an output
2793    // buffer size, then write 0s to the output
2794    if (sleepTime == 0) {
2795        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
2796            sleepTime = activeSleepTime >> sleepTimeShift;
2797            if (sleepTime < kMinThreadSleepTimeUs) {
2798                sleepTime = kMinThreadSleepTimeUs;
2799            }
2800            // reduce sleep time in case of consecutive application underruns to avoid
2801            // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2802            // duration we would end up writing less data than needed by the audio HAL if
2803            // the condition persists.
2804            if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2805                sleepTimeShift++;
2806            }
2807        } else {
2808            sleepTime = idleSleepTime;
2809        }
2810    } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
2811        memset (mMixBuffer, 0, mixBufferSize);
2812        sleepTime = 0;
2813        ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
2814    }
2815    // TODO add standby time extension fct of effect tail
2816}
2817
2818// prepareTracks_l() must be called with ThreadBase::mLock held
2819AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2820        Vector< sp<Track> > *tracksToRemove)
2821{
2822
2823    mixer_state mixerStatus = MIXER_IDLE;
2824    // find out which tracks need to be processed
2825    size_t count = mActiveTracks.size();
2826    size_t mixedTracks = 0;
2827    size_t tracksWithEffect = 0;
2828    // counts only _active_ fast tracks
2829    size_t fastTracks = 0;
2830    uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
2831
2832    float masterVolume = mMasterVolume;
2833    bool masterMute = mMasterMute;
2834
2835    if (masterMute) {
2836        masterVolume = 0;
2837    }
2838    // Delegate master volume control to effect in output mix effect chain if needed
2839    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2840    if (chain != 0) {
2841        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2842        chain->setVolume_l(&v, &v);
2843        masterVolume = (float)((v + (1 << 23)) >> 24);
2844        chain.clear();
2845    }
2846
2847    // prepare a new state to push
2848    FastMixerStateQueue *sq = NULL;
2849    FastMixerState *state = NULL;
2850    bool didModify = false;
2851    FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2852    if (mFastMixer != NULL) {
2853        sq = mFastMixer->sq();
2854        state = sq->begin();
2855    }
2856
2857    for (size_t i=0 ; i<count ; i++) {
2858        sp<Track> t = mActiveTracks[i].promote();
2859        if (t == 0) continue;
2860
2861        // this const just means the local variable doesn't change
2862        Track* const track = t.get();
2863
2864        // process fast tracks
2865        if (track->isFastTrack()) {
2866
2867            // It's theoretically possible (though unlikely) for a fast track to be created
2868            // and then removed within the same normal mix cycle.  This is not a problem, as
2869            // the track never becomes active so it's fast mixer slot is never touched.
2870            // The converse, of removing an (active) track and then creating a new track
2871            // at the identical fast mixer slot within the same normal mix cycle,
2872            // is impossible because the slot isn't marked available until the end of each cycle.
2873            int j = track->mFastIndex;
2874            ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2875            ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
2876            FastTrack *fastTrack = &state->mFastTracks[j];
2877
2878            // Determine whether the track is currently in underrun condition,
2879            // and whether it had a recent underrun.
2880            FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2881            FastTrackUnderruns underruns = ftDump->mUnderruns;
2882            uint32_t recentFull = (underruns.mBitFields.mFull -
2883                    track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2884            uint32_t recentPartial = (underruns.mBitFields.mPartial -
2885                    track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2886            uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2887                    track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2888            uint32_t recentUnderruns = recentPartial + recentEmpty;
2889            track->mObservedUnderruns = underruns;
2890            // don't count underruns that occur while stopping or pausing
2891            // or stopped which can occur when flush() is called while active
2892            if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
2893                track->mUnderrunCount += recentUnderruns;
2894            }
2895
2896            // This is similar to the state machine for normal tracks,
2897            // with a few modifications for fast tracks.
2898            bool isActive = true;
2899            switch (track->mState) {
2900            case TrackBase::STOPPING_1:
2901                // track stays active in STOPPING_1 state until first underrun
2902                if (recentUnderruns > 0) {
2903                    track->mState = TrackBase::STOPPING_2;
2904                }
2905                break;
2906            case TrackBase::PAUSING:
2907                // ramp down is not yet implemented
2908                track->setPaused();
2909                break;
2910            case TrackBase::RESUMING:
2911                // ramp up is not yet implemented
2912                track->mState = TrackBase::ACTIVE;
2913                break;
2914            case TrackBase::ACTIVE:
2915                if (recentFull > 0 || recentPartial > 0) {
2916                    // track has provided at least some frames recently: reset retry count
2917                    track->mRetryCount = kMaxTrackRetries;
2918                }
2919                if (recentUnderruns == 0) {
2920                    // no recent underruns: stay active
2921                    break;
2922                }
2923                // there has recently been an underrun of some kind
2924                if (track->sharedBuffer() == 0) {
2925                    // were any of the recent underruns "empty" (no frames available)?
2926                    if (recentEmpty == 0) {
2927                        // no, then ignore the partial underruns as they are allowed indefinitely
2928                        break;
2929                    }
2930                    // there has recently been an "empty" underrun: decrement the retry counter
2931                    if (--(track->mRetryCount) > 0) {
2932                        break;
2933                    }
2934                    // indicate to client process that the track was disabled because of underrun;
2935                    // it will then automatically call start() when data is available
2936                    android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2937                    // remove from active list, but state remains ACTIVE [confusing but true]
2938                    isActive = false;
2939                    break;
2940                }
2941                // fall through
2942            case TrackBase::STOPPING_2:
2943            case TrackBase::PAUSED:
2944            case TrackBase::TERMINATED:
2945            case TrackBase::STOPPED:
2946            case TrackBase::FLUSHED:   // flush() while active
2947                // Check for presentation complete if track is inactive
2948                // We have consumed all the buffers of this track.
2949                // This would be incomplete if we auto-paused on underrun
2950                {
2951                    size_t audioHALFrames =
2952                            (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2953                    size_t framesWritten =
2954                            mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2955                    if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2956                        // track stays in active list until presentation is complete
2957                        break;
2958                    }
2959                }
2960                if (track->isStopping_2()) {
2961                    track->mState = TrackBase::STOPPED;
2962                }
2963                if (track->isStopped()) {
2964                    // Can't reset directly, as fast mixer is still polling this track
2965                    //   track->reset();
2966                    // So instead mark this track as needing to be reset after push with ack
2967                    resetMask |= 1 << i;
2968                }
2969                isActive = false;
2970                break;
2971            case TrackBase::IDLE:
2972            default:
2973                LOG_FATAL("unexpected track state %d", track->mState);
2974            }
2975
2976            if (isActive) {
2977                // was it previously inactive?
2978                if (!(state->mTrackMask & (1 << j))) {
2979                    ExtendedAudioBufferProvider *eabp = track;
2980                    VolumeProvider *vp = track;
2981                    fastTrack->mBufferProvider = eabp;
2982                    fastTrack->mVolumeProvider = vp;
2983                    fastTrack->mSampleRate = track->mSampleRate;
2984                    fastTrack->mChannelMask = track->mChannelMask;
2985                    fastTrack->mGeneration++;
2986                    state->mTrackMask |= 1 << j;
2987                    didModify = true;
2988                    // no acknowledgement required for newly active tracks
2989                }
2990                // cache the combined master volume and stream type volume for fast mixer; this
2991                // lacks any synchronization or barrier so VolumeProvider may read a stale value
2992                track->mCachedVolume = track->isMuted() ?
2993                        0 : masterVolume * mStreamTypes[track->streamType()].volume;
2994                ++fastTracks;
2995            } else {
2996                // was it previously active?
2997                if (state->mTrackMask & (1 << j)) {
2998                    fastTrack->mBufferProvider = NULL;
2999                    fastTrack->mGeneration++;
3000                    state->mTrackMask &= ~(1 << j);
3001                    didModify = true;
3002                    // If any fast tracks were removed, we must wait for acknowledgement
3003                    // because we're about to decrement the last sp<> on those tracks.
3004                    block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3005                } else {
3006                    LOG_FATAL("fast track %d should have been active", j);
3007                }
3008                tracksToRemove->add(track);
3009                // Avoids a misleading display in dumpsys
3010                track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3011            }
3012            continue;
3013        }
3014
3015        {   // local variable scope to avoid goto warning
3016
3017        audio_track_cblk_t* cblk = track->cblk();
3018
3019        // The first time a track is added we wait
3020        // for all its buffers to be filled before processing it
3021        int name = track->name();
3022        // make sure that we have enough frames to mix one full buffer.
3023        // enforce this condition only once to enable draining the buffer in case the client
3024        // app does not call stop() and relies on underrun to stop:
3025        // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3026        // during last round
3027        uint32_t minFrames = 1;
3028        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3029                (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
3030            if (t->sampleRate() == (int)mSampleRate) {
3031                minFrames = mNormalFrameCount;
3032            } else {
3033                // +1 for rounding and +1 for additional sample needed for interpolation
3034                minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
3035                // add frames already consumed but not yet released by the resampler
3036                // because cblk->framesReady() will include these frames
3037                minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3038                // the minimum track buffer size is normally twice the number of frames necessary
3039                // to fill one buffer and the resampler should not leave more than one buffer worth
3040                // of unreleased frames after each pass, but just in case...
3041                ALOG_ASSERT(minFrames <= cblk->frameCount);
3042            }
3043        }
3044        if ((track->framesReady() >= minFrames) && track->isReady() &&
3045                !track->isPaused() && !track->isTerminated())
3046        {
3047            //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
3048
3049            mixedTracks++;
3050
3051            // track->mainBuffer() != mMixBuffer means there is an effect chain
3052            // connected to the track
3053            chain.clear();
3054            if (track->mainBuffer() != mMixBuffer) {
3055                chain = getEffectChain_l(track->sessionId());
3056                // Delegate volume control to effect in track effect chain if needed
3057                if (chain != 0) {
3058                    tracksWithEffect++;
3059                } else {
3060                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
3061                            name, track->sessionId());
3062                }
3063            }
3064
3065
3066            int param = AudioMixer::VOLUME;
3067            if (track->mFillingUpStatus == Track::FS_FILLED) {
3068                // no ramp for the first volume setting
3069                track->mFillingUpStatus = Track::FS_ACTIVE;
3070                if (track->mState == TrackBase::RESUMING) {
3071                    track->mState = TrackBase::ACTIVE;
3072                    param = AudioMixer::RAMP_VOLUME;
3073                }
3074                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
3075            } else if (cblk->server != 0) {
3076                // If the track is stopped before the first frame was mixed,
3077                // do not apply ramp
3078                param = AudioMixer::RAMP_VOLUME;
3079            }
3080
3081            // compute volume for this track
3082            uint32_t vl, vr, va;
3083            if (track->isMuted() || track->isPausing() ||
3084                mStreamTypes[track->streamType()].mute) {
3085                vl = vr = va = 0;
3086                if (track->isPausing()) {
3087                    track->setPaused();
3088                }
3089            } else {
3090
3091                // read original volumes with volume control
3092                float typeVolume = mStreamTypes[track->streamType()].volume;
3093                float v = masterVolume * typeVolume;
3094                uint32_t vlr = cblk->getVolumeLR();
3095                vl = vlr & 0xFFFF;
3096                vr = vlr >> 16;
3097                // track volumes come from shared memory, so can't be trusted and must be clamped
3098                if (vl > MAX_GAIN_INT) {
3099                    ALOGV("Track left volume out of range: %04X", vl);
3100                    vl = MAX_GAIN_INT;
3101                }
3102                if (vr > MAX_GAIN_INT) {
3103                    ALOGV("Track right volume out of range: %04X", vr);
3104                    vr = MAX_GAIN_INT;
3105                }
3106                // now apply the master volume and stream type volume
3107                vl = (uint32_t)(v * vl) << 12;
3108                vr = (uint32_t)(v * vr) << 12;
3109                // assuming master volume and stream type volume each go up to 1.0,
3110                // vl and vr are now in 8.24 format
3111
3112                uint16_t sendLevel = cblk->getSendLevel_U4_12();
3113                // send level comes from shared memory and so may be corrupt
3114                if (sendLevel > MAX_GAIN_INT) {
3115                    ALOGV("Track send level out of range: %04X", sendLevel);
3116                    sendLevel = MAX_GAIN_INT;
3117                }
3118                va = (uint32_t)(v * sendLevel);
3119            }
3120            // Delegate volume control to effect in track effect chain if needed
3121            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3122                // Do not ramp volume if volume is controlled by effect
3123                param = AudioMixer::VOLUME;
3124                track->mHasVolumeController = true;
3125            } else {
3126                // force no volume ramp when volume controller was just disabled or removed
3127                // from effect chain to avoid volume spike
3128                if (track->mHasVolumeController) {
3129                    param = AudioMixer::VOLUME;
3130                }
3131                track->mHasVolumeController = false;
3132            }
3133
3134            // Convert volumes from 8.24 to 4.12 format
3135            // This additional clamping is needed in case chain->setVolume_l() overshot
3136            vl = (vl + (1 << 11)) >> 12;
3137            if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3138            vr = (vr + (1 << 11)) >> 12;
3139            if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
3140
3141            if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;   // va is uint32_t, so no need to check for -
3142
3143            // XXX: these things DON'T need to be done each time
3144            mAudioMixer->setBufferProvider(name, track);
3145            mAudioMixer->enable(name);
3146
3147            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3148            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3149            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
3150            mAudioMixer->setParameter(
3151                name,
3152                AudioMixer::TRACK,
3153                AudioMixer::FORMAT, (void *)track->format());
3154            mAudioMixer->setParameter(
3155                name,
3156                AudioMixer::TRACK,
3157                AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
3158            mAudioMixer->setParameter(
3159                name,
3160                AudioMixer::RESAMPLE,
3161                AudioMixer::SAMPLE_RATE,
3162                (void *)(cblk->sampleRate));
3163            mAudioMixer->setParameter(
3164                name,
3165                AudioMixer::TRACK,
3166                AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3167            mAudioMixer->setParameter(
3168                name,
3169                AudioMixer::TRACK,
3170                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3171
3172            // reset retry count
3173            track->mRetryCount = kMaxTrackRetries;
3174
3175            // If one track is ready, set the mixer ready if:
3176            //  - the mixer was not ready during previous round OR
3177            //  - no other track is not ready
3178            if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3179                    mixerStatus != MIXER_TRACKS_ENABLED) {
3180                mixerStatus = MIXER_TRACKS_READY;
3181            }
3182        } else {
3183            // clear effect chain input buffer if an active track underruns to avoid sending
3184            // previous audio buffer again to effects
3185            chain = getEffectChain_l(track->sessionId());
3186            if (chain != 0) {
3187                chain->clearInputBuffer();
3188            }
3189
3190            //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
3191            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3192                    track->isStopped() || track->isPaused()) {
3193                // We have consumed all the buffers of this track.
3194                // Remove it from the list of active tracks.
3195                // TODO: use actual buffer filling status instead of latency when available from
3196                // audio HAL
3197                size_t audioHALFrames =
3198                        (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3199                size_t framesWritten =
3200                        mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3201                if (track->presentationComplete(framesWritten, audioHALFrames)) {
3202                    if (track->isStopped()) {
3203                        track->reset();
3204                    }
3205                    tracksToRemove->add(track);
3206                }
3207            } else {
3208                track->mUnderrunCount++;
3209                // No buffers for this track. Give it a few chances to
3210                // fill a buffer, then remove it from active list.
3211                if (--(track->mRetryCount) <= 0) {
3212                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
3213                    tracksToRemove->add(track);
3214                    // indicate to client process that the track was disabled because of underrun;
3215                    // it will then automatically call start() when data is available
3216                    android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
3217                // If one track is not ready, mark the mixer also not ready if:
3218                //  - the mixer was ready during previous round OR
3219                //  - no other track is ready
3220                } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3221                                mixerStatus != MIXER_TRACKS_READY) {
3222                    mixerStatus = MIXER_TRACKS_ENABLED;
3223                }
3224            }
3225            mAudioMixer->disable(name);
3226        }
3227
3228        }   // local variable scope to avoid goto warning
3229track_is_ready: ;
3230
3231    }
3232
3233    // Push the new FastMixer state if necessary
3234    bool pauseAudioWatchdog = false;
3235    if (didModify) {
3236        state->mFastTracksGen++;
3237        // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3238        if (kUseFastMixer == FastMixer_Dynamic &&
3239                state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3240            state->mCommand = FastMixerState::COLD_IDLE;
3241            state->mColdFutexAddr = &mFastMixerFutex;
3242            state->mColdGen++;
3243            mFastMixerFutex = 0;
3244            if (kUseFastMixer == FastMixer_Dynamic) {
3245                mNormalSink = mOutputSink;
3246            }
3247            // If we go into cold idle, need to wait for acknowledgement
3248            // so that fast mixer stops doing I/O.
3249            block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3250            pauseAudioWatchdog = true;
3251        }
3252        sq->end();
3253    }
3254    if (sq != NULL) {
3255        sq->end(didModify);
3256        sq->push(block);
3257    }
3258    if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3259        mAudioWatchdog->pause();
3260    }
3261
3262    // Now perform the deferred reset on fast tracks that have stopped
3263    while (resetMask != 0) {
3264        size_t i = __builtin_ctz(resetMask);
3265        ALOG_ASSERT(i < count);
3266        resetMask &= ~(1 << i);
3267        sp<Track> t = mActiveTracks[i].promote();
3268        if (t == 0) continue;
3269        Track* track = t.get();
3270        ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3271        track->reset();
3272    }
3273
3274    // remove all the tracks that need to be...
3275    count = tracksToRemove->size();
3276    if (CC_UNLIKELY(count)) {
3277        for (size_t i=0 ; i<count ; i++) {
3278            const sp<Track>& track = tracksToRemove->itemAt(i);
3279            mActiveTracks.remove(track);
3280            if (track->mainBuffer() != mMixBuffer) {
3281                chain = getEffectChain_l(track->sessionId());
3282                if (chain != 0) {
3283                    ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
3284                    chain->decActiveTrackCnt();
3285                }
3286            }
3287            if (track->isTerminated()) {
3288                removeTrack_l(track);
3289            }
3290        }
3291    }
3292
3293    // mix buffer must be cleared if all tracks are connected to an
3294    // effect chain as in this case the mixer will not write to
3295    // mix buffer and track effects will accumulate into it
3296    if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3297        // FIXME as a performance optimization, should remember previous zero status
3298        memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
3299    }
3300
3301    // if any fast tracks, then status is ready
3302    mMixerStatusIgnoringFastTracks = mixerStatus;
3303    if (fastTracks > 0) {
3304        mixerStatus = MIXER_TRACKS_READY;
3305    }
3306    return mixerStatus;
3307}
3308
3309/*
3310The derived values that are cached:
3311 - mixBufferSize from frame count * frame size
3312 - activeSleepTime from activeSleepTimeUs()
3313 - idleSleepTime from idleSleepTimeUs()
3314 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3315 - maxPeriod from frame count and sample rate (MIXER only)
3316
3317The parameters that affect these derived values are:
3318 - frame count
3319 - frame size
3320 - sample rate
3321 - device type: A2DP or not
3322 - device latency
3323 - format: PCM or not
3324 - active sleep time
3325 - idle sleep time
3326*/
3327
3328void AudioFlinger::PlaybackThread::cacheParameters_l()
3329{
3330    mixBufferSize = mNormalFrameCount * mFrameSize;
3331    activeSleepTime = activeSleepTimeUs();
3332    idleSleepTime = idleSleepTimeUs();
3333}
3334
3335void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3336{
3337    ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
3338            this,  streamType, mTracks.size());
3339    Mutex::Autolock _l(mLock);
3340
3341    size_t size = mTracks.size();
3342    for (size_t i = 0; i < size; i++) {
3343        sp<Track> t = mTracks[i];
3344        if (t->streamType() == streamType) {
3345            android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
3346            t->mCblk->cv.signal();
3347        }
3348    }
3349}
3350
3351// getTrackName_l() must be called with ThreadBase::mLock held
3352int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
3353{
3354    return mAudioMixer->getTrackName(channelMask);
3355}
3356
3357// deleteTrackName_l() must be called with ThreadBase::mLock held
3358void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3359{
3360    ALOGV("remove track (%d) and delete from mixer", name);
3361    mAudioMixer->deleteTrackName(name);
3362}
3363
3364// checkForNewParameters_l() must be called with ThreadBase::mLock held
3365bool AudioFlinger::MixerThread::checkForNewParameters_l()
3366{
3367    // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3368    FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3369    bool reconfig = false;
3370
3371    while (!mNewParameters.isEmpty()) {
3372
3373        if (mFastMixer != NULL) {
3374            FastMixerStateQueue *sq = mFastMixer->sq();
3375            FastMixerState *state = sq->begin();
3376            if (!(state->mCommand & FastMixerState::IDLE)) {
3377                previousCommand = state->mCommand;
3378                state->mCommand = FastMixerState::HOT_IDLE;
3379                sq->end();
3380                sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3381            } else {
3382                sq->end(false /*didModify*/);
3383            }
3384        }
3385
3386        status_t status = NO_ERROR;
3387        String8 keyValuePair = mNewParameters[0];
3388        AudioParameter param = AudioParameter(keyValuePair);
3389        int value;
3390
3391        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3392            reconfig = true;
3393        }
3394        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3395            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
3396                status = BAD_VALUE;
3397            } else {
3398                reconfig = true;
3399            }
3400        }
3401        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3402            if (value != AUDIO_CHANNEL_OUT_STEREO) {
3403                status = BAD_VALUE;
3404            } else {
3405                reconfig = true;
3406            }
3407        }
3408        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3409            // do not accept frame count changes if tracks are open as the track buffer
3410            // size depends on frame count and correct behavior would not be guaranteed
3411            // if frame count is changed after track creation
3412            if (!mTracks.isEmpty()) {
3413                status = INVALID_OPERATION;
3414            } else {
3415                reconfig = true;
3416            }
3417        }
3418        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
3419#ifdef ADD_BATTERY_DATA
3420            // when changing the audio output device, call addBatteryData to notify
3421            // the change
3422            if ((int)mDevice != value) {
3423                uint32_t params = 0;
3424                // check whether speaker is on
3425                if (value & AUDIO_DEVICE_OUT_SPEAKER) {
3426                    params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3427                }
3428
3429                audio_devices_t deviceWithoutSpeaker
3430                    = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3431                // check if any other device (except speaker) is on
3432                if (value & deviceWithoutSpeaker ) {
3433                    params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3434                }
3435
3436                if (params != 0) {
3437                    addBatteryData(params);
3438                }
3439            }
3440#endif
3441
3442            // forward device change to effects that have requested to be
3443            // aware of attached audio device.
3444            mDevice = (audio_devices_t) value;
3445            for (size_t i = 0; i < mEffectChains.size(); i++) {
3446                mEffectChains[i]->setDevice_l(mDevice);
3447            }
3448        }
3449
3450        if (status == NO_ERROR) {
3451            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3452                                                    keyValuePair.string());
3453            if (!mStandby && status == INVALID_OPERATION) {
3454                mOutput->stream->common.standby(&mOutput->stream->common);
3455                mStandby = true;
3456                mBytesWritten = 0;
3457                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3458                                                       keyValuePair.string());
3459            }
3460            if (status == NO_ERROR && reconfig) {
3461                delete mAudioMixer;
3462                // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3463                mAudioMixer = NULL;
3464                readOutputParameters();
3465                mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3466                for (size_t i = 0; i < mTracks.size() ; i++) {
3467                    int name = getTrackName_l(mTracks[i]->mChannelMask);
3468                    if (name < 0) break;
3469                    mTracks[i]->mName = name;
3470                    // limit track sample rate to 2 x new output sample rate
3471                    if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3472                        mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3473                    }
3474                }
3475                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3476            }
3477        }
3478
3479        mNewParameters.removeAt(0);
3480
3481        mParamStatus = status;
3482        mParamCond.signal();
3483        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3484        // already timed out waiting for the status and will never signal the condition.
3485        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3486    }
3487
3488    if (!(previousCommand & FastMixerState::IDLE)) {
3489        ALOG_ASSERT(mFastMixer != NULL);
3490        FastMixerStateQueue *sq = mFastMixer->sq();
3491        FastMixerState *state = sq->begin();
3492        ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3493        state->mCommand = previousCommand;
3494        sq->end();
3495        sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3496    }
3497
3498    return reconfig;
3499}
3500
3501status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3502{
3503    const size_t SIZE = 256;
3504    char buffer[SIZE];
3505    String8 result;
3506
3507    PlaybackThread::dumpInternals(fd, args);
3508
3509    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3510    result.append(buffer);
3511    write(fd, result.string(), result.size());
3512
3513    // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3514    FastMixerDumpState copy = mFastMixerDumpState;
3515    copy.dump(fd);
3516
3517#ifdef STATE_QUEUE_DUMP
3518    // Similar for state queue
3519    StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3520    observerCopy.dump(fd);
3521    StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3522    mutatorCopy.dump(fd);
3523#endif
3524
3525    // Write the tee output to a .wav file
3526    NBAIO_Source *teeSource = mTeeSource.get();
3527    if (teeSource != NULL) {
3528        char teePath[64];
3529        struct timeval tv;
3530        gettimeofday(&tv, NULL);
3531        struct tm tm;
3532        localtime_r(&tv.tv_sec, &tm);
3533        strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3534        int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3535        if (teeFd >= 0) {
3536            char wavHeader[44];
3537            memcpy(wavHeader,
3538                "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
3539                sizeof(wavHeader));
3540            NBAIO_Format format = teeSource->format();
3541            unsigned channelCount = Format_channelCount(format);
3542            ALOG_ASSERT(channelCount <= FCC_2);
3543            unsigned sampleRate = Format_sampleRate(format);
3544            wavHeader[22] = channelCount;       // number of channels
3545            wavHeader[24] = sampleRate;         // sample rate
3546            wavHeader[25] = sampleRate >> 8;
3547            wavHeader[32] = channelCount * 2;   // block alignment
3548            write(teeFd, wavHeader, sizeof(wavHeader));
3549            size_t total = 0;
3550            bool firstRead = true;
3551            for (;;) {
3552#define TEE_SINK_READ 1024
3553                short buffer[TEE_SINK_READ * FCC_2];
3554                size_t count = TEE_SINK_READ;
3555                ssize_t actual = teeSource->read(buffer, count);
3556                bool wasFirstRead = firstRead;
3557                firstRead = false;
3558                if (actual <= 0) {
3559                    if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3560                        continue;
3561                    }
3562                    break;
3563                }
3564                ALOG_ASSERT(actual <= (ssize_t)count);
3565                write(teeFd, buffer, actual * channelCount * sizeof(short));
3566                total += actual;
3567            }
3568            lseek(teeFd, (off_t) 4, SEEK_SET);
3569            uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3570            write(teeFd, &temp, sizeof(temp));
3571            lseek(teeFd, (off_t) 40, SEEK_SET);
3572            temp =  total * channelCount * sizeof(short);
3573            write(teeFd, &temp, sizeof(temp));
3574            close(teeFd);
3575            fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3576        } else {
3577            fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3578        }
3579    }
3580
3581    if (mAudioWatchdog != 0) {
3582        // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3583        AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3584        wdCopy.dump(fd);
3585    }
3586
3587    return NO_ERROR;
3588}
3589
3590uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
3591{
3592    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
3593}
3594
3595uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
3596{
3597    return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3598}
3599
3600void AudioFlinger::MixerThread::cacheParameters_l()
3601{
3602    PlaybackThread::cacheParameters_l();
3603
3604    // FIXME: Relaxed timing because of a certain device that can't meet latency
3605    // Should be reduced to 2x after the vendor fixes the driver issue
3606    // increase threshold again due to low power audio mode. The way this warning
3607    // threshold is calculated and its usefulness should be reconsidered anyway.
3608    maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
3609}
3610
3611// ----------------------------------------------------------------------------
3612AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3613        AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
3614    :   PlaybackThread(audioFlinger, output, id, device, DIRECT)
3615        // mLeftVolFloat, mRightVolFloat
3616{
3617}
3618
3619AudioFlinger::DirectOutputThread::~DirectOutputThread()
3620{
3621}
3622
3623AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3624    Vector< sp<Track> > *tracksToRemove
3625)
3626{
3627    sp<Track> trackToRemove;
3628
3629    mixer_state mixerStatus = MIXER_IDLE;
3630
3631    // find out which tracks need to be processed
3632    if (mActiveTracks.size() != 0) {
3633        sp<Track> t = mActiveTracks[0].promote();
3634        // The track died recently
3635        if (t == 0) return MIXER_IDLE;
3636
3637        Track* const track = t.get();
3638        audio_track_cblk_t* cblk = track->cblk();
3639
3640        // The first time a track is added we wait
3641        // for all its buffers to be filled before processing it
3642        uint32_t minFrames;
3643        if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3644            minFrames = mNormalFrameCount;
3645        } else {
3646            minFrames = 1;
3647        }
3648        if ((track->framesReady() >= minFrames) && track->isReady() &&
3649                !track->isPaused() && !track->isTerminated())
3650        {
3651            //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
3652
3653            if (track->mFillingUpStatus == Track::FS_FILLED) {
3654                track->mFillingUpStatus = Track::FS_ACTIVE;
3655                mLeftVolFloat = mRightVolFloat = 0;
3656                if (track->mState == TrackBase::RESUMING) {
3657                    track->mState = TrackBase::ACTIVE;
3658                }
3659            }
3660
3661            // compute volume for this track
3662            float left, right;
3663            if (track->isMuted() || mMasterMute || track->isPausing() ||
3664                mStreamTypes[track->streamType()].mute) {
3665                left = right = 0;
3666                if (track->isPausing()) {
3667                    track->setPaused();
3668                }
3669            } else {
3670                float typeVolume = mStreamTypes[track->streamType()].volume;
3671                float v = mMasterVolume * typeVolume;
3672                uint32_t vlr = cblk->getVolumeLR();
3673                float v_clamped = v * (vlr & 0xFFFF);
3674                if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3675                left = v_clamped/MAX_GAIN;
3676                v_clamped = v * (vlr >> 16);
3677                if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3678                right = v_clamped/MAX_GAIN;
3679            }
3680
3681            if (left != mLeftVolFloat || right != mRightVolFloat) {
3682                mLeftVolFloat = left;
3683                mRightVolFloat = right;
3684
3685                // Convert volumes from float to 8.24
3686                uint32_t vl = (uint32_t)(left * (1 << 24));
3687                uint32_t vr = (uint32_t)(right * (1 << 24));
3688
3689                // Delegate volume control to effect in track effect chain if needed
3690                // only one effect chain can be present on DirectOutputThread, so if
3691                // there is one, the track is connected to it
3692                if (!mEffectChains.isEmpty()) {
3693                    // Do not ramp volume if volume is controlled by effect
3694                    mEffectChains[0]->setVolume_l(&vl, &vr);
3695                    left = (float)vl / (1 << 24);
3696                    right = (float)vr / (1 << 24);
3697                }
3698                mOutput->stream->set_volume(mOutput->stream, left, right);
3699            }
3700
3701            // reset retry count
3702            track->mRetryCount = kMaxTrackRetriesDirect;
3703            mActiveTrack = t;
3704            mixerStatus = MIXER_TRACKS_READY;
3705        } else {
3706            // clear effect chain input buffer if an active track underruns to avoid sending
3707            // previous audio buffer again to effects
3708            if (!mEffectChains.isEmpty()) {
3709                mEffectChains[0]->clearInputBuffer();
3710            }
3711
3712            //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3713            if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3714                    track->isStopped() || track->isPaused()) {
3715                // We have consumed all the buffers of this track.
3716                // Remove it from the list of active tracks.
3717                // TODO: implement behavior for compressed audio
3718                size_t audioHALFrames =
3719                        (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3720                size_t framesWritten =
3721                        mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3722                if (track->presentationComplete(framesWritten, audioHALFrames)) {
3723                    if (track->isStopped()) {
3724                        track->reset();
3725                    }
3726                    trackToRemove = track;
3727                }
3728            } else {
3729                // No buffers for this track. Give it a few chances to
3730                // fill a buffer, then remove it from active list.
3731                if (--(track->mRetryCount) <= 0) {
3732                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3733                    trackToRemove = track;
3734                } else {
3735                    mixerStatus = MIXER_TRACKS_ENABLED;
3736                }
3737            }
3738        }
3739    }
3740
3741    // FIXME merge this with similar code for removing multiple tracks
3742    // remove all the tracks that need to be...
3743    if (CC_UNLIKELY(trackToRemove != 0)) {
3744        tracksToRemove->add(trackToRemove);
3745        mActiveTracks.remove(trackToRemove);
3746        if (!mEffectChains.isEmpty()) {
3747            ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
3748                    trackToRemove->sessionId());
3749            mEffectChains[0]->decActiveTrackCnt();
3750        }
3751        if (trackToRemove->isTerminated()) {
3752            removeTrack_l(trackToRemove);
3753        }
3754    }
3755
3756    return mixerStatus;
3757}
3758
3759void AudioFlinger::DirectOutputThread::threadLoop_mix()
3760{
3761    AudioBufferProvider::Buffer buffer;
3762    size_t frameCount = mFrameCount;
3763    int8_t *curBuf = (int8_t *)mMixBuffer;
3764    // output audio to hardware
3765    while (frameCount) {
3766        buffer.frameCount = frameCount;
3767        mActiveTrack->getNextBuffer(&buffer);
3768        if (CC_UNLIKELY(buffer.raw == NULL)) {
3769            memset(curBuf, 0, frameCount * mFrameSize);
3770            break;
3771        }
3772        memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3773        frameCount -= buffer.frameCount;
3774        curBuf += buffer.frameCount * mFrameSize;
3775        mActiveTrack->releaseBuffer(&buffer);
3776    }
3777    sleepTime = 0;
3778    standbyTime = systemTime() + standbyDelay;
3779    mActiveTrack.clear();
3780
3781}
3782
3783void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3784{
3785    if (sleepTime == 0) {
3786        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3787            sleepTime = activeSleepTime;
3788        } else {
3789            sleepTime = idleSleepTime;
3790        }
3791    } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
3792        memset(mMixBuffer, 0, mFrameCount * mFrameSize);
3793        sleepTime = 0;
3794    }
3795}
3796
3797// getTrackName_l() must be called with ThreadBase::mLock held
3798int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
3799{
3800    return 0;
3801}
3802
3803// deleteTrackName_l() must be called with ThreadBase::mLock held
3804void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3805{
3806}
3807
3808// checkForNewParameters_l() must be called with ThreadBase::mLock held
3809bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3810{
3811    bool reconfig = false;
3812
3813    while (!mNewParameters.isEmpty()) {
3814        status_t status = NO_ERROR;
3815        String8 keyValuePair = mNewParameters[0];
3816        AudioParameter param = AudioParameter(keyValuePair);
3817        int value;
3818
3819        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3820            // do not accept frame count changes if tracks are open as the track buffer
3821            // size depends on frame count and correct behavior would not be garantied
3822            // if frame count is changed after track creation
3823            if (!mTracks.isEmpty()) {
3824                status = INVALID_OPERATION;
3825            } else {
3826                reconfig = true;
3827            }
3828        }
3829        if (status == NO_ERROR) {
3830            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3831                                                    keyValuePair.string());
3832            if (!mStandby && status == INVALID_OPERATION) {
3833                mOutput->stream->common.standby(&mOutput->stream->common);
3834                mStandby = true;
3835                mBytesWritten = 0;
3836                status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3837                                                       keyValuePair.string());
3838            }
3839            if (status == NO_ERROR && reconfig) {
3840                readOutputParameters();
3841                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3842            }
3843        }
3844
3845        mNewParameters.removeAt(0);
3846
3847        mParamStatus = status;
3848        mParamCond.signal();
3849        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3850        // already timed out waiting for the status and will never signal the condition.
3851        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
3852    }
3853    return reconfig;
3854}
3855
3856uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
3857{
3858    uint32_t time;
3859    if (audio_is_linear_pcm(mFormat)) {
3860        time = PlaybackThread::activeSleepTimeUs();
3861    } else {
3862        time = 10000;
3863    }
3864    return time;
3865}
3866
3867uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
3868{
3869    uint32_t time;
3870    if (audio_is_linear_pcm(mFormat)) {
3871        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
3872    } else {
3873        time = 10000;
3874    }
3875    return time;
3876}
3877
3878uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
3879{
3880    uint32_t time;
3881    if (audio_is_linear_pcm(mFormat)) {
3882        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3883    } else {
3884        time = 10000;
3885    }
3886    return time;
3887}
3888
3889void AudioFlinger::DirectOutputThread::cacheParameters_l()
3890{
3891    PlaybackThread::cacheParameters_l();
3892
3893    // use shorter standby delay as on normal output to release
3894    // hardware resources as soon as possible
3895    standbyDelay = microseconds(activeSleepTime*2);
3896}
3897
3898// ----------------------------------------------------------------------------
3899
3900AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3901        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
3902    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3903        mWaitTimeMs(UINT_MAX)
3904{
3905    addOutputTrack(mainThread);
3906}
3907
3908AudioFlinger::DuplicatingThread::~DuplicatingThread()
3909{
3910    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3911        mOutputTracks[i]->destroy();
3912    }
3913}
3914
3915void AudioFlinger::DuplicatingThread::threadLoop_mix()
3916{
3917    // mix buffers...
3918    if (outputsReady(outputTracks)) {
3919        mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3920    } else {
3921        memset(mMixBuffer, 0, mixBufferSize);
3922    }
3923    sleepTime = 0;
3924    writeFrames = mNormalFrameCount;
3925    standbyTime = systemTime() + standbyDelay;
3926}
3927
3928void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3929{
3930    if (sleepTime == 0) {
3931        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3932            sleepTime = activeSleepTime;
3933        } else {
3934            sleepTime = idleSleepTime;
3935        }
3936    } else if (mBytesWritten != 0) {
3937        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3938            writeFrames = mNormalFrameCount;
3939            memset(mMixBuffer, 0, mixBufferSize);
3940        } else {
3941            // flush remaining overflow buffers in output tracks
3942            writeFrames = 0;
3943        }
3944        sleepTime = 0;
3945    }
3946}
3947
3948void AudioFlinger::DuplicatingThread::threadLoop_write()
3949{
3950    for (size_t i = 0; i < outputTracks.size(); i++) {
3951        outputTracks[i]->write(mMixBuffer, writeFrames);
3952    }
3953    mBytesWritten += mixBufferSize;
3954}
3955
3956void AudioFlinger::DuplicatingThread::threadLoop_standby()
3957{
3958    // DuplicatingThread implements standby by stopping all tracks
3959    for (size_t i = 0; i < outputTracks.size(); i++) {
3960        outputTracks[i]->stop();
3961    }
3962}
3963
3964void AudioFlinger::DuplicatingThread::saveOutputTracks()
3965{
3966    outputTracks = mOutputTracks;
3967}
3968
3969void AudioFlinger::DuplicatingThread::clearOutputTracks()
3970{
3971    outputTracks.clear();
3972}
3973
3974void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3975{
3976    Mutex::Autolock _l(mLock);
3977    // FIXME explain this formula
3978    int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
3979    OutputTrack *outputTrack = new OutputTrack(thread,
3980                                            this,
3981                                            mSampleRate,
3982                                            mFormat,
3983                                            mChannelMask,
3984                                            frameCount);
3985    if (outputTrack->cblk() != NULL) {
3986        thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
3987        mOutputTracks.add(outputTrack);
3988        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3989        updateWaitTime_l();
3990    }
3991}
3992
3993void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3994{
3995    Mutex::Autolock _l(mLock);
3996    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3997        if (mOutputTracks[i]->thread() == thread) {
3998            mOutputTracks[i]->destroy();
3999            mOutputTracks.removeAt(i);
4000            updateWaitTime_l();
4001            return;
4002        }
4003    }
4004    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
4005}
4006
4007// caller must hold mLock
4008void AudioFlinger::DuplicatingThread::updateWaitTime_l()
4009{
4010    mWaitTimeMs = UINT_MAX;
4011    for (size_t i = 0; i < mOutputTracks.size(); i++) {
4012        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
4013        if (strong != 0) {
4014            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4015            if (waitTimeMs < mWaitTimeMs) {
4016                mWaitTimeMs = waitTimeMs;
4017            }
4018        }
4019    }
4020}
4021
4022
4023bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
4024{
4025    for (size_t i = 0; i < outputTracks.size(); i++) {
4026        sp<ThreadBase> thread = outputTracks[i]->thread().promote();
4027        if (thread == 0) {
4028            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
4029            return false;
4030        }
4031        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4032        // see note at standby() declaration
4033        if (playbackThread->standby() && !playbackThread->isSuspended()) {
4034            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
4035            return false;
4036        }
4037    }
4038    return true;
4039}
4040
4041uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
4042{
4043    return (mWaitTimeMs * 1000) / 2;
4044}
4045
4046void AudioFlinger::DuplicatingThread::cacheParameters_l()
4047{
4048    // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4049    updateWaitTime_l();
4050
4051    MixerThread::cacheParameters_l();
4052}
4053
4054// ----------------------------------------------------------------------------
4055
4056// TrackBase constructor must be called with AudioFlinger::mLock held
4057AudioFlinger::ThreadBase::TrackBase::TrackBase(
4058            ThreadBase *thread,
4059            const sp<Client>& client,
4060            uint32_t sampleRate,
4061            audio_format_t format,
4062            audio_channel_mask_t channelMask,
4063            int frameCount,
4064            const sp<IMemory>& sharedBuffer,
4065            int sessionId)
4066    :   RefBase(),
4067        mThread(thread),
4068        mClient(client),
4069        mCblk(NULL),
4070        // mBuffer
4071        // mBufferEnd
4072        mFrameCount(0),
4073        mState(IDLE),
4074        mSampleRate(sampleRate),
4075        mFormat(format),
4076        mStepServerFailed(false),
4077        mSessionId(sessionId)
4078        // mChannelCount
4079        // mChannelMask
4080{
4081    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
4082
4083    // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
4084    size_t size = sizeof(audio_track_cblk_t);
4085    uint8_t channelCount = popcount(channelMask);
4086    size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4087    if (sharedBuffer == 0) {
4088        size += bufferSize;
4089    }
4090
4091    if (client != NULL) {
4092        mCblkMemory = client->heap()->allocate(size);
4093        if (mCblkMemory != 0) {
4094            mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
4095            if (mCblk != NULL) { // construct the shared structure in-place.
4096                new(mCblk) audio_track_cblk_t();
4097                // clear all buffers
4098                mCblk->frameCount = frameCount;
4099                mCblk->sampleRate = sampleRate;
4100// uncomment the following lines to quickly test 32-bit wraparound
4101//                mCblk->user = 0xffff0000;
4102//                mCblk->server = 0xffff0000;
4103//                mCblk->userBase = 0xffff0000;
4104//                mCblk->serverBase = 0xffff0000;
4105                mChannelCount = channelCount;
4106                mChannelMask = channelMask;
4107                if (sharedBuffer == 0) {
4108                    mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4109                    memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4110                    // Force underrun condition to avoid false underrun callback until first data is
4111                    // written to buffer (other flags are cleared)
4112                    mCblk->flags = CBLK_UNDERRUN_ON;
4113                } else {
4114                    mBuffer = sharedBuffer->pointer();
4115                }
4116                mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4117            }
4118        } else {
4119            ALOGE("not enough memory for AudioTrack size=%u", size);
4120            client->heap()->dump("AudioTrack");
4121            return;
4122        }
4123    } else {
4124        mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
4125        // construct the shared structure in-place.
4126        new(mCblk) audio_track_cblk_t();
4127        // clear all buffers
4128        mCblk->frameCount = frameCount;
4129        mCblk->sampleRate = sampleRate;
4130// uncomment the following lines to quickly test 32-bit wraparound
4131//        mCblk->user = 0xffff0000;
4132//        mCblk->server = 0xffff0000;
4133//        mCblk->userBase = 0xffff0000;
4134//        mCblk->serverBase = 0xffff0000;
4135        mChannelCount = channelCount;
4136        mChannelMask = channelMask;
4137        mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4138        memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4139        // Force underrun condition to avoid false underrun callback until first data is
4140        // written to buffer (other flags are cleared)
4141        mCblk->flags = CBLK_UNDERRUN_ON;
4142        mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4143    }
4144}
4145
4146AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4147{
4148    if (mCblk != NULL) {
4149        if (mClient == 0) {
4150            delete mCblk;
4151        } else {
4152            mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
4153        }
4154    }
4155    mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
4156    if (mClient != 0) {
4157        // Client destructor must run with AudioFlinger mutex locked
4158        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
4159        // If the client's reference count drops to zero, the associated destructor
4160        // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4161        // relying on the automatic clear() at end of scope.
4162        mClient.clear();
4163    }
4164}
4165
4166// AudioBufferProvider interface
4167// getNextBuffer() = 0;
4168// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
4169void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4170{
4171    buffer->raw = NULL;
4172    mFrameCount = buffer->frameCount;
4173    // FIXME See note at getNextBuffer()
4174    (void) step();      // ignore return value of step()
4175    buffer->frameCount = 0;
4176}
4177
4178bool AudioFlinger::ThreadBase::TrackBase::step() {
4179    bool result;
4180    audio_track_cblk_t* cblk = this->cblk();
4181
4182    result = cblk->stepServer(mFrameCount);
4183    if (!result) {
4184        ALOGV("stepServer failed acquiring cblk mutex");
4185        mStepServerFailed = true;
4186    }
4187    return result;
4188}
4189
4190void AudioFlinger::ThreadBase::TrackBase::reset() {
4191    audio_track_cblk_t* cblk = this->cblk();
4192
4193    cblk->user = 0;
4194    cblk->server = 0;
4195    cblk->userBase = 0;
4196    cblk->serverBase = 0;
4197    mStepServerFailed = false;
4198    ALOGV("TrackBase::reset");
4199}
4200
4201int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4202    return (int)mCblk->sampleRate;
4203}
4204
4205void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4206    audio_track_cblk_t* cblk = this->cblk();
4207    size_t frameSize = cblk->frameSize;
4208    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4209    int8_t *bufferEnd = bufferStart + frames * frameSize;
4210
4211    // Check validity of returned pointer in case the track control block would have been corrupted.
4212    ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4213            "TrackBase::getBuffer buffer out of range:\n"
4214                "    start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4215                "    server %u, serverBase %u, user %u, userBase %u, frameSize %d",
4216                bufferStart, bufferEnd, mBuffer, mBufferEnd,
4217                cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
4218
4219    return bufferStart;
4220}
4221
4222status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4223{
4224    mSyncEvents.add(event);
4225    return NO_ERROR;
4226}
4227
4228// ----------------------------------------------------------------------------
4229
4230// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4231AudioFlinger::PlaybackThread::Track::Track(
4232            PlaybackThread *thread,
4233            const sp<Client>& client,
4234            audio_stream_type_t streamType,
4235            uint32_t sampleRate,
4236            audio_format_t format,
4237            audio_channel_mask_t channelMask,
4238            int frameCount,
4239            const sp<IMemory>& sharedBuffer,
4240            int sessionId,
4241            IAudioFlinger::track_flags_t flags)
4242    :   TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
4243    mMute(false),
4244    mFillingUpStatus(FS_INVALID),
4245    // mRetryCount initialized later when needed
4246    mSharedBuffer(sharedBuffer),
4247    mStreamType(streamType),
4248    mName(-1),  // see note below
4249    mMainBuffer(thread->mixBuffer()),
4250    mAuxBuffer(NULL),
4251    mAuxEffectId(0), mHasVolumeController(false),
4252    mPresentationCompleteFrames(0),
4253    mFlags(flags),
4254    mFastIndex(-1),
4255    mUnderrunCount(0),
4256    mCachedVolume(1.0)
4257{
4258    if (mCblk != NULL) {
4259        // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4260        // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
4261        mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
4262        // to avoid leaking a track name, do not allocate one unless there is an mCblk
4263        mName = thread->getTrackName_l(channelMask);
4264        mCblk->mName = mName;
4265        if (mName < 0) {
4266            ALOGE("no more track names available");
4267            return;
4268        }
4269        // only allocate a fast track index if we were able to allocate a normal track name
4270        if (flags & IAudioFlinger::TRACK_FAST) {
4271            mCblk->flags |= CBLK_FAST;  // atomic op not needed yet
4272            ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4273            int i = __builtin_ctz(thread->mFastTrackAvailMask);
4274            ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
4275            // FIXME This is too eager.  We allocate a fast track index before the
4276            //       fast track becomes active.  Since fast tracks are a scarce resource,
4277            //       this means we are potentially denying other more important fast tracks from
4278            //       being created.  It would be better to allocate the index dynamically.
4279            mFastIndex = i;
4280            mCblk->mName = i;
4281            // Read the initial underruns because this field is never cleared by the fast mixer
4282            mObservedUnderruns = thread->getFastTrackUnderruns(i);
4283            thread->mFastTrackAvailMask &= ~(1 << i);
4284        }
4285    }
4286    ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4287}
4288
4289AudioFlinger::PlaybackThread::Track::~Track()
4290{
4291    ALOGV("PlaybackThread::Track destructor");
4292    sp<ThreadBase> thread = mThread.promote();
4293    if (thread != 0) {
4294        Mutex::Autolock _l(thread->mLock);
4295        mState = TERMINATED;
4296    }
4297}
4298
4299void AudioFlinger::PlaybackThread::Track::destroy()
4300{
4301    // NOTE: destroyTrack_l() can remove a strong reference to this Track
4302    // by removing it from mTracks vector, so there is a risk that this Tracks's
4303    // destructor is called. As the destructor needs to lock mLock,
4304    // we must acquire a strong reference on this Track before locking mLock
4305    // here so that the destructor is called only when exiting this function.
4306    // On the other hand, as long as Track::destroy() is only called by
4307    // TrackHandle destructor, the TrackHandle still holds a strong ref on
4308    // this Track with its member mTrack.
4309    sp<Track> keep(this);
4310    { // scope for mLock
4311        sp<ThreadBase> thread = mThread.promote();
4312        if (thread != 0) {
4313            if (!isOutputTrack()) {
4314                if (mState == ACTIVE || mState == RESUMING) {
4315                    AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4316
4317#ifdef ADD_BATTERY_DATA
4318                    // to track the speaker usage
4319                    addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4320#endif
4321                }
4322                AudioSystem::releaseOutput(thread->id());
4323            }
4324            Mutex::Autolock _l(thread->mLock);
4325            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4326            playbackThread->destroyTrack_l(this);
4327        }
4328    }
4329}
4330
4331/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4332{
4333    result.append("   Name Client Type Fmt Chn mask   Session mFrCnt fCount S M F SRate  L dB  R dB  "
4334                  "  Server      User     Main buf    Aux Buf  Flags Underruns\n");
4335}
4336
4337void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4338{
4339    uint32_t vlr = mCblk->getVolumeLR();
4340    if (isFastTrack()) {
4341        sprintf(buffer, "   F %2d", mFastIndex);
4342    } else {
4343        sprintf(buffer, "   %4d", mName - AudioMixer::TRACK0);
4344    }
4345    track_state state = mState;
4346    char stateChar;
4347    switch (state) {
4348    case IDLE:
4349        stateChar = 'I';
4350        break;
4351    case TERMINATED:
4352        stateChar = 'T';
4353        break;
4354    case STOPPING_1:
4355        stateChar = 's';
4356        break;
4357    case STOPPING_2:
4358        stateChar = '5';
4359        break;
4360    case STOPPED:
4361        stateChar = 'S';
4362        break;
4363    case RESUMING:
4364        stateChar = 'R';
4365        break;
4366    case ACTIVE:
4367        stateChar = 'A';
4368        break;
4369    case PAUSING:
4370        stateChar = 'p';
4371        break;
4372    case PAUSED:
4373        stateChar = 'P';
4374        break;
4375    case FLUSHED:
4376        stateChar = 'F';
4377        break;
4378    default:
4379        stateChar = '?';
4380        break;
4381    }
4382    char nowInUnderrun;
4383    switch (mObservedUnderruns.mBitFields.mMostRecent) {
4384    case UNDERRUN_FULL:
4385        nowInUnderrun = ' ';
4386        break;
4387    case UNDERRUN_PARTIAL:
4388        nowInUnderrun = '<';
4389        break;
4390    case UNDERRUN_EMPTY:
4391        nowInUnderrun = '*';
4392        break;
4393    default:
4394        nowInUnderrun = '?';
4395        break;
4396    }
4397    snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g  "
4398            "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
4399            (mClient == 0) ? getpid_cached : mClient->pid(),
4400            mStreamType,
4401            mFormat,
4402            mChannelMask,
4403            mSessionId,
4404            mFrameCount,
4405            mCblk->frameCount,
4406            stateChar,
4407            mMute,
4408            mFillingUpStatus,
4409            mCblk->sampleRate,
4410            20.0 * log10((vlr & 0xFFFF) / 4096.0),
4411            20.0 * log10((vlr >> 16) / 4096.0),
4412            mCblk->server,
4413            mCblk->user,
4414            (int)mMainBuffer,
4415            (int)mAuxBuffer,
4416            mCblk->flags,
4417            mUnderrunCount,
4418            nowInUnderrun);
4419}
4420
4421// AudioBufferProvider interface
4422status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
4423        AudioBufferProvider::Buffer* buffer, int64_t pts)
4424{
4425    audio_track_cblk_t* cblk = this->cblk();
4426    uint32_t framesReady;
4427    uint32_t framesReq = buffer->frameCount;
4428
4429    // Check if last stepServer failed, try to step now
4430    if (mStepServerFailed) {
4431        // FIXME When called by fast mixer, this takes a mutex with tryLock().
4432        //       Since the fast mixer is higher priority than client callback thread,
4433        //       it does not result in priority inversion for client.
4434        //       But a non-blocking solution would be preferable to avoid
4435        //       fast mixer being unable to tryLock(), and
4436        //       to avoid the extra context switches if the client wakes up,
4437        //       discovers the mutex is locked, then has to wait for fast mixer to unlock.
4438        if (!step())  goto getNextBuffer_exit;
4439        ALOGV("stepServer recovered");
4440        mStepServerFailed = false;
4441    }
4442
4443    // FIXME Same as above
4444    framesReady = cblk->framesReady();
4445
4446    if (CC_LIKELY(framesReady)) {
4447        uint32_t s = cblk->server;
4448        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4449
4450        bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4451        if (framesReq > framesReady) {
4452            framesReq = framesReady;
4453        }
4454        if (framesReq > bufferEnd - s) {
4455            framesReq = bufferEnd - s;
4456        }
4457
4458        buffer->raw = getBuffer(s, framesReq);
4459        buffer->frameCount = framesReq;
4460        return NO_ERROR;
4461    }
4462
4463getNextBuffer_exit:
4464    buffer->raw = NULL;
4465    buffer->frameCount = 0;
4466    ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4467    return NOT_ENOUGH_DATA;
4468}
4469
4470// Note that framesReady() takes a mutex on the control block using tryLock().
4471// This could result in priority inversion if framesReady() is called by the normal mixer,
4472// as the normal mixer thread runs at lower
4473// priority than the client's callback thread:  there is a short window within framesReady()
4474// during which the normal mixer could be preempted, and the client callback would block.
4475// Another problem can occur if framesReady() is called by the fast mixer:
4476// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4477// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4478size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
4479    return mCblk->framesReady();
4480}
4481
4482// Don't call for fast tracks; the framesReady() could result in priority inversion
4483bool AudioFlinger::PlaybackThread::Track::isReady() const {
4484    if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
4485
4486    if (framesReady() >= mCblk->frameCount ||
4487            (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4488        mFillingUpStatus = FS_FILLED;
4489        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4490        return true;
4491    }
4492    return false;
4493}
4494
4495status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
4496                                                    int triggerSession)
4497{
4498    status_t status = NO_ERROR;
4499    ALOGV("start(%d), calling pid %d session %d",
4500            mName, IPCThreadState::self()->getCallingPid(), mSessionId);
4501
4502    sp<ThreadBase> thread = mThread.promote();
4503    if (thread != 0) {
4504        Mutex::Autolock _l(thread->mLock);
4505        track_state state = mState;
4506        // here the track could be either new, or restarted
4507        // in both cases "unstop" the track
4508        if (mState == PAUSED) {
4509            mState = TrackBase::RESUMING;
4510            ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
4511        } else {
4512            mState = TrackBase::ACTIVE;
4513            ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
4514        }
4515
4516        if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4517            thread->mLock.unlock();
4518            status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
4519            thread->mLock.lock();
4520
4521#ifdef ADD_BATTERY_DATA
4522            // to track the speaker usage
4523            if (status == NO_ERROR) {
4524                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4525            }
4526#endif
4527        }
4528        if (status == NO_ERROR) {
4529            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4530            playbackThread->addTrack_l(this);
4531        } else {
4532            mState = state;
4533            triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4534        }
4535    } else {
4536        status = BAD_VALUE;
4537    }
4538    return status;
4539}
4540
4541void AudioFlinger::PlaybackThread::Track::stop()
4542{
4543    ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4544    sp<ThreadBase> thread = mThread.promote();
4545    if (thread != 0) {
4546        Mutex::Autolock _l(thread->mLock);
4547        track_state state = mState;
4548        if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
4549            // If the track is not active (PAUSED and buffers full), flush buffers
4550            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4551            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4552                reset();
4553                mState = STOPPED;
4554            } else if (!isFastTrack()) {
4555                mState = STOPPED;
4556            } else {
4557                // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4558                // and then to STOPPED and reset() when presentation is complete
4559                mState = STOPPING_1;
4560            }
4561            ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
4562        }
4563        if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4564            thread->mLock.unlock();
4565            AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4566            thread->mLock.lock();
4567
4568#ifdef ADD_BATTERY_DATA
4569            // to track the speaker usage
4570            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4571#endif
4572        }
4573    }
4574}
4575
4576void AudioFlinger::PlaybackThread::Track::pause()
4577{
4578    ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
4579    sp<ThreadBase> thread = mThread.promote();
4580    if (thread != 0) {
4581        Mutex::Autolock _l(thread->mLock);
4582        if (mState == ACTIVE || mState == RESUMING) {
4583            mState = PAUSING;
4584            ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
4585            if (!isOutputTrack()) {
4586                thread->mLock.unlock();
4587                AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
4588                thread->mLock.lock();
4589
4590#ifdef ADD_BATTERY_DATA
4591                // to track the speaker usage
4592                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
4593#endif
4594            }
4595        }
4596    }
4597}
4598
4599void AudioFlinger::PlaybackThread::Track::flush()
4600{
4601    ALOGV("flush(%d)", mName);
4602    sp<ThreadBase> thread = mThread.promote();
4603    if (thread != 0) {
4604        Mutex::Autolock _l(thread->mLock);
4605        if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4606                mState != PAUSING) {
4607            return;
4608        }
4609        // No point remaining in PAUSED state after a flush => go to
4610        // FLUSHED state
4611        mState = FLUSHED;
4612        // do not reset the track if it is still in the process of being stopped or paused.
4613        // this will be done by prepareTracks_l() when the track is stopped.
4614        // prepareTracks_l() will see mState == FLUSHED, then
4615        // remove from active track list, reset(), and trigger presentation complete
4616        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4617        if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4618            reset();
4619        }
4620    }
4621}
4622
4623void AudioFlinger::PlaybackThread::Track::reset()
4624{
4625    // Do not reset twice to avoid discarding data written just after a flush and before
4626    // the audioflinger thread detects the track is stopped.
4627    if (!mResetDone) {
4628        TrackBase::reset();
4629        // Force underrun condition to avoid false underrun callback until first data is
4630        // written to buffer
4631        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4632        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
4633        mFillingUpStatus = FS_FILLING;
4634        mResetDone = true;
4635        if (mState == FLUSHED) {
4636            mState = IDLE;
4637        }
4638    }
4639}
4640
4641void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4642{
4643    mMute = muted;
4644}
4645
4646status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4647{
4648    status_t status = DEAD_OBJECT;
4649    sp<ThreadBase> thread = mThread.promote();
4650    if (thread != 0) {
4651        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4652        sp<AudioFlinger> af = mClient->audioFlinger();
4653
4654        Mutex::Autolock _l(af->mLock);
4655
4656        sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
4657
4658        if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
4659            Mutex::Autolock _dl(playbackThread->mLock);
4660            Mutex::Autolock _sl(srcThread->mLock);
4661            sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4662            if (chain == 0) {
4663                return INVALID_OPERATION;
4664            }
4665
4666            sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4667            if (effect == 0) {
4668                return INVALID_OPERATION;
4669            }
4670            srcThread->removeEffect_l(effect);
4671            playbackThread->addEffect_l(effect);
4672            // removeEffect_l() has stopped the effect if it was active so it must be restarted
4673            if (effect->state() == EffectModule::ACTIVE ||
4674                    effect->state() == EffectModule::STOPPING) {
4675                effect->start();
4676            }
4677
4678            sp<EffectChain> dstChain = effect->chain().promote();
4679            if (dstChain == 0) {
4680                srcThread->addEffect_l(effect);
4681                return INVALID_OPERATION;
4682            }
4683            AudioSystem::unregisterEffect(effect->id());
4684            AudioSystem::registerEffect(&effect->desc(),
4685                                        srcThread->id(),
4686                                        dstChain->strategy(),
4687                                        AUDIO_SESSION_OUTPUT_MIX,
4688                                        effect->id());
4689        }
4690        status = playbackThread->attachAuxEffect(this, EffectId);
4691    }
4692    return status;
4693}
4694
4695void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4696{
4697    mAuxEffectId = EffectId;
4698    mAuxBuffer = buffer;
4699}
4700
4701bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4702                                                         size_t audioHalFrames)
4703{
4704    // a track is considered presented when the total number of frames written to audio HAL
4705    // corresponds to the number of frames written when presentationComplete() is called for the
4706    // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4707    if (mPresentationCompleteFrames == 0) {
4708        mPresentationCompleteFrames = framesWritten + audioHalFrames;
4709        ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4710                  mPresentationCompleteFrames, audioHalFrames);
4711    }
4712    if (framesWritten >= mPresentationCompleteFrames) {
4713        ALOGV("presentationComplete() session %d complete: framesWritten %d",
4714                  mSessionId, framesWritten);
4715        triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4716        return true;
4717    }
4718    return false;
4719}
4720
4721void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4722{
4723    for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4724        if (mSyncEvents[i]->type() == type) {
4725            mSyncEvents[i]->trigger();
4726            mSyncEvents.removeAt(i);
4727            i--;
4728        }
4729    }
4730}
4731
4732// implement VolumeBufferProvider interface
4733
4734uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4735{
4736    // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4737    ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4738    uint32_t vlr = mCblk->getVolumeLR();
4739    uint32_t vl = vlr & 0xFFFF;
4740    uint32_t vr = vlr >> 16;
4741    // track volumes come from shared memory, so can't be trusted and must be clamped
4742    if (vl > MAX_GAIN_INT) {
4743        vl = MAX_GAIN_INT;
4744    }
4745    if (vr > MAX_GAIN_INT) {
4746        vr = MAX_GAIN_INT;
4747    }
4748    // now apply the cached master volume and stream type volume;
4749    // this is trusted but lacks any synchronization or barrier so may be stale
4750    float v = mCachedVolume;
4751    vl *= v;
4752    vr *= v;
4753    // re-combine into U4.16
4754    vlr = (vr << 16) | (vl & 0xFFFF);
4755    // FIXME look at mute, pause, and stop flags
4756    return vlr;
4757}
4758
4759status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4760{
4761    if (mState == TERMINATED || mState == PAUSED ||
4762            ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4763                                      (mState == STOPPED)))) {
4764        ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4765              mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4766        event->cancel();
4767        return INVALID_OPERATION;
4768    }
4769    TrackBase::setSyncEvent(event);
4770    return NO_ERROR;
4771}
4772
4773// timed audio tracks
4774
4775sp<AudioFlinger::PlaybackThread::TimedTrack>
4776AudioFlinger::PlaybackThread::TimedTrack::create(
4777            PlaybackThread *thread,
4778            const sp<Client>& client,
4779            audio_stream_type_t streamType,
4780            uint32_t sampleRate,
4781            audio_format_t format,
4782            audio_channel_mask_t channelMask,
4783            int frameCount,
4784            const sp<IMemory>& sharedBuffer,
4785            int sessionId) {
4786    if (!client->reserveTimedTrack())
4787        return 0;
4788
4789    return new TimedTrack(
4790        thread, client, streamType, sampleRate, format, channelMask, frameCount,
4791        sharedBuffer, sessionId);
4792}
4793
4794AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
4795            PlaybackThread *thread,
4796            const sp<Client>& client,
4797            audio_stream_type_t streamType,
4798            uint32_t sampleRate,
4799            audio_format_t format,
4800            audio_channel_mask_t channelMask,
4801            int frameCount,
4802            const sp<IMemory>& sharedBuffer,
4803            int sessionId)
4804    : Track(thread, client, streamType, sampleRate, format, channelMask,
4805            frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
4806      mQueueHeadInFlight(false),
4807      mTrimQueueHeadOnRelease(false),
4808      mFramesPendingInQueue(0),
4809      mTimedSilenceBuffer(NULL),
4810      mTimedSilenceBufferSize(0),
4811      mTimedAudioOutputOnTime(false),
4812      mMediaTimeTransformValid(false)
4813{
4814    LocalClock lc;
4815    mLocalTimeFreq = lc.getLocalFreq();
4816
4817    mLocalTimeToSampleTransform.a_zero = 0;
4818    mLocalTimeToSampleTransform.b_zero = 0;
4819    mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4820    mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4821    LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4822                            &mLocalTimeToSampleTransform.a_to_b_denom);
4823
4824    mMediaTimeToSampleTransform.a_zero = 0;
4825    mMediaTimeToSampleTransform.b_zero = 0;
4826    mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4827    mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4828    LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4829                            &mMediaTimeToSampleTransform.a_to_b_denom);
4830}
4831
4832AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4833    mClient->releaseTimedTrack();
4834    delete [] mTimedSilenceBuffer;
4835}
4836
4837status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4838    size_t size, sp<IMemory>* buffer) {
4839
4840    Mutex::Autolock _l(mTimedBufferQueueLock);
4841
4842    trimTimedBufferQueue_l();
4843
4844    // lazily initialize the shared memory heap for timed buffers
4845    if (mTimedMemoryDealer == NULL) {
4846        const int kTimedBufferHeapSize = 512 << 10;
4847
4848        mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4849                                              "AudioFlingerTimed");
4850        if (mTimedMemoryDealer == NULL)
4851            return NO_MEMORY;
4852    }
4853
4854    sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4855    if (newBuffer == NULL) {
4856        newBuffer = mTimedMemoryDealer->allocate(size);
4857        if (newBuffer == NULL)
4858            return NO_MEMORY;
4859    }
4860
4861    *buffer = newBuffer;
4862    return NO_ERROR;
4863}
4864
4865// caller must hold mTimedBufferQueueLock
4866void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4867    int64_t mediaTimeNow;
4868    {
4869        Mutex::Autolock mttLock(mMediaTimeTransformLock);
4870        if (!mMediaTimeTransformValid)
4871            return;
4872
4873        int64_t targetTimeNow;
4874        status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4875            ? mCCHelper.getCommonTime(&targetTimeNow)
4876            : mCCHelper.getLocalTime(&targetTimeNow);
4877
4878        if (OK != res)
4879            return;
4880
4881        if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4882                                                    &mediaTimeNow)) {
4883            return;
4884        }
4885    }
4886
4887    size_t trimEnd;
4888    for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
4889        int64_t bufEnd;
4890
4891        if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4892            // We have a next buffer.  Just use its PTS as the PTS of the frame
4893            // following the last frame in this buffer.  If the stream is sparse
4894            // (ie, there are deliberate gaps left in the stream which should be
4895            // filled with silence by the TimedAudioTrack), then this can result
4896            // in one extra buffer being left un-trimmed when it could have
4897            // been.  In general, this is not typical, and we would rather
4898            // optimized away the TS calculation below for the more common case
4899            // where PTSes are contiguous.
4900            bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4901        } else {
4902            // We have no next buffer.  Compute the PTS of the frame following
4903            // the last frame in this buffer by computing the duration of of
4904            // this frame in media time units and adding it to the PTS of the
4905            // buffer.
4906            int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4907                               / mCblk->frameSize;
4908
4909            if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4910                                                                &bufEnd)) {
4911                ALOGE("Failed to convert frame count of %lld to media time"
4912                      " duration" " (scale factor %d/%u) in %s",
4913                      frameCount,
4914                      mMediaTimeToSampleTransform.a_to_b_numer,
4915                      mMediaTimeToSampleTransform.a_to_b_denom,
4916                      __PRETTY_FUNCTION__);
4917                break;
4918            }
4919            bufEnd += mTimedBufferQueue[trimEnd].pts();
4920        }
4921
4922        if (bufEnd > mediaTimeNow)
4923            break;
4924
4925        // Is the buffer we want to use in the middle of a mix operation right
4926        // now?  If so, don't actually trim it.  Just wait for the releaseBuffer
4927        // from the mixer which should be coming back shortly.
4928        if (!trimEnd && mQueueHeadInFlight) {
4929            mTrimQueueHeadOnRelease = true;
4930        }
4931    }
4932
4933    size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
4934    if (trimStart < trimEnd) {
4935        // Update the bookkeeping for framesReady()
4936        for (size_t i = trimStart; i < trimEnd; ++i) {
4937            updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4938        }
4939
4940        // Now actually remove the buffers from the queue.
4941        mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
4942    }
4943}
4944
4945void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4946        const char* logTag) {
4947    ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4948                "%s called (reason \"%s\"), but timed buffer queue has no"
4949                " elements to trim.", __FUNCTION__, logTag);
4950
4951    updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4952    mTimedBufferQueue.removeAt(0);
4953}
4954
4955void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4956        const TimedBuffer& buf,
4957        const char* logTag) {
4958    uint32_t bufBytes        = buf.buffer()->size();
4959    uint32_t consumedAlready = buf.position();
4960
4961    ALOG_ASSERT(consumedAlready <= bufBytes,
4962                "Bad bookkeeping while updating frames pending.  Timed buffer is"
4963                " only %u bytes long, but claims to have consumed %u"
4964                " bytes.  (update reason: \"%s\")",
4965                bufBytes, consumedAlready, logTag);
4966
4967    uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
4968    ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4969                "Bad bookkeeping while updating frames pending.  Should have at"
4970                " least %u queued frames, but we think we have only %u.  (update"
4971                " reason: \"%s\")",
4972                bufFrames, mFramesPendingInQueue, logTag);
4973
4974    mFramesPendingInQueue -= bufFrames;
4975}
4976
4977status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4978    const sp<IMemory>& buffer, int64_t pts) {
4979
4980    {
4981        Mutex::Autolock mttLock(mMediaTimeTransformLock);
4982        if (!mMediaTimeTransformValid)
4983            return INVALID_OPERATION;
4984    }
4985
4986    Mutex::Autolock _l(mTimedBufferQueueLock);
4987
4988    uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4989    mFramesPendingInQueue += bufFrames;
4990    mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4991
4992    return NO_ERROR;
4993}
4994
4995status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4996    const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4997
4998    ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4999           xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5000           target);
5001
5002    if (!(target == TimedAudioTrack::LOCAL_TIME ||
5003          target == TimedAudioTrack::COMMON_TIME)) {
5004        return BAD_VALUE;
5005    }
5006
5007    Mutex::Autolock lock(mMediaTimeTransformLock);
5008    mMediaTimeTransform = xform;
5009    mMediaTimeTransformTarget = target;
5010    mMediaTimeTransformValid = true;
5011
5012    return NO_ERROR;
5013}
5014
5015#define min(a, b) ((a) < (b) ? (a) : (b))
5016
5017// implementation of getNextBuffer for tracks whose buffers have timestamps
5018status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5019    AudioBufferProvider::Buffer* buffer, int64_t pts)
5020{
5021    if (pts == AudioBufferProvider::kInvalidPTS) {
5022        buffer->raw = NULL;
5023        buffer->frameCount = 0;
5024        mTimedAudioOutputOnTime = false;
5025        return INVALID_OPERATION;
5026    }
5027
5028    Mutex::Autolock _l(mTimedBufferQueueLock);
5029
5030    ALOG_ASSERT(!mQueueHeadInFlight,
5031                "getNextBuffer called without releaseBuffer!");
5032
5033    while (true) {
5034
5035        // if we have no timed buffers, then fail
5036        if (mTimedBufferQueue.isEmpty()) {
5037            buffer->raw = NULL;
5038            buffer->frameCount = 0;
5039            return NOT_ENOUGH_DATA;
5040        }
5041
5042        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5043
5044        // calculate the PTS of the head of the timed buffer queue expressed in
5045        // local time
5046        int64_t headLocalPTS;
5047        {
5048            Mutex::Autolock mttLock(mMediaTimeTransformLock);
5049
5050            ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
5051
5052            if (mMediaTimeTransform.a_to_b_denom == 0) {
5053                // the transform represents a pause, so yield silence
5054                timedYieldSilence_l(buffer->frameCount, buffer);
5055                return NO_ERROR;
5056            }
5057
5058            int64_t transformedPTS;
5059            if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5060                                                        &transformedPTS)) {
5061                // the transform failed.  this shouldn't happen, but if it does
5062                // then just drop this buffer
5063                ALOGW("timedGetNextBuffer transform failed");
5064                buffer->raw = NULL;
5065                buffer->frameCount = 0;
5066                trimTimedBufferQueueHead_l("getNextBuffer; no transform");
5067                return NO_ERROR;
5068            }
5069
5070            if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5071                if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5072                                                          &headLocalPTS)) {
5073                    buffer->raw = NULL;
5074                    buffer->frameCount = 0;
5075                    return INVALID_OPERATION;
5076                }
5077            } else {
5078                headLocalPTS = transformedPTS;
5079            }
5080        }
5081
5082        // adjust the head buffer's PTS to reflect the portion of the head buffer
5083        // that has already been consumed
5084        int64_t effectivePTS = headLocalPTS +
5085                ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5086
5087        // Calculate the delta in samples between the head of the input buffer
5088        // queue and the start of the next output buffer that will be written.
5089        // If the transformation fails because of over or underflow, it means
5090        // that the sample's position in the output stream is so far out of
5091        // whack that it should just be dropped.
5092        int64_t sampleDelta;
5093        if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5094            ALOGV("*** head buffer is too far from PTS: dropped buffer");
5095            trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5096                                       " mix");
5097            continue;
5098        }
5099        if (!mLocalTimeToSampleTransform.doForwardTransform(
5100                (effectivePTS - pts) << 32, &sampleDelta)) {
5101            ALOGV("*** too late during sample rate transform: dropped buffer");
5102            trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
5103            continue;
5104        }
5105
5106        ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5107               " sampleDelta=[%d.%08x]",
5108               head.pts(), head.position(), pts,
5109               static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5110                   + (sampleDelta >> 32)),
5111               static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
5112
5113        // if the delta between the ideal placement for the next input sample and
5114        // the current output position is within this threshold, then we will
5115        // concatenate the next input samples to the previous output
5116        const int64_t kSampleContinuityThreshold =
5117                (static_cast<int64_t>(sampleRate()) << 32) / 250;
5118
5119        // if this is the first buffer of audio that we're emitting from this track
5120        // then it should be almost exactly on time.
5121        const int64_t kSampleStartupThreshold = 1LL << 32;
5122
5123        if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
5124           (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
5125            // the next input is close enough to being on time, so concatenate it
5126            // with the last output
5127            timedYieldSamples_l(buffer);
5128
5129            ALOGVV("*** on time: head.pos=%d frameCount=%u",
5130                    head.position(), buffer->frameCount);
5131            return NO_ERROR;
5132        }
5133
5134        // Looks like our output is not on time.  Reset our on timed status.
5135        // Next time we mix samples from our input queue, then should be within
5136        // the StartupThreshold.
5137        mTimedAudioOutputOnTime = false;
5138        if (sampleDelta > 0) {
5139            // the gap between the current output position and the proper start of
5140            // the next input sample is too big, so fill it with silence
5141            uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5142
5143            timedYieldSilence_l(framesUntilNextInput, buffer);
5144            ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5145            return NO_ERROR;
5146        } else {
5147            // the next input sample is late
5148            uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5149            size_t onTimeSamplePosition =
5150                    head.position() + lateFrames * mCblk->frameSize;
5151
5152            if (onTimeSamplePosition > head.buffer()->size()) {
5153                // all the remaining samples in the head are too late, so
5154                // drop it and move on
5155                ALOGV("*** too late: dropped buffer");
5156                trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
5157                continue;
5158            } else {
5159                // skip over the late samples
5160                head.setPosition(onTimeSamplePosition);
5161
5162                // yield the available samples
5163                timedYieldSamples_l(buffer);
5164
5165                ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5166                return NO_ERROR;
5167            }
5168        }
5169    }
5170}
5171
5172// Yield samples from the timed buffer queue head up to the given output
5173// buffer's capacity.
5174//
5175// Caller must hold mTimedBufferQueueLock
5176void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
5177    AudioBufferProvider::Buffer* buffer) {
5178
5179    const TimedBuffer& head = mTimedBufferQueue[0];
5180
5181    buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5182                   head.position());
5183
5184    uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5185                                 mCblk->frameSize);
5186    size_t framesRequested = buffer->frameCount;
5187    buffer->frameCount = min(framesLeftInHead, framesRequested);
5188
5189    mQueueHeadInFlight = true;
5190    mTimedAudioOutputOnTime = true;
5191}
5192
5193// Yield samples of silence up to the given output buffer's capacity
5194//
5195// Caller must hold mTimedBufferQueueLock
5196void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
5197    uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5198
5199    // lazily allocate a buffer filled with silence
5200    if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5201        delete [] mTimedSilenceBuffer;
5202        mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5203        mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5204        memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5205    }
5206
5207    buffer->raw = mTimedSilenceBuffer;
5208    size_t framesRequested = buffer->frameCount;
5209    buffer->frameCount = min(numFrames, framesRequested);
5210
5211    mTimedAudioOutputOnTime = false;
5212}
5213
5214// AudioBufferProvider interface
5215void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5216    AudioBufferProvider::Buffer* buffer) {
5217
5218    Mutex::Autolock _l(mTimedBufferQueueLock);
5219
5220    // If the buffer which was just released is part of the buffer at the head
5221    // of the queue, be sure to update the amt of the buffer which has been
5222    // consumed.  If the buffer being returned is not part of the head of the
5223    // queue, its either because the buffer is part of the silence buffer, or
5224    // because the head of the timed queue was trimmed after the mixer called
5225    // getNextBuffer but before the mixer called releaseBuffer.
5226    if (buffer->raw == mTimedSilenceBuffer) {
5227        ALOG_ASSERT(!mQueueHeadInFlight,
5228                    "Queue head in flight during release of silence buffer!");
5229        goto done;
5230    }
5231
5232    ALOG_ASSERT(mQueueHeadInFlight,
5233                "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5234                " head in flight.");
5235
5236    if (mTimedBufferQueue.size()) {
5237        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5238
5239        void* start = head.buffer()->pointer();
5240        void* end   = reinterpret_cast<void*>(
5241                        reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5242                        + head.buffer()->size());
5243
5244        ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5245                    "released buffer not within the head of the timed buffer"
5246                    " queue; qHead = [%p, %p], released buffer = %p",
5247                    start, end, buffer->raw);
5248
5249        head.setPosition(head.position() +
5250                (buffer->frameCount * mCblk->frameSize));
5251        mQueueHeadInFlight = false;
5252
5253        ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5254                    "Bad bookkeeping during releaseBuffer!  Should have at"
5255                    " least %u queued frames, but we think we have only %u",
5256                    buffer->frameCount, mFramesPendingInQueue);
5257
5258        mFramesPendingInQueue -= buffer->frameCount;
5259
5260        if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5261            || mTrimQueueHeadOnRelease) {
5262            trimTimedBufferQueueHead_l("releaseBuffer");
5263            mTrimQueueHeadOnRelease = false;
5264        }
5265    } else {
5266        LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5267                  " buffers in the timed buffer queue");
5268    }
5269
5270done:
5271    buffer->raw = 0;
5272    buffer->frameCount = 0;
5273}
5274
5275size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
5276    Mutex::Autolock _l(mTimedBufferQueueLock);
5277    return mFramesPendingInQueue;
5278}
5279
5280AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5281        : mPTS(0), mPosition(0) {}
5282
5283AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5284    const sp<IMemory>& buffer, int64_t pts)
5285        : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5286
5287// ----------------------------------------------------------------------------
5288
5289// RecordTrack constructor must be called with AudioFlinger::mLock held
5290AudioFlinger::RecordThread::RecordTrack::RecordTrack(
5291            RecordThread *thread,
5292            const sp<Client>& client,
5293            uint32_t sampleRate,
5294            audio_format_t format,
5295            audio_channel_mask_t channelMask,
5296            int frameCount,
5297            int sessionId)
5298    :   TrackBase(thread, client, sampleRate, format,
5299                  channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
5300        mOverflow(false)
5301{
5302    if (mCblk != NULL) {
5303        ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5304        if (format == AUDIO_FORMAT_PCM_16_BIT) {
5305            mCblk->frameSize = mChannelCount * sizeof(int16_t);
5306        } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5307            mCblk->frameSize = mChannelCount * sizeof(int8_t);
5308        } else {
5309            mCblk->frameSize = sizeof(int8_t);
5310        }
5311    }
5312}
5313
5314AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5315{
5316    sp<ThreadBase> thread = mThread.promote();
5317    if (thread != 0) {
5318        AudioSystem::releaseInput(thread->id());
5319    }
5320}
5321
5322// AudioBufferProvider interface
5323status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
5324{
5325    audio_track_cblk_t* cblk = this->cblk();
5326    uint32_t framesAvail;
5327    uint32_t framesReq = buffer->frameCount;
5328
5329    // Check if last stepServer failed, try to step now
5330    if (mStepServerFailed) {
5331        if (!step()) goto getNextBuffer_exit;
5332        ALOGV("stepServer recovered");
5333        mStepServerFailed = false;
5334    }
5335
5336    framesAvail = cblk->framesAvailable_l();
5337
5338    if (CC_LIKELY(framesAvail)) {
5339        uint32_t s = cblk->server;
5340        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5341
5342        if (framesReq > framesAvail) {
5343            framesReq = framesAvail;
5344        }
5345        if (framesReq > bufferEnd - s) {
5346            framesReq = bufferEnd - s;
5347        }
5348
5349        buffer->raw = getBuffer(s, framesReq);
5350        buffer->frameCount = framesReq;
5351        return NO_ERROR;
5352    }
5353
5354getNextBuffer_exit:
5355    buffer->raw = NULL;
5356    buffer->frameCount = 0;
5357    return NOT_ENOUGH_DATA;
5358}
5359
5360status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
5361                                                        int triggerSession)
5362{
5363    sp<ThreadBase> thread = mThread.promote();
5364    if (thread != 0) {
5365        RecordThread *recordThread = (RecordThread *)thread.get();
5366        return recordThread->start(this, event, triggerSession);
5367    } else {
5368        return BAD_VALUE;
5369    }
5370}
5371
5372void AudioFlinger::RecordThread::RecordTrack::stop()
5373{
5374    sp<ThreadBase> thread = mThread.promote();
5375    if (thread != 0) {
5376        RecordThread *recordThread = (RecordThread *)thread.get();
5377        recordThread->stop(this);
5378        TrackBase::reset();
5379        // Force overrun condition to avoid false overrun callback until first data is
5380        // read from buffer
5381        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5382    }
5383}
5384
5385void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5386{
5387    snprintf(buffer, size, "   %05d %03u 0x%08x %05d   %04u %01d %05u  %08x %08x\n",
5388            (mClient == 0) ? getpid_cached : mClient->pid(),
5389            mFormat,
5390            mChannelMask,
5391            mSessionId,
5392            mFrameCount,
5393            mState,
5394            mCblk->sampleRate,
5395            mCblk->server,
5396            mCblk->user);
5397}
5398
5399
5400// ----------------------------------------------------------------------------
5401
5402AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
5403            PlaybackThread *playbackThread,
5404            DuplicatingThread *sourceThread,
5405            uint32_t sampleRate,
5406            audio_format_t format,
5407            audio_channel_mask_t channelMask,
5408            int frameCount)
5409    :   Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5410                NULL, 0, IAudioFlinger::TRACK_DEFAULT),
5411    mActive(false), mSourceThread(sourceThread)
5412{
5413
5414    if (mCblk != NULL) {
5415        mCblk->flags |= CBLK_DIRECTION_OUT;
5416        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
5417        mOutBuffer.frameCount = 0;
5418        playbackThread->mTracks.add(this);
5419        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
5420                "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5421                mCblk, mBuffer, mCblk->buffers,
5422                mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
5423    } else {
5424        ALOGW("Error creating output track on thread %p", playbackThread);
5425    }
5426}
5427
5428AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5429{
5430    clearBufferQueue();
5431}
5432
5433status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
5434                                                          int triggerSession)
5435{
5436    status_t status = Track::start(event, triggerSession);
5437    if (status != NO_ERROR) {
5438        return status;
5439    }
5440
5441    mActive = true;
5442    mRetryCount = 127;
5443    return status;
5444}
5445
5446void AudioFlinger::PlaybackThread::OutputTrack::stop()
5447{
5448    Track::stop();
5449    clearBufferQueue();
5450    mOutBuffer.frameCount = 0;
5451    mActive = false;
5452}
5453
5454bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5455{
5456    Buffer *pInBuffer;
5457    Buffer inBuffer;
5458    uint32_t channelCount = mChannelCount;
5459    bool outputBufferFull = false;
5460    inBuffer.frameCount = frames;
5461    inBuffer.i16 = data;
5462
5463    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5464
5465    if (!mActive && frames != 0) {
5466        start();
5467        sp<ThreadBase> thread = mThread.promote();
5468        if (thread != 0) {
5469            MixerThread *mixerThread = (MixerThread *)thread.get();
5470            if (mCblk->frameCount > frames){
5471                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5472                    uint32_t startFrames = (mCblk->frameCount - frames);
5473                    pInBuffer = new Buffer;
5474                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5475                    pInBuffer->frameCount = startFrames;
5476                    pInBuffer->i16 = pInBuffer->mBuffer;
5477                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5478                    mBufferQueue.add(pInBuffer);
5479                } else {
5480                    ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
5481                }
5482            }
5483        }
5484    }
5485
5486    while (waitTimeLeftMs) {
5487        // First write pending buffers, then new data
5488        if (mBufferQueue.size()) {
5489            pInBuffer = mBufferQueue.itemAt(0);
5490        } else {
5491            pInBuffer = &inBuffer;
5492        }
5493
5494        if (pInBuffer->frameCount == 0) {
5495            break;
5496        }
5497
5498        if (mOutBuffer.frameCount == 0) {
5499            mOutBuffer.frameCount = pInBuffer->frameCount;
5500            nsecs_t startTime = systemTime();
5501            if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
5502                ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
5503                outputBufferFull = true;
5504                break;
5505            }
5506            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5507            if (waitTimeLeftMs >= waitTimeMs) {
5508                waitTimeLeftMs -= waitTimeMs;
5509            } else {
5510                waitTimeLeftMs = 0;
5511            }
5512        }
5513
5514        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5515        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5516        mCblk->stepUser(outFrames);
5517        pInBuffer->frameCount -= outFrames;
5518        pInBuffer->i16 += outFrames * channelCount;
5519        mOutBuffer.frameCount -= outFrames;
5520        mOutBuffer.i16 += outFrames * channelCount;
5521
5522        if (pInBuffer->frameCount == 0) {
5523            if (mBufferQueue.size()) {
5524                mBufferQueue.removeAt(0);
5525                delete [] pInBuffer->mBuffer;
5526                delete pInBuffer;
5527                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
5528            } else {
5529                break;
5530            }
5531        }
5532    }
5533
5534    // If we could not write all frames, allocate a buffer and queue it for next time.
5535    if (inBuffer.frameCount) {
5536        sp<ThreadBase> thread = mThread.promote();
5537        if (thread != 0 && !thread->standby()) {
5538            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5539                pInBuffer = new Buffer;
5540                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5541                pInBuffer->frameCount = inBuffer.frameCount;
5542                pInBuffer->i16 = pInBuffer->mBuffer;
5543                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5544                mBufferQueue.add(pInBuffer);
5545                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
5546            } else {
5547                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
5548            }
5549        }
5550    }
5551
5552    // Calling write() with a 0 length buffer, means that no more data will be written:
5553    // If no more buffers are pending, fill output track buffer to make sure it is started
5554    // by output mixer.
5555    if (frames == 0 && mBufferQueue.size() == 0) {
5556        if (mCblk->user < mCblk->frameCount) {
5557            frames = mCblk->frameCount - mCblk->user;
5558            pInBuffer = new Buffer;
5559            pInBuffer->mBuffer = new int16_t[frames * channelCount];
5560            pInBuffer->frameCount = frames;
5561            pInBuffer->i16 = pInBuffer->mBuffer;
5562            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5563            mBufferQueue.add(pInBuffer);
5564        } else if (mActive) {
5565            stop();
5566        }
5567    }
5568
5569    return outputBufferFull;
5570}
5571
5572status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5573{
5574    int active;
5575    status_t result;
5576    audio_track_cblk_t* cblk = mCblk;
5577    uint32_t framesReq = buffer->frameCount;
5578
5579//    ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
5580    buffer->frameCount  = 0;
5581
5582    uint32_t framesAvail = cblk->framesAvailable();
5583
5584
5585    if (framesAvail == 0) {
5586        Mutex::Autolock _l(cblk->lock);
5587        goto start_loop_here;
5588        while (framesAvail == 0) {
5589            active = mActive;
5590            if (CC_UNLIKELY(!active)) {
5591                ALOGV("Not active and NO_MORE_BUFFERS");
5592                return NO_MORE_BUFFERS;
5593            }
5594            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5595            if (result != NO_ERROR) {
5596                return NO_MORE_BUFFERS;
5597            }
5598            // read the server count again
5599        start_loop_here:
5600            framesAvail = cblk->framesAvailable_l();
5601        }
5602    }
5603
5604//    if (framesAvail < framesReq) {
5605//        return NO_MORE_BUFFERS;
5606//    }
5607
5608    if (framesReq > framesAvail) {
5609        framesReq = framesAvail;
5610    }
5611
5612    uint32_t u = cblk->user;
5613    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5614
5615    if (framesReq > bufferEnd - u) {
5616        framesReq = bufferEnd - u;
5617    }
5618
5619    buffer->frameCount  = framesReq;
5620    buffer->raw         = (void *)cblk->buffer(u);
5621    return NO_ERROR;
5622}
5623
5624
5625void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5626{
5627    size_t size = mBufferQueue.size();
5628
5629    for (size_t i = 0; i < size; i++) {
5630        Buffer *pBuffer = mBufferQueue.itemAt(i);
5631        delete [] pBuffer->mBuffer;
5632        delete pBuffer;
5633    }
5634    mBufferQueue.clear();
5635}
5636
5637// ----------------------------------------------------------------------------
5638
5639AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5640    :   RefBase(),
5641        mAudioFlinger(audioFlinger),
5642        // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
5643        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
5644        mPid(pid),
5645        mTimedTrackCount(0)
5646{
5647    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5648}
5649
5650// Client destructor must be called with AudioFlinger::mLock held
5651AudioFlinger::Client::~Client()
5652{
5653    mAudioFlinger->removeClient_l(mPid);
5654}
5655
5656sp<MemoryDealer> AudioFlinger::Client::heap() const
5657{
5658    return mMemoryDealer;
5659}
5660
5661// Reserve one of the limited slots for a timed audio track associated
5662// with this client
5663bool AudioFlinger::Client::reserveTimedTrack()
5664{
5665    const int kMaxTimedTracksPerClient = 4;
5666
5667    Mutex::Autolock _l(mTimedTrackLock);
5668
5669    if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5670        ALOGW("can not create timed track - pid %d has exceeded the limit",
5671             mPid);
5672        return false;
5673    }
5674
5675    mTimedTrackCount++;
5676    return true;
5677}
5678
5679// Release a slot for a timed audio track
5680void AudioFlinger::Client::releaseTimedTrack()
5681{
5682    Mutex::Autolock _l(mTimedTrackLock);
5683    mTimedTrackCount--;
5684}
5685
5686// ----------------------------------------------------------------------------
5687
5688AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5689                                                     const sp<IAudioFlingerClient>& client,
5690                                                     pid_t pid)
5691    : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
5692{
5693}
5694
5695AudioFlinger::NotificationClient::~NotificationClient()
5696{
5697}
5698
5699void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5700{
5701    sp<NotificationClient> keep(this);
5702    mAudioFlinger->removeNotificationClient(mPid);
5703}
5704
5705// ----------------------------------------------------------------------------
5706
5707AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5708    : BnAudioTrack(),
5709      mTrack(track)
5710{
5711}
5712
5713AudioFlinger::TrackHandle::~TrackHandle() {
5714    // just stop the track on deletion, associated resources
5715    // will be freed from the main thread once all pending buffers have
5716    // been played. Unless it's not in the active track list, in which
5717    // case we free everything now...
5718    mTrack->destroy();
5719}
5720
5721sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5722    return mTrack->getCblk();
5723}
5724
5725status_t AudioFlinger::TrackHandle::start() {
5726    return mTrack->start();
5727}
5728
5729void AudioFlinger::TrackHandle::stop() {
5730    mTrack->stop();
5731}
5732
5733void AudioFlinger::TrackHandle::flush() {
5734    mTrack->flush();
5735}
5736
5737void AudioFlinger::TrackHandle::mute(bool e) {
5738    mTrack->mute(e);
5739}
5740
5741void AudioFlinger::TrackHandle::pause() {
5742    mTrack->pause();
5743}
5744
5745status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5746{
5747    return mTrack->attachAuxEffect(EffectId);
5748}
5749
5750status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5751                                                         sp<IMemory>* buffer) {
5752    if (!mTrack->isTimedTrack())
5753        return INVALID_OPERATION;
5754
5755    PlaybackThread::TimedTrack* tt =
5756            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5757    return tt->allocateTimedBuffer(size, buffer);
5758}
5759
5760status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5761                                                     int64_t pts) {
5762    if (!mTrack->isTimedTrack())
5763        return INVALID_OPERATION;
5764
5765    PlaybackThread::TimedTrack* tt =
5766            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5767    return tt->queueTimedBuffer(buffer, pts);
5768}
5769
5770status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5771    const LinearTransform& xform, int target) {
5772
5773    if (!mTrack->isTimedTrack())
5774        return INVALID_OPERATION;
5775
5776    PlaybackThread::TimedTrack* tt =
5777            reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5778    return tt->setMediaTimeTransform(
5779        xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5780}
5781
5782status_t AudioFlinger::TrackHandle::onTransact(
5783    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5784{
5785    return BnAudioTrack::onTransact(code, data, reply, flags);
5786}
5787
5788// ----------------------------------------------------------------------------
5789
5790sp<IAudioRecord> AudioFlinger::openRecord(
5791        pid_t pid,
5792        audio_io_handle_t input,
5793        uint32_t sampleRate,
5794        audio_format_t format,
5795        audio_channel_mask_t channelMask,
5796        int frameCount,
5797        IAudioFlinger::track_flags_t flags,
5798        pid_t tid,
5799        int *sessionId,
5800        status_t *status)
5801{
5802    sp<RecordThread::RecordTrack> recordTrack;
5803    sp<RecordHandle> recordHandle;
5804    sp<Client> client;
5805    status_t lStatus;
5806    RecordThread *thread;
5807    size_t inFrameCount;
5808    int lSessionId;
5809
5810    // check calling permissions
5811    if (!recordingAllowed()) {
5812        lStatus = PERMISSION_DENIED;
5813        goto Exit;
5814    }
5815
5816    // add client to list
5817    { // scope for mLock
5818        Mutex::Autolock _l(mLock);
5819        thread = checkRecordThread_l(input);
5820        if (thread == NULL) {
5821            lStatus = BAD_VALUE;
5822            goto Exit;
5823        }
5824
5825        client = registerPid_l(pid);
5826
5827        // If no audio session id is provided, create one here
5828        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
5829            lSessionId = *sessionId;
5830        } else {
5831            lSessionId = nextUniqueId();
5832            if (sessionId != NULL) {
5833                *sessionId = lSessionId;
5834            }
5835        }
5836        // create new record track. The record track uses one track in mHardwareMixerThread by convention.
5837        recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5838                                                  frameCount, lSessionId, flags, tid, &lStatus);
5839    }
5840    if (lStatus != NO_ERROR) {
5841        // remove local strong reference to Client before deleting the RecordTrack so that the Client
5842        // destructor is called by the TrackBase destructor with mLock held
5843        client.clear();
5844        recordTrack.clear();
5845        goto Exit;
5846    }
5847
5848    // return to handle to client
5849    recordHandle = new RecordHandle(recordTrack);
5850    lStatus = NO_ERROR;
5851
5852Exit:
5853    if (status) {
5854        *status = lStatus;
5855    }
5856    return recordHandle;
5857}
5858
5859// ----------------------------------------------------------------------------
5860
5861AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5862    : BnAudioRecord(),
5863    mRecordTrack(recordTrack)
5864{
5865}
5866
5867AudioFlinger::RecordHandle::~RecordHandle() {
5868    stop_nonvirtual();
5869}
5870
5871sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5872    return mRecordTrack->getCblk();
5873}
5874
5875status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
5876    ALOGV("RecordHandle::start()");
5877    return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
5878}
5879
5880void AudioFlinger::RecordHandle::stop() {
5881    stop_nonvirtual();
5882}
5883
5884void AudioFlinger::RecordHandle::stop_nonvirtual() {
5885    ALOGV("RecordHandle::stop()");
5886    mRecordTrack->stop();
5887}
5888
5889status_t AudioFlinger::RecordHandle::onTransact(
5890    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5891{
5892    return BnAudioRecord::onTransact(code, data, reply, flags);
5893}
5894
5895// ----------------------------------------------------------------------------
5896
5897AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5898                                         AudioStreamIn *input,
5899                                         uint32_t sampleRate,
5900                                         audio_channel_mask_t channelMask,
5901                                         audio_io_handle_t id,
5902                                         audio_devices_t device) :
5903    ThreadBase(audioFlinger, id, device, RECORD),
5904    mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5905    // mRsmpInIndex and mInputBytes set by readInputParameters()
5906    mReqChannelCount(popcount(channelMask)),
5907    mReqSampleRate(sampleRate)
5908    // mBytesRead is only meaningful while active, and so is cleared in start()
5909    // (but might be better to also clear here for dump?)
5910{
5911    snprintf(mName, kNameLength, "AudioIn_%X", id);
5912
5913    readInputParameters();
5914}
5915
5916
5917AudioFlinger::RecordThread::~RecordThread()
5918{
5919    delete[] mRsmpInBuffer;
5920    delete mResampler;
5921    delete[] mRsmpOutBuffer;
5922}
5923
5924void AudioFlinger::RecordThread::onFirstRef()
5925{
5926    run(mName, PRIORITY_URGENT_AUDIO);
5927}
5928
5929status_t AudioFlinger::RecordThread::readyToRun()
5930{
5931    status_t status = initCheck();
5932    ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
5933    return status;
5934}
5935
5936bool AudioFlinger::RecordThread::threadLoop()
5937{
5938    AudioBufferProvider::Buffer buffer;
5939    sp<RecordTrack> activeTrack;
5940    Vector< sp<EffectChain> > effectChains;
5941
5942    nsecs_t lastWarning = 0;
5943
5944    acquireWakeLock();
5945
5946    // start recording
5947    while (!exitPending()) {
5948
5949        processConfigEvents();
5950
5951        { // scope for mLock
5952            Mutex::Autolock _l(mLock);
5953            checkForNewParameters_l();
5954            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5955                if (!mStandby) {
5956                    mInput->stream->common.standby(&mInput->stream->common);
5957                    mStandby = true;
5958                }
5959
5960                if (exitPending()) break;
5961
5962                releaseWakeLock_l();
5963                ALOGV("RecordThread: loop stopping");
5964                // go to sleep
5965                mWaitWorkCV.wait(mLock);
5966                ALOGV("RecordThread: loop starting");
5967                acquireWakeLock_l();
5968                continue;
5969            }
5970            if (mActiveTrack != 0) {
5971                if (mActiveTrack->mState == TrackBase::PAUSING) {
5972                    if (!mStandby) {
5973                        mInput->stream->common.standby(&mInput->stream->common);
5974                        mStandby = true;
5975                    }
5976                    mActiveTrack.clear();
5977                    mStartStopCond.broadcast();
5978                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5979                    if (mReqChannelCount != mActiveTrack->channelCount()) {
5980                        mActiveTrack.clear();
5981                        mStartStopCond.broadcast();
5982                    } else if (mBytesRead != 0) {
5983                        // record start succeeds only if first read from audio input
5984                        // succeeds
5985                        if (mBytesRead > 0) {
5986                            mActiveTrack->mState = TrackBase::ACTIVE;
5987                        } else {
5988                            mActiveTrack.clear();
5989                        }
5990                        mStartStopCond.broadcast();
5991                    }
5992                    mStandby = false;
5993                }
5994            }
5995            lockEffectChains_l(effectChains);
5996        }
5997
5998        if (mActiveTrack != 0) {
5999            if (mActiveTrack->mState != TrackBase::ACTIVE &&
6000                mActiveTrack->mState != TrackBase::RESUMING) {
6001                unlockEffectChains(effectChains);
6002                usleep(kRecordThreadSleepUs);
6003                continue;
6004            }
6005            for (size_t i = 0; i < effectChains.size(); i ++) {
6006                effectChains[i]->process_l();
6007            }
6008
6009            buffer.frameCount = mFrameCount;
6010            if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
6011                size_t framesOut = buffer.frameCount;
6012                if (mResampler == NULL) {
6013                    // no resampling
6014                    while (framesOut) {
6015                        size_t framesIn = mFrameCount - mRsmpInIndex;
6016                        if (framesIn) {
6017                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6018                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6019                            if (framesIn > framesOut)
6020                                framesIn = framesOut;
6021                            mRsmpInIndex += framesIn;
6022                            framesOut -= framesIn;
6023                            if ((int)mChannelCount == mReqChannelCount ||
6024                                mFormat != AUDIO_FORMAT_PCM_16_BIT) {
6025                                memcpy(dst, src, framesIn * mFrameSize);
6026                            } else {
6027                                int16_t *src16 = (int16_t *)src;
6028                                int16_t *dst16 = (int16_t *)dst;
6029                                if (mChannelCount == 1) {
6030                                    while (framesIn--) {
6031                                        *dst16++ = *src16;
6032                                        *dst16++ = *src16++;
6033                                    }
6034                                } else {
6035                                    while (framesIn--) {
6036                                        *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
6037                                        src16 += 2;
6038                                    }
6039                                }
6040                            }
6041                        }
6042                        if (framesOut && mFrameCount == mRsmpInIndex) {
6043                            if (framesOut == mFrameCount &&
6044                                ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
6045                                mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
6046                                framesOut = 0;
6047                            } else {
6048                                mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
6049                                mRsmpInIndex = 0;
6050                            }
6051                            if (mBytesRead < 0) {
6052                                ALOGE("Error reading audio input");
6053                                if (mActiveTrack->mState == TrackBase::ACTIVE) {
6054                                    // Force input into standby so that it tries to
6055                                    // recover at next read attempt
6056                                    mInput->stream->common.standby(&mInput->stream->common);
6057                                    usleep(kRecordThreadSleepUs);
6058                                }
6059                                mRsmpInIndex = mFrameCount;
6060                                framesOut = 0;
6061                                buffer.frameCount = 0;
6062                            }
6063                        }
6064                    }
6065                } else {
6066                    // resampling
6067
6068                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6069                    // alter output frame count as if we were expecting stereo samples
6070                    if (mChannelCount == 1 && mReqChannelCount == 1) {
6071                        framesOut >>= 1;
6072                    }
6073                    mResampler->resample(mRsmpOutBuffer, framesOut, this);
6074                    // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6075                    // are 32 bit aligned which should be always true.
6076                    if (mChannelCount == 2 && mReqChannelCount == 1) {
6077                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
6078                        // the resampler always outputs stereo samples: do post stereo to mono conversion
6079                        int16_t *src = (int16_t *)mRsmpOutBuffer;
6080                        int16_t *dst = buffer.i16;
6081                        while (framesOut--) {
6082                            *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
6083                            src += 2;
6084                        }
6085                    } else {
6086                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
6087                    }
6088
6089                }
6090                if (mFramestoDrop == 0) {
6091                    mActiveTrack->releaseBuffer(&buffer);
6092                } else {
6093                    if (mFramestoDrop > 0) {
6094                        mFramestoDrop -= buffer.frameCount;
6095                        if (mFramestoDrop <= 0) {
6096                            clearSyncStartEvent();
6097                        }
6098                    } else {
6099                        mFramestoDrop += buffer.frameCount;
6100                        if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6101                                mSyncStartEvent->isCancelled()) {
6102                            ALOGW("Synced record %s, session %d, trigger session %d",
6103                                  (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6104                                  mActiveTrack->sessionId(),
6105                                  (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6106                            clearSyncStartEvent();
6107                        }
6108                    }
6109                }
6110                mActiveTrack->clearOverflow();
6111            }
6112            // client isn't retrieving buffers fast enough
6113            else {
6114                if (!mActiveTrack->setOverflow()) {
6115                    nsecs_t now = systemTime();
6116                    if ((now - lastWarning) > kWarningThrottleNs) {
6117                        ALOGW("RecordThread: buffer overflow");
6118                        lastWarning = now;
6119                    }
6120                }
6121                // Release the processor for a while before asking for a new buffer.
6122                // This will give the application more chance to read from the buffer and
6123                // clear the overflow.
6124                usleep(kRecordThreadSleepUs);
6125            }
6126        }
6127        // enable changes in effect chain
6128        unlockEffectChains(effectChains);
6129        effectChains.clear();
6130    }
6131
6132    if (!mStandby) {
6133        mInput->stream->common.standby(&mInput->stream->common);
6134    }
6135    mActiveTrack.clear();
6136
6137    mStartStopCond.broadcast();
6138
6139    releaseWakeLock();
6140
6141    ALOGV("RecordThread %p exiting", this);
6142    return false;
6143}
6144
6145
6146sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
6147        const sp<AudioFlinger::Client>& client,
6148        uint32_t sampleRate,
6149        audio_format_t format,
6150        audio_channel_mask_t channelMask,
6151        int frameCount,
6152        int sessionId,
6153        IAudioFlinger::track_flags_t flags,
6154        pid_t tid,
6155        status_t *status)
6156{
6157    sp<RecordTrack> track;
6158    status_t lStatus;
6159
6160    lStatus = initCheck();
6161    if (lStatus != NO_ERROR) {
6162        ALOGE("Audio driver not initialized.");
6163        goto Exit;
6164    }
6165
6166    // FIXME use flags and tid similar to createTrack_l()
6167
6168    { // scope for mLock
6169        Mutex::Autolock _l(mLock);
6170
6171        track = new RecordTrack(this, client, sampleRate,
6172                      format, channelMask, frameCount, sessionId);
6173
6174        if (track->getCblk() == 0) {
6175            lStatus = NO_MEMORY;
6176            goto Exit;
6177        }
6178
6179        mTrack = track.get();
6180        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6181        bool suspend = audio_is_bluetooth_sco_device(mDevice & AUDIO_DEVICE_IN_ALL) &&
6182                        mAudioFlinger->btNrecIsOff();
6183        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6184        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
6185    }
6186    lStatus = NO_ERROR;
6187
6188Exit:
6189    if (status) {
6190        *status = lStatus;
6191    }
6192    return track;
6193}
6194
6195status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6196                                           AudioSystem::sync_event_t event,
6197                                           int triggerSession)
6198{
6199    ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6200    sp<ThreadBase> strongMe = this;
6201    status_t status = NO_ERROR;
6202
6203    if (event == AudioSystem::SYNC_EVENT_NONE) {
6204        clearSyncStartEvent();
6205    } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6206        mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6207                                       triggerSession,
6208                                       recordTrack->sessionId(),
6209                                       syncStartEventCallback,
6210                                       this);
6211        // Sync event can be cancelled by the trigger session if the track is not in a
6212        // compatible state in which case we start record immediately
6213        if (mSyncStartEvent->isCancelled()) {
6214            clearSyncStartEvent();
6215        } else {
6216            // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6217            mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6218        }
6219    }
6220
6221    {
6222        AutoMutex lock(mLock);
6223        if (mActiveTrack != 0) {
6224            if (recordTrack != mActiveTrack.get()) {
6225                status = -EBUSY;
6226            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6227                mActiveTrack->mState = TrackBase::ACTIVE;
6228            }
6229            return status;
6230        }
6231
6232        recordTrack->mState = TrackBase::IDLE;
6233        mActiveTrack = recordTrack;
6234        mLock.unlock();
6235        status_t status = AudioSystem::startInput(mId);
6236        mLock.lock();
6237        if (status != NO_ERROR) {
6238            mActiveTrack.clear();
6239            clearSyncStartEvent();
6240            return status;
6241        }
6242        mRsmpInIndex = mFrameCount;
6243        mBytesRead = 0;
6244        if (mResampler != NULL) {
6245            mResampler->reset();
6246        }
6247        mActiveTrack->mState = TrackBase::RESUMING;
6248        // signal thread to start
6249        ALOGV("Signal record thread");
6250        mWaitWorkCV.signal();
6251        // do not wait for mStartStopCond if exiting
6252        if (exitPending()) {
6253            mActiveTrack.clear();
6254            status = INVALID_OPERATION;
6255            goto startError;
6256        }
6257        mStartStopCond.wait(mLock);
6258        if (mActiveTrack == 0) {
6259            ALOGV("Record failed to start");
6260            status = BAD_VALUE;
6261            goto startError;
6262        }
6263        ALOGV("Record started OK");
6264        return status;
6265    }
6266startError:
6267    AudioSystem::stopInput(mId);
6268    clearSyncStartEvent();
6269    return status;
6270}
6271
6272void AudioFlinger::RecordThread::clearSyncStartEvent()
6273{
6274    if (mSyncStartEvent != 0) {
6275        mSyncStartEvent->cancel();
6276    }
6277    mSyncStartEvent.clear();
6278    mFramestoDrop = 0;
6279}
6280
6281void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6282{
6283    sp<SyncEvent> strongEvent = event.promote();
6284
6285    if (strongEvent != 0) {
6286        RecordThread *me = (RecordThread *)strongEvent->cookie();
6287        me->handleSyncStartEvent(strongEvent);
6288    }
6289}
6290
6291void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6292{
6293    if (event == mSyncStartEvent) {
6294        // TODO: use actual buffer filling status instead of 2 buffers when info is available
6295        // from audio HAL
6296        mFramestoDrop = mFrameCount * 2;
6297    }
6298}
6299
6300void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
6301    ALOGV("RecordThread::stop");
6302    sp<ThreadBase> strongMe = this;
6303    {
6304        AutoMutex lock(mLock);
6305        if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6306            mActiveTrack->mState = TrackBase::PAUSING;
6307            // do not wait for mStartStopCond if exiting
6308            if (exitPending()) {
6309                return;
6310            }
6311            mStartStopCond.wait(mLock);
6312            // if we have been restarted, recordTrack == mActiveTrack.get() here
6313            if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6314                mLock.unlock();
6315                AudioSystem::stopInput(mId);
6316                mLock.lock();
6317                ALOGV("Record stopped OK");
6318            }
6319        }
6320    }
6321}
6322
6323bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6324{
6325    return false;
6326}
6327
6328status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6329{
6330    if (!isValidSyncEvent(event)) {
6331        return BAD_VALUE;
6332    }
6333
6334    Mutex::Autolock _l(mLock);
6335
6336    if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6337        mTrack->setSyncEvent(event);
6338        return NO_ERROR;
6339    }
6340    return NAME_NOT_FOUND;
6341}
6342
6343status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6344{
6345    const size_t SIZE = 256;
6346    char buffer[SIZE];
6347    String8 result;
6348
6349    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6350    result.append(buffer);
6351
6352    if (mActiveTrack != 0) {
6353        result.append("Active Track:\n");
6354        result.append("   Clien Fmt Chn mask   Session Buf  S SRate  Serv     User\n");
6355        mActiveTrack->dump(buffer, SIZE);
6356        result.append(buffer);
6357
6358        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6359        result.append(buffer);
6360        snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6361        result.append(buffer);
6362        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
6363        result.append(buffer);
6364        snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6365        result.append(buffer);
6366        snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6367        result.append(buffer);
6368
6369
6370    } else {
6371        result.append("No record client\n");
6372    }
6373    write(fd, result.string(), result.size());
6374
6375    dumpBase(fd, args);
6376    dumpEffectChains(fd, args);
6377
6378    return NO_ERROR;
6379}
6380
6381// AudioBufferProvider interface
6382status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
6383{
6384    size_t framesReq = buffer->frameCount;
6385    size_t framesReady = mFrameCount - mRsmpInIndex;
6386    int channelCount;
6387
6388    if (framesReady == 0) {
6389        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
6390        if (mBytesRead < 0) {
6391            ALOGE("RecordThread::getNextBuffer() Error reading audio input");
6392            if (mActiveTrack->mState == TrackBase::ACTIVE) {
6393                // Force input into standby so that it tries to
6394                // recover at next read attempt
6395                mInput->stream->common.standby(&mInput->stream->common);
6396                usleep(kRecordThreadSleepUs);
6397            }
6398            buffer->raw = NULL;
6399            buffer->frameCount = 0;
6400            return NOT_ENOUGH_DATA;
6401        }
6402        mRsmpInIndex = 0;
6403        framesReady = mFrameCount;
6404    }
6405
6406    if (framesReq > framesReady) {
6407        framesReq = framesReady;
6408    }
6409
6410    if (mChannelCount == 1 && mReqChannelCount == 2) {
6411        channelCount = 1;
6412    } else {
6413        channelCount = 2;
6414    }
6415    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6416    buffer->frameCount = framesReq;
6417    return NO_ERROR;
6418}
6419
6420// AudioBufferProvider interface
6421void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6422{
6423    mRsmpInIndex += buffer->frameCount;
6424    buffer->frameCount = 0;
6425}
6426
6427bool AudioFlinger::RecordThread::checkForNewParameters_l()
6428{
6429    bool reconfig = false;
6430
6431    while (!mNewParameters.isEmpty()) {
6432        status_t status = NO_ERROR;
6433        String8 keyValuePair = mNewParameters[0];
6434        AudioParameter param = AudioParameter(keyValuePair);
6435        int value;
6436        audio_format_t reqFormat = mFormat;
6437        int reqSamplingRate = mReqSampleRate;
6438        int reqChannelCount = mReqChannelCount;
6439
6440        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6441            reqSamplingRate = value;
6442            reconfig = true;
6443        }
6444        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6445            reqFormat = (audio_format_t) value;
6446            reconfig = true;
6447        }
6448        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6449            reqChannelCount = popcount(value);
6450            reconfig = true;
6451        }
6452        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6453            // do not accept frame count changes if tracks are open as the track buffer
6454            // size depends on frame count and correct behavior would not be guaranteed
6455            // if frame count is changed after track creation
6456            if (mActiveTrack != 0) {
6457                status = INVALID_OPERATION;
6458            } else {
6459                reconfig = true;
6460            }
6461        }
6462        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6463            // forward device change to effects that have requested to be
6464            // aware of attached audio device.
6465            for (size_t i = 0; i < mEffectChains.size(); i++) {
6466                mEffectChains[i]->setDevice_l(value);
6467            }
6468            // store input device and output device but do not forward output device to audio HAL.
6469            // Note that status is ignored by the caller for output device
6470            // (see AudioFlinger::setParameters()
6471            uint32_t /*audio_devices_t*/ newDevice = mDevice;
6472            if (value & AUDIO_DEVICE_OUT_ALL) {
6473                newDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6474                status = BAD_VALUE;
6475            } else {
6476                newDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
6477                // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6478                if (mTrack != NULL) {
6479                    bool suspend = audio_is_bluetooth_sco_device(
6480                            (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
6481                    setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6482                    setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6483                }
6484            }
6485            newDevice |= value;
6486            mDevice = (audio_devices_t) newDevice;    // since mDevice is read by other threads, only write to it once
6487        }
6488        if (status == NO_ERROR) {
6489            status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
6490            if (status == INVALID_OPERATION) {
6491                mInput->stream->common.standby(&mInput->stream->common);
6492                status = mInput->stream->common.set_parameters(&mInput->stream->common,
6493                        keyValuePair.string());
6494            }
6495            if (reconfig) {
6496                if (status == BAD_VALUE &&
6497                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6498                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6499                    ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
6500                    popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6501                    (reqChannelCount <= FCC_2)) {
6502                    status = NO_ERROR;
6503                }
6504                if (status == NO_ERROR) {
6505                    readInputParameters();
6506                    sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6507                }
6508            }
6509        }
6510
6511        mNewParameters.removeAt(0);
6512
6513        mParamStatus = status;
6514        mParamCond.signal();
6515        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6516        // already timed out waiting for the status and will never signal the condition.
6517        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
6518    }
6519    return reconfig;
6520}
6521
6522String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6523{
6524    char *s;
6525    String8 out_s8 = String8();
6526
6527    Mutex::Autolock _l(mLock);
6528    if (initCheck() != NO_ERROR) {
6529        return out_s8;
6530    }
6531
6532    s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6533    out_s8 = String8(s);
6534    free(s);
6535    return out_s8;
6536}
6537
6538void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6539    AudioSystem::OutputDescriptor desc;
6540    void *param2 = NULL;
6541
6542    switch (event) {
6543    case AudioSystem::INPUT_OPENED:
6544    case AudioSystem::INPUT_CONFIG_CHANGED:
6545        desc.channels = mChannelMask;
6546        desc.samplingRate = mSampleRate;
6547        desc.format = mFormat;
6548        desc.frameCount = mFrameCount;
6549        desc.latency = 0;
6550        param2 = &desc;
6551        break;
6552
6553    case AudioSystem::INPUT_CLOSED:
6554    default:
6555        break;
6556    }
6557    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6558}
6559
6560void AudioFlinger::RecordThread::readInputParameters()
6561{
6562    delete mRsmpInBuffer;
6563    // mRsmpInBuffer is always assigned a new[] below
6564    delete mRsmpOutBuffer;
6565    mRsmpOutBuffer = NULL;
6566    delete mResampler;
6567    mResampler = NULL;
6568
6569    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6570    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6571    mChannelCount = (uint16_t)popcount(mChannelMask);
6572    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
6573    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
6574    mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6575    mFrameCount = mInputBytes / mFrameSize;
6576    mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
6577    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6578
6579    if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
6580    {
6581        int channelCount;
6582        // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6583        // stereo to mono post process as the resampler always outputs stereo.
6584        if (mChannelCount == 1 && mReqChannelCount == 2) {
6585            channelCount = 1;
6586        } else {
6587            channelCount = 2;
6588        }
6589        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6590        mResampler->setSampleRate(mSampleRate);
6591        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6592        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6593
6594        // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6595        if (mChannelCount == 1 && mReqChannelCount == 1) {
6596            mFrameCount >>= 1;
6597        }
6598
6599    }
6600    mRsmpInIndex = mFrameCount;
6601}
6602
6603unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6604{
6605    Mutex::Autolock _l(mLock);
6606    if (initCheck() != NO_ERROR) {
6607        return 0;
6608    }
6609
6610    return mInput->stream->get_input_frames_lost(mInput->stream);
6611}
6612
6613uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6614{
6615    Mutex::Autolock _l(mLock);
6616    uint32_t result = 0;
6617    if (getEffectChain_l(sessionId) != 0) {
6618        result = EFFECT_SESSION;
6619    }
6620
6621    if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6622        result |= TRACK_SESSION;
6623    }
6624
6625    return result;
6626}
6627
6628AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6629{
6630    Mutex::Autolock _l(mLock);
6631    return mTrack;
6632}
6633
6634AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6635{
6636    Mutex::Autolock _l(mLock);
6637    AudioStreamIn *input = mInput;
6638    mInput = NULL;
6639    return input;
6640}
6641
6642// this method must always be called either with ThreadBase mLock held or inside the thread loop
6643audio_stream_t* AudioFlinger::RecordThread::stream() const
6644{
6645    if (mInput == NULL) {
6646        return NULL;
6647    }
6648    return &mInput->stream->common;
6649}
6650
6651
6652// ----------------------------------------------------------------------------
6653
6654audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6655{
6656    if (!settingsAllowed()) {
6657        return 0;
6658    }
6659    Mutex::Autolock _l(mLock);
6660    return loadHwModule_l(name);
6661}
6662
6663// loadHwModule_l() must be called with AudioFlinger::mLock held
6664audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6665{
6666    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6667        if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6668            ALOGW("loadHwModule() module %s already loaded", name);
6669            return mAudioHwDevs.keyAt(i);
6670        }
6671    }
6672
6673    audio_hw_device_t *dev;
6674
6675    int rc = load_audio_interface(name, &dev);
6676    if (rc) {
6677        ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6678        return 0;
6679    }
6680
6681    mHardwareStatus = AUDIO_HW_INIT;
6682    rc = dev->init_check(dev);
6683    mHardwareStatus = AUDIO_HW_IDLE;
6684    if (rc) {
6685        ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6686        return 0;
6687    }
6688
6689    if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6690        (NULL != dev->set_master_volume)) {
6691        AutoMutex lock(mHardwareLock);
6692        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6693        dev->set_master_volume(dev, mMasterVolume);
6694        mHardwareStatus = AUDIO_HW_IDLE;
6695    }
6696
6697    audio_module_handle_t handle = nextUniqueId();
6698    mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6699
6700    ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
6701          name, dev->common.module->name, dev->common.module->id, handle);
6702
6703    return handle;
6704
6705}
6706
6707audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6708                                           audio_devices_t *pDevices,
6709                                           uint32_t *pSamplingRate,
6710                                           audio_format_t *pFormat,
6711                                           audio_channel_mask_t *pChannelMask,
6712                                           uint32_t *pLatencyMs,
6713                                           audio_output_flags_t flags)
6714{
6715    status_t status;
6716    PlaybackThread *thread = NULL;
6717    struct audio_config config = {
6718        sample_rate: pSamplingRate ? *pSamplingRate : 0,
6719        channel_mask: pChannelMask ? *pChannelMask : 0,
6720        format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6721    };
6722    audio_stream_out_t *outStream = NULL;
6723    audio_hw_device_t *outHwDev;
6724
6725    ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6726              module,
6727              (pDevices != NULL) ? *pDevices : 0,
6728              config.sample_rate,
6729              config.format,
6730              config.channel_mask,
6731              flags);
6732
6733    if (pDevices == NULL || *pDevices == 0) {
6734        return 0;
6735    }
6736
6737    Mutex::Autolock _l(mLock);
6738
6739    outHwDev = findSuitableHwDev_l(module, *pDevices);
6740    if (outHwDev == NULL)
6741        return 0;
6742
6743    audio_io_handle_t id = nextUniqueId();
6744
6745    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
6746
6747    status = outHwDev->open_output_stream(outHwDev,
6748                                          id,
6749                                          *pDevices,
6750                                          (audio_output_flags_t)flags,
6751                                          &config,
6752                                          &outStream);
6753
6754    mHardwareStatus = AUDIO_HW_IDLE;
6755    ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
6756            outStream,
6757            config.sample_rate,
6758            config.format,
6759            config.channel_mask,
6760            status);
6761
6762    if (status == NO_ERROR && outStream != NULL) {
6763        AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
6764
6765        if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
6766            (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6767            (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
6768            thread = new DirectOutputThread(this, output, id, *pDevices);
6769            ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
6770        } else {
6771            thread = new MixerThread(this, output, id, *pDevices);
6772            ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
6773        }
6774        mPlaybackThreads.add(id, thread);
6775
6776        if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6777        if (pFormat != NULL) *pFormat = config.format;
6778        if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
6779        if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
6780
6781        // notify client processes of the new output creation
6782        thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6783
6784        // the first primary output opened designates the primary hw device
6785        if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
6786            ALOGI("Using module %d has the primary audio interface", module);
6787            mPrimaryHardwareDev = outHwDev;
6788
6789            AutoMutex lock(mHardwareLock);
6790            mHardwareStatus = AUDIO_HW_SET_MODE;
6791            outHwDev->set_mode(outHwDev, mMode);
6792
6793            // Determine the level of master volume support the primary audio HAL has,
6794            // and set the initial master volume at the same time.
6795            float initialVolume = 1.0;
6796            mMasterVolumeSupportLvl = MVS_NONE;
6797
6798            mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6799            if ((NULL != outHwDev->get_master_volume) &&
6800                (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6801                mMasterVolumeSupportLvl = MVS_FULL;
6802            } else {
6803                mMasterVolumeSupportLvl = MVS_SETONLY;
6804                initialVolume = 1.0;
6805            }
6806
6807            mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6808            if ((NULL == outHwDev->set_master_volume) ||
6809                (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6810                mMasterVolumeSupportLvl = MVS_NONE;
6811            }
6812            // now that we have a primary device, initialize master volume on other devices
6813            for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6814                audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6815
6816                if ((dev != mPrimaryHardwareDev) &&
6817                    (NULL != dev->set_master_volume)) {
6818                    dev->set_master_volume(dev, initialVolume);
6819                }
6820            }
6821            mHardwareStatus = AUDIO_HW_IDLE;
6822            mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6823                                    ? initialVolume
6824                                    : 1.0;
6825            mMasterVolume   = initialVolume;
6826        }
6827        return id;
6828    }
6829
6830    return 0;
6831}
6832
6833audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6834        audio_io_handle_t output2)
6835{
6836    Mutex::Autolock _l(mLock);
6837    MixerThread *thread1 = checkMixerThread_l(output1);
6838    MixerThread *thread2 = checkMixerThread_l(output2);
6839
6840    if (thread1 == NULL || thread2 == NULL) {
6841        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
6842        return 0;
6843    }
6844
6845    audio_io_handle_t id = nextUniqueId();
6846    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6847    thread->addOutputTrack(thread2);
6848    mPlaybackThreads.add(id, thread);
6849    // notify client processes of the new output creation
6850    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6851    return id;
6852}
6853
6854status_t AudioFlinger::closeOutput(audio_io_handle_t output)
6855{
6856    return closeOutput_nonvirtual(output);
6857}
6858
6859status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6860{
6861    // keep strong reference on the playback thread so that
6862    // it is not destroyed while exit() is executed
6863    sp<PlaybackThread> thread;
6864    {
6865        Mutex::Autolock _l(mLock);
6866        thread = checkPlaybackThread_l(output);
6867        if (thread == NULL) {
6868            return BAD_VALUE;
6869        }
6870
6871        ALOGV("closeOutput() %d", output);
6872
6873        if (thread->type() == ThreadBase::MIXER) {
6874            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6875                if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
6876                    DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6877                    dupThread->removeOutputTrack((MixerThread *)thread.get());
6878                }
6879            }
6880        }
6881        audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
6882        mPlaybackThreads.removeItem(output);
6883    }
6884    thread->exit();
6885    // The thread entity (active unit of execution) is no longer running here,
6886    // but the ThreadBase container still exists.
6887
6888    if (thread->type() != ThreadBase::DUPLICATING) {
6889        AudioStreamOut *out = thread->clearOutput();
6890        ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
6891        // from now on thread->mOutput is NULL
6892        out->hwDev->close_output_stream(out->hwDev, out->stream);
6893        delete out;
6894    }
6895    return NO_ERROR;
6896}
6897
6898status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
6899{
6900    Mutex::Autolock _l(mLock);
6901    PlaybackThread *thread = checkPlaybackThread_l(output);
6902
6903    if (thread == NULL) {
6904        return BAD_VALUE;
6905    }
6906
6907    ALOGV("suspendOutput() %d", output);
6908    thread->suspend();
6909
6910    return NO_ERROR;
6911}
6912
6913status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
6914{
6915    Mutex::Autolock _l(mLock);
6916    PlaybackThread *thread = checkPlaybackThread_l(output);
6917
6918    if (thread == NULL) {
6919        return BAD_VALUE;
6920    }
6921
6922    ALOGV("restoreOutput() %d", output);
6923
6924    thread->restore();
6925
6926    return NO_ERROR;
6927}
6928
6929audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6930                                          audio_devices_t *pDevices,
6931                                          uint32_t *pSamplingRate,
6932                                          audio_format_t *pFormat,
6933                                          audio_channel_mask_t *pChannelMask)
6934{
6935    status_t status;
6936    RecordThread *thread = NULL;
6937    struct audio_config config = {
6938        sample_rate: pSamplingRate ? *pSamplingRate : 0,
6939        channel_mask: pChannelMask ? *pChannelMask : 0,
6940        format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6941    };
6942    uint32_t reqSamplingRate = config.sample_rate;
6943    audio_format_t reqFormat = config.format;
6944    audio_channel_mask_t reqChannels = config.channel_mask;
6945    audio_stream_in_t *inStream = NULL;
6946    audio_hw_device_t *inHwDev;
6947
6948    if (pDevices == NULL || *pDevices == 0) {
6949        return 0;
6950    }
6951
6952    Mutex::Autolock _l(mLock);
6953
6954    inHwDev = findSuitableHwDev_l(module, *pDevices);
6955    if (inHwDev == NULL)
6956        return 0;
6957
6958    audio_io_handle_t id = nextUniqueId();
6959
6960    status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
6961                                        &inStream);
6962    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
6963            inStream,
6964            config.sample_rate,
6965            config.format,
6966            config.channel_mask,
6967            status);
6968
6969    // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6970    // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6971    // or stereo to mono conversions on 16 bit PCM inputs.
6972    if (status == BAD_VALUE &&
6973        reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6974        (config.sample_rate <= 2 * reqSamplingRate) &&
6975        (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
6976        ALOGV("openInput() reopening with proposed sampling rate and channel mask");
6977        inStream = NULL;
6978        status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
6979    }
6980
6981    if (status == NO_ERROR && inStream != NULL) {
6982        AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6983
6984        // Start record thread
6985        // RecorThread require both input and output device indication to forward to audio
6986        // pre processing modules
6987        audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
6988        thread = new RecordThread(this,
6989                                  input,
6990                                  reqSamplingRate,
6991                                  reqChannels,
6992                                  id,
6993                                  device);
6994        mRecordThreads.add(id, thread);
6995        ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
6996        if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
6997        if (pFormat != NULL) *pFormat = config.format;
6998        if (pChannelMask != NULL) *pChannelMask = reqChannels;
6999
7000        input->stream->common.standby(&input->stream->common);
7001
7002        // notify client processes of the new input creation
7003        thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7004        return id;
7005    }
7006
7007    return 0;
7008}
7009
7010status_t AudioFlinger::closeInput(audio_io_handle_t input)
7011{
7012    return closeInput_nonvirtual(input);
7013}
7014
7015status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7016{
7017    // keep strong reference on the record thread so that
7018    // it is not destroyed while exit() is executed
7019    sp<RecordThread> thread;
7020    {
7021        Mutex::Autolock _l(mLock);
7022        thread = checkRecordThread_l(input);
7023        if (thread == 0) {
7024            return BAD_VALUE;
7025        }
7026
7027        ALOGV("closeInput() %d", input);
7028        audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
7029        mRecordThreads.removeItem(input);
7030    }
7031    thread->exit();
7032    // The thread entity (active unit of execution) is no longer running here,
7033    // but the ThreadBase container still exists.
7034
7035    AudioStreamIn *in = thread->clearInput();
7036    ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
7037    // from now on thread->mInput is NULL
7038    in->hwDev->close_input_stream(in->hwDev, in->stream);
7039    delete in;
7040
7041    return NO_ERROR;
7042}
7043
7044status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
7045{
7046    Mutex::Autolock _l(mLock);
7047    ALOGV("setStreamOutput() stream %d to output %d", stream, output);
7048
7049    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7050        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
7051        thread->invalidateTracks(stream);
7052    }
7053
7054    return NO_ERROR;
7055}
7056
7057
7058int AudioFlinger::newAudioSessionId()
7059{
7060    return nextUniqueId();
7061}
7062
7063void AudioFlinger::acquireAudioSessionId(int audioSession)
7064{
7065    Mutex::Autolock _l(mLock);
7066    pid_t caller = IPCThreadState::self()->getCallingPid();
7067    ALOGV("acquiring %d from %d", audioSession, caller);
7068    size_t num = mAudioSessionRefs.size();
7069    for (size_t i = 0; i< num; i++) {
7070        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
7071        if (ref->mSessionid == audioSession && ref->mPid == caller) {
7072            ref->mCnt++;
7073            ALOGV(" incremented refcount to %d", ref->mCnt);
7074            return;
7075        }
7076    }
7077    mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7078    ALOGV(" added new entry for %d", audioSession);
7079}
7080
7081void AudioFlinger::releaseAudioSessionId(int audioSession)
7082{
7083    Mutex::Autolock _l(mLock);
7084    pid_t caller = IPCThreadState::self()->getCallingPid();
7085    ALOGV("releasing %d from %d", audioSession, caller);
7086    size_t num = mAudioSessionRefs.size();
7087    for (size_t i = 0; i< num; i++) {
7088        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
7089        if (ref->mSessionid == audioSession && ref->mPid == caller) {
7090            ref->mCnt--;
7091            ALOGV(" decremented refcount to %d", ref->mCnt);
7092            if (ref->mCnt == 0) {
7093                mAudioSessionRefs.removeAt(i);
7094                delete ref;
7095                purgeStaleEffects_l();
7096            }
7097            return;
7098        }
7099    }
7100    ALOGW("session id %d not found for pid %d", audioSession, caller);
7101}
7102
7103void AudioFlinger::purgeStaleEffects_l() {
7104
7105    ALOGV("purging stale effects");
7106
7107    Vector< sp<EffectChain> > chains;
7108
7109    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7110        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7111        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7112            sp<EffectChain> ec = t->mEffectChains[j];
7113            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7114                chains.push(ec);
7115            }
7116        }
7117    }
7118    for (size_t i = 0; i < mRecordThreads.size(); i++) {
7119        sp<RecordThread> t = mRecordThreads.valueAt(i);
7120        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7121            sp<EffectChain> ec = t->mEffectChains[j];
7122            chains.push(ec);
7123        }
7124    }
7125
7126    for (size_t i = 0; i < chains.size(); i++) {
7127        sp<EffectChain> ec = chains[i];
7128        int sessionid = ec->sessionId();
7129        sp<ThreadBase> t = ec->mThread.promote();
7130        if (t == 0) {
7131            continue;
7132        }
7133        size_t numsessionrefs = mAudioSessionRefs.size();
7134        bool found = false;
7135        for (size_t k = 0; k < numsessionrefs; k++) {
7136            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
7137            if (ref->mSessionid == sessionid) {
7138                ALOGV(" session %d still exists for %d with %d refs",
7139                    sessionid, ref->mPid, ref->mCnt);
7140                found = true;
7141                break;
7142            }
7143        }
7144        if (!found) {
7145            Mutex::Autolock _l (t->mLock);
7146            // remove all effects from the chain
7147            while (ec->mEffects.size()) {
7148                sp<EffectModule> effect = ec->mEffects[0];
7149                effect->unPin();
7150                t->removeEffect_l(effect);
7151                if (effect->purgeHandles()) {
7152                    t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
7153                }
7154                AudioSystem::unregisterEffect(effect->id());
7155            }
7156        }
7157    }
7158    return;
7159}
7160
7161// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
7162AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
7163{
7164    return mPlaybackThreads.valueFor(output).get();
7165}
7166
7167// checkMixerThread_l() must be called with AudioFlinger::mLock held
7168AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
7169{
7170    PlaybackThread *thread = checkPlaybackThread_l(output);
7171    return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
7172}
7173
7174// checkRecordThread_l() must be called with AudioFlinger::mLock held
7175AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
7176{
7177    return mRecordThreads.valueFor(input).get();
7178}
7179
7180uint32_t AudioFlinger::nextUniqueId()
7181{
7182    return android_atomic_inc(&mNextUniqueId);
7183}
7184
7185AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
7186{
7187    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7188        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
7189        AudioStreamOut *output = thread->getOutput();
7190        if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
7191            return thread;
7192        }
7193    }
7194    return NULL;
7195}
7196
7197audio_devices_t AudioFlinger::primaryOutputDevice_l() const
7198{
7199    PlaybackThread *thread = primaryPlaybackThread_l();
7200
7201    if (thread == NULL) {
7202        return 0;
7203    }
7204
7205    return thread->device();
7206}
7207
7208sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7209                                    int triggerSession,
7210                                    int listenerSession,
7211                                    sync_event_callback_t callBack,
7212                                    void *cookie)
7213{
7214    Mutex::Autolock _l(mLock);
7215
7216    sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7217    status_t playStatus = NAME_NOT_FOUND;
7218    status_t recStatus = NAME_NOT_FOUND;
7219    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7220        playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7221        if (playStatus == NO_ERROR) {
7222            return event;
7223        }
7224    }
7225    for (size_t i = 0; i < mRecordThreads.size(); i++) {
7226        recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7227        if (recStatus == NO_ERROR) {
7228            return event;
7229        }
7230    }
7231    if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7232        mPendingSyncEvents.add(event);
7233    } else {
7234        ALOGV("createSyncEvent() invalid event %d", event->type());
7235        event.clear();
7236    }
7237    return event;
7238}
7239
7240// ----------------------------------------------------------------------------
7241//  Effect management
7242// ----------------------------------------------------------------------------
7243
7244
7245status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
7246{
7247    Mutex::Autolock _l(mLock);
7248    return EffectQueryNumberEffects(numEffects);
7249}
7250
7251status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
7252{
7253    Mutex::Autolock _l(mLock);
7254    return EffectQueryEffect(index, descriptor);
7255}
7256
7257status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
7258        effect_descriptor_t *descriptor) const
7259{
7260    Mutex::Autolock _l(mLock);
7261    return EffectGetDescriptor(pUuid, descriptor);
7262}
7263
7264
7265sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7266        effect_descriptor_t *pDesc,
7267        const sp<IEffectClient>& effectClient,
7268        int32_t priority,
7269        audio_io_handle_t io,
7270        int sessionId,
7271        status_t *status,
7272        int *id,
7273        int *enabled)
7274{
7275    status_t lStatus = NO_ERROR;
7276    sp<EffectHandle> handle;
7277    effect_descriptor_t desc;
7278
7279    ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
7280            pid, effectClient.get(), priority, sessionId, io);
7281
7282    if (pDesc == NULL) {
7283        lStatus = BAD_VALUE;
7284        goto Exit;
7285    }
7286
7287    // check audio settings permission for global effects
7288    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
7289        lStatus = PERMISSION_DENIED;
7290        goto Exit;
7291    }
7292
7293    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
7294    // that can only be created by audio policy manager (running in same process)
7295    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
7296        lStatus = PERMISSION_DENIED;
7297        goto Exit;
7298    }
7299
7300    if (io == 0) {
7301        if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
7302            // output must be specified by AudioPolicyManager when using session
7303            // AUDIO_SESSION_OUTPUT_STAGE
7304            lStatus = BAD_VALUE;
7305            goto Exit;
7306        } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
7307            // if the output returned by getOutputForEffect() is removed before we lock the
7308            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
7309            // and we will exit safely
7310            io = AudioSystem::getOutputForEffect(&desc);
7311        }
7312    }
7313
7314    {
7315        Mutex::Autolock _l(mLock);
7316
7317
7318        if (!EffectIsNullUuid(&pDesc->uuid)) {
7319            // if uuid is specified, request effect descriptor
7320            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7321            if (lStatus < 0) {
7322                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
7323                goto Exit;
7324            }
7325        } else {
7326            // if uuid is not specified, look for an available implementation
7327            // of the required type in effect factory
7328            if (EffectIsNullUuid(&pDesc->type)) {
7329                ALOGW("createEffect() no effect type");
7330                lStatus = BAD_VALUE;
7331                goto Exit;
7332            }
7333            uint32_t numEffects = 0;
7334            effect_descriptor_t d;
7335            d.flags = 0; // prevent compiler warning
7336            bool found = false;
7337
7338            lStatus = EffectQueryNumberEffects(&numEffects);
7339            if (lStatus < 0) {
7340                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
7341                goto Exit;
7342            }
7343            for (uint32_t i = 0; i < numEffects; i++) {
7344                lStatus = EffectQueryEffect(i, &desc);
7345                if (lStatus < 0) {
7346                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
7347                    continue;
7348                }
7349                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7350                    // If matching type found save effect descriptor. If the session is
7351                    // 0 and the effect is not auxiliary, continue enumeration in case
7352                    // an auxiliary version of this effect type is available
7353                    found = true;
7354                    d = desc;
7355                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
7356                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7357                        break;
7358                    }
7359                }
7360            }
7361            if (!found) {
7362                lStatus = BAD_VALUE;
7363                ALOGW("createEffect() effect not found");
7364                goto Exit;
7365            }
7366            // For same effect type, chose auxiliary version over insert version if
7367            // connect to output mix (Compliance to OpenSL ES)
7368            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
7369                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7370                desc = d;
7371            }
7372        }
7373
7374        // Do not allow auxiliary effects on a session different from 0 (output mix)
7375        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
7376             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7377            lStatus = INVALID_OPERATION;
7378            goto Exit;
7379        }
7380
7381        // check recording permission for visualizer
7382        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7383            !recordingAllowed()) {
7384            lStatus = PERMISSION_DENIED;
7385            goto Exit;
7386        }
7387
7388        // return effect descriptor
7389        *pDesc = desc;
7390
7391        // If output is not specified try to find a matching audio session ID in one of the
7392        // output threads.
7393        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7394        // because of code checking output when entering the function.
7395        // Note: io is never 0 when creating an effect on an input
7396        if (io == 0) {
7397            // look for the thread where the specified audio session is present
7398            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7399                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7400                    io = mPlaybackThreads.keyAt(i);
7401                    break;
7402                }
7403            }
7404            if (io == 0) {
7405                for (size_t i = 0; i < mRecordThreads.size(); i++) {
7406                    if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7407                        io = mRecordThreads.keyAt(i);
7408                        break;
7409                    }
7410                }
7411            }
7412            // If no output thread contains the requested session ID, default to
7413            // first output. The effect chain will be moved to the correct output
7414            // thread when a track with the same session ID is created
7415            if (io == 0 && mPlaybackThreads.size()) {
7416                io = mPlaybackThreads.keyAt(0);
7417            }
7418            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
7419        }
7420        ThreadBase *thread = checkRecordThread_l(io);
7421        if (thread == NULL) {
7422            thread = checkPlaybackThread_l(io);
7423            if (thread == NULL) {
7424                ALOGE("createEffect() unknown output thread");
7425                lStatus = BAD_VALUE;
7426                goto Exit;
7427            }
7428        }
7429
7430        sp<Client> client = registerPid_l(pid);
7431
7432        // create effect on selected output thread
7433        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7434                &desc, enabled, &lStatus);
7435        if (handle != 0 && id != NULL) {
7436            *id = handle->id();
7437        }
7438    }
7439
7440Exit:
7441    if (status != NULL) {
7442        *status = lStatus;
7443    }
7444    return handle;
7445}
7446
7447status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7448        audio_io_handle_t dstOutput)
7449{
7450    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
7451            sessionId, srcOutput, dstOutput);
7452    Mutex::Autolock _l(mLock);
7453    if (srcOutput == dstOutput) {
7454        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
7455        return NO_ERROR;
7456    }
7457    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7458    if (srcThread == NULL) {
7459        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
7460        return BAD_VALUE;
7461    }
7462    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7463    if (dstThread == NULL) {
7464        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
7465        return BAD_VALUE;
7466    }
7467
7468    Mutex::Autolock _dl(dstThread->mLock);
7469    Mutex::Autolock _sl(srcThread->mLock);
7470    moveEffectChain_l(sessionId, srcThread, dstThread, false);
7471
7472    return NO_ERROR;
7473}
7474
7475// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
7476status_t AudioFlinger::moveEffectChain_l(int sessionId,
7477                                   AudioFlinger::PlaybackThread *srcThread,
7478                                   AudioFlinger::PlaybackThread *dstThread,
7479                                   bool reRegister)
7480{
7481    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
7482            sessionId, srcThread, dstThread);
7483
7484    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
7485    if (chain == 0) {
7486        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
7487                sessionId, srcThread);
7488        return INVALID_OPERATION;
7489    }
7490
7491    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
7492    // so that a new chain is created with correct parameters when first effect is added. This is
7493    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
7494    // removed.
7495    srcThread->removeEffectChain_l(chain);
7496
7497    // transfer all effects one by one so that new effect chain is created on new thread with
7498    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
7499    audio_io_handle_t dstOutput = dstThread->id();
7500    sp<EffectChain> dstChain;
7501    uint32_t strategy = 0; // prevent compiler warning
7502    sp<EffectModule> effect = chain->getEffectFromId_l(0);
7503    while (effect != 0) {
7504        srcThread->removeEffect_l(effect);
7505        dstThread->addEffect_l(effect);
7506        // removeEffect_l() has stopped the effect if it was active so it must be restarted
7507        if (effect->state() == EffectModule::ACTIVE ||
7508                effect->state() == EffectModule::STOPPING) {
7509            effect->start();
7510        }
7511        // if the move request is not received from audio policy manager, the effect must be
7512        // re-registered with the new strategy and output
7513        if (dstChain == 0) {
7514            dstChain = effect->chain().promote();
7515            if (dstChain == 0) {
7516                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
7517                srcThread->addEffect_l(effect);
7518                return NO_INIT;
7519            }
7520            strategy = dstChain->strategy();
7521        }
7522        if (reRegister) {
7523            AudioSystem::unregisterEffect(effect->id());
7524            AudioSystem::registerEffect(&effect->desc(),
7525                                        dstOutput,
7526                                        strategy,
7527                                        sessionId,
7528                                        effect->id());
7529        }
7530        effect = chain->getEffectFromId_l(0);
7531    }
7532
7533    return NO_ERROR;
7534}
7535
7536
7537// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
7538sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
7539        const sp<AudioFlinger::Client>& client,
7540        const sp<IEffectClient>& effectClient,
7541        int32_t priority,
7542        int sessionId,
7543        effect_descriptor_t *desc,
7544        int *enabled,
7545        status_t *status
7546        )
7547{
7548    sp<EffectModule> effect;
7549    sp<EffectHandle> handle;
7550    status_t lStatus;
7551    sp<EffectChain> chain;
7552    bool chainCreated = false;
7553    bool effectCreated = false;
7554    bool effectRegistered = false;
7555
7556    lStatus = initCheck();
7557    if (lStatus != NO_ERROR) {
7558        ALOGW("createEffect_l() Audio driver not initialized.");
7559        goto Exit;
7560    }
7561
7562    // Do not allow effects with session ID 0 on direct output or duplicating threads
7563    // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
7564    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
7565        ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
7566                desc->name, sessionId);
7567        lStatus = BAD_VALUE;
7568        goto Exit;
7569    }
7570    // Only Pre processor effects are allowed on input threads and only on input threads
7571    if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
7572        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
7573                desc->name, desc->flags, mType);
7574        lStatus = BAD_VALUE;
7575        goto Exit;
7576    }
7577
7578    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
7579
7580    { // scope for mLock
7581        Mutex::Autolock _l(mLock);
7582
7583        // check for existing effect chain with the requested audio session
7584        chain = getEffectChain_l(sessionId);
7585        if (chain == 0) {
7586            // create a new chain for this session
7587            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
7588            chain = new EffectChain(this, sessionId);
7589            addEffectChain_l(chain);
7590            chain->setStrategy(getStrategyForSession_l(sessionId));
7591            chainCreated = true;
7592        } else {
7593            effect = chain->getEffectFromDesc_l(desc);
7594        }
7595
7596        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
7597
7598        if (effect == 0) {
7599            int id = mAudioFlinger->nextUniqueId();
7600            // Check CPU and memory usage
7601            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
7602            if (lStatus != NO_ERROR) {
7603                goto Exit;
7604            }
7605            effectRegistered = true;
7606            // create a new effect module if none present in the chain
7607            effect = new EffectModule(this, chain, desc, id, sessionId);
7608            lStatus = effect->status();
7609            if (lStatus != NO_ERROR) {
7610                goto Exit;
7611            }
7612            lStatus = chain->addEffect_l(effect);
7613            if (lStatus != NO_ERROR) {
7614                goto Exit;
7615            }
7616            effectCreated = true;
7617
7618            effect->setDevice(mDevice);
7619            effect->setMode(mAudioFlinger->getMode());
7620        }
7621        // create effect handle and connect it to effect module
7622        handle = new EffectHandle(effect, client, effectClient, priority);
7623        lStatus = effect->addHandle(handle.get());
7624        if (enabled != NULL) {
7625            *enabled = (int)effect->isEnabled();
7626        }
7627    }
7628
7629Exit:
7630    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
7631        Mutex::Autolock _l(mLock);
7632        if (effectCreated) {
7633            chain->removeEffect_l(effect);
7634        }
7635        if (effectRegistered) {
7636            AudioSystem::unregisterEffect(effect->id());
7637        }
7638        if (chainCreated) {
7639            removeEffectChain_l(chain);
7640        }
7641        handle.clear();
7642    }
7643
7644    if (status != NULL) {
7645        *status = lStatus;
7646    }
7647    return handle;
7648}
7649
7650sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7651{
7652    Mutex::Autolock _l(mLock);
7653    return getEffect_l(sessionId, effectId);
7654}
7655
7656sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7657{
7658    sp<EffectChain> chain = getEffectChain_l(sessionId);
7659    return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
7660}
7661
7662// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7663// PlaybackThread::mLock held
7664status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
7665{
7666    // check for existing effect chain with the requested audio session
7667    int sessionId = effect->sessionId();
7668    sp<EffectChain> chain = getEffectChain_l(sessionId);
7669    bool chainCreated = false;
7670
7671    if (chain == 0) {
7672        // create a new chain for this session
7673        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
7674        chain = new EffectChain(this, sessionId);
7675        addEffectChain_l(chain);
7676        chain->setStrategy(getStrategyForSession_l(sessionId));
7677        chainCreated = true;
7678    }
7679    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
7680
7681    if (chain->getEffectFromId_l(effect->id()) != 0) {
7682        ALOGW("addEffect_l() %p effect %s already present in chain %p",
7683                this, effect->desc().name, chain.get());
7684        return BAD_VALUE;
7685    }
7686
7687    status_t status = chain->addEffect_l(effect);
7688    if (status != NO_ERROR) {
7689        if (chainCreated) {
7690            removeEffectChain_l(chain);
7691        }
7692        return status;
7693    }
7694
7695    effect->setDevice(mDevice);
7696    effect->setMode(mAudioFlinger->getMode());
7697    return NO_ERROR;
7698}
7699
7700void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
7701
7702    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
7703    effect_descriptor_t desc = effect->desc();
7704    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7705        detachAuxEffect_l(effect->id());
7706    }
7707
7708    sp<EffectChain> chain = effect->chain().promote();
7709    if (chain != 0) {
7710        // remove effect chain if removing last effect
7711        if (chain->removeEffect_l(effect) == 0) {
7712            removeEffectChain_l(chain);
7713        }
7714    } else {
7715        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
7716    }
7717}
7718
7719void AudioFlinger::ThreadBase::lockEffectChains_l(
7720        Vector< sp<AudioFlinger::EffectChain> >& effectChains)
7721{
7722    effectChains = mEffectChains;
7723    for (size_t i = 0; i < mEffectChains.size(); i++) {
7724        mEffectChains[i]->lock();
7725    }
7726}
7727
7728void AudioFlinger::ThreadBase::unlockEffectChains(
7729        const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
7730{
7731    for (size_t i = 0; i < effectChains.size(); i++) {
7732        effectChains[i]->unlock();
7733    }
7734}
7735
7736sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7737{
7738    Mutex::Autolock _l(mLock);
7739    return getEffectChain_l(sessionId);
7740}
7741
7742sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7743{
7744    size_t size = mEffectChains.size();
7745    for (size_t i = 0; i < size; i++) {
7746        if (mEffectChains[i]->sessionId() == sessionId) {
7747            return mEffectChains[i];
7748        }
7749    }
7750    return 0;
7751}
7752
7753void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
7754{
7755    Mutex::Autolock _l(mLock);
7756    size_t size = mEffectChains.size();
7757    for (size_t i = 0; i < size; i++) {
7758        mEffectChains[i]->setMode_l(mode);
7759    }
7760}
7761
7762void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
7763                                                    EffectHandle *handle,
7764                                                    bool unpinIfLast) {
7765
7766    Mutex::Autolock _l(mLock);
7767    ALOGV("disconnectEffect() %p effect %p", this, effect.get());
7768    // delete the effect module if removing last handle on it
7769    if (effect->removeHandle(handle) == 0) {
7770        if (!effect->isPinned() || unpinIfLast) {
7771            removeEffect_l(effect);
7772            AudioSystem::unregisterEffect(effect->id());
7773        }
7774    }
7775}
7776
7777status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7778{
7779    int session = chain->sessionId();
7780    int16_t *buffer = mMixBuffer;
7781    bool ownsBuffer = false;
7782
7783    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
7784    if (session > 0) {
7785        // Only one effect chain can be present in direct output thread and it uses
7786        // the mix buffer as input
7787        if (mType != DIRECT) {
7788            size_t numSamples = mNormalFrameCount * mChannelCount;
7789            buffer = new int16_t[numSamples];
7790            memset(buffer, 0, numSamples * sizeof(int16_t));
7791            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
7792            ownsBuffer = true;
7793        }
7794
7795        // Attach all tracks with same session ID to this chain.
7796        for (size_t i = 0; i < mTracks.size(); ++i) {
7797            sp<Track> track = mTracks[i];
7798            if (session == track->sessionId()) {
7799                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
7800                track->setMainBuffer(buffer);
7801                chain->incTrackCnt();
7802            }
7803        }
7804
7805        // indicate all active tracks in the chain
7806        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7807            sp<Track> track = mActiveTracks[i].promote();
7808            if (track == 0) continue;
7809            if (session == track->sessionId()) {
7810                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
7811                chain->incActiveTrackCnt();
7812            }
7813        }
7814    }
7815
7816    chain->setInBuffer(buffer, ownsBuffer);
7817    chain->setOutBuffer(mMixBuffer);
7818    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
7819    // chains list in order to be processed last as it contains output stage effects
7820    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7821    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
7822    // after track specific effects and before output stage
7823    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7824    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
7825    // Effect chain for other sessions are inserted at beginning of effect
7826    // chains list to be processed before output mix effects. Relative order between other
7827    // sessions is not important
7828    size_t size = mEffectChains.size();
7829    size_t i = 0;
7830    for (i = 0; i < size; i++) {
7831        if (mEffectChains[i]->sessionId() < session) break;
7832    }
7833    mEffectChains.insertAt(chain, i);
7834    checkSuspendOnAddEffectChain_l(chain);
7835
7836    return NO_ERROR;
7837}
7838
7839size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7840{
7841    int session = chain->sessionId();
7842
7843    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
7844
7845    for (size_t i = 0; i < mEffectChains.size(); i++) {
7846        if (chain == mEffectChains[i]) {
7847            mEffectChains.removeAt(i);
7848            // detach all active tracks from the chain
7849            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7850                sp<Track> track = mActiveTracks[i].promote();
7851                if (track == 0) continue;
7852                if (session == track->sessionId()) {
7853                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
7854                            chain.get(), session);
7855                    chain->decActiveTrackCnt();
7856                }
7857            }
7858
7859            // detach all tracks with same session ID from this chain
7860            for (size_t i = 0; i < mTracks.size(); ++i) {
7861                sp<Track> track = mTracks[i];
7862                if (session == track->sessionId()) {
7863                    track->setMainBuffer(mMixBuffer);
7864                    chain->decTrackCnt();
7865                }
7866            }
7867            break;
7868        }
7869    }
7870    return mEffectChains.size();
7871}
7872
7873status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7874        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
7875{
7876    Mutex::Autolock _l(mLock);
7877    return attachAuxEffect_l(track, EffectId);
7878}
7879
7880status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7881        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
7882{
7883    status_t status = NO_ERROR;
7884
7885    if (EffectId == 0) {
7886        track->setAuxBuffer(0, NULL);
7887    } else {
7888        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7889        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
7890        if (effect != 0) {
7891            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7892                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7893            } else {
7894                status = INVALID_OPERATION;
7895            }
7896        } else {
7897            status = BAD_VALUE;
7898        }
7899    }
7900    return status;
7901}
7902
7903void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7904{
7905    for (size_t i = 0; i < mTracks.size(); ++i) {
7906        sp<Track> track = mTracks[i];
7907        if (track->auxEffectId() == effectId) {
7908            attachAuxEffect_l(track, 0);
7909        }
7910    }
7911}
7912
7913status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7914{
7915    // only one chain per input thread
7916    if (mEffectChains.size() != 0) {
7917        return INVALID_OPERATION;
7918    }
7919    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
7920
7921    chain->setInBuffer(NULL);
7922    chain->setOutBuffer(NULL);
7923
7924    checkSuspendOnAddEffectChain_l(chain);
7925
7926    mEffectChains.add(chain);
7927
7928    return NO_ERROR;
7929}
7930
7931size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7932{
7933    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7934    ALOGW_IF(mEffectChains.size() != 1,
7935            "removeEffectChain_l() %p invalid chain size %d on thread %p",
7936            chain.get(), mEffectChains.size(), this);
7937    if (mEffectChains.size() == 1) {
7938        mEffectChains.removeAt(0);
7939    }
7940    return 0;
7941}
7942
7943// ----------------------------------------------------------------------------
7944//  EffectModule implementation
7945// ----------------------------------------------------------------------------
7946
7947#undef LOG_TAG
7948#define LOG_TAG "AudioFlinger::EffectModule"
7949
7950AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
7951                                        const wp<AudioFlinger::EffectChain>& chain,
7952                                        effect_descriptor_t *desc,
7953                                        int id,
7954                                        int sessionId)
7955    : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7956      mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
7957      // mDescriptor is set below
7958      // mConfig is set by configure() and not used before then
7959      mEffectInterface(NULL),
7960      mStatus(NO_INIT), mState(IDLE),
7961      // mMaxDisableWaitCnt is set by configure() and not used before then
7962      // mDisableWaitCnt is set by process() and updateState() and not used before then
7963      mSuspended(false)
7964{
7965    ALOGV("Constructor %p", this);
7966    int lStatus;
7967    if (thread == NULL) {
7968        return;
7969    }
7970
7971    memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7972
7973    // create effect engine from effect factory
7974    mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
7975
7976    if (mStatus != NO_ERROR) {
7977        return;
7978    }
7979    lStatus = init();
7980    if (lStatus < 0) {
7981        mStatus = lStatus;
7982        goto Error;
7983    }
7984
7985    ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
7986    return;
7987Error:
7988    EffectRelease(mEffectInterface);
7989    mEffectInterface = NULL;
7990    ALOGV("Constructor Error %d", mStatus);
7991}
7992
7993AudioFlinger::EffectModule::~EffectModule()
7994{
7995    ALOGV("Destructor %p", this);
7996    if (mEffectInterface != NULL) {
7997        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7998                (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7999            sp<ThreadBase> thread = mThread.promote();
8000            if (thread != 0) {
8001                audio_stream_t *stream = thread->stream();
8002                if (stream != NULL) {
8003                    stream->remove_audio_effect(stream, mEffectInterface);
8004                }
8005            }
8006        }
8007        // release effect engine
8008        EffectRelease(mEffectInterface);
8009    }
8010}
8011
8012status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
8013{
8014    status_t status;
8015
8016    Mutex::Autolock _l(mLock);
8017    int priority = handle->priority();
8018    size_t size = mHandles.size();
8019    EffectHandle *controlHandle = NULL;
8020    size_t i;
8021    for (i = 0; i < size; i++) {
8022        EffectHandle *h = mHandles[i];
8023        if (h == NULL || h->destroyed_l()) continue;
8024        // first non destroyed handle is considered in control
8025        if (controlHandle == NULL)
8026            controlHandle = h;
8027        if (h->priority() <= priority) break;
8028    }
8029    // if inserted in first place, move effect control from previous owner to this handle
8030    if (i == 0) {
8031        bool enabled = false;
8032        if (controlHandle != NULL) {
8033            enabled = controlHandle->enabled();
8034            controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
8035        }
8036        handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
8037        status = NO_ERROR;
8038    } else {
8039        status = ALREADY_EXISTS;
8040    }
8041    ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
8042    mHandles.insertAt(handle, i);
8043    return status;
8044}
8045
8046size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
8047{
8048    Mutex::Autolock _l(mLock);
8049    size_t size = mHandles.size();
8050    size_t i;
8051    for (i = 0; i < size; i++) {
8052        if (mHandles[i] == handle) break;
8053    }
8054    if (i == size) {
8055        return size;
8056    }
8057    ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
8058
8059    mHandles.removeAt(i);
8060    // if removed from first place, move effect control from this handle to next in line
8061    if (i == 0) {
8062        EffectHandle *h = controlHandle_l();
8063        if (h != NULL) {
8064            h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
8065        }
8066    }
8067
8068    // Prevent calls to process() and other functions on effect interface from now on.
8069    // The effect engine will be released by the destructor when the last strong reference on
8070    // this object is released which can happen after next process is called.
8071    if (mHandles.size() == 0 && !mPinned) {
8072        mState = DESTROYED;
8073    }
8074
8075    return size;
8076}
8077
8078// must be called with EffectModule::mLock held
8079AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
8080{
8081    // the first valid handle in the list has control over the module
8082    for (size_t i = 0; i < mHandles.size(); i++) {
8083        EffectHandle *h = mHandles[i];
8084        if (h != NULL && !h->destroyed_l()) {
8085            return h;
8086        }
8087    }
8088
8089    return NULL;
8090}
8091
8092size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
8093{
8094    ALOGV("disconnect() %p handle %p", this, handle);
8095    // keep a strong reference on this EffectModule to avoid calling the
8096    // destructor before we exit
8097    sp<EffectModule> keep(this);
8098    {
8099        sp<ThreadBase> thread = mThread.promote();
8100        if (thread != 0) {
8101            thread->disconnectEffect(keep, handle, unpinIfLast);
8102        }
8103    }
8104    return mHandles.size();
8105}
8106
8107void AudioFlinger::EffectModule::updateState() {
8108    Mutex::Autolock _l(mLock);
8109
8110    switch (mState) {
8111    case RESTART:
8112        reset_l();
8113        // FALL THROUGH
8114
8115    case STARTING:
8116        // clear auxiliary effect input buffer for next accumulation
8117        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8118            memset(mConfig.inputCfg.buffer.raw,
8119                   0,
8120                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8121        }
8122        start_l();
8123        mState = ACTIVE;
8124        break;
8125    case STOPPING:
8126        stop_l();
8127        mDisableWaitCnt = mMaxDisableWaitCnt;
8128        mState = STOPPED;
8129        break;
8130    case STOPPED:
8131        // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8132        // turn off sequence.
8133        if (--mDisableWaitCnt == 0) {
8134            reset_l();
8135            mState = IDLE;
8136        }
8137        break;
8138    default: //IDLE , ACTIVE, DESTROYED
8139        break;
8140    }
8141}
8142
8143void AudioFlinger::EffectModule::process()
8144{
8145    Mutex::Autolock _l(mLock);
8146
8147    if (mState == DESTROYED || mEffectInterface == NULL ||
8148            mConfig.inputCfg.buffer.raw == NULL ||
8149            mConfig.outputCfg.buffer.raw == NULL) {
8150        return;
8151    }
8152
8153    if (isProcessEnabled()) {
8154        // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8155        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8156            ditherAndClamp(mConfig.inputCfg.buffer.s32,
8157                                        mConfig.inputCfg.buffer.s32,
8158                                        mConfig.inputCfg.buffer.frameCount/2);
8159        }
8160
8161        // do the actual processing in the effect engine
8162        int ret = (*mEffectInterface)->process(mEffectInterface,
8163                                               &mConfig.inputCfg.buffer,
8164                                               &mConfig.outputCfg.buffer);
8165
8166        // force transition to IDLE state when engine is ready
8167        if (mState == STOPPED && ret == -ENODATA) {
8168            mDisableWaitCnt = 1;
8169        }
8170
8171        // clear auxiliary effect input buffer for next accumulation
8172        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8173            memset(mConfig.inputCfg.buffer.raw, 0,
8174                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8175        }
8176    } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
8177                mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8178        // If an insert effect is idle and input buffer is different from output buffer,
8179        // accumulate input onto output
8180        sp<EffectChain> chain = mChain.promote();
8181        if (chain != 0 && chain->activeTrackCnt() != 0) {
8182            size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2;  //always stereo here
8183            int16_t *in = mConfig.inputCfg.buffer.s16;
8184            int16_t *out = mConfig.outputCfg.buffer.s16;
8185            for (size_t i = 0; i < frameCnt; i++) {
8186                out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
8187            }
8188        }
8189    }
8190}
8191
8192void AudioFlinger::EffectModule::reset_l()
8193{
8194    if (mEffectInterface == NULL) {
8195        return;
8196    }
8197    (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8198}
8199
8200status_t AudioFlinger::EffectModule::configure()
8201{
8202    if (mEffectInterface == NULL) {
8203        return NO_INIT;
8204    }
8205
8206    sp<ThreadBase> thread = mThread.promote();
8207    if (thread == 0) {
8208        return DEAD_OBJECT;
8209    }
8210
8211    // TODO: handle configuration of effects replacing track process
8212    audio_channel_mask_t channelMask = thread->channelMask();
8213
8214    if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8215        mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
8216    } else {
8217        mConfig.inputCfg.channels = channelMask;
8218    }
8219    mConfig.outputCfg.channels = channelMask;
8220    mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8221    mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8222    mConfig.inputCfg.samplingRate = thread->sampleRate();
8223    mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8224    mConfig.inputCfg.bufferProvider.cookie = NULL;
8225    mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8226    mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8227    mConfig.outputCfg.bufferProvider.cookie = NULL;
8228    mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8229    mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8230    mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8231    // Insert effect:
8232    // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
8233    // always overwrites output buffer: input buffer == output buffer
8234    // - in other sessions:
8235    //      last effect in the chain accumulates in output buffer: input buffer != output buffer
8236    //      other effect: overwrites output buffer: input buffer == output buffer
8237    // Auxiliary effect:
8238    //      accumulates in output buffer: input buffer != output buffer
8239    // Therefore: accumulate <=> input buffer != output buffer
8240    if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8241        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8242    } else {
8243        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8244    }
8245    mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8246    mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8247    mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8248    mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8249
8250    ALOGV("configure() %p thread %p buffer %p framecount %d",
8251            this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8252
8253    status_t cmdStatus;
8254    uint32_t size = sizeof(int);
8255    status_t status = (*mEffectInterface)->command(mEffectInterface,
8256                                                   EFFECT_CMD_SET_CONFIG,
8257                                                   sizeof(effect_config_t),
8258                                                   &mConfig,
8259                                                   &size,
8260                                                   &cmdStatus);
8261    if (status == 0) {
8262        status = cmdStatus;
8263    }
8264
8265    if (status == 0 &&
8266            (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8267        uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8268        effect_param_t *p = (effect_param_t *)buf32;
8269
8270        p->psize = sizeof(uint32_t);
8271        p->vsize = sizeof(uint32_t);
8272        size = sizeof(int);
8273        *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8274
8275        uint32_t latency = 0;
8276        PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8277        if (pbt != NULL) {
8278            latency = pbt->latency_l();
8279        }
8280
8281        *((int32_t *)p->data + 1)= latency;
8282        (*mEffectInterface)->command(mEffectInterface,
8283                                     EFFECT_CMD_SET_PARAM,
8284                                     sizeof(effect_param_t) + 8,
8285                                     &buf32,
8286                                     &size,
8287                                     &cmdStatus);
8288    }
8289
8290    mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8291            (1000 * mConfig.outputCfg.buffer.frameCount);
8292
8293    return status;
8294}
8295
8296status_t AudioFlinger::EffectModule::init()
8297{
8298    Mutex::Autolock _l(mLock);
8299    if (mEffectInterface == NULL) {
8300        return NO_INIT;
8301    }
8302    status_t cmdStatus;
8303    uint32_t size = sizeof(status_t);
8304    status_t status = (*mEffectInterface)->command(mEffectInterface,
8305                                                   EFFECT_CMD_INIT,
8306                                                   0,
8307                                                   NULL,
8308                                                   &size,
8309                                                   &cmdStatus);
8310    if (status == 0) {
8311        status = cmdStatus;
8312    }
8313    return status;
8314}
8315
8316status_t AudioFlinger::EffectModule::start()
8317{
8318    Mutex::Autolock _l(mLock);
8319    return start_l();
8320}
8321
8322status_t AudioFlinger::EffectModule::start_l()
8323{
8324    if (mEffectInterface == NULL) {
8325        return NO_INIT;
8326    }
8327    status_t cmdStatus;
8328    uint32_t size = sizeof(status_t);
8329    status_t status = (*mEffectInterface)->command(mEffectInterface,
8330                                                   EFFECT_CMD_ENABLE,
8331                                                   0,
8332                                                   NULL,
8333                                                   &size,
8334                                                   &cmdStatus);
8335    if (status == 0) {
8336        status = cmdStatus;
8337    }
8338    if (status == 0 &&
8339            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8340             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8341        sp<ThreadBase> thread = mThread.promote();
8342        if (thread != 0) {
8343            audio_stream_t *stream = thread->stream();
8344            if (stream != NULL) {
8345                stream->add_audio_effect(stream, mEffectInterface);
8346            }
8347        }
8348    }
8349    return status;
8350}
8351
8352status_t AudioFlinger::EffectModule::stop()
8353{
8354    Mutex::Autolock _l(mLock);
8355    return stop_l();
8356}
8357
8358status_t AudioFlinger::EffectModule::stop_l()
8359{
8360    if (mEffectInterface == NULL) {
8361        return NO_INIT;
8362    }
8363    status_t cmdStatus;
8364    uint32_t size = sizeof(status_t);
8365    status_t status = (*mEffectInterface)->command(mEffectInterface,
8366                                                   EFFECT_CMD_DISABLE,
8367                                                   0,
8368                                                   NULL,
8369                                                   &size,
8370                                                   &cmdStatus);
8371    if (status == 0) {
8372        status = cmdStatus;
8373    }
8374    if (status == 0 &&
8375            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8376             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8377        sp<ThreadBase> thread = mThread.promote();
8378        if (thread != 0) {
8379            audio_stream_t *stream = thread->stream();
8380            if (stream != NULL) {
8381                stream->remove_audio_effect(stream, mEffectInterface);
8382            }
8383        }
8384    }
8385    return status;
8386}
8387
8388status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8389                                             uint32_t cmdSize,
8390                                             void *pCmdData,
8391                                             uint32_t *replySize,
8392                                             void *pReplyData)
8393{
8394    Mutex::Autolock _l(mLock);
8395//    ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
8396
8397    if (mState == DESTROYED || mEffectInterface == NULL) {
8398        return NO_INIT;
8399    }
8400    status_t status = (*mEffectInterface)->command(mEffectInterface,
8401                                                   cmdCode,
8402                                                   cmdSize,
8403                                                   pCmdData,
8404                                                   replySize,
8405                                                   pReplyData);
8406    if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
8407        uint32_t size = (replySize == NULL) ? 0 : *replySize;
8408        for (size_t i = 1; i < mHandles.size(); i++) {
8409            EffectHandle *h = mHandles[i];
8410            if (h != NULL && !h->destroyed_l()) {
8411                h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8412            }
8413        }
8414    }
8415    return status;
8416}
8417
8418status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8419{
8420    Mutex::Autolock _l(mLock);
8421    return setEnabled_l(enabled);
8422}
8423
8424// must be called with EffectModule::mLock held
8425status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8426{
8427
8428    ALOGV("setEnabled %p enabled %d", this, enabled);
8429
8430    if (enabled != isEnabled()) {
8431        status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8432        if (enabled && status != NO_ERROR) {
8433            return status;
8434        }
8435
8436        switch (mState) {
8437        // going from disabled to enabled
8438        case IDLE:
8439            mState = STARTING;
8440            break;
8441        case STOPPED:
8442            mState = RESTART;
8443            break;
8444        case STOPPING:
8445            mState = ACTIVE;
8446            break;
8447
8448        // going from enabled to disabled
8449        case RESTART:
8450            mState = STOPPED;
8451            break;
8452        case STARTING:
8453            mState = IDLE;
8454            break;
8455        case ACTIVE:
8456            mState = STOPPING;
8457            break;
8458        case DESTROYED:
8459            return NO_ERROR; // simply ignore as we are being destroyed
8460        }
8461        for (size_t i = 1; i < mHandles.size(); i++) {
8462            EffectHandle *h = mHandles[i];
8463            if (h != NULL && !h->destroyed_l()) {
8464                h->setEnabled(enabled);
8465            }
8466        }
8467    }
8468    return NO_ERROR;
8469}
8470
8471bool AudioFlinger::EffectModule::isEnabled() const
8472{
8473    switch (mState) {
8474    case RESTART:
8475    case STARTING:
8476    case ACTIVE:
8477        return true;
8478    case IDLE:
8479    case STOPPING:
8480    case STOPPED:
8481    case DESTROYED:
8482    default:
8483        return false;
8484    }
8485}
8486
8487bool AudioFlinger::EffectModule::isProcessEnabled() const
8488{
8489    switch (mState) {
8490    case RESTART:
8491    case ACTIVE:
8492    case STOPPING:
8493    case STOPPED:
8494        return true;
8495    case IDLE:
8496    case STARTING:
8497    case DESTROYED:
8498    default:
8499        return false;
8500    }
8501}
8502
8503status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8504{
8505    Mutex::Autolock _l(mLock);
8506    status_t status = NO_ERROR;
8507
8508    // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8509    // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
8510    if (isProcessEnabled() &&
8511            ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8512            (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
8513        status_t cmdStatus;
8514        uint32_t volume[2];
8515        uint32_t *pVolume = NULL;
8516        uint32_t size = sizeof(volume);
8517        volume[0] = *left;
8518        volume[1] = *right;
8519        if (controller) {
8520            pVolume = volume;
8521        }
8522        status = (*mEffectInterface)->command(mEffectInterface,
8523                                              EFFECT_CMD_SET_VOLUME,
8524                                              size,
8525                                              volume,
8526                                              &size,
8527                                              pVolume);
8528        if (controller && status == NO_ERROR && size == sizeof(volume)) {
8529            *left = volume[0];
8530            *right = volume[1];
8531        }
8532    }
8533    return status;
8534}
8535
8536status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
8537{
8538    Mutex::Autolock _l(mLock);
8539    status_t status = NO_ERROR;
8540    if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8541        // audio pre processing modules on RecordThread can receive both output and
8542        // input device indication in the same call
8543        audio_devices_t dev = device & AUDIO_DEVICE_OUT_ALL;
8544        if (dev) {
8545            status_t cmdStatus;
8546            uint32_t size = sizeof(status_t);
8547
8548            status = (*mEffectInterface)->command(mEffectInterface,
8549                                                  EFFECT_CMD_SET_DEVICE,
8550                                                  sizeof(uint32_t),
8551                                                  &dev,
8552                                                  &size,
8553                                                  &cmdStatus);
8554            if (status == NO_ERROR) {
8555                status = cmdStatus;
8556            }
8557        }
8558        dev = device & AUDIO_DEVICE_IN_ALL;
8559        if (dev) {
8560            status_t cmdStatus;
8561            uint32_t size = sizeof(status_t);
8562
8563            status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8564                                                  EFFECT_CMD_SET_INPUT_DEVICE,
8565                                                  sizeof(uint32_t),
8566                                                  &dev,
8567                                                  &size,
8568                                                  &cmdStatus);
8569            if (status2 == NO_ERROR) {
8570                status2 = cmdStatus;
8571            }
8572            if (status == NO_ERROR) {
8573                status = status2;
8574            }
8575        }
8576    }
8577    return status;
8578}
8579
8580status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
8581{
8582    Mutex::Autolock _l(mLock);
8583    status_t status = NO_ERROR;
8584    if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
8585        status_t cmdStatus;
8586        uint32_t size = sizeof(status_t);
8587        status = (*mEffectInterface)->command(mEffectInterface,
8588                                              EFFECT_CMD_SET_AUDIO_MODE,
8589                                              sizeof(audio_mode_t),
8590                                              &mode,
8591                                              &size,
8592                                              &cmdStatus);
8593        if (status == NO_ERROR) {
8594            status = cmdStatus;
8595        }
8596    }
8597    return status;
8598}
8599
8600void AudioFlinger::EffectModule::setSuspended(bool suspended)
8601{
8602    Mutex::Autolock _l(mLock);
8603    mSuspended = suspended;
8604}
8605
8606bool AudioFlinger::EffectModule::suspended() const
8607{
8608    Mutex::Autolock _l(mLock);
8609    return mSuspended;
8610}
8611
8612bool AudioFlinger::EffectModule::purgeHandles()
8613{
8614    bool enabled = false;
8615    Mutex::Autolock _l(mLock);
8616    for (size_t i = 0; i < mHandles.size(); i++) {
8617        EffectHandle *handle = mHandles[i];
8618        if (handle != NULL && !handle->destroyed_l()) {
8619            handle->effect().clear();
8620            if (handle->hasControl()) {
8621                enabled = handle->enabled();
8622            }
8623        }
8624    }
8625    return enabled;
8626}
8627
8628status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8629{
8630    const size_t SIZE = 256;
8631    char buffer[SIZE];
8632    String8 result;
8633
8634    snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8635    result.append(buffer);
8636
8637    bool locked = tryLock(mLock);
8638    // failed to lock - AudioFlinger is probably deadlocked
8639    if (!locked) {
8640        result.append("\t\tCould not lock Fx mutex:\n");
8641    }
8642
8643    result.append("\t\tSession Status State Engine:\n");
8644    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   0x%08x\n",
8645            mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8646    result.append(buffer);
8647
8648    result.append("\t\tDescriptor:\n");
8649    snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8650            mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8651            mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8652            mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8653    result.append(buffer);
8654    snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8655                mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8656                mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8657                mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8658    result.append(buffer);
8659    snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
8660            mDescriptor.apiVersion,
8661            mDescriptor.flags);
8662    result.append(buffer);
8663    snprintf(buffer, SIZE, "\t\t- name: %s\n",
8664            mDescriptor.name);
8665    result.append(buffer);
8666    snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8667            mDescriptor.implementor);
8668    result.append(buffer);
8669
8670    result.append("\t\t- Input configuration:\n");
8671    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
8672    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
8673            (uint32_t)mConfig.inputCfg.buffer.raw,
8674            mConfig.inputCfg.buffer.frameCount,
8675            mConfig.inputCfg.samplingRate,
8676            mConfig.inputCfg.channels,
8677            mConfig.inputCfg.format);
8678    result.append(buffer);
8679
8680    result.append("\t\t- Output configuration:\n");
8681    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
8682    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
8683            (uint32_t)mConfig.outputCfg.buffer.raw,
8684            mConfig.outputCfg.buffer.frameCount,
8685            mConfig.outputCfg.samplingRate,
8686            mConfig.outputCfg.channels,
8687            mConfig.outputCfg.format);
8688    result.append(buffer);
8689
8690    snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8691    result.append(buffer);
8692    result.append("\t\t\tPid   Priority Ctrl Locked client server\n");
8693    for (size_t i = 0; i < mHandles.size(); ++i) {
8694        EffectHandle *handle = mHandles[i];
8695        if (handle != NULL && !handle->destroyed_l()) {
8696            handle->dump(buffer, SIZE);
8697            result.append(buffer);
8698        }
8699    }
8700
8701    result.append("\n");
8702
8703    write(fd, result.string(), result.length());
8704
8705    if (locked) {
8706        mLock.unlock();
8707    }
8708
8709    return NO_ERROR;
8710}
8711
8712// ----------------------------------------------------------------------------
8713//  EffectHandle implementation
8714// ----------------------------------------------------------------------------
8715
8716#undef LOG_TAG
8717#define LOG_TAG "AudioFlinger::EffectHandle"
8718
8719AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8720                                        const sp<AudioFlinger::Client>& client,
8721                                        const sp<IEffectClient>& effectClient,
8722                                        int32_t priority)
8723    : BnEffect(),
8724    mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
8725    mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
8726{
8727    ALOGV("constructor %p", this);
8728
8729    if (client == 0) {
8730        return;
8731    }
8732    int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8733    mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8734    if (mCblkMemory != 0) {
8735        mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8736
8737        if (mCblk != NULL) {
8738            new(mCblk) effect_param_cblk_t();
8739            mBuffer = (uint8_t *)mCblk + bufOffset;
8740        }
8741    } else {
8742        ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
8743        return;
8744    }
8745}
8746
8747AudioFlinger::EffectHandle::~EffectHandle()
8748{
8749    ALOGV("Destructor %p", this);
8750
8751    if (mEffect == 0) {
8752        mDestroyed = true;
8753        return;
8754    }
8755    mEffect->lock();
8756    mDestroyed = true;
8757    mEffect->unlock();
8758    disconnect(false);
8759}
8760
8761status_t AudioFlinger::EffectHandle::enable()
8762{
8763    ALOGV("enable %p", this);
8764    if (!mHasControl) return INVALID_OPERATION;
8765    if (mEffect == 0) return DEAD_OBJECT;
8766
8767    if (mEnabled) {
8768        return NO_ERROR;
8769    }
8770
8771    mEnabled = true;
8772
8773    sp<ThreadBase> thread = mEffect->thread().promote();
8774    if (thread != 0) {
8775        thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8776    }
8777
8778    // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8779    if (mEffect->suspended()) {
8780        return NO_ERROR;
8781    }
8782
8783    status_t status = mEffect->setEnabled(true);
8784    if (status != NO_ERROR) {
8785        if (thread != 0) {
8786            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8787        }
8788        mEnabled = false;
8789    }
8790    return status;
8791}
8792
8793status_t AudioFlinger::EffectHandle::disable()
8794{
8795    ALOGV("disable %p", this);
8796    if (!mHasControl) return INVALID_OPERATION;
8797    if (mEffect == 0) return DEAD_OBJECT;
8798
8799    if (!mEnabled) {
8800        return NO_ERROR;
8801    }
8802    mEnabled = false;
8803
8804    if (mEffect->suspended()) {
8805        return NO_ERROR;
8806    }
8807
8808    status_t status = mEffect->setEnabled(false);
8809
8810    sp<ThreadBase> thread = mEffect->thread().promote();
8811    if (thread != 0) {
8812        thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8813    }
8814
8815    return status;
8816}
8817
8818void AudioFlinger::EffectHandle::disconnect()
8819{
8820    disconnect(true);
8821}
8822
8823void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
8824{
8825    ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
8826    if (mEffect == 0) {
8827        return;
8828    }
8829    // restore suspended effects if the disconnected handle was enabled and the last one.
8830    if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
8831        sp<ThreadBase> thread = mEffect->thread().promote();
8832        if (thread != 0) {
8833            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8834        }
8835    }
8836
8837    // release sp on module => module destructor can be called now
8838    mEffect.clear();
8839    if (mClient != 0) {
8840        if (mCblk != NULL) {
8841            // unlike ~TrackBase(), mCblk is never a local new, so don't delete
8842            mCblk->~effect_param_cblk_t();   // destroy our shared-structure.
8843        }
8844        mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
8845        // Client destructor must run with AudioFlinger mutex locked
8846        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8847        mClient.clear();
8848    }
8849}
8850
8851status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8852                                             uint32_t cmdSize,
8853                                             void *pCmdData,
8854                                             uint32_t *replySize,
8855                                             void *pReplyData)
8856{
8857//    ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
8858//              cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
8859
8860    // only get parameter command is permitted for applications not controlling the effect
8861    if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8862        return INVALID_OPERATION;
8863    }
8864    if (mEffect == 0) return DEAD_OBJECT;
8865    if (mClient == 0) return INVALID_OPERATION;
8866
8867    // handle commands that are not forwarded transparently to effect engine
8868    if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8869        // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8870        // no risk to block the whole media server process or mixer threads is we are stuck here
8871        Mutex::Autolock _l(mCblk->lock);
8872        if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8873            mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8874            mCblk->serverIndex = 0;
8875            mCblk->clientIndex = 0;
8876            return BAD_VALUE;
8877        }
8878        status_t status = NO_ERROR;
8879        while (mCblk->serverIndex < mCblk->clientIndex) {
8880            int reply;
8881            uint32_t rsize = sizeof(int);
8882            int *p = (int *)(mBuffer + mCblk->serverIndex);
8883            int size = *p++;
8884            if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
8885                ALOGW("command(): invalid parameter block size");
8886                break;
8887            }
8888            effect_param_t *param = (effect_param_t *)p;
8889            if (param->psize == 0 || param->vsize == 0) {
8890                ALOGW("command(): null parameter or value size");
8891                mCblk->serverIndex += size;
8892                continue;
8893            }
8894            uint32_t psize = sizeof(effect_param_t) +
8895                             ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8896                             param->vsize;
8897            status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8898                                            psize,
8899                                            p,
8900                                            &rsize,
8901                                            &reply);
8902            // stop at first error encountered
8903            if (ret != NO_ERROR) {
8904                status = ret;
8905                *(int *)pReplyData = reply;
8906                break;
8907            } else if (reply != NO_ERROR) {
8908                *(int *)pReplyData = reply;
8909                break;
8910            }
8911            mCblk->serverIndex += size;
8912        }
8913        mCblk->serverIndex = 0;
8914        mCblk->clientIndex = 0;
8915        return status;
8916    } else if (cmdCode == EFFECT_CMD_ENABLE) {
8917        *(int *)pReplyData = NO_ERROR;
8918        return enable();
8919    } else if (cmdCode == EFFECT_CMD_DISABLE) {
8920        *(int *)pReplyData = NO_ERROR;
8921        return disable();
8922    }
8923
8924    return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8925}
8926
8927void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
8928{
8929    ALOGV("setControl %p control %d", this, hasControl);
8930
8931    mHasControl = hasControl;
8932    mEnabled = enabled;
8933
8934    if (signal && mEffectClient != 0) {
8935        mEffectClient->controlStatusChanged(hasControl);
8936    }
8937}
8938
8939void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8940                                                 uint32_t cmdSize,
8941                                                 void *pCmdData,
8942                                                 uint32_t replySize,
8943                                                 void *pReplyData)
8944{
8945    if (mEffectClient != 0) {
8946        mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8947    }
8948}
8949
8950
8951
8952void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8953{
8954    if (mEffectClient != 0) {
8955        mEffectClient->enableStatusChanged(enabled);
8956    }
8957}
8958
8959status_t AudioFlinger::EffectHandle::onTransact(
8960    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8961{
8962    return BnEffect::onTransact(code, data, reply, flags);
8963}
8964
8965
8966void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8967{
8968    bool locked = mCblk != NULL && tryLock(mCblk->lock);
8969
8970    snprintf(buffer, size, "\t\t\t%05d %05d    %01u    %01u      %05u  %05u\n",
8971            (mClient == 0) ? getpid_cached : mClient->pid(),
8972            mPriority,
8973            mHasControl,
8974            !locked,
8975            mCblk ? mCblk->clientIndex : 0,
8976            mCblk ? mCblk->serverIndex : 0
8977            );
8978
8979    if (locked) {
8980        mCblk->lock.unlock();
8981    }
8982}
8983
8984#undef LOG_TAG
8985#define LOG_TAG "AudioFlinger::EffectChain"
8986
8987AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
8988                                        int sessionId)
8989    : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
8990      mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8991      mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
8992{
8993    mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
8994    if (thread == NULL) {
8995        return;
8996    }
8997    mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8998                                    thread->frameCount();
8999}
9000
9001AudioFlinger::EffectChain::~EffectChain()
9002{
9003    if (mOwnInBuffer) {
9004        delete mInBuffer;
9005    }
9006
9007}
9008
9009// getEffectFromDesc_l() must be called with ThreadBase::mLock held
9010sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
9011{
9012    size_t size = mEffects.size();
9013
9014    for (size_t i = 0; i < size; i++) {
9015        if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
9016            return mEffects[i];
9017        }
9018    }
9019    return 0;
9020}
9021
9022// getEffectFromId_l() must be called with ThreadBase::mLock held
9023sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
9024{
9025    size_t size = mEffects.size();
9026
9027    for (size_t i = 0; i < size; i++) {
9028        // by convention, return first effect if id provided is 0 (0 is never a valid id)
9029        if (id == 0 || mEffects[i]->id() == id) {
9030            return mEffects[i];
9031        }
9032    }
9033    return 0;
9034}
9035
9036// getEffectFromType_l() must be called with ThreadBase::mLock held
9037sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9038        const effect_uuid_t *type)
9039{
9040    size_t size = mEffects.size();
9041
9042    for (size_t i = 0; i < size; i++) {
9043        if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
9044            return mEffects[i];
9045        }
9046    }
9047    return 0;
9048}
9049
9050void AudioFlinger::EffectChain::clearInputBuffer()
9051{
9052    Mutex::Autolock _l(mLock);
9053    sp<ThreadBase> thread = mThread.promote();
9054    if (thread == 0) {
9055        ALOGW("clearInputBuffer(): cannot promote mixer thread");
9056        return;
9057    }
9058    clearInputBuffer_l(thread);
9059}
9060
9061// Must be called with EffectChain::mLock locked
9062void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9063{
9064    size_t numSamples = thread->frameCount() * thread->channelCount();
9065    memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9066
9067}
9068
9069// Must be called with EffectChain::mLock locked
9070void AudioFlinger::EffectChain::process_l()
9071{
9072    sp<ThreadBase> thread = mThread.promote();
9073    if (thread == 0) {
9074        ALOGW("process_l(): cannot promote mixer thread");
9075        return;
9076    }
9077    bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9078            (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
9079    // always process effects unless no more tracks are on the session and the effect tail
9080    // has been rendered
9081    bool doProcess = true;
9082    if (!isGlobalSession) {
9083        bool tracksOnSession = (trackCnt() != 0);
9084
9085        if (!tracksOnSession && mTailBufferCount == 0) {
9086            doProcess = false;
9087        }
9088
9089        if (activeTrackCnt() == 0) {
9090            // if no track is active and the effect tail has not been rendered,
9091            // the input buffer must be cleared here as the mixer process will not do it
9092            if (tracksOnSession || mTailBufferCount > 0) {
9093                clearInputBuffer_l(thread);
9094                if (mTailBufferCount > 0) {
9095                    mTailBufferCount--;
9096                }
9097            }
9098        }
9099    }
9100
9101    size_t size = mEffects.size();
9102    if (doProcess) {
9103        for (size_t i = 0; i < size; i++) {
9104            mEffects[i]->process();
9105        }
9106    }
9107    for (size_t i = 0; i < size; i++) {
9108        mEffects[i]->updateState();
9109    }
9110}
9111
9112// addEffect_l() must be called with PlaybackThread::mLock held
9113status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
9114{
9115    effect_descriptor_t desc = effect->desc();
9116    uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9117
9118    Mutex::Autolock _l(mLock);
9119    effect->setChain(this);
9120    sp<ThreadBase> thread = mThread.promote();
9121    if (thread == 0) {
9122        return NO_INIT;
9123    }
9124    effect->setThread(thread);
9125
9126    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9127        // Auxiliary effects are inserted at the beginning of mEffects vector as
9128        // they are processed first and accumulated in chain input buffer
9129        mEffects.insertAt(effect, 0);
9130
9131        // the input buffer for auxiliary effect contains mono samples in
9132        // 32 bit format. This is to avoid saturation in AudoMixer
9133        // accumulation stage. Saturation is done in EffectModule::process() before
9134        // calling the process in effect engine
9135        size_t numSamples = thread->frameCount();
9136        int32_t *buffer = new int32_t[numSamples];
9137        memset(buffer, 0, numSamples * sizeof(int32_t));
9138        effect->setInBuffer((int16_t *)buffer);
9139        // auxiliary effects output samples to chain input buffer for further processing
9140        // by insert effects
9141        effect->setOutBuffer(mInBuffer);
9142    } else {
9143        // Insert effects are inserted at the end of mEffects vector as they are processed
9144        //  after track and auxiliary effects.
9145        // Insert effect order as a function of indicated preference:
9146        //  if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9147        //  another effect is present
9148        //  else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9149        //  last effect claiming first position
9150        //  else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9151        //  first effect claiming last position
9152        //  else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9153        // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9154        // already present
9155
9156        size_t size = mEffects.size();
9157        size_t idx_insert = size;
9158        ssize_t idx_insert_first = -1;
9159        ssize_t idx_insert_last = -1;
9160
9161        for (size_t i = 0; i < size; i++) {
9162            effect_descriptor_t d = mEffects[i]->desc();
9163            uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9164            uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9165            if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9166                // check invalid effect chaining combinations
9167                if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9168                    iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
9169                    ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
9170                    return INVALID_OPERATION;
9171                }
9172                // remember position of first insert effect and by default
9173                // select this as insert position for new effect
9174                if (idx_insert == size) {
9175                    idx_insert = i;
9176                }
9177                // remember position of last insert effect claiming
9178                // first position
9179                if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9180                    idx_insert_first = i;
9181                }
9182                // remember position of first insert effect claiming
9183                // last position
9184                if (iPref == EFFECT_FLAG_INSERT_LAST &&
9185                    idx_insert_last == -1) {
9186                    idx_insert_last = i;
9187                }
9188            }
9189        }
9190
9191        // modify idx_insert from first position if needed
9192        if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9193            if (idx_insert_last != -1) {
9194                idx_insert = idx_insert_last;
9195            } else {
9196                idx_insert = size;
9197            }
9198        } else {
9199            if (idx_insert_first != -1) {
9200                idx_insert = idx_insert_first + 1;
9201            }
9202        }
9203
9204        // always read samples from chain input buffer
9205        effect->setInBuffer(mInBuffer);
9206
9207        // if last effect in the chain, output samples to chain
9208        // output buffer, otherwise to chain input buffer
9209        if (idx_insert == size) {
9210            if (idx_insert != 0) {
9211                mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9212                mEffects[idx_insert-1]->configure();
9213            }
9214            effect->setOutBuffer(mOutBuffer);
9215        } else {
9216            effect->setOutBuffer(mInBuffer);
9217        }
9218        mEffects.insertAt(effect, idx_insert);
9219
9220        ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
9221    }
9222    effect->configure();
9223    return NO_ERROR;
9224}
9225
9226// removeEffect_l() must be called with PlaybackThread::mLock held
9227size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
9228{
9229    Mutex::Autolock _l(mLock);
9230    size_t size = mEffects.size();
9231    uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9232
9233    for (size_t i = 0; i < size; i++) {
9234        if (effect == mEffects[i]) {
9235            // calling stop here will remove pre-processing effect from the audio HAL.
9236            // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9237            // the middle of a read from audio HAL
9238            if (mEffects[i]->state() == EffectModule::ACTIVE ||
9239                    mEffects[i]->state() == EffectModule::STOPPING) {
9240                mEffects[i]->stop();
9241            }
9242            if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9243                delete[] effect->inBuffer();
9244            } else {
9245                if (i == size - 1 && i != 0) {
9246                    mEffects[i - 1]->setOutBuffer(mOutBuffer);
9247                    mEffects[i - 1]->configure();
9248                }
9249            }
9250            mEffects.removeAt(i);
9251            ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
9252            break;
9253        }
9254    }
9255
9256    return mEffects.size();
9257}
9258
9259// setDevice_l() must be called with PlaybackThread::mLock held
9260void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
9261{
9262    size_t size = mEffects.size();
9263    for (size_t i = 0; i < size; i++) {
9264        mEffects[i]->setDevice(device);
9265    }
9266}
9267
9268// setMode_l() must be called with PlaybackThread::mLock held
9269void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
9270{
9271    size_t size = mEffects.size();
9272    for (size_t i = 0; i < size; i++) {
9273        mEffects[i]->setMode(mode);
9274    }
9275}
9276
9277// setVolume_l() must be called with PlaybackThread::mLock held
9278bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
9279{
9280    uint32_t newLeft = *left;
9281    uint32_t newRight = *right;
9282    bool hasControl = false;
9283    int ctrlIdx = -1;
9284    size_t size = mEffects.size();
9285
9286    // first update volume controller
9287    for (size_t i = size; i > 0; i--) {
9288        if (mEffects[i - 1]->isProcessEnabled() &&
9289            (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9290            ctrlIdx = i - 1;
9291            hasControl = true;
9292            break;
9293        }
9294    }
9295
9296    if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
9297        if (hasControl) {
9298            *left = mNewLeftVolume;
9299            *right = mNewRightVolume;
9300        }
9301        return hasControl;
9302    }
9303
9304    mVolumeCtrlIdx = ctrlIdx;
9305    mLeftVolume = newLeft;
9306    mRightVolume = newRight;
9307
9308    // second get volume update from volume controller
9309    if (ctrlIdx >= 0) {
9310        mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
9311        mNewLeftVolume = newLeft;
9312        mNewRightVolume = newRight;
9313    }
9314    // then indicate volume to all other effects in chain.
9315    // Pass altered volume to effects before volume controller
9316    // and requested volume to effects after controller
9317    uint32_t lVol = newLeft;
9318    uint32_t rVol = newRight;
9319
9320    for (size_t i = 0; i < size; i++) {
9321        if ((int)i == ctrlIdx) continue;
9322        // this also works for ctrlIdx == -1 when there is no volume controller
9323        if ((int)i > ctrlIdx) {
9324            lVol = *left;
9325            rVol = *right;
9326        }
9327        mEffects[i]->setVolume(&lVol, &rVol, false);
9328    }
9329    *left = newLeft;
9330    *right = newRight;
9331
9332    return hasControl;
9333}
9334
9335status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9336{
9337    const size_t SIZE = 256;
9338    char buffer[SIZE];
9339    String8 result;
9340
9341    snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9342    result.append(buffer);
9343
9344    bool locked = tryLock(mLock);
9345    // failed to lock - AudioFlinger is probably deadlocked
9346    if (!locked) {
9347        result.append("\tCould not lock mutex:\n");
9348    }
9349
9350    result.append("\tNum fx In buffer   Out buffer   Active tracks:\n");
9351    snprintf(buffer, SIZE, "\t%02d     0x%08x  0x%08x   %d\n",
9352            mEffects.size(),
9353            (uint32_t)mInBuffer,
9354            (uint32_t)mOutBuffer,
9355            mActiveTrackCnt);
9356    result.append(buffer);
9357    write(fd, result.string(), result.size());
9358
9359    for (size_t i = 0; i < mEffects.size(); ++i) {
9360        sp<EffectModule> effect = mEffects[i];
9361        if (effect != 0) {
9362            effect->dump(fd, args);
9363        }
9364    }
9365
9366    if (locked) {
9367        mLock.unlock();
9368    }
9369
9370    return NO_ERROR;
9371}
9372
9373// must be called with ThreadBase::mLock held
9374void AudioFlinger::EffectChain::setEffectSuspended_l(
9375        const effect_uuid_t *type, bool suspend)
9376{
9377    sp<SuspendedEffectDesc> desc;
9378    // use effect type UUID timelow as key as there is no real risk of identical
9379    // timeLow fields among effect type UUIDs.
9380    ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
9381    if (suspend) {
9382        if (index >= 0) {
9383            desc = mSuspendedEffects.valueAt(index);
9384        } else {
9385            desc = new SuspendedEffectDesc();
9386            desc->mType = *type;
9387            mSuspendedEffects.add(type->timeLow, desc);
9388            ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
9389        }
9390        if (desc->mRefCount++ == 0) {
9391            sp<EffectModule> effect = getEffectIfEnabled(type);
9392            if (effect != 0) {
9393                desc->mEffect = effect;
9394                effect->setSuspended(true);
9395                effect->setEnabled(false);
9396            }
9397        }
9398    } else {
9399        if (index < 0) {
9400            return;
9401        }
9402        desc = mSuspendedEffects.valueAt(index);
9403        if (desc->mRefCount <= 0) {
9404            ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
9405            desc->mRefCount = 1;
9406        }
9407        if (--desc->mRefCount == 0) {
9408            ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
9409            if (desc->mEffect != 0) {
9410                sp<EffectModule> effect = desc->mEffect.promote();
9411                if (effect != 0) {
9412                    effect->setSuspended(false);
9413                    effect->lock();
9414                    EffectHandle *handle = effect->controlHandle_l();
9415                    if (handle != NULL && !handle->destroyed_l()) {
9416                        effect->setEnabled_l(handle->enabled());
9417                    }
9418                    effect->unlock();
9419                }
9420                desc->mEffect.clear();
9421            }
9422            mSuspendedEffects.removeItemsAt(index);
9423        }
9424    }
9425}
9426
9427// must be called with ThreadBase::mLock held
9428void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9429{
9430    sp<SuspendedEffectDesc> desc;
9431
9432    ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9433    if (suspend) {
9434        if (index >= 0) {
9435            desc = mSuspendedEffects.valueAt(index);
9436        } else {
9437            desc = new SuspendedEffectDesc();
9438            mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
9439            ALOGV("setEffectSuspendedAll_l() add entry for 0");
9440        }
9441        if (desc->mRefCount++ == 0) {
9442            Vector< sp<EffectModule> > effects;
9443            getSuspendEligibleEffects(effects);
9444            for (size_t i = 0; i < effects.size(); i++) {
9445                setEffectSuspended_l(&effects[i]->desc().type, true);
9446            }
9447        }
9448    } else {
9449        if (index < 0) {
9450            return;
9451        }
9452        desc = mSuspendedEffects.valueAt(index);
9453        if (desc->mRefCount <= 0) {
9454            ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
9455            desc->mRefCount = 1;
9456        }
9457        if (--desc->mRefCount == 0) {
9458            Vector<const effect_uuid_t *> types;
9459            for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9460                if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9461                    continue;
9462                }
9463                types.add(&mSuspendedEffects.valueAt(i)->mType);
9464            }
9465            for (size_t i = 0; i < types.size(); i++) {
9466                setEffectSuspended_l(types[i], false);
9467            }
9468            ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
9469            mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9470        }
9471    }
9472}
9473
9474
9475// The volume effect is used for automated tests only
9476#ifndef OPENSL_ES_H_
9477static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9478                                            { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9479const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9480#endif //OPENSL_ES_H_
9481
9482bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9483{
9484    // auxiliary effects and visualizer are never suspended on output mix
9485    if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9486        (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
9487         (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9488         (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
9489        return false;
9490    }
9491    return true;
9492}
9493
9494void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
9495{
9496    effects.clear();
9497    for (size_t i = 0; i < mEffects.size(); i++) {
9498        if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9499            effects.add(mEffects[i]);
9500        }
9501    }
9502}
9503
9504sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9505                                                            const effect_uuid_t *type)
9506{
9507    sp<EffectModule> effect = getEffectFromType_l(type);
9508    return effect != 0 && effect->isEnabled() ? effect : 0;
9509}
9510
9511void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9512                                                            bool enabled)
9513{
9514    ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
9515    if (enabled) {
9516        if (index < 0) {
9517            // if the effect is not suspend check if all effects are suspended
9518            index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9519            if (index < 0) {
9520                return;
9521            }
9522            if (!isEffectEligibleForSuspend(effect->desc())) {
9523                return;
9524            }
9525            setEffectSuspended_l(&effect->desc().type, enabled);
9526            index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
9527            if (index < 0) {
9528                ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
9529                return;
9530            }
9531        }
9532        ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
9533            effect->desc().type.timeLow);
9534        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9535        // if effect is requested to suspended but was not yet enabled, supend it now.
9536        if (desc->mEffect == 0) {
9537            desc->mEffect = effect;
9538            effect->setEnabled(false);
9539            effect->setSuspended(true);
9540        }
9541    } else {
9542        if (index < 0) {
9543            return;
9544        }
9545        ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
9546            effect->desc().type.timeLow);
9547        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9548        desc->mEffect.clear();
9549        effect->setSuspended(false);
9550    }
9551}
9552
9553#undef LOG_TAG
9554#define LOG_TAG "AudioFlinger"
9555
9556// ----------------------------------------------------------------------------
9557
9558status_t AudioFlinger::onTransact(
9559        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9560{
9561    return BnAudioFlinger::onTransact(code, data, reply, flags);
9562}
9563
9564}; // namespace android
9565