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