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