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