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