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