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