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