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