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