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