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