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