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