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