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