AudioFlinger.cpp revision 25cbe0ecd6df8be7e40537c5d85c82f105038479
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 = suspendSleepTimeUs();
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    if (masterMute) {
1679        masterVolume = 0;
1680    }
1681#ifdef LVMX
1682    bool tracksConnectedChanged = false;
1683    bool stateChanged = false;
1684
1685    int audioOutputType = LifeVibes::getMixerType(mId, mType);
1686    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1687    {
1688        int activeTypes = 0;
1689        for (size_t i=0 ; i<count ; i++) {
1690            sp<Track> t = activeTracks[i].promote();
1691            if (t == 0) continue;
1692            Track* const track = t.get();
1693            int iTracktype=track->type();
1694            activeTypes |= 1<<track->type();
1695        }
1696        LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
1697    }
1698#endif
1699    // Delegate master volume control to effect in output mix effect chain if needed
1700    sp<EffectChain> chain = getEffectChain_l(AudioSystem::SESSION_OUTPUT_MIX);
1701    if (chain != 0) {
1702        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
1703        chain->setVolume_l(&v, &v);
1704        masterVolume = (float)((v + (1 << 23)) >> 24);
1705        chain.clear();
1706    }
1707
1708    for (size_t i=0 ; i<count ; i++) {
1709        sp<Track> t = activeTracks[i].promote();
1710        if (t == 0) continue;
1711
1712        Track* const track = t.get();
1713        audio_track_cblk_t* cblk = track->cblk();
1714
1715        // The first time a track is added we wait
1716        // for all its buffers to be filled before processing it
1717        mAudioMixer->setActiveTrack(track->name());
1718        if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1719                !track->isPaused() && !track->isTerminated())
1720        {
1721            //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
1722
1723            mixedTracks++;
1724
1725            // track->mainBuffer() != mMixBuffer means there is an effect chain
1726            // connected to the track
1727            chain.clear();
1728            if (track->mainBuffer() != mMixBuffer) {
1729                chain = getEffectChain_l(track->sessionId());
1730                // Delegate volume control to effect in track effect chain if needed
1731                if (chain != 0) {
1732                    tracksWithEffect++;
1733                } else {
1734                    LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1735                            track->name(), track->sessionId());
1736                }
1737            }
1738
1739
1740            int param = AudioMixer::VOLUME;
1741            if (track->mFillingUpStatus == Track::FS_FILLED) {
1742                // no ramp for the first volume setting
1743                track->mFillingUpStatus = Track::FS_ACTIVE;
1744                if (track->mState == TrackBase::RESUMING) {
1745                    track->mState = TrackBase::ACTIVE;
1746                    param = AudioMixer::RAMP_VOLUME;
1747                }
1748            } else if (cblk->server != 0) {
1749                // If the track is stopped before the first frame was mixed,
1750                // do not apply ramp
1751                param = AudioMixer::RAMP_VOLUME;
1752            }
1753
1754            // compute volume for this track
1755            int16_t left, right, aux;
1756            if (track->isMuted() || track->isPausing() ||
1757                mStreamTypes[track->type()].mute) {
1758                left = right = aux = 0;
1759                if (track->isPausing()) {
1760                    track->setPaused();
1761                }
1762            } else {
1763                // read original volumes with volume control
1764                float typeVolume = mStreamTypes[track->type()].volume;
1765#ifdef LVMX
1766                bool streamMute=false;
1767                // read the volume from the LivesVibes audio engine.
1768                if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1769                {
1770                    LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
1771                    if (streamMute) {
1772                        typeVolume = 0;
1773                    }
1774                }
1775#endif
1776                float v = masterVolume * typeVolume;
1777                uint32_t vl = (uint32_t)(v * cblk->volume[0]) << 12;
1778                uint32_t vr = (uint32_t)(v * cblk->volume[1]) << 12;
1779
1780                // Delegate volume control to effect in track effect chain if needed
1781                if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1782                    // Do not ramp volume is volume is controlled by effect
1783                    param = AudioMixer::VOLUME;
1784                }
1785
1786                // Convert volumes from 8.24 to 4.12 format
1787                uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1788                if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1789                left = int16_t(v_clamped);
1790                v_clamped = (vr + (1 << 11)) >> 12;
1791                if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1792                right = int16_t(v_clamped);
1793
1794                v_clamped = (uint32_t)(v * cblk->sendLevel);
1795                if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1796                aux = int16_t(v_clamped);
1797            }
1798
1799#ifdef LVMX
1800            if ( tracksConnectedChanged || stateChanged )
1801            {
1802                 // only do the ramp when the volume is changed by the user / application
1803                 param = AudioMixer::VOLUME;
1804            }
1805#endif
1806
1807            // XXX: these things DON'T need to be done each time
1808            mAudioMixer->setBufferProvider(track);
1809            mAudioMixer->enable(AudioMixer::MIXING);
1810
1811            mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1812            mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1813            mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
1814            mAudioMixer->setParameter(
1815                AudioMixer::TRACK,
1816                AudioMixer::FORMAT, (void *)track->format());
1817            mAudioMixer->setParameter(
1818                AudioMixer::TRACK,
1819                AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
1820            mAudioMixer->setParameter(
1821                AudioMixer::RESAMPLE,
1822                AudioMixer::SAMPLE_RATE,
1823                (void *)(cblk->sampleRate));
1824            mAudioMixer->setParameter(
1825                AudioMixer::TRACK,
1826                AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1827            mAudioMixer->setParameter(
1828                AudioMixer::TRACK,
1829                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
1830
1831            // reset retry count
1832            track->mRetryCount = kMaxTrackRetries;
1833            mixerStatus = MIXER_TRACKS_READY;
1834        } else {
1835            //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
1836            if (track->isStopped()) {
1837                track->reset();
1838            }
1839            if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1840                // We have consumed all the buffers of this track.
1841                // Remove it from the list of active tracks.
1842                tracksToRemove->add(track);
1843            } else {
1844                // No buffers for this track. Give it a few chances to
1845                // fill a buffer, then remove it from active list.
1846                if (--(track->mRetryCount) <= 0) {
1847                    LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
1848                    tracksToRemove->add(track);
1849                } else if (mixerStatus != MIXER_TRACKS_READY) {
1850                    mixerStatus = MIXER_TRACKS_ENABLED;
1851                }
1852            }
1853            mAudioMixer->disable(AudioMixer::MIXING);
1854        }
1855    }
1856
1857    // remove all the tracks that need to be...
1858    count = tracksToRemove->size();
1859    if (UNLIKELY(count)) {
1860        for (size_t i=0 ; i<count ; i++) {
1861            const sp<Track>& track = tracksToRemove->itemAt(i);
1862            mActiveTracks.remove(track);
1863            if (track->mainBuffer() != mMixBuffer) {
1864                chain = getEffectChain_l(track->sessionId());
1865                if (chain != 0) {
1866                    LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1867                    chain->stopTrack();
1868                }
1869            }
1870            if (track->isTerminated()) {
1871                mTracks.remove(track);
1872                deleteTrackName_l(track->mName);
1873            }
1874        }
1875    }
1876
1877    // mix buffer must be cleared if all tracks are connected to an
1878    // effect chain as in this case the mixer will not write to
1879    // mix buffer and track effects will accumulate into it
1880    if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1881        memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1882    }
1883
1884    return mixerStatus;
1885}
1886
1887void AudioFlinger::MixerThread::invalidateTracks(int streamType)
1888{
1889    LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1890            this,  streamType, mTracks.size());
1891    Mutex::Autolock _l(mLock);
1892
1893    size_t size = mTracks.size();
1894    for (size_t i = 0; i < size; i++) {
1895        sp<Track> t = mTracks[i];
1896        if (t->type() == streamType) {
1897            t->mCblk->lock.lock();
1898            t->mCblk->flags |= CBLK_INVALID_ON;
1899            t->mCblk->cv.signal();
1900            t->mCblk->lock.unlock();
1901        }
1902    }
1903}
1904
1905
1906// getTrackName_l() must be called with ThreadBase::mLock held
1907int AudioFlinger::MixerThread::getTrackName_l()
1908{
1909    return mAudioMixer->getTrackName();
1910}
1911
1912// deleteTrackName_l() must be called with ThreadBase::mLock held
1913void AudioFlinger::MixerThread::deleteTrackName_l(int name)
1914{
1915    LOGV("remove track (%d) and delete from mixer", name);
1916    mAudioMixer->deleteTrackName(name);
1917}
1918
1919// checkForNewParameters_l() must be called with ThreadBase::mLock held
1920bool AudioFlinger::MixerThread::checkForNewParameters_l()
1921{
1922    bool reconfig = false;
1923
1924    while (!mNewParameters.isEmpty()) {
1925        status_t status = NO_ERROR;
1926        String8 keyValuePair = mNewParameters[0];
1927        AudioParameter param = AudioParameter(keyValuePair);
1928        int value;
1929
1930        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1931            reconfig = true;
1932        }
1933        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1934            if (value != AudioSystem::PCM_16_BIT) {
1935                status = BAD_VALUE;
1936            } else {
1937                reconfig = true;
1938            }
1939        }
1940        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1941            if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1942                status = BAD_VALUE;
1943            } else {
1944                reconfig = true;
1945            }
1946        }
1947        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1948            // do not accept frame count changes if tracks are open as the track buffer
1949            // size depends on frame count and correct behavior would not be garantied
1950            // if frame count is changed after track creation
1951            if (!mTracks.isEmpty()) {
1952                status = INVALID_OPERATION;
1953            } else {
1954                reconfig = true;
1955            }
1956        }
1957        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
1958            // forward device change to effects that have requested to be
1959            // aware of attached audio device.
1960            mDevice = (uint32_t)value;
1961            for (size_t i = 0; i < mEffectChains.size(); i++) {
1962                mEffectChains[i]->setDevice_l(mDevice);
1963            }
1964        }
1965
1966        if (status == NO_ERROR) {
1967            status = mOutput->setParameters(keyValuePair);
1968            if (!mStandby && status == INVALID_OPERATION) {
1969               mOutput->standby();
1970               mStandby = true;
1971               mBytesWritten = 0;
1972               status = mOutput->setParameters(keyValuePair);
1973            }
1974            if (status == NO_ERROR && reconfig) {
1975                delete mAudioMixer;
1976                readOutputParameters();
1977                mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1978                for (size_t i = 0; i < mTracks.size() ; i++) {
1979                    int name = getTrackName_l();
1980                    if (name < 0) break;
1981                    mTracks[i]->mName = name;
1982                    // limit track sample rate to 2 x new output sample rate
1983                    if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1984                        mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1985                    }
1986                }
1987                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
1988            }
1989        }
1990
1991        mNewParameters.removeAt(0);
1992
1993        mParamStatus = status;
1994        mParamCond.signal();
1995        mWaitWorkCV.wait(mLock);
1996    }
1997    return reconfig;
1998}
1999
2000status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2001{
2002    const size_t SIZE = 256;
2003    char buffer[SIZE];
2004    String8 result;
2005
2006    PlaybackThread::dumpInternals(fd, args);
2007
2008    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2009    result.append(buffer);
2010    write(fd, result.string(), result.size());
2011    return NO_ERROR;
2012}
2013
2014uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2015{
2016    return (uint32_t)(mOutput->latency() * 1000) / 2;
2017}
2018
2019uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2020{
2021    return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
2022}
2023
2024uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2025{
2026    return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2027}
2028
2029// ----------------------------------------------------------------------------
2030AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
2031    :   PlaybackThread(audioFlinger, output, id, device)
2032{
2033    mType = PlaybackThread::DIRECT;
2034}
2035
2036AudioFlinger::DirectOutputThread::~DirectOutputThread()
2037{
2038}
2039
2040
2041static inline int16_t clamp16(int32_t sample)
2042{
2043    if ((sample>>15) ^ (sample>>31))
2044        sample = 0x7FFF ^ (sample>>31);
2045    return sample;
2046}
2047
2048static inline
2049int32_t mul(int16_t in, int16_t v)
2050{
2051#if defined(__arm__) && !defined(__thumb__)
2052    int32_t out;
2053    asm( "smulbb %[out], %[in], %[v] \n"
2054         : [out]"=r"(out)
2055         : [in]"%r"(in), [v]"r"(v)
2056         : );
2057    return out;
2058#else
2059    return in * int32_t(v);
2060#endif
2061}
2062
2063void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2064{
2065    // Do not apply volume on compressed audio
2066    if (!AudioSystem::isLinearPCM(mFormat)) {
2067        return;
2068    }
2069
2070    // convert to signed 16 bit before volume calculation
2071    if (mFormat == AudioSystem::PCM_8_BIT) {
2072        size_t count = mFrameCount * mChannelCount;
2073        uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2074        int16_t *dst = mMixBuffer + count-1;
2075        while(count--) {
2076            *dst-- = (int16_t)(*src--^0x80) << 8;
2077        }
2078    }
2079
2080    size_t frameCount = mFrameCount;
2081    int16_t *out = mMixBuffer;
2082    if (ramp) {
2083        if (mChannelCount == 1) {
2084            int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2085            int32_t vlInc = d / (int32_t)frameCount;
2086            int32_t vl = ((int32_t)mLeftVolShort << 16);
2087            do {
2088                out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2089                out++;
2090                vl += vlInc;
2091            } while (--frameCount);
2092
2093        } else {
2094            int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2095            int32_t vlInc = d / (int32_t)frameCount;
2096            d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2097            int32_t vrInc = d / (int32_t)frameCount;
2098            int32_t vl = ((int32_t)mLeftVolShort << 16);
2099            int32_t vr = ((int32_t)mRightVolShort << 16);
2100            do {
2101                out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2102                out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2103                out += 2;
2104                vl += vlInc;
2105                vr += vrInc;
2106            } while (--frameCount);
2107        }
2108    } else {
2109        if (mChannelCount == 1) {
2110            do {
2111                out[0] = clamp16(mul(out[0], leftVol) >> 12);
2112                out++;
2113            } while (--frameCount);
2114        } else {
2115            do {
2116                out[0] = clamp16(mul(out[0], leftVol) >> 12);
2117                out[1] = clamp16(mul(out[1], rightVol) >> 12);
2118                out += 2;
2119            } while (--frameCount);
2120        }
2121    }
2122
2123    // convert back to unsigned 8 bit after volume calculation
2124    if (mFormat == AudioSystem::PCM_8_BIT) {
2125        size_t count = mFrameCount * mChannelCount;
2126        int16_t *src = mMixBuffer;
2127        uint8_t *dst = (uint8_t *)mMixBuffer;
2128        while(count--) {
2129            *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2130        }
2131    }
2132
2133    mLeftVolShort = leftVol;
2134    mRightVolShort = rightVol;
2135}
2136
2137bool AudioFlinger::DirectOutputThread::threadLoop()
2138{
2139    uint32_t mixerStatus = MIXER_IDLE;
2140    sp<Track> trackToRemove;
2141    sp<Track> activeTrack;
2142    nsecs_t standbyTime = systemTime();
2143    int8_t *curBuf;
2144    size_t mixBufferSize = mFrameCount*mFrameSize;
2145    uint32_t activeSleepTime = activeSleepTimeUs();
2146    uint32_t idleSleepTime = idleSleepTimeUs();
2147    uint32_t sleepTime = idleSleepTime;
2148    // use shorter standby delay as on normal output to release
2149    // hardware resources as soon as possible
2150    nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2151
2152    while (!exitPending())
2153    {
2154        bool rampVolume;
2155        uint16_t leftVol;
2156        uint16_t rightVol;
2157        Vector< sp<EffectChain> > effectChains;
2158
2159        processConfigEvents();
2160
2161        mixerStatus = MIXER_IDLE;
2162
2163        { // scope for the mLock
2164
2165            Mutex::Autolock _l(mLock);
2166
2167            if (checkForNewParameters_l()) {
2168                mixBufferSize = mFrameCount*mFrameSize;
2169                activeSleepTime = activeSleepTimeUs();
2170                idleSleepTime = idleSleepTimeUs();
2171                standbyDelay = microseconds(activeSleepTime*2);
2172            }
2173
2174            // put audio hardware into standby after short delay
2175            if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2176                        mSuspended) {
2177                // wait until we have something to do...
2178                if (!mStandby) {
2179                    LOGV("Audio hardware entering standby, mixer %p\n", this);
2180                    mOutput->standby();
2181                    mStandby = true;
2182                    mBytesWritten = 0;
2183                }
2184
2185                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2186                    // we're about to wait, flush the binder command buffer
2187                    IPCThreadState::self()->flushCommands();
2188
2189                    if (exitPending()) break;
2190
2191                    LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2192                    mWaitWorkCV.wait(mLock);
2193                    LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2194
2195                    if (mMasterMute == false) {
2196                        char value[PROPERTY_VALUE_MAX];
2197                        property_get("ro.audio.silent", value, "0");
2198                        if (atoi(value)) {
2199                            LOGD("Silence is golden");
2200                            setMasterMute(true);
2201                        }
2202                    }
2203
2204                    standbyTime = systemTime() + standbyDelay;
2205                    sleepTime = idleSleepTime;
2206                    continue;
2207                }
2208            }
2209
2210            effectChains = mEffectChains;
2211
2212            // find out which tracks need to be processed
2213            if (mActiveTracks.size() != 0) {
2214                sp<Track> t = mActiveTracks[0].promote();
2215                if (t == 0) continue;
2216
2217                Track* const track = t.get();
2218                audio_track_cblk_t* cblk = track->cblk();
2219
2220                // The first time a track is added we wait
2221                // for all its buffers to be filled before processing it
2222                if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
2223                        !track->isPaused() && !track->isTerminated())
2224                {
2225                    //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2226
2227                    if (track->mFillingUpStatus == Track::FS_FILLED) {
2228                        track->mFillingUpStatus = Track::FS_ACTIVE;
2229                        mLeftVolFloat = mRightVolFloat = 0;
2230                        mLeftVolShort = mRightVolShort = 0;
2231                        if (track->mState == TrackBase::RESUMING) {
2232                            track->mState = TrackBase::ACTIVE;
2233                            rampVolume = true;
2234                        }
2235                    } else if (cblk->server != 0) {
2236                        // If the track is stopped before the first frame was mixed,
2237                        // do not apply ramp
2238                        rampVolume = true;
2239                    }
2240                    // compute volume for this track
2241                    float left, right;
2242                    if (track->isMuted() || mMasterMute || track->isPausing() ||
2243                        mStreamTypes[track->type()].mute) {
2244                        left = right = 0;
2245                        if (track->isPausing()) {
2246                            track->setPaused();
2247                        }
2248                    } else {
2249                        float typeVolume = mStreamTypes[track->type()].volume;
2250                        float v = mMasterVolume * typeVolume;
2251                        float v_clamped = v * cblk->volume[0];
2252                        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2253                        left = v_clamped/MAX_GAIN;
2254                        v_clamped = v * cblk->volume[1];
2255                        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2256                        right = v_clamped/MAX_GAIN;
2257                    }
2258
2259                    if (left != mLeftVolFloat || right != mRightVolFloat) {
2260                        mLeftVolFloat = left;
2261                        mRightVolFloat = right;
2262
2263                        // If audio HAL implements volume control,
2264                        // force software volume to nominal value
2265                        if (mOutput->setVolume(left, right) == NO_ERROR) {
2266                            left = 1.0f;
2267                            right = 1.0f;
2268                        }
2269
2270                        // Convert volumes from float to 8.24
2271                        uint32_t vl = (uint32_t)(left * (1 << 24));
2272                        uint32_t vr = (uint32_t)(right * (1 << 24));
2273
2274                        // Delegate volume control to effect in track effect chain if needed
2275                        // only one effect chain can be present on DirectOutputThread, so if
2276                        // there is one, the track is connected to it
2277                        if (!effectChains.isEmpty()) {
2278                            // Do not ramp volume is volume is controlled by effect
2279                            if(effectChains[0]->setVolume_l(&vl, &vr)) {
2280                                rampVolume = false;
2281                            }
2282                        }
2283
2284                        // Convert volumes from 8.24 to 4.12 format
2285                        uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2286                        if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2287                        leftVol = (uint16_t)v_clamped;
2288                        v_clamped = (vr + (1 << 11)) >> 12;
2289                        if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2290                        rightVol = (uint16_t)v_clamped;
2291                    } else {
2292                        leftVol = mLeftVolShort;
2293                        rightVol = mRightVolShort;
2294                        rampVolume = false;
2295                    }
2296
2297                    // reset retry count
2298                    track->mRetryCount = kMaxTrackRetriesDirect;
2299                    activeTrack = t;
2300                    mixerStatus = MIXER_TRACKS_READY;
2301                } else {
2302                    //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2303                    if (track->isStopped()) {
2304                        track->reset();
2305                    }
2306                    if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2307                        // We have consumed all the buffers of this track.
2308                        // Remove it from the list of active tracks.
2309                        trackToRemove = track;
2310                    } else {
2311                        // No buffers for this track. Give it a few chances to
2312                        // fill a buffer, then remove it from active list.
2313                        if (--(track->mRetryCount) <= 0) {
2314                            LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2315                            trackToRemove = track;
2316                        } else {
2317                            mixerStatus = MIXER_TRACKS_ENABLED;
2318                        }
2319                    }
2320                }
2321            }
2322
2323            // remove all the tracks that need to be...
2324            if (UNLIKELY(trackToRemove != 0)) {
2325                mActiveTracks.remove(trackToRemove);
2326                if (!effectChains.isEmpty()) {
2327                    LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2328                            trackToRemove->sessionId());
2329                    effectChains[0]->stopTrack();
2330                }
2331                if (trackToRemove->isTerminated()) {
2332                    mTracks.remove(trackToRemove);
2333                    deleteTrackName_l(trackToRemove->mName);
2334                }
2335            }
2336
2337            lockEffectChains_l(effectChains);
2338       }
2339
2340        if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2341            AudioBufferProvider::Buffer buffer;
2342            size_t frameCount = mFrameCount;
2343            curBuf = (int8_t *)mMixBuffer;
2344            // output audio to hardware
2345            while (frameCount) {
2346                buffer.frameCount = frameCount;
2347                activeTrack->getNextBuffer(&buffer);
2348                if (UNLIKELY(buffer.raw == 0)) {
2349                    memset(curBuf, 0, frameCount * mFrameSize);
2350                    break;
2351                }
2352                memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2353                frameCount -= buffer.frameCount;
2354                curBuf += buffer.frameCount * mFrameSize;
2355                activeTrack->releaseBuffer(&buffer);
2356            }
2357            sleepTime = 0;
2358            standbyTime = systemTime() + standbyDelay;
2359        } else {
2360            if (sleepTime == 0) {
2361                if (mixerStatus == MIXER_TRACKS_ENABLED) {
2362                    sleepTime = activeSleepTime;
2363                } else {
2364                    sleepTime = idleSleepTime;
2365                }
2366            } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
2367                memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2368                sleepTime = 0;
2369            }
2370        }
2371
2372        if (mSuspended) {
2373            sleepTime = suspendSleepTimeUs();
2374        }
2375        // sleepTime == 0 means we must write to audio hardware
2376        if (sleepTime == 0) {
2377            if (mixerStatus == MIXER_TRACKS_READY) {
2378                applyVolume(leftVol, rightVol, rampVolume);
2379            }
2380            for (size_t i = 0; i < effectChains.size(); i ++) {
2381                effectChains[i]->process_l();
2382            }
2383            unlockEffectChains(effectChains);
2384
2385            mLastWriteTime = systemTime();
2386            mInWrite = true;
2387            mBytesWritten += mixBufferSize;
2388            int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
2389            if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2390            mNumWrites++;
2391            mInWrite = false;
2392            mStandby = false;
2393        } else {
2394            unlockEffectChains(effectChains);
2395            usleep(sleepTime);
2396        }
2397
2398        // finally let go of removed track, without the lock held
2399        // since we can't guarantee the destructors won't acquire that
2400        // same lock.
2401        trackToRemove.clear();
2402        activeTrack.clear();
2403
2404        // Effect chains will be actually deleted here if they were removed from
2405        // mEffectChains list during mixing or effects processing
2406        effectChains.clear();
2407    }
2408
2409    if (!mStandby) {
2410        mOutput->standby();
2411    }
2412
2413    LOGV("DirectOutputThread %p exiting", this);
2414    return false;
2415}
2416
2417// getTrackName_l() must be called with ThreadBase::mLock held
2418int AudioFlinger::DirectOutputThread::getTrackName_l()
2419{
2420    return 0;
2421}
2422
2423// deleteTrackName_l() must be called with ThreadBase::mLock held
2424void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2425{
2426}
2427
2428// checkForNewParameters_l() must be called with ThreadBase::mLock held
2429bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2430{
2431    bool reconfig = false;
2432
2433    while (!mNewParameters.isEmpty()) {
2434        status_t status = NO_ERROR;
2435        String8 keyValuePair = mNewParameters[0];
2436        AudioParameter param = AudioParameter(keyValuePair);
2437        int value;
2438
2439        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2440            // do not accept frame count changes if tracks are open as the track buffer
2441            // size depends on frame count and correct behavior would not be garantied
2442            // if frame count is changed after track creation
2443            if (!mTracks.isEmpty()) {
2444                status = INVALID_OPERATION;
2445            } else {
2446                reconfig = true;
2447            }
2448        }
2449        if (status == NO_ERROR) {
2450            status = mOutput->setParameters(keyValuePair);
2451            if (!mStandby && status == INVALID_OPERATION) {
2452               mOutput->standby();
2453               mStandby = true;
2454               mBytesWritten = 0;
2455               status = mOutput->setParameters(keyValuePair);
2456            }
2457            if (status == NO_ERROR && reconfig) {
2458                readOutputParameters();
2459                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2460            }
2461        }
2462
2463        mNewParameters.removeAt(0);
2464
2465        mParamStatus = status;
2466        mParamCond.signal();
2467        mWaitWorkCV.wait(mLock);
2468    }
2469    return reconfig;
2470}
2471
2472uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2473{
2474    uint32_t time;
2475    if (AudioSystem::isLinearPCM(mFormat)) {
2476        time = (uint32_t)(mOutput->latency() * 1000) / 2;
2477    } else {
2478        time = 10000;
2479    }
2480    return time;
2481}
2482
2483uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2484{
2485    uint32_t time;
2486    if (AudioSystem::isLinearPCM(mFormat)) {
2487        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
2488    } else {
2489        time = 10000;
2490    }
2491    return time;
2492}
2493
2494uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2495{
2496    uint32_t time;
2497    if (AudioSystem::isLinearPCM(mFormat)) {
2498        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2499    } else {
2500        time = 10000;
2501    }
2502    return time;
2503}
2504
2505
2506// ----------------------------------------------------------------------------
2507
2508AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2509    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2510{
2511    mType = PlaybackThread::DUPLICATING;
2512    addOutputTrack(mainThread);
2513}
2514
2515AudioFlinger::DuplicatingThread::~DuplicatingThread()
2516{
2517    for (size_t i = 0; i < mOutputTracks.size(); i++) {
2518        mOutputTracks[i]->destroy();
2519    }
2520    mOutputTracks.clear();
2521}
2522
2523bool AudioFlinger::DuplicatingThread::threadLoop()
2524{
2525    Vector< sp<Track> > tracksToRemove;
2526    uint32_t mixerStatus = MIXER_IDLE;
2527    nsecs_t standbyTime = systemTime();
2528    size_t mixBufferSize = mFrameCount*mFrameSize;
2529    SortedVector< sp<OutputTrack> > outputTracks;
2530    uint32_t writeFrames = 0;
2531    uint32_t activeSleepTime = activeSleepTimeUs();
2532    uint32_t idleSleepTime = idleSleepTimeUs();
2533    uint32_t sleepTime = idleSleepTime;
2534    Vector< sp<EffectChain> > effectChains;
2535
2536    while (!exitPending())
2537    {
2538        processConfigEvents();
2539
2540        mixerStatus = MIXER_IDLE;
2541        { // scope for the mLock
2542
2543            Mutex::Autolock _l(mLock);
2544
2545            if (checkForNewParameters_l()) {
2546                mixBufferSize = mFrameCount*mFrameSize;
2547                updateWaitTime();
2548                activeSleepTime = activeSleepTimeUs();
2549                idleSleepTime = idleSleepTimeUs();
2550            }
2551
2552            const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2553
2554            for (size_t i = 0; i < mOutputTracks.size(); i++) {
2555                outputTracks.add(mOutputTracks[i]);
2556            }
2557
2558            // put audio hardware into standby after short delay
2559            if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2560                         mSuspended) {
2561                if (!mStandby) {
2562                    for (size_t i = 0; i < outputTracks.size(); i++) {
2563                        outputTracks[i]->stop();
2564                    }
2565                    mStandby = true;
2566                    mBytesWritten = 0;
2567                }
2568
2569                if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2570                    // we're about to wait, flush the binder command buffer
2571                    IPCThreadState::self()->flushCommands();
2572                    outputTracks.clear();
2573
2574                    if (exitPending()) break;
2575
2576                    LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2577                    mWaitWorkCV.wait(mLock);
2578                    LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2579                    if (mMasterMute == false) {
2580                        char value[PROPERTY_VALUE_MAX];
2581                        property_get("ro.audio.silent", value, "0");
2582                        if (atoi(value)) {
2583                            LOGD("Silence is golden");
2584                            setMasterMute(true);
2585                        }
2586                    }
2587
2588                    standbyTime = systemTime() + kStandbyTimeInNsecs;
2589                    sleepTime = idleSleepTime;
2590                    continue;
2591                }
2592            }
2593
2594            mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2595
2596            // prevent any changes in effect chain list and in each effect chain
2597            // during mixing and effect process as the audio buffers could be deleted
2598            // or modified if an effect is created or deleted
2599            lockEffectChains_l(effectChains);
2600        }
2601
2602        if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2603            // mix buffers...
2604            if (outputsReady(outputTracks)) {
2605                mAudioMixer->process();
2606            } else {
2607                memset(mMixBuffer, 0, mixBufferSize);
2608            }
2609            sleepTime = 0;
2610            writeFrames = mFrameCount;
2611        } else {
2612            if (sleepTime == 0) {
2613                if (mixerStatus == MIXER_TRACKS_ENABLED) {
2614                    sleepTime = activeSleepTime;
2615                } else {
2616                    sleepTime = idleSleepTime;
2617                }
2618            } else if (mBytesWritten != 0) {
2619                // flush remaining overflow buffers in output tracks
2620                for (size_t i = 0; i < outputTracks.size(); i++) {
2621                    if (outputTracks[i]->isActive()) {
2622                        sleepTime = 0;
2623                        writeFrames = 0;
2624                        memset(mMixBuffer, 0, mixBufferSize);
2625                        break;
2626                    }
2627                }
2628            }
2629        }
2630
2631        if (mSuspended) {
2632            sleepTime = suspendSleepTimeUs();
2633        }
2634        // sleepTime == 0 means we must write to audio hardware
2635        if (sleepTime == 0) {
2636            for (size_t i = 0; i < effectChains.size(); i ++) {
2637                effectChains[i]->process_l();
2638            }
2639            // enable changes in effect chain
2640            unlockEffectChains(effectChains);
2641
2642            standbyTime = systemTime() + kStandbyTimeInNsecs;
2643            for (size_t i = 0; i < outputTracks.size(); i++) {
2644                outputTracks[i]->write(mMixBuffer, writeFrames);
2645            }
2646            mStandby = false;
2647            mBytesWritten += mixBufferSize;
2648        } else {
2649            // enable changes in effect chain
2650            unlockEffectChains(effectChains);
2651            usleep(sleepTime);
2652        }
2653
2654        // finally let go of all our tracks, without the lock held
2655        // since we can't guarantee the destructors won't acquire that
2656        // same lock.
2657        tracksToRemove.clear();
2658        outputTracks.clear();
2659
2660        // Effect chains will be actually deleted here if they were removed from
2661        // mEffectChains list during mixing or effects processing
2662        effectChains.clear();
2663    }
2664
2665    return false;
2666}
2667
2668void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2669{
2670    int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2671    OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
2672                                            this,
2673                                            mSampleRate,
2674                                            mFormat,
2675                                            mChannelCount,
2676                                            frameCount);
2677    if (outputTrack->cblk() != NULL) {
2678        thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2679        mOutputTracks.add(outputTrack);
2680        LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
2681        updateWaitTime();
2682    }
2683}
2684
2685void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2686{
2687    Mutex::Autolock _l(mLock);
2688    for (size_t i = 0; i < mOutputTracks.size(); i++) {
2689        if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
2690            mOutputTracks[i]->destroy();
2691            mOutputTracks.removeAt(i);
2692            updateWaitTime();
2693            return;
2694        }
2695    }
2696    LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2697}
2698
2699void AudioFlinger::DuplicatingThread::updateWaitTime()
2700{
2701    mWaitTimeMs = UINT_MAX;
2702    for (size_t i = 0; i < mOutputTracks.size(); i++) {
2703        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2704        if (strong != NULL) {
2705            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2706            if (waitTimeMs < mWaitTimeMs) {
2707                mWaitTimeMs = waitTimeMs;
2708            }
2709        }
2710    }
2711}
2712
2713
2714bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2715{
2716    for (size_t i = 0; i < outputTracks.size(); i++) {
2717        sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2718        if (thread == 0) {
2719            LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2720            return false;
2721        }
2722        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2723        if (playbackThread->standby() && !playbackThread->isSuspended()) {
2724            LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2725            return false;
2726        }
2727    }
2728    return true;
2729}
2730
2731uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2732{
2733    return (mWaitTimeMs * 1000) / 2;
2734}
2735
2736// ----------------------------------------------------------------------------
2737
2738// TrackBase constructor must be called with AudioFlinger::mLock held
2739AudioFlinger::ThreadBase::TrackBase::TrackBase(
2740            const wp<ThreadBase>& thread,
2741            const sp<Client>& client,
2742            uint32_t sampleRate,
2743            int format,
2744            int channelCount,
2745            int frameCount,
2746            uint32_t flags,
2747            const sp<IMemory>& sharedBuffer,
2748            int sessionId)
2749    :   RefBase(),
2750        mThread(thread),
2751        mClient(client),
2752        mCblk(0),
2753        mFrameCount(0),
2754        mState(IDLE),
2755        mClientTid(-1),
2756        mFormat(format),
2757        mFlags(flags & ~SYSTEM_FLAGS_MASK),
2758        mSessionId(sessionId)
2759{
2760    LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2761
2762    // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
2763   size_t size = sizeof(audio_track_cblk_t);
2764   size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2765   if (sharedBuffer == 0) {
2766       size += bufferSize;
2767   }
2768
2769   if (client != NULL) {
2770        mCblkMemory = client->heap()->allocate(size);
2771        if (mCblkMemory != 0) {
2772            mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2773            if (mCblk) { // construct the shared structure in-place.
2774                new(mCblk) audio_track_cblk_t();
2775                // clear all buffers
2776                mCblk->frameCount = frameCount;
2777                mCblk->sampleRate = sampleRate;
2778                mCblk->channelCount = (uint8_t)channelCount;
2779                if (sharedBuffer == 0) {
2780                    mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2781                    memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2782                    // Force underrun condition to avoid false underrun callback until first data is
2783                    // written to buffer
2784                    mCblk->flags = CBLK_UNDERRUN_ON;
2785                } else {
2786                    mBuffer = sharedBuffer->pointer();
2787                }
2788                mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2789            }
2790        } else {
2791            LOGE("not enough memory for AudioTrack size=%u", size);
2792            client->heap()->dump("AudioTrack");
2793            return;
2794        }
2795   } else {
2796       mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2797       if (mCblk) { // construct the shared structure in-place.
2798           new(mCblk) audio_track_cblk_t();
2799           // clear all buffers
2800           mCblk->frameCount = frameCount;
2801           mCblk->sampleRate = sampleRate;
2802           mCblk->channelCount = (uint8_t)channelCount;
2803           mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2804           memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2805           // Force underrun condition to avoid false underrun callback until first data is
2806           // written to buffer
2807           mCblk->flags = CBLK_UNDERRUN_ON;
2808           mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2809       }
2810   }
2811}
2812
2813AudioFlinger::ThreadBase::TrackBase::~TrackBase()
2814{
2815    if (mCblk) {
2816        mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
2817        if (mClient == NULL) {
2818            delete mCblk;
2819        }
2820    }
2821    mCblkMemory.clear();            // and free the shared memory
2822    if (mClient != NULL) {
2823        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2824        mClient.clear();
2825    }
2826}
2827
2828void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2829{
2830    buffer->raw = 0;
2831    mFrameCount = buffer->frameCount;
2832    step();
2833    buffer->frameCount = 0;
2834}
2835
2836bool AudioFlinger::ThreadBase::TrackBase::step() {
2837    bool result;
2838    audio_track_cblk_t* cblk = this->cblk();
2839
2840    result = cblk->stepServer(mFrameCount);
2841    if (!result) {
2842        LOGV("stepServer failed acquiring cblk mutex");
2843        mFlags |= STEPSERVER_FAILED;
2844    }
2845    return result;
2846}
2847
2848void AudioFlinger::ThreadBase::TrackBase::reset() {
2849    audio_track_cblk_t* cblk = this->cblk();
2850
2851    cblk->user = 0;
2852    cblk->server = 0;
2853    cblk->userBase = 0;
2854    cblk->serverBase = 0;
2855    mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
2856    LOGV("TrackBase::reset");
2857}
2858
2859sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
2860{
2861    return mCblkMemory;
2862}
2863
2864int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
2865    return (int)mCblk->sampleRate;
2866}
2867
2868int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
2869    return (int)mCblk->channelCount;
2870}
2871
2872void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
2873    audio_track_cblk_t* cblk = this->cblk();
2874    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2875    int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
2876
2877    // Check validity of returned pointer in case the track control block would have been corrupted.
2878    if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2879        ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
2880        LOGE("TrackBase::getBuffer buffer out of range:\n    start: %p, end %p , mBuffer %p mBufferEnd %p\n    \
2881                server %d, serverBase %d, user %d, userBase %d, channelCount %d",
2882                bufferStart, bufferEnd, mBuffer, mBufferEnd,
2883                cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
2884        return 0;
2885    }
2886
2887    return bufferStart;
2888}
2889
2890// ----------------------------------------------------------------------------
2891
2892// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2893AudioFlinger::PlaybackThread::Track::Track(
2894            const wp<ThreadBase>& thread,
2895            const sp<Client>& client,
2896            int streamType,
2897            uint32_t sampleRate,
2898            int format,
2899            int channelCount,
2900            int frameCount,
2901            const sp<IMemory>& sharedBuffer,
2902            int sessionId)
2903    :   TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
2904    mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL), mAuxEffectId(0)
2905{
2906    if (mCblk != NULL) {
2907        sp<ThreadBase> baseThread = thread.promote();
2908        if (baseThread != 0) {
2909            PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2910            mName = playbackThread->getTrackName_l();
2911            mMainBuffer = playbackThread->mixBuffer();
2912        }
2913        LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2914        if (mName < 0) {
2915            LOGE("no more track names available");
2916        }
2917        mVolume[0] = 1.0f;
2918        mVolume[1] = 1.0f;
2919        mStreamType = streamType;
2920        // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2921        // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2922        mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
2923    }
2924}
2925
2926AudioFlinger::PlaybackThread::Track::~Track()
2927{
2928    LOGV("PlaybackThread::Track destructor");
2929    sp<ThreadBase> thread = mThread.promote();
2930    if (thread != 0) {
2931        Mutex::Autolock _l(thread->mLock);
2932        mState = TERMINATED;
2933    }
2934}
2935
2936void AudioFlinger::PlaybackThread::Track::destroy()
2937{
2938    // NOTE: destroyTrack_l() can remove a strong reference to this Track
2939    // by removing it from mTracks vector, so there is a risk that this Tracks's
2940    // desctructor is called. As the destructor needs to lock mLock,
2941    // we must acquire a strong reference on this Track before locking mLock
2942    // here so that the destructor is called only when exiting this function.
2943    // On the other hand, as long as Track::destroy() is only called by
2944    // TrackHandle destructor, the TrackHandle still holds a strong ref on
2945    // this Track with its member mTrack.
2946    sp<Track> keep(this);
2947    { // scope for mLock
2948        sp<ThreadBase> thread = mThread.promote();
2949        if (thread != 0) {
2950            if (!isOutputTrack()) {
2951                if (mState == ACTIVE || mState == RESUMING) {
2952                    AudioSystem::stopOutput(thread->id(),
2953                                            (AudioSystem::stream_type)mStreamType,
2954                                            mSessionId);
2955                }
2956                AudioSystem::releaseOutput(thread->id());
2957            }
2958            Mutex::Autolock _l(thread->mLock);
2959            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2960            playbackThread->destroyTrack_l(this);
2961        }
2962    }
2963}
2964
2965void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
2966{
2967    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",
2968            mName - AudioMixer::TRACK0,
2969            (mClient == NULL) ? getpid() : mClient->pid(),
2970            mStreamType,
2971            mFormat,
2972            mCblk->channelCount,
2973            mSessionId,
2974            mFrameCount,
2975            mState,
2976            mMute,
2977            mFillingUpStatus,
2978            mCblk->sampleRate,
2979            mCblk->volume[0],
2980            mCblk->volume[1],
2981            mCblk->server,
2982            mCblk->user,
2983            (int)mMainBuffer,
2984            (int)mAuxBuffer);
2985}
2986
2987status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
2988{
2989     audio_track_cblk_t* cblk = this->cblk();
2990     uint32_t framesReady;
2991     uint32_t framesReq = buffer->frameCount;
2992
2993     // Check if last stepServer failed, try to step now
2994     if (mFlags & TrackBase::STEPSERVER_FAILED) {
2995         if (!step())  goto getNextBuffer_exit;
2996         LOGV("stepServer recovered");
2997         mFlags &= ~TrackBase::STEPSERVER_FAILED;
2998     }
2999
3000     framesReady = cblk->framesReady();
3001
3002     if (LIKELY(framesReady)) {
3003        uint32_t s = cblk->server;
3004        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3005
3006        bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3007        if (framesReq > framesReady) {
3008            framesReq = framesReady;
3009        }
3010        if (s + framesReq > bufferEnd) {
3011            framesReq = bufferEnd - s;
3012        }
3013
3014         buffer->raw = getBuffer(s, framesReq);
3015         if (buffer->raw == 0) goto getNextBuffer_exit;
3016
3017         buffer->frameCount = framesReq;
3018        return NO_ERROR;
3019     }
3020
3021getNextBuffer_exit:
3022     buffer->raw = 0;
3023     buffer->frameCount = 0;
3024     LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3025     return NOT_ENOUGH_DATA;
3026}
3027
3028bool AudioFlinger::PlaybackThread::Track::isReady() const {
3029    if (mFillingUpStatus != FS_FILLING) return true;
3030
3031    if (mCblk->framesReady() >= mCblk->frameCount ||
3032            (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3033        mFillingUpStatus = FS_FILLED;
3034        mCblk->flags &= ~CBLK_FORCEREADY_MSK;
3035        return true;
3036    }
3037    return false;
3038}
3039
3040status_t AudioFlinger::PlaybackThread::Track::start()
3041{
3042    status_t status = NO_ERROR;
3043    LOGV("start(%d), calling thread %d session %d",
3044            mName, IPCThreadState::self()->getCallingPid(), mSessionId);
3045    sp<ThreadBase> thread = mThread.promote();
3046    if (thread != 0) {
3047        Mutex::Autolock _l(thread->mLock);
3048        int state = mState;
3049        // here the track could be either new, or restarted
3050        // in both cases "unstop" the track
3051        if (mState == PAUSED) {
3052            mState = TrackBase::RESUMING;
3053            LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3054        } else {
3055            mState = TrackBase::ACTIVE;
3056            LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3057        }
3058
3059        if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3060            thread->mLock.unlock();
3061            status = AudioSystem::startOutput(thread->id(),
3062                                              (AudioSystem::stream_type)mStreamType,
3063                                              mSessionId);
3064            thread->mLock.lock();
3065        }
3066        if (status == NO_ERROR) {
3067            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3068            playbackThread->addTrack_l(this);
3069        } else {
3070            mState = state;
3071        }
3072    } else {
3073        status = BAD_VALUE;
3074    }
3075    return status;
3076}
3077
3078void AudioFlinger::PlaybackThread::Track::stop()
3079{
3080    LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3081    sp<ThreadBase> thread = mThread.promote();
3082    if (thread != 0) {
3083        Mutex::Autolock _l(thread->mLock);
3084        int state = mState;
3085        if (mState > STOPPED) {
3086            mState = STOPPED;
3087            // If the track is not active (PAUSED and buffers full), flush buffers
3088            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3089            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3090                reset();
3091            }
3092            LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3093        }
3094        if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3095            thread->mLock.unlock();
3096            AudioSystem::stopOutput(thread->id(),
3097                                    (AudioSystem::stream_type)mStreamType,
3098                                    mSessionId);
3099            thread->mLock.lock();
3100        }
3101    }
3102}
3103
3104void AudioFlinger::PlaybackThread::Track::pause()
3105{
3106    LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3107    sp<ThreadBase> thread = mThread.promote();
3108    if (thread != 0) {
3109        Mutex::Autolock _l(thread->mLock);
3110        if (mState == ACTIVE || mState == RESUMING) {
3111            mState = PAUSING;
3112            LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3113            if (!isOutputTrack()) {
3114                thread->mLock.unlock();
3115                AudioSystem::stopOutput(thread->id(),
3116                                        (AudioSystem::stream_type)mStreamType,
3117                                        mSessionId);
3118                thread->mLock.lock();
3119            }
3120        }
3121    }
3122}
3123
3124void AudioFlinger::PlaybackThread::Track::flush()
3125{
3126    LOGV("flush(%d)", mName);
3127    sp<ThreadBase> thread = mThread.promote();
3128    if (thread != 0) {
3129        Mutex::Autolock _l(thread->mLock);
3130        if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3131            return;
3132        }
3133        // No point remaining in PAUSED state after a flush => go to
3134        // STOPPED state
3135        mState = STOPPED;
3136
3137        mCblk->lock.lock();
3138        // NOTE: reset() will reset cblk->user and cblk->server with
3139        // the risk that at the same time, the AudioMixer is trying to read
3140        // data. In this case, getNextBuffer() would return a NULL pointer
3141        // as audio buffer => the AudioMixer code MUST always test that pointer
3142        // returned by getNextBuffer() is not NULL!
3143        reset();
3144        mCblk->lock.unlock();
3145    }
3146}
3147
3148void AudioFlinger::PlaybackThread::Track::reset()
3149{
3150    // Do not reset twice to avoid discarding data written just after a flush and before
3151    // the audioflinger thread detects the track is stopped.
3152    if (!mResetDone) {
3153        TrackBase::reset();
3154        // Force underrun condition to avoid false underrun callback until first data is
3155        // written to buffer
3156        mCblk->flags |= CBLK_UNDERRUN_ON;
3157        mCblk->flags &= ~CBLK_FORCEREADY_MSK;
3158        mFillingUpStatus = FS_FILLING;
3159        mResetDone = true;
3160    }
3161}
3162
3163void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3164{
3165    mMute = muted;
3166}
3167
3168void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3169{
3170    mVolume[0] = left;
3171    mVolume[1] = right;
3172}
3173
3174status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3175{
3176    status_t status = DEAD_OBJECT;
3177    sp<ThreadBase> thread = mThread.promote();
3178    if (thread != 0) {
3179       PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3180       status = playbackThread->attachAuxEffect(this, EffectId);
3181    }
3182    return status;
3183}
3184
3185void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3186{
3187    mAuxEffectId = EffectId;
3188    mAuxBuffer = buffer;
3189}
3190
3191// ----------------------------------------------------------------------------
3192
3193// RecordTrack constructor must be called with AudioFlinger::mLock held
3194AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3195            const wp<ThreadBase>& thread,
3196            const sp<Client>& client,
3197            uint32_t sampleRate,
3198            int format,
3199            int channelCount,
3200            int frameCount,
3201            uint32_t flags,
3202            int sessionId)
3203    :   TrackBase(thread, client, sampleRate, format,
3204                  channelCount, frameCount, flags, 0, sessionId),
3205        mOverflow(false)
3206{
3207    if (mCblk != NULL) {
3208       LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3209       if (format == AudioSystem::PCM_16_BIT) {
3210           mCblk->frameSize = channelCount * sizeof(int16_t);
3211       } else if (format == AudioSystem::PCM_8_BIT) {
3212           mCblk->frameSize = channelCount * sizeof(int8_t);
3213       } else {
3214           mCblk->frameSize = sizeof(int8_t);
3215       }
3216    }
3217}
3218
3219AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3220{
3221    sp<ThreadBase> thread = mThread.promote();
3222    if (thread != 0) {
3223        AudioSystem::releaseInput(thread->id());
3224    }
3225}
3226
3227status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3228{
3229    audio_track_cblk_t* cblk = this->cblk();
3230    uint32_t framesAvail;
3231    uint32_t framesReq = buffer->frameCount;
3232
3233     // Check if last stepServer failed, try to step now
3234    if (mFlags & TrackBase::STEPSERVER_FAILED) {
3235        if (!step()) goto getNextBuffer_exit;
3236        LOGV("stepServer recovered");
3237        mFlags &= ~TrackBase::STEPSERVER_FAILED;
3238    }
3239
3240    framesAvail = cblk->framesAvailable_l();
3241
3242    if (LIKELY(framesAvail)) {
3243        uint32_t s = cblk->server;
3244        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3245
3246        if (framesReq > framesAvail) {
3247            framesReq = framesAvail;
3248        }
3249        if (s + framesReq > bufferEnd) {
3250            framesReq = bufferEnd - s;
3251        }
3252
3253        buffer->raw = getBuffer(s, framesReq);
3254        if (buffer->raw == 0) goto getNextBuffer_exit;
3255
3256        buffer->frameCount = framesReq;
3257        return NO_ERROR;
3258    }
3259
3260getNextBuffer_exit:
3261    buffer->raw = 0;
3262    buffer->frameCount = 0;
3263    return NOT_ENOUGH_DATA;
3264}
3265
3266status_t AudioFlinger::RecordThread::RecordTrack::start()
3267{
3268    sp<ThreadBase> thread = mThread.promote();
3269    if (thread != 0) {
3270        RecordThread *recordThread = (RecordThread *)thread.get();
3271        return recordThread->start(this);
3272    } else {
3273        return BAD_VALUE;
3274    }
3275}
3276
3277void AudioFlinger::RecordThread::RecordTrack::stop()
3278{
3279    sp<ThreadBase> thread = mThread.promote();
3280    if (thread != 0) {
3281        RecordThread *recordThread = (RecordThread *)thread.get();
3282        recordThread->stop(this);
3283        TrackBase::reset();
3284        // Force overerrun condition to avoid false overrun callback until first data is
3285        // read from buffer
3286        mCblk->flags |= CBLK_UNDERRUN_ON;
3287    }
3288}
3289
3290void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3291{
3292    snprintf(buffer, size, "   %05d %03u %03u %05d   %04u %01d %05u  %08x %08x\n",
3293            (mClient == NULL) ? getpid() : mClient->pid(),
3294            mFormat,
3295            mCblk->channelCount,
3296            mSessionId,
3297            mFrameCount,
3298            mState,
3299            mCblk->sampleRate,
3300            mCblk->server,
3301            mCblk->user);
3302}
3303
3304
3305// ----------------------------------------------------------------------------
3306
3307AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3308            const wp<ThreadBase>& thread,
3309            DuplicatingThread *sourceThread,
3310            uint32_t sampleRate,
3311            int format,
3312            int channelCount,
3313            int frameCount)
3314    :   Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
3315    mActive(false), mSourceThread(sourceThread)
3316{
3317
3318    PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3319    if (mCblk != NULL) {
3320        mCblk->flags |= CBLK_DIRECTION_OUT;
3321        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3322        mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3323        mOutBuffer.frameCount = 0;
3324        playbackThread->mTracks.add(this);
3325        LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3326                mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
3327    } else {
3328        LOGW("Error creating output track on thread %p", playbackThread);
3329    }
3330}
3331
3332AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3333{
3334    clearBufferQueue();
3335}
3336
3337status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3338{
3339    status_t status = Track::start();
3340    if (status != NO_ERROR) {
3341        return status;
3342    }
3343
3344    mActive = true;
3345    mRetryCount = 127;
3346    return status;
3347}
3348
3349void AudioFlinger::PlaybackThread::OutputTrack::stop()
3350{
3351    Track::stop();
3352    clearBufferQueue();
3353    mOutBuffer.frameCount = 0;
3354    mActive = false;
3355}
3356
3357bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3358{
3359    Buffer *pInBuffer;
3360    Buffer inBuffer;
3361    uint32_t channelCount = mCblk->channelCount;
3362    bool outputBufferFull = false;
3363    inBuffer.frameCount = frames;
3364    inBuffer.i16 = data;
3365
3366    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3367
3368    if (!mActive && frames != 0) {
3369        start();
3370        sp<ThreadBase> thread = mThread.promote();
3371        if (thread != 0) {
3372            MixerThread *mixerThread = (MixerThread *)thread.get();
3373            if (mCblk->frameCount > frames){
3374                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3375                    uint32_t startFrames = (mCblk->frameCount - frames);
3376                    pInBuffer = new Buffer;
3377                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3378                    pInBuffer->frameCount = startFrames;
3379                    pInBuffer->i16 = pInBuffer->mBuffer;
3380                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3381                    mBufferQueue.add(pInBuffer);
3382                } else {
3383                    LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3384                }
3385            }
3386        }
3387    }
3388
3389    while (waitTimeLeftMs) {
3390        // First write pending buffers, then new data
3391        if (mBufferQueue.size()) {
3392            pInBuffer = mBufferQueue.itemAt(0);
3393        } else {
3394            pInBuffer = &inBuffer;
3395        }
3396
3397        if (pInBuffer->frameCount == 0) {
3398            break;
3399        }
3400
3401        if (mOutBuffer.frameCount == 0) {
3402            mOutBuffer.frameCount = pInBuffer->frameCount;
3403            nsecs_t startTime = systemTime();
3404            if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3405                LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3406                outputBufferFull = true;
3407                break;
3408            }
3409            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3410            if (waitTimeLeftMs >= waitTimeMs) {
3411                waitTimeLeftMs -= waitTimeMs;
3412            } else {
3413                waitTimeLeftMs = 0;
3414            }
3415        }
3416
3417        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3418        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3419        mCblk->stepUser(outFrames);
3420        pInBuffer->frameCount -= outFrames;
3421        pInBuffer->i16 += outFrames * channelCount;
3422        mOutBuffer.frameCount -= outFrames;
3423        mOutBuffer.i16 += outFrames * channelCount;
3424
3425        if (pInBuffer->frameCount == 0) {
3426            if (mBufferQueue.size()) {
3427                mBufferQueue.removeAt(0);
3428                delete [] pInBuffer->mBuffer;
3429                delete pInBuffer;
3430                LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3431            } else {
3432                break;
3433            }
3434        }
3435    }
3436
3437    // If we could not write all frames, allocate a buffer and queue it for next time.
3438    if (inBuffer.frameCount) {
3439        sp<ThreadBase> thread = mThread.promote();
3440        if (thread != 0 && !thread->standby()) {
3441            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3442                pInBuffer = new Buffer;
3443                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3444                pInBuffer->frameCount = inBuffer.frameCount;
3445                pInBuffer->i16 = pInBuffer->mBuffer;
3446                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3447                mBufferQueue.add(pInBuffer);
3448                LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3449            } else {
3450                LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3451            }
3452        }
3453    }
3454
3455    // Calling write() with a 0 length buffer, means that no more data will be written:
3456    // If no more buffers are pending, fill output track buffer to make sure it is started
3457    // by output mixer.
3458    if (frames == 0 && mBufferQueue.size() == 0) {
3459        if (mCblk->user < mCblk->frameCount) {
3460            frames = mCblk->frameCount - mCblk->user;
3461            pInBuffer = new Buffer;
3462            pInBuffer->mBuffer = new int16_t[frames * channelCount];
3463            pInBuffer->frameCount = frames;
3464            pInBuffer->i16 = pInBuffer->mBuffer;
3465            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3466            mBufferQueue.add(pInBuffer);
3467        } else if (mActive) {
3468            stop();
3469        }
3470    }
3471
3472    return outputBufferFull;
3473}
3474
3475status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3476{
3477    int active;
3478    status_t result;
3479    audio_track_cblk_t* cblk = mCblk;
3480    uint32_t framesReq = buffer->frameCount;
3481
3482//    LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3483    buffer->frameCount  = 0;
3484
3485    uint32_t framesAvail = cblk->framesAvailable();
3486
3487
3488    if (framesAvail == 0) {
3489        Mutex::Autolock _l(cblk->lock);
3490        goto start_loop_here;
3491        while (framesAvail == 0) {
3492            active = mActive;
3493            if (UNLIKELY(!active)) {
3494                LOGV("Not active and NO_MORE_BUFFERS");
3495                return AudioTrack::NO_MORE_BUFFERS;
3496            }
3497            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3498            if (result != NO_ERROR) {
3499                return AudioTrack::NO_MORE_BUFFERS;
3500            }
3501            // read the server count again
3502        start_loop_here:
3503            framesAvail = cblk->framesAvailable_l();
3504        }
3505    }
3506
3507//    if (framesAvail < framesReq) {
3508//        return AudioTrack::NO_MORE_BUFFERS;
3509//    }
3510
3511    if (framesReq > framesAvail) {
3512        framesReq = framesAvail;
3513    }
3514
3515    uint32_t u = cblk->user;
3516    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3517
3518    if (u + framesReq > bufferEnd) {
3519        framesReq = bufferEnd - u;
3520    }
3521
3522    buffer->frameCount  = framesReq;
3523    buffer->raw         = (void *)cblk->buffer(u);
3524    return NO_ERROR;
3525}
3526
3527
3528void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3529{
3530    size_t size = mBufferQueue.size();
3531    Buffer *pBuffer;
3532
3533    for (size_t i = 0; i < size; i++) {
3534        pBuffer = mBufferQueue.itemAt(i);
3535        delete [] pBuffer->mBuffer;
3536        delete pBuffer;
3537    }
3538    mBufferQueue.clear();
3539}
3540
3541// ----------------------------------------------------------------------------
3542
3543AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3544    :   RefBase(),
3545        mAudioFlinger(audioFlinger),
3546        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3547        mPid(pid)
3548{
3549    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3550}
3551
3552// Client destructor must be called with AudioFlinger::mLock held
3553AudioFlinger::Client::~Client()
3554{
3555    mAudioFlinger->removeClient_l(mPid);
3556}
3557
3558const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3559{
3560    return mMemoryDealer;
3561}
3562
3563// ----------------------------------------------------------------------------
3564
3565AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3566                                                     const sp<IAudioFlingerClient>& client,
3567                                                     pid_t pid)
3568    : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3569{
3570}
3571
3572AudioFlinger::NotificationClient::~NotificationClient()
3573{
3574    mClient.clear();
3575}
3576
3577void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3578{
3579    sp<NotificationClient> keep(this);
3580    {
3581        mAudioFlinger->removeNotificationClient(mPid);
3582    }
3583}
3584
3585// ----------------------------------------------------------------------------
3586
3587AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3588    : BnAudioTrack(),
3589      mTrack(track)
3590{
3591}
3592
3593AudioFlinger::TrackHandle::~TrackHandle() {
3594    // just stop the track on deletion, associated resources
3595    // will be freed from the main thread once all pending buffers have
3596    // been played. Unless it's not in the active track list, in which
3597    // case we free everything now...
3598    mTrack->destroy();
3599}
3600
3601status_t AudioFlinger::TrackHandle::start() {
3602    return mTrack->start();
3603}
3604
3605void AudioFlinger::TrackHandle::stop() {
3606    mTrack->stop();
3607}
3608
3609void AudioFlinger::TrackHandle::flush() {
3610    mTrack->flush();
3611}
3612
3613void AudioFlinger::TrackHandle::mute(bool e) {
3614    mTrack->mute(e);
3615}
3616
3617void AudioFlinger::TrackHandle::pause() {
3618    mTrack->pause();
3619}
3620
3621void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3622    mTrack->setVolume(left, right);
3623}
3624
3625sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3626    return mTrack->getCblk();
3627}
3628
3629status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3630{
3631    return mTrack->attachAuxEffect(EffectId);
3632}
3633
3634status_t AudioFlinger::TrackHandle::onTransact(
3635    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3636{
3637    return BnAudioTrack::onTransact(code, data, reply, flags);
3638}
3639
3640// ----------------------------------------------------------------------------
3641
3642sp<IAudioRecord> AudioFlinger::openRecord(
3643        pid_t pid,
3644        int input,
3645        uint32_t sampleRate,
3646        int format,
3647        int channelCount,
3648        int frameCount,
3649        uint32_t flags,
3650        int *sessionId,
3651        status_t *status)
3652{
3653    sp<RecordThread::RecordTrack> recordTrack;
3654    sp<RecordHandle> recordHandle;
3655    sp<Client> client;
3656    wp<Client> wclient;
3657    status_t lStatus;
3658    RecordThread *thread;
3659    size_t inFrameCount;
3660    int lSessionId;
3661
3662    // check calling permissions
3663    if (!recordingAllowed()) {
3664        lStatus = PERMISSION_DENIED;
3665        goto Exit;
3666    }
3667
3668    // add client to list
3669    { // scope for mLock
3670        Mutex::Autolock _l(mLock);
3671        thread = checkRecordThread_l(input);
3672        if (thread == NULL) {
3673            lStatus = BAD_VALUE;
3674            goto Exit;
3675        }
3676
3677        wclient = mClients.valueFor(pid);
3678        if (wclient != NULL) {
3679            client = wclient.promote();
3680        } else {
3681            client = new Client(this, pid);
3682            mClients.add(pid, client);
3683        }
3684
3685        // If no audio session id is provided, create one here
3686        if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
3687            lSessionId = *sessionId;
3688        } else {
3689            lSessionId = nextUniqueId();
3690            if (sessionId != NULL) {
3691                *sessionId = lSessionId;
3692            }
3693        }
3694        // create new record track. The record track uses one track in mHardwareMixerThread by convention.
3695        recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
3696                                                   format, channelCount, frameCount, flags, lSessionId);
3697    }
3698    if (recordTrack->getCblk() == NULL) {
3699        // remove local strong reference to Client before deleting the RecordTrack so that the Client
3700        // destructor is called by the TrackBase destructor with mLock held
3701        client.clear();
3702        recordTrack.clear();
3703        lStatus = NO_MEMORY;
3704        goto Exit;
3705    }
3706
3707    // return to handle to client
3708    recordHandle = new RecordHandle(recordTrack);
3709    lStatus = NO_ERROR;
3710
3711Exit:
3712    if (status) {
3713        *status = lStatus;
3714    }
3715    return recordHandle;
3716}
3717
3718// ----------------------------------------------------------------------------
3719
3720AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
3721    : BnAudioRecord(),
3722    mRecordTrack(recordTrack)
3723{
3724}
3725
3726AudioFlinger::RecordHandle::~RecordHandle() {
3727    stop();
3728}
3729
3730status_t AudioFlinger::RecordHandle::start() {
3731    LOGV("RecordHandle::start()");
3732    return mRecordTrack->start();
3733}
3734
3735void AudioFlinger::RecordHandle::stop() {
3736    LOGV("RecordHandle::stop()");
3737    mRecordTrack->stop();
3738}
3739
3740sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3741    return mRecordTrack->getCblk();
3742}
3743
3744status_t AudioFlinger::RecordHandle::onTransact(
3745    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3746{
3747    return BnAudioRecord::onTransact(code, data, reply, flags);
3748}
3749
3750// ----------------------------------------------------------------------------
3751
3752AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3753    ThreadBase(audioFlinger, id),
3754    mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
3755{
3756    mReqChannelCount = AudioSystem::popCount(channels);
3757    mReqSampleRate = sampleRate;
3758    readInputParameters();
3759}
3760
3761
3762AudioFlinger::RecordThread::~RecordThread()
3763{
3764    delete[] mRsmpInBuffer;
3765    if (mResampler != 0) {
3766        delete mResampler;
3767        delete[] mRsmpOutBuffer;
3768    }
3769}
3770
3771void AudioFlinger::RecordThread::onFirstRef()
3772{
3773    const size_t SIZE = 256;
3774    char buffer[SIZE];
3775
3776    snprintf(buffer, SIZE, "Record Thread %p", this);
3777
3778    run(buffer, PRIORITY_URGENT_AUDIO);
3779}
3780
3781bool AudioFlinger::RecordThread::threadLoop()
3782{
3783    AudioBufferProvider::Buffer buffer;
3784    sp<RecordTrack> activeTrack;
3785
3786    // start recording
3787    while (!exitPending()) {
3788
3789        processConfigEvents();
3790
3791        { // scope for mLock
3792            Mutex::Autolock _l(mLock);
3793            checkForNewParameters_l();
3794            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3795                if (!mStandby) {
3796                    mInput->standby();
3797                    mStandby = true;
3798                }
3799
3800                if (exitPending()) break;
3801
3802                LOGV("RecordThread: loop stopping");
3803                // go to sleep
3804                mWaitWorkCV.wait(mLock);
3805                LOGV("RecordThread: loop starting");
3806                continue;
3807            }
3808            if (mActiveTrack != 0) {
3809                if (mActiveTrack->mState == TrackBase::PAUSING) {
3810                    if (!mStandby) {
3811                        mInput->standby();
3812                        mStandby = true;
3813                    }
3814                    mActiveTrack.clear();
3815                    mStartStopCond.broadcast();
3816                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
3817                    if (mReqChannelCount != mActiveTrack->channelCount()) {
3818                        mActiveTrack.clear();
3819                        mStartStopCond.broadcast();
3820                    } else if (mBytesRead != 0) {
3821                        // record start succeeds only if first read from audio input
3822                        // succeeds
3823                        if (mBytesRead > 0) {
3824                            mActiveTrack->mState = TrackBase::ACTIVE;
3825                        } else {
3826                            mActiveTrack.clear();
3827                        }
3828                        mStartStopCond.broadcast();
3829                    }
3830                    mStandby = false;
3831                }
3832            }
3833        }
3834
3835        if (mActiveTrack != 0) {
3836            if (mActiveTrack->mState != TrackBase::ACTIVE &&
3837                mActiveTrack->mState != TrackBase::RESUMING) {
3838                usleep(5000);
3839                continue;
3840            }
3841            buffer.frameCount = mFrameCount;
3842            if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3843                size_t framesOut = buffer.frameCount;
3844                if (mResampler == 0) {
3845                    // no resampling
3846                    while (framesOut) {
3847                        size_t framesIn = mFrameCount - mRsmpInIndex;
3848                        if (framesIn) {
3849                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3850                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3851                            if (framesIn > framesOut)
3852                                framesIn = framesOut;
3853                            mRsmpInIndex += framesIn;
3854                            framesOut -= framesIn;
3855                            if ((int)mChannelCount == mReqChannelCount ||
3856                                mFormat != AudioSystem::PCM_16_BIT) {
3857                                memcpy(dst, src, framesIn * mFrameSize);
3858                            } else {
3859                                int16_t *src16 = (int16_t *)src;
3860                                int16_t *dst16 = (int16_t *)dst;
3861                                if (mChannelCount == 1) {
3862                                    while (framesIn--) {
3863                                        *dst16++ = *src16;
3864                                        *dst16++ = *src16++;
3865                                    }
3866                                } else {
3867                                    while (framesIn--) {
3868                                        *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3869                                        src16 += 2;
3870                                    }
3871                                }
3872                            }
3873                        }
3874                        if (framesOut && mFrameCount == mRsmpInIndex) {
3875                            if (framesOut == mFrameCount &&
3876                                ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
3877                                mBytesRead = mInput->read(buffer.raw, mInputBytes);
3878                                framesOut = 0;
3879                            } else {
3880                                mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3881                                mRsmpInIndex = 0;
3882                            }
3883                            if (mBytesRead < 0) {
3884                                LOGE("Error reading audio input");
3885                                if (mActiveTrack->mState == TrackBase::ACTIVE) {
3886                                    // Force input into standby so that it tries to
3887                                    // recover at next read attempt
3888                                    mInput->standby();
3889                                    usleep(5000);
3890                                }
3891                                mRsmpInIndex = mFrameCount;
3892                                framesOut = 0;
3893                                buffer.frameCount = 0;
3894                            }
3895                        }
3896                    }
3897                } else {
3898                    // resampling
3899
3900                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3901                    // alter output frame count as if we were expecting stereo samples
3902                    if (mChannelCount == 1 && mReqChannelCount == 1) {
3903                        framesOut >>= 1;
3904                    }
3905                    mResampler->resample(mRsmpOutBuffer, framesOut, this);
3906                    // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3907                    // are 32 bit aligned which should be always true.
3908                    if (mChannelCount == 2 && mReqChannelCount == 1) {
3909                        AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3910                        // the resampler always outputs stereo samples: do post stereo to mono conversion
3911                        int16_t *src = (int16_t *)mRsmpOutBuffer;
3912                        int16_t *dst = buffer.i16;
3913                        while (framesOut--) {
3914                            *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3915                            src += 2;
3916                        }
3917                    } else {
3918                        AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3919                    }
3920
3921                }
3922                mActiveTrack->releaseBuffer(&buffer);
3923                mActiveTrack->overflow();
3924            }
3925            // client isn't retrieving buffers fast enough
3926            else {
3927                if (!mActiveTrack->setOverflow())
3928                    LOGW("RecordThread: buffer overflow");
3929                // Release the processor for a while before asking for a new buffer.
3930                // This will give the application more chance to read from the buffer and
3931                // clear the overflow.
3932                usleep(5000);
3933            }
3934        }
3935    }
3936
3937    if (!mStandby) {
3938        mInput->standby();
3939    }
3940    mActiveTrack.clear();
3941
3942    mStartStopCond.broadcast();
3943
3944    LOGV("RecordThread %p exiting", this);
3945    return false;
3946}
3947
3948status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
3949{
3950    LOGV("RecordThread::start");
3951    sp <ThreadBase> strongMe = this;
3952    status_t status = NO_ERROR;
3953    {
3954        AutoMutex lock(&mLock);
3955        if (mActiveTrack != 0) {
3956            if (recordTrack != mActiveTrack.get()) {
3957                status = -EBUSY;
3958            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
3959                mActiveTrack->mState = TrackBase::ACTIVE;
3960            }
3961            return status;
3962        }
3963
3964        recordTrack->mState = TrackBase::IDLE;
3965        mActiveTrack = recordTrack;
3966        mLock.unlock();
3967        status_t status = AudioSystem::startInput(mId);
3968        mLock.lock();
3969        if (status != NO_ERROR) {
3970            mActiveTrack.clear();
3971            return status;
3972        }
3973        mActiveTrack->mState = TrackBase::RESUMING;
3974        mRsmpInIndex = mFrameCount;
3975        mBytesRead = 0;
3976        // signal thread to start
3977        LOGV("Signal record thread");
3978        mWaitWorkCV.signal();
3979        // do not wait for mStartStopCond if exiting
3980        if (mExiting) {
3981            mActiveTrack.clear();
3982            status = INVALID_OPERATION;
3983            goto startError;
3984        }
3985        mStartStopCond.wait(mLock);
3986        if (mActiveTrack == 0) {
3987            LOGV("Record failed to start");
3988            status = BAD_VALUE;
3989            goto startError;
3990        }
3991        LOGV("Record started OK");
3992        return status;
3993    }
3994startError:
3995    AudioSystem::stopInput(mId);
3996    return status;
3997}
3998
3999void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4000    LOGV("RecordThread::stop");
4001    sp <ThreadBase> strongMe = this;
4002    {
4003        AutoMutex lock(&mLock);
4004        if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4005            mActiveTrack->mState = TrackBase::PAUSING;
4006            // do not wait for mStartStopCond if exiting
4007            if (mExiting) {
4008                return;
4009            }
4010            mStartStopCond.wait(mLock);
4011            // if we have been restarted, recordTrack == mActiveTrack.get() here
4012            if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4013                mLock.unlock();
4014                AudioSystem::stopInput(mId);
4015                mLock.lock();
4016                LOGV("Record stopped OK");
4017            }
4018        }
4019    }
4020}
4021
4022status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4023{
4024    const size_t SIZE = 256;
4025    char buffer[SIZE];
4026    String8 result;
4027    pid_t pid = 0;
4028
4029    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4030    result.append(buffer);
4031
4032    if (mActiveTrack != 0) {
4033        result.append("Active Track:\n");
4034        result.append("   Clien Fmt Chn Session Buf  S SRate  Serv     User\n");
4035        mActiveTrack->dump(buffer, SIZE);
4036        result.append(buffer);
4037
4038        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4039        result.append(buffer);
4040        snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4041        result.append(buffer);
4042        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4043        result.append(buffer);
4044        snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4045        result.append(buffer);
4046        snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4047        result.append(buffer);
4048
4049
4050    } else {
4051        result.append("No record client\n");
4052    }
4053    write(fd, result.string(), result.size());
4054
4055    dumpBase(fd, args);
4056
4057    return NO_ERROR;
4058}
4059
4060status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4061{
4062    size_t framesReq = buffer->frameCount;
4063    size_t framesReady = mFrameCount - mRsmpInIndex;
4064    int channelCount;
4065
4066    if (framesReady == 0) {
4067        mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
4068        if (mBytesRead < 0) {
4069            LOGE("RecordThread::getNextBuffer() Error reading audio input");
4070            if (mActiveTrack->mState == TrackBase::ACTIVE) {
4071                // Force input into standby so that it tries to
4072                // recover at next read attempt
4073                mInput->standby();
4074                usleep(5000);
4075            }
4076            buffer->raw = 0;
4077            buffer->frameCount = 0;
4078            return NOT_ENOUGH_DATA;
4079        }
4080        mRsmpInIndex = 0;
4081        framesReady = mFrameCount;
4082    }
4083
4084    if (framesReq > framesReady) {
4085        framesReq = framesReady;
4086    }
4087
4088    if (mChannelCount == 1 && mReqChannelCount == 2) {
4089        channelCount = 1;
4090    } else {
4091        channelCount = 2;
4092    }
4093    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4094    buffer->frameCount = framesReq;
4095    return NO_ERROR;
4096}
4097
4098void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4099{
4100    mRsmpInIndex += buffer->frameCount;
4101    buffer->frameCount = 0;
4102}
4103
4104bool AudioFlinger::RecordThread::checkForNewParameters_l()
4105{
4106    bool reconfig = false;
4107
4108    while (!mNewParameters.isEmpty()) {
4109        status_t status = NO_ERROR;
4110        String8 keyValuePair = mNewParameters[0];
4111        AudioParameter param = AudioParameter(keyValuePair);
4112        int value;
4113        int reqFormat = mFormat;
4114        int reqSamplingRate = mReqSampleRate;
4115        int reqChannelCount = mReqChannelCount;
4116
4117        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4118            reqSamplingRate = value;
4119            reconfig = true;
4120        }
4121        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4122            reqFormat = value;
4123            reconfig = true;
4124        }
4125        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4126            reqChannelCount = AudioSystem::popCount(value);
4127            reconfig = true;
4128        }
4129        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4130            // do not accept frame count changes if tracks are open as the track buffer
4131            // size depends on frame count and correct behavior would not be garantied
4132            // if frame count is changed after track creation
4133            if (mActiveTrack != 0) {
4134                status = INVALID_OPERATION;
4135            } else {
4136                reconfig = true;
4137            }
4138        }
4139        if (status == NO_ERROR) {
4140            status = mInput->setParameters(keyValuePair);
4141            if (status == INVALID_OPERATION) {
4142               mInput->standby();
4143               status = mInput->setParameters(keyValuePair);
4144            }
4145            if (reconfig) {
4146                if (status == BAD_VALUE &&
4147                    reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4148                    ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4149                    (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4150                    status = NO_ERROR;
4151                }
4152                if (status == NO_ERROR) {
4153                    readInputParameters();
4154                    sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4155                }
4156            }
4157        }
4158
4159        mNewParameters.removeAt(0);
4160
4161        mParamStatus = status;
4162        mParamCond.signal();
4163        mWaitWorkCV.wait(mLock);
4164    }
4165    return reconfig;
4166}
4167
4168String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4169{
4170    return mInput->getParameters(keys);
4171}
4172
4173void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4174    AudioSystem::OutputDescriptor desc;
4175    void *param2 = 0;
4176
4177    switch (event) {
4178    case AudioSystem::INPUT_OPENED:
4179    case AudioSystem::INPUT_CONFIG_CHANGED:
4180        desc.channels = mChannels;
4181        desc.samplingRate = mSampleRate;
4182        desc.format = mFormat;
4183        desc.frameCount = mFrameCount;
4184        desc.latency = 0;
4185        param2 = &desc;
4186        break;
4187
4188    case AudioSystem::INPUT_CLOSED:
4189    default:
4190        break;
4191    }
4192    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4193}
4194
4195void AudioFlinger::RecordThread::readInputParameters()
4196{
4197    if (mRsmpInBuffer) delete mRsmpInBuffer;
4198    if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4199    if (mResampler) delete mResampler;
4200    mResampler = 0;
4201
4202    mSampleRate = mInput->sampleRate();
4203    mChannels = mInput->channels();
4204    mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
4205    mFormat = mInput->format();
4206    mFrameSize = (uint16_t)mInput->frameSize();
4207    mInputBytes = mInput->bufferSize();
4208    mFrameCount = mInputBytes / mFrameSize;
4209    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4210
4211    if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4212    {
4213        int channelCount;
4214         // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4215         // stereo to mono post process as the resampler always outputs stereo.
4216        if (mChannelCount == 1 && mReqChannelCount == 2) {
4217            channelCount = 1;
4218        } else {
4219            channelCount = 2;
4220        }
4221        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4222        mResampler->setSampleRate(mSampleRate);
4223        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4224        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4225
4226        // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4227        if (mChannelCount == 1 && mReqChannelCount == 1) {
4228            mFrameCount >>= 1;
4229        }
4230
4231    }
4232    mRsmpInIndex = mFrameCount;
4233}
4234
4235unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4236{
4237    return mInput->getInputFramesLost();
4238}
4239
4240// ----------------------------------------------------------------------------
4241
4242int AudioFlinger::openOutput(uint32_t *pDevices,
4243                                uint32_t *pSamplingRate,
4244                                uint32_t *pFormat,
4245                                uint32_t *pChannels,
4246                                uint32_t *pLatencyMs,
4247                                uint32_t flags)
4248{
4249    status_t status;
4250    PlaybackThread *thread = NULL;
4251    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4252    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4253    uint32_t format = pFormat ? *pFormat : 0;
4254    uint32_t channels = pChannels ? *pChannels : 0;
4255    uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4256
4257    LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4258            pDevices ? *pDevices : 0,
4259            samplingRate,
4260            format,
4261            channels,
4262            flags);
4263
4264    if (pDevices == NULL || *pDevices == 0) {
4265        return 0;
4266    }
4267    Mutex::Autolock _l(mLock);
4268
4269    AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4270                                                             (int *)&format,
4271                                                             &channels,
4272                                                             &samplingRate,
4273                                                             &status);
4274    LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4275            output,
4276            samplingRate,
4277            format,
4278            channels,
4279            status);
4280
4281    mHardwareStatus = AUDIO_HW_IDLE;
4282    if (output != 0) {
4283        int id = nextUniqueId();
4284        if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4285            (format != AudioSystem::PCM_16_BIT) ||
4286            (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
4287            thread = new DirectOutputThread(this, output, id, *pDevices);
4288            LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4289        } else {
4290            thread = new MixerThread(this, output, id, *pDevices);
4291            LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
4292
4293#ifdef LVMX
4294            unsigned bitsPerSample =
4295                (format == AudioSystem::PCM_16_BIT) ? 16 :
4296                    ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
4297            unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
4298            int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
4299
4300            LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
4301            LifeVibes::setDevice(audioOutputType, *pDevices);
4302#endif
4303
4304        }
4305        mPlaybackThreads.add(id, thread);
4306
4307        if (pSamplingRate) *pSamplingRate = samplingRate;
4308        if (pFormat) *pFormat = format;
4309        if (pChannels) *pChannels = channels;
4310        if (pLatencyMs) *pLatencyMs = thread->latency();
4311
4312        // notify client processes of the new output creation
4313        thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4314        return id;
4315    }
4316
4317    return 0;
4318}
4319
4320int AudioFlinger::openDuplicateOutput(int output1, int output2)
4321{
4322    Mutex::Autolock _l(mLock);
4323    MixerThread *thread1 = checkMixerThread_l(output1);
4324    MixerThread *thread2 = checkMixerThread_l(output2);
4325
4326    if (thread1 == NULL || thread2 == NULL) {
4327        LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4328        return 0;
4329    }
4330
4331    int id = nextUniqueId();
4332    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4333    thread->addOutputTrack(thread2);
4334    mPlaybackThreads.add(id, thread);
4335    // notify client processes of the new output creation
4336    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4337    return id;
4338}
4339
4340status_t AudioFlinger::closeOutput(int output)
4341{
4342    // keep strong reference on the playback thread so that
4343    // it is not destroyed while exit() is executed
4344    sp <PlaybackThread> thread;
4345    {
4346        Mutex::Autolock _l(mLock);
4347        thread = checkPlaybackThread_l(output);
4348        if (thread == NULL) {
4349            return BAD_VALUE;
4350        }
4351
4352        LOGV("closeOutput() %d", output);
4353
4354        if (thread->type() == PlaybackThread::MIXER) {
4355            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4356                if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4357                    DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4358                    dupThread->removeOutputTrack((MixerThread *)thread.get());
4359                }
4360            }
4361        }
4362        void *param2 = 0;
4363        audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4364        mPlaybackThreads.removeItem(output);
4365    }
4366    thread->exit();
4367
4368    if (thread->type() != PlaybackThread::DUPLICATING) {
4369        mAudioHardware->closeOutputStream(thread->getOutput());
4370    }
4371    return NO_ERROR;
4372}
4373
4374status_t AudioFlinger::suspendOutput(int output)
4375{
4376    Mutex::Autolock _l(mLock);
4377    PlaybackThread *thread = checkPlaybackThread_l(output);
4378
4379    if (thread == NULL) {
4380        return BAD_VALUE;
4381    }
4382
4383    LOGV("suspendOutput() %d", output);
4384    thread->suspend();
4385
4386    return NO_ERROR;
4387}
4388
4389status_t AudioFlinger::restoreOutput(int output)
4390{
4391    Mutex::Autolock _l(mLock);
4392    PlaybackThread *thread = checkPlaybackThread_l(output);
4393
4394    if (thread == NULL) {
4395        return BAD_VALUE;
4396    }
4397
4398    LOGV("restoreOutput() %d", output);
4399
4400    thread->restore();
4401
4402    return NO_ERROR;
4403}
4404
4405int AudioFlinger::openInput(uint32_t *pDevices,
4406                                uint32_t *pSamplingRate,
4407                                uint32_t *pFormat,
4408                                uint32_t *pChannels,
4409                                uint32_t acoustics)
4410{
4411    status_t status;
4412    RecordThread *thread = NULL;
4413    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4414    uint32_t format = pFormat ? *pFormat : 0;
4415    uint32_t channels = pChannels ? *pChannels : 0;
4416    uint32_t reqSamplingRate = samplingRate;
4417    uint32_t reqFormat = format;
4418    uint32_t reqChannels = channels;
4419
4420    if (pDevices == NULL || *pDevices == 0) {
4421        return 0;
4422    }
4423    Mutex::Autolock _l(mLock);
4424
4425    AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4426                                                             (int *)&format,
4427                                                             &channels,
4428                                                             &samplingRate,
4429                                                             &status,
4430                                                             (AudioSystem::audio_in_acoustics)acoustics);
4431    LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4432            input,
4433            samplingRate,
4434            format,
4435            channels,
4436            acoustics,
4437            status);
4438
4439    // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4440    // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4441    // or stereo to mono conversions on 16 bit PCM inputs.
4442    if (input == 0 && status == BAD_VALUE &&
4443        reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4444        (samplingRate <= 2 * reqSamplingRate) &&
4445        (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4446        LOGV("openInput() reopening with proposed sampling rate and channels");
4447        input = mAudioHardware->openInputStream(*pDevices,
4448                                                 (int *)&format,
4449                                                 &channels,
4450                                                 &samplingRate,
4451                                                 &status,
4452                                                 (AudioSystem::audio_in_acoustics)acoustics);
4453    }
4454
4455    if (input != 0) {
4456        int id = nextUniqueId();
4457         // Start record thread
4458        thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4459        mRecordThreads.add(id, thread);
4460        LOGV("openInput() created record thread: ID %d thread %p", id, thread);
4461        if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4462        if (pFormat) *pFormat = format;
4463        if (pChannels) *pChannels = reqChannels;
4464
4465        input->standby();
4466
4467        // notify client processes of the new input creation
4468        thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
4469        return id;
4470    }
4471
4472    return 0;
4473}
4474
4475status_t AudioFlinger::closeInput(int input)
4476{
4477    // keep strong reference on the record thread so that
4478    // it is not destroyed while exit() is executed
4479    sp <RecordThread> thread;
4480    {
4481        Mutex::Autolock _l(mLock);
4482        thread = checkRecordThread_l(input);
4483        if (thread == NULL) {
4484            return BAD_VALUE;
4485        }
4486
4487        LOGV("closeInput() %d", input);
4488        void *param2 = 0;
4489        audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
4490        mRecordThreads.removeItem(input);
4491    }
4492    thread->exit();
4493
4494    mAudioHardware->closeInputStream(thread->getInput());
4495
4496    return NO_ERROR;
4497}
4498
4499status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
4500{
4501    Mutex::Autolock _l(mLock);
4502    MixerThread *dstThread = checkMixerThread_l(output);
4503    if (dstThread == NULL) {
4504        LOGW("setStreamOutput() bad output id %d", output);
4505        return BAD_VALUE;
4506    }
4507
4508    LOGV("setStreamOutput() stream %d to output %d", stream, output);
4509    audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
4510
4511    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4512        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4513        if (thread != dstThread &&
4514            thread->type() != PlaybackThread::DIRECT) {
4515            MixerThread *srcThread = (MixerThread *)thread;
4516            srcThread->invalidateTracks(stream);
4517        }
4518    }
4519
4520    return NO_ERROR;
4521}
4522
4523
4524int AudioFlinger::newAudioSessionId()
4525{
4526    return nextUniqueId();
4527}
4528
4529// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
4530AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
4531{
4532    PlaybackThread *thread = NULL;
4533    if (mPlaybackThreads.indexOfKey(output) >= 0) {
4534        thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
4535    }
4536    return thread;
4537}
4538
4539// checkMixerThread_l() must be called with AudioFlinger::mLock held
4540AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
4541{
4542    PlaybackThread *thread = checkPlaybackThread_l(output);
4543    if (thread != NULL) {
4544        if (thread->type() == PlaybackThread::DIRECT) {
4545            thread = NULL;
4546        }
4547    }
4548    return (MixerThread *)thread;
4549}
4550
4551// checkRecordThread_l() must be called with AudioFlinger::mLock held
4552AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
4553{
4554    RecordThread *thread = NULL;
4555    if (mRecordThreads.indexOfKey(input) >= 0) {
4556        thread = (RecordThread *)mRecordThreads.valueFor(input).get();
4557    }
4558    return thread;
4559}
4560
4561int AudioFlinger::nextUniqueId()
4562{
4563    return android_atomic_inc(&mNextUniqueId);
4564}
4565
4566// ----------------------------------------------------------------------------
4567//  Effect management
4568// ----------------------------------------------------------------------------
4569
4570
4571status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4572{
4573    // check calling permissions
4574    if (!settingsAllowed()) {
4575        return PERMISSION_DENIED;
4576    }
4577    // only allow libraries loaded from /system/lib/soundfx for now
4578    if (strncmp(gEffectLibPath, libPath, strlen(gEffectLibPath)) != 0) {
4579        return PERMISSION_DENIED;
4580    }
4581
4582    Mutex::Autolock _l(mLock);
4583    return EffectLoadLibrary(libPath, handle);
4584}
4585
4586status_t AudioFlinger::unloadEffectLibrary(int handle)
4587{
4588    // check calling permissions
4589    if (!settingsAllowed()) {
4590        return PERMISSION_DENIED;
4591    }
4592
4593    Mutex::Autolock _l(mLock);
4594    return EffectUnloadLibrary(handle);
4595}
4596
4597status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4598{
4599    Mutex::Autolock _l(mLock);
4600    return EffectQueryNumberEffects(numEffects);
4601}
4602
4603status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
4604{
4605    Mutex::Autolock _l(mLock);
4606    return EffectQueryEffect(index, descriptor);
4607}
4608
4609status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4610{
4611    Mutex::Autolock _l(mLock);
4612    return EffectGetDescriptor(pUuid, descriptor);
4613}
4614
4615
4616// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4617static const effect_uuid_t VISUALIZATION_UUID_ =
4618    {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4619
4620sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4621        effect_descriptor_t *pDesc,
4622        const sp<IEffectClient>& effectClient,
4623        int32_t priority,
4624        int output,
4625        int sessionId,
4626        status_t *status,
4627        int *id,
4628        int *enabled)
4629{
4630    status_t lStatus = NO_ERROR;
4631    sp<EffectHandle> handle;
4632    effect_interface_t itfe;
4633    effect_descriptor_t desc;
4634    sp<Client> client;
4635    wp<Client> wclient;
4636
4637    LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4638            pid, effectClient.get(), priority, sessionId, output);
4639
4640    if (pDesc == NULL) {
4641        lStatus = BAD_VALUE;
4642        goto Exit;
4643    }
4644
4645    {
4646        Mutex::Autolock _l(mLock);
4647
4648        // check recording permission for visualizer
4649        if (memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4650            memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) {
4651            if (!recordingAllowed()) {
4652                lStatus = PERMISSION_DENIED;
4653                goto Exit;
4654            }
4655        }
4656
4657        if (!EffectIsNullUuid(&pDesc->uuid)) {
4658            // if uuid is specified, request effect descriptor
4659            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4660            if (lStatus < 0) {
4661                LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4662                goto Exit;
4663            }
4664        } else {
4665            // if uuid is not specified, look for an available implementation
4666            // of the required type in effect factory
4667            if (EffectIsNullUuid(&pDesc->type)) {
4668                LOGW("createEffect() no effect type");
4669                lStatus = BAD_VALUE;
4670                goto Exit;
4671            }
4672            uint32_t numEffects = 0;
4673            effect_descriptor_t d;
4674            bool found = false;
4675
4676            lStatus = EffectQueryNumberEffects(&numEffects);
4677            if (lStatus < 0) {
4678                LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4679                goto Exit;
4680            }
4681            for (uint32_t i = 0; i < numEffects; i++) {
4682                lStatus = EffectQueryEffect(i, &desc);
4683                if (lStatus < 0) {
4684                    LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
4685                    continue;
4686                }
4687                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4688                    // If matching type found save effect descriptor. If the session is
4689                    // 0 and the effect is not auxiliary, continue enumeration in case
4690                    // an auxiliary version of this effect type is available
4691                    found = true;
4692                    memcpy(&d, &desc, sizeof(effect_descriptor_t));
4693                    if (sessionId != AudioSystem::SESSION_OUTPUT_MIX ||
4694                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4695                        break;
4696                    }
4697                }
4698            }
4699            if (!found) {
4700                lStatus = BAD_VALUE;
4701                LOGW("createEffect() effect not found");
4702                goto Exit;
4703            }
4704            // For same effect type, chose auxiliary version over insert version if
4705            // connect to output mix (Compliance to OpenSL ES)
4706            if (sessionId == AudioSystem::SESSION_OUTPUT_MIX &&
4707                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4708                memcpy(&desc, &d, sizeof(effect_descriptor_t));
4709            }
4710        }
4711
4712        // Do not allow auxiliary effects on a session different from 0 (output mix)
4713        if (sessionId != AudioSystem::SESSION_OUTPUT_MIX &&
4714             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4715            lStatus = INVALID_OPERATION;
4716            goto Exit;
4717        }
4718
4719        // Session AudioSystem::SESSION_OUTPUT_STAGE is reserved for output stage effects
4720        // that can only be created by audio policy manager (running in same process)
4721        if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE &&
4722                getpid() != IPCThreadState::self()->getCallingPid()) {
4723            lStatus = INVALID_OPERATION;
4724            goto Exit;
4725        }
4726
4727        // return effect descriptor
4728        memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4729
4730        // If output is not specified try to find a matching audio session ID in one of the
4731        // output threads.
4732        // TODO: allow attachment of effect to inputs
4733        if (output == 0) {
4734            if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE) {
4735                // output must be specified by AudioPolicyManager when using session
4736                // AudioSystem::SESSION_OUTPUT_STAGE
4737                lStatus = BAD_VALUE;
4738                goto Exit;
4739            } else if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
4740                output = AudioSystem::getOutputForEffect(&desc);
4741                LOGV("createEffect() got output %d for effect %s", output, desc.name);
4742            } else {
4743                 // look for the thread where the specified audio session is present
4744                for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4745                    if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4746                        output = mPlaybackThreads.keyAt(i);
4747                        break;
4748                    }
4749                }
4750                // If no output thread contains the requested session ID, default to
4751                // first output. The effect chain will be moved to the correct output
4752                // thread when a track with the same session ID is created
4753                if (output == 0 && mPlaybackThreads.size()) {
4754                    output = mPlaybackThreads.keyAt(0);
4755                }
4756            }
4757        }
4758        PlaybackThread *thread = checkPlaybackThread_l(output);
4759        if (thread == NULL) {
4760            LOGE("createEffect() unknown output thread");
4761            lStatus = BAD_VALUE;
4762            goto Exit;
4763        }
4764
4765        wclient = mClients.valueFor(pid);
4766
4767        if (wclient != NULL) {
4768            client = wclient.promote();
4769        } else {
4770            client = new Client(this, pid);
4771            mClients.add(pid, client);
4772        }
4773
4774        // create effect on selected output trhead
4775        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4776                &desc, enabled, &lStatus);
4777        if (handle != 0 && id != NULL) {
4778            *id = handle->id();
4779        }
4780    }
4781
4782Exit:
4783    if(status) {
4784        *status = lStatus;
4785    }
4786    return handle;
4787}
4788
4789status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4790{
4791    LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4792            session, srcOutput, dstOutput);
4793    Mutex::Autolock _l(mLock);
4794    if (srcOutput == dstOutput) {
4795        LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4796        return NO_ERROR;
4797    }
4798    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4799    if (srcThread == NULL) {
4800        LOGW("moveEffects() bad srcOutput %d", srcOutput);
4801        return BAD_VALUE;
4802    }
4803    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4804    if (dstThread == NULL) {
4805        LOGW("moveEffects() bad dstOutput %d", dstOutput);
4806        return BAD_VALUE;
4807    }
4808
4809    Mutex::Autolock _dl(dstThread->mLock);
4810    Mutex::Autolock _sl(srcThread->mLock);
4811    moveEffectChain_l(session, srcThread, dstThread, false);
4812
4813    return NO_ERROR;
4814}
4815
4816// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4817status_t AudioFlinger::moveEffectChain_l(int session,
4818                                   AudioFlinger::PlaybackThread *srcThread,
4819                                   AudioFlinger::PlaybackThread *dstThread,
4820                                   bool reRegister)
4821{
4822    LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4823            session, srcThread, dstThread);
4824
4825    sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4826    if (chain == 0) {
4827        LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4828                session, srcThread);
4829        return INVALID_OPERATION;
4830    }
4831
4832    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
4833    // so that a new chain is created with correct parameters when first effect is added. This is
4834    // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4835    // removed.
4836    srcThread->removeEffectChain_l(chain);
4837
4838    // transfer all effects one by one so that new effect chain is created on new thread with
4839    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
4840    int dstOutput = dstThread->id();
4841    sp<EffectChain> dstChain;
4842    uint32_t strategy;
4843    sp<EffectModule> effect = chain->getEffectFromId_l(0);
4844    while (effect != 0) {
4845        srcThread->removeEffect_l(effect);
4846        dstThread->addEffect_l(effect);
4847        // if the move request is not received from audio policy manager, the effect must be
4848        // re-registered with the new strategy and output
4849        if (dstChain == 0) {
4850            dstChain = effect->chain().promote();
4851            if (dstChain == 0) {
4852                LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4853                srcThread->addEffect_l(effect);
4854                return NO_INIT;
4855            }
4856            strategy = dstChain->strategy();
4857        }
4858        if (reRegister) {
4859            AudioSystem::unregisterEffect(effect->id());
4860            AudioSystem::registerEffect(&effect->desc(),
4861                                        dstOutput,
4862                                        strategy,
4863                                        session,
4864                                        effect->id());
4865        }
4866        effect = chain->getEffectFromId_l(0);
4867    }
4868
4869    return NO_ERROR;
4870}
4871
4872// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4873sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4874        const sp<AudioFlinger::Client>& client,
4875        const sp<IEffectClient>& effectClient,
4876        int32_t priority,
4877        int sessionId,
4878        effect_descriptor_t *desc,
4879        int *enabled,
4880        status_t *status
4881        )
4882{
4883    sp<EffectModule> effect;
4884    sp<EffectHandle> handle;
4885    status_t lStatus;
4886    sp<Track> track;
4887    sp<EffectChain> chain;
4888    bool chainCreated = false;
4889    bool effectCreated = false;
4890    bool effectRegistered = false;
4891
4892    if (mOutput == 0) {
4893        LOGW("createEffect_l() Audio driver not initialized.");
4894        lStatus = NO_INIT;
4895        goto Exit;
4896    }
4897
4898    // Do not allow auxiliary effect on session other than 0
4899    if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
4900        sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
4901        LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4902                desc->name, sessionId);
4903        lStatus = BAD_VALUE;
4904        goto Exit;
4905    }
4906
4907    // Do not allow effects with session ID 0 on direct output or duplicating threads
4908    // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
4909    if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && mType != MIXER) {
4910        LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4911                desc->name, sessionId);
4912        lStatus = BAD_VALUE;
4913        goto Exit;
4914    }
4915
4916    LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4917
4918    { // scope for mLock
4919        Mutex::Autolock _l(mLock);
4920
4921        // check for existing effect chain with the requested audio session
4922        chain = getEffectChain_l(sessionId);
4923        if (chain == 0) {
4924            // create a new chain for this session
4925            LOGV("createEffect_l() new effect chain for session %d", sessionId);
4926            chain = new EffectChain(this, sessionId);
4927            addEffectChain_l(chain);
4928            chain->setStrategy(getStrategyForSession_l(sessionId));
4929            chainCreated = true;
4930        } else {
4931            effect = chain->getEffectFromDesc_l(desc);
4932        }
4933
4934        LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4935
4936        if (effect == 0) {
4937            int id = mAudioFlinger->nextUniqueId();
4938            // Check CPU and memory usage
4939            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
4940            if (lStatus != NO_ERROR) {
4941                goto Exit;
4942            }
4943            effectRegistered = true;
4944            // create a new effect module if none present in the chain
4945            effect = new EffectModule(this, chain, desc, id, sessionId);
4946            lStatus = effect->status();
4947            if (lStatus != NO_ERROR) {
4948                goto Exit;
4949            }
4950            lStatus = chain->addEffect_l(effect);
4951            if (lStatus != NO_ERROR) {
4952                goto Exit;
4953            }
4954            effectCreated = true;
4955
4956            effect->setDevice(mDevice);
4957            effect->setMode(mAudioFlinger->getMode());
4958        }
4959        // create effect handle and connect it to effect module
4960        handle = new EffectHandle(effect, client, effectClient, priority);
4961        lStatus = effect->addHandle(handle);
4962        if (enabled) {
4963            *enabled = (int)effect->isEnabled();
4964        }
4965    }
4966
4967Exit:
4968    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4969        Mutex::Autolock _l(mLock);
4970        if (effectCreated) {
4971            chain->removeEffect_l(effect);
4972        }
4973        if (effectRegistered) {
4974            AudioSystem::unregisterEffect(effect->id());
4975        }
4976        if (chainCreated) {
4977            removeEffectChain_l(chain);
4978        }
4979        handle.clear();
4980    }
4981
4982    if(status) {
4983        *status = lStatus;
4984    }
4985    return handle;
4986}
4987
4988// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
4989// PlaybackThread::mLock held
4990status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
4991{
4992    // check for existing effect chain with the requested audio session
4993    int sessionId = effect->sessionId();
4994    sp<EffectChain> chain = getEffectChain_l(sessionId);
4995    bool chainCreated = false;
4996
4997    if (chain == 0) {
4998        // create a new chain for this session
4999        LOGV("addEffect_l() new effect chain for session %d", sessionId);
5000        chain = new EffectChain(this, sessionId);
5001        addEffectChain_l(chain);
5002        chain->setStrategy(getStrategyForSession_l(sessionId));
5003        chainCreated = true;
5004    }
5005    LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5006
5007    if (chain->getEffectFromId_l(effect->id()) != 0) {
5008        LOGW("addEffect_l() %p effect %s already present in chain %p",
5009                this, effect->desc().name, chain.get());
5010        return BAD_VALUE;
5011    }
5012
5013    status_t status = chain->addEffect_l(effect);
5014    if (status != NO_ERROR) {
5015        if (chainCreated) {
5016            removeEffectChain_l(chain);
5017        }
5018        return status;
5019    }
5020
5021    effect->setDevice(mDevice);
5022    effect->setMode(mAudioFlinger->getMode());
5023    return NO_ERROR;
5024}
5025
5026void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
5027
5028    LOGV("removeEffect_l() %p effect %p", this, effect.get());
5029    effect_descriptor_t desc = effect->desc();
5030    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5031        detachAuxEffect_l(effect->id());
5032    }
5033
5034    sp<EffectChain> chain = effect->chain().promote();
5035    if (chain != 0) {
5036        // remove effect chain if removing last effect
5037        if (chain->removeEffect_l(effect) == 0) {
5038            removeEffectChain_l(chain);
5039        }
5040    } else {
5041        LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5042    }
5043}
5044
5045void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
5046                                                    const wp<EffectHandle>& handle) {
5047    Mutex::Autolock _l(mLock);
5048    LOGV("disconnectEffect() %p effect %p", this, effect.get());
5049    // delete the effect module if removing last handle on it
5050    if (effect->removeHandle(handle) == 0) {
5051        removeEffect_l(effect);
5052        AudioSystem::unregisterEffect(effect->id());
5053    }
5054}
5055
5056status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5057{
5058    int session = chain->sessionId();
5059    int16_t *buffer = mMixBuffer;
5060    bool ownsBuffer = false;
5061
5062    LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5063    if (session > 0) {
5064        // Only one effect chain can be present in direct output thread and it uses
5065        // the mix buffer as input
5066        if (mType != DIRECT) {
5067            size_t numSamples = mFrameCount * mChannelCount;
5068            buffer = new int16_t[numSamples];
5069            memset(buffer, 0, numSamples * sizeof(int16_t));
5070            LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5071            ownsBuffer = true;
5072        }
5073
5074        // Attach all tracks with same session ID to this chain.
5075        for (size_t i = 0; i < mTracks.size(); ++i) {
5076            sp<Track> track = mTracks[i];
5077            if (session == track->sessionId()) {
5078                LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5079                track->setMainBuffer(buffer);
5080            }
5081        }
5082
5083        // indicate all active tracks in the chain
5084        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5085            sp<Track> track = mActiveTracks[i].promote();
5086            if (track == 0) continue;
5087            if (session == track->sessionId()) {
5088                LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5089                chain->startTrack();
5090            }
5091        }
5092    }
5093
5094    chain->setInBuffer(buffer, ownsBuffer);
5095    chain->setOutBuffer(mMixBuffer);
5096    // Effect chain for session AudioSystem::SESSION_OUTPUT_STAGE is inserted at end of effect
5097    // chains list in order to be processed last as it contains output stage effects
5098    // Effect chain for session AudioSystem::SESSION_OUTPUT_MIX is inserted before
5099    // session AudioSystem::SESSION_OUTPUT_STAGE to be processed
5100    // after track specific effects and before output stage
5101    // It is therefore mandatory that AudioSystem::SESSION_OUTPUT_MIX == 0 and
5102    // that AudioSystem::SESSION_OUTPUT_STAGE < AudioSystem::SESSION_OUTPUT_MIX
5103    // Effect chain for other sessions are inserted at beginning of effect
5104    // chains list to be processed before output mix effects. Relative order between other
5105    // sessions is not important
5106    size_t size = mEffectChains.size();
5107    size_t i = 0;
5108    for (i = 0; i < size; i++) {
5109        if (mEffectChains[i]->sessionId() < session) break;
5110    }
5111    mEffectChains.insertAt(chain, i);
5112
5113    return NO_ERROR;
5114}
5115
5116size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5117{
5118    int session = chain->sessionId();
5119
5120    LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5121
5122    for (size_t i = 0; i < mEffectChains.size(); i++) {
5123        if (chain == mEffectChains[i]) {
5124            mEffectChains.removeAt(i);
5125            // detach all tracks with same session ID from this chain
5126            for (size_t i = 0; i < mTracks.size(); ++i) {
5127                sp<Track> track = mTracks[i];
5128                if (session == track->sessionId()) {
5129                    track->setMainBuffer(mMixBuffer);
5130                }
5131            }
5132            break;
5133        }
5134    }
5135    return mEffectChains.size();
5136}
5137
5138void AudioFlinger::PlaybackThread::lockEffectChains_l(
5139        Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5140{
5141    effectChains = mEffectChains;
5142    for (size_t i = 0; i < mEffectChains.size(); i++) {
5143        mEffectChains[i]->lock();
5144    }
5145}
5146
5147void AudioFlinger::PlaybackThread::unlockEffectChains(
5148        Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5149{
5150    for (size_t i = 0; i < effectChains.size(); i++) {
5151        effectChains[i]->unlock();
5152    }
5153}
5154
5155
5156sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5157{
5158    sp<EffectModule> effect;
5159
5160    sp<EffectChain> chain = getEffectChain_l(sessionId);
5161    if (chain != 0) {
5162        effect = chain->getEffectFromId_l(effectId);
5163    }
5164    return effect;
5165}
5166
5167status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5168        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
5169{
5170    Mutex::Autolock _l(mLock);
5171    return attachAuxEffect_l(track, EffectId);
5172}
5173
5174status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5175        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
5176{
5177    status_t status = NO_ERROR;
5178
5179    if (EffectId == 0) {
5180        track->setAuxBuffer(0, NULL);
5181    } else {
5182        // Auxiliary effects are always in audio session AudioSystem::SESSION_OUTPUT_MIX
5183        sp<EffectModule> effect = getEffect_l(AudioSystem::SESSION_OUTPUT_MIX, EffectId);
5184        if (effect != 0) {
5185            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5186                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5187            } else {
5188                status = INVALID_OPERATION;
5189            }
5190        } else {
5191            status = BAD_VALUE;
5192        }
5193    }
5194    return status;
5195}
5196
5197void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5198{
5199     for (size_t i = 0; i < mTracks.size(); ++i) {
5200        sp<Track> track = mTracks[i];
5201        if (track->auxEffectId() == effectId) {
5202            attachAuxEffect_l(track, 0);
5203        }
5204    }
5205}
5206
5207// ----------------------------------------------------------------------------
5208//  EffectModule implementation
5209// ----------------------------------------------------------------------------
5210
5211#undef LOG_TAG
5212#define LOG_TAG "AudioFlinger::EffectModule"
5213
5214AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5215                                        const wp<AudioFlinger::EffectChain>& chain,
5216                                        effect_descriptor_t *desc,
5217                                        int id,
5218                                        int sessionId)
5219    : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5220      mStatus(NO_INIT), mState(IDLE)
5221{
5222    LOGV("Constructor %p", this);
5223    int lStatus;
5224    sp<ThreadBase> thread = mThread.promote();
5225    if (thread == 0) {
5226        return;
5227    }
5228    PlaybackThread *p = (PlaybackThread *)thread.get();
5229
5230    memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5231
5232    // create effect engine from effect factory
5233    mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5234
5235    if (mStatus != NO_ERROR) {
5236        return;
5237    }
5238    lStatus = init();
5239    if (lStatus < 0) {
5240        mStatus = lStatus;
5241        goto Error;
5242    }
5243
5244    LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5245    return;
5246Error:
5247    EffectRelease(mEffectInterface);
5248    mEffectInterface = NULL;
5249    LOGV("Constructor Error %d", mStatus);
5250}
5251
5252AudioFlinger::EffectModule::~EffectModule()
5253{
5254    LOGV("Destructor %p", this);
5255    if (mEffectInterface != NULL) {
5256        // release effect engine
5257        EffectRelease(mEffectInterface);
5258    }
5259}
5260
5261status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5262{
5263    status_t status;
5264
5265    Mutex::Autolock _l(mLock);
5266    // First handle in mHandles has highest priority and controls the effect module
5267    int priority = handle->priority();
5268    size_t size = mHandles.size();
5269    sp<EffectHandle> h;
5270    size_t i;
5271    for (i = 0; i < size; i++) {
5272        h = mHandles[i].promote();
5273        if (h == 0) continue;
5274        if (h->priority() <= priority) break;
5275    }
5276    // if inserted in first place, move effect control from previous owner to this handle
5277    if (i == 0) {
5278        if (h != 0) {
5279            h->setControl(false, true);
5280        }
5281        handle->setControl(true, false);
5282        status = NO_ERROR;
5283    } else {
5284        status = ALREADY_EXISTS;
5285    }
5286    mHandles.insertAt(handle, i);
5287    return status;
5288}
5289
5290size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5291{
5292    Mutex::Autolock _l(mLock);
5293    size_t size = mHandles.size();
5294    size_t i;
5295    for (i = 0; i < size; i++) {
5296        if (mHandles[i] == handle) break;
5297    }
5298    if (i == size) {
5299        return size;
5300    }
5301    mHandles.removeAt(i);
5302    size = mHandles.size();
5303    // if removed from first place, move effect control from this handle to next in line
5304    if (i == 0 && size != 0) {
5305        sp<EffectHandle> h = mHandles[0].promote();
5306        if (h != 0) {
5307            h->setControl(true, true);
5308        }
5309    }
5310
5311    return size;
5312}
5313
5314void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5315{
5316    // keep a strong reference on this EffectModule to avoid calling the
5317    // destructor before we exit
5318    sp<EffectModule> keep(this);
5319    {
5320        sp<ThreadBase> thread = mThread.promote();
5321        if (thread != 0) {
5322            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5323            playbackThread->disconnectEffect(keep, handle);
5324        }
5325    }
5326}
5327
5328void AudioFlinger::EffectModule::updateState() {
5329    Mutex::Autolock _l(mLock);
5330
5331    switch (mState) {
5332    case RESTART:
5333        reset_l();
5334        // FALL THROUGH
5335
5336    case STARTING:
5337        // clear auxiliary effect input buffer for next accumulation
5338        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5339            memset(mConfig.inputCfg.buffer.raw,
5340                   0,
5341                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5342        }
5343        start_l();
5344        mState = ACTIVE;
5345        break;
5346    case STOPPING:
5347        stop_l();
5348        mDisableWaitCnt = mMaxDisableWaitCnt;
5349        mState = STOPPED;
5350        break;
5351    case STOPPED:
5352        // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5353        // turn off sequence.
5354        if (--mDisableWaitCnt == 0) {
5355            reset_l();
5356            mState = IDLE;
5357        }
5358        break;
5359    default: //IDLE , ACTIVE
5360        break;
5361    }
5362}
5363
5364void AudioFlinger::EffectModule::process()
5365{
5366    Mutex::Autolock _l(mLock);
5367
5368    if (mEffectInterface == NULL ||
5369            mConfig.inputCfg.buffer.raw == NULL ||
5370            mConfig.outputCfg.buffer.raw == NULL) {
5371        return;
5372    }
5373
5374    if (mState == ACTIVE || mState == STOPPING || mState == STOPPED || mState == RESTART) {
5375        // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5376        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5377            AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5378                                        mConfig.inputCfg.buffer.s32,
5379                                        mConfig.inputCfg.buffer.frameCount/2);
5380        }
5381
5382        // do the actual processing in the effect engine
5383        int ret = (*mEffectInterface)->process(mEffectInterface,
5384                                               &mConfig.inputCfg.buffer,
5385                                               &mConfig.outputCfg.buffer);
5386
5387        // force transition to IDLE state when engine is ready
5388        if (mState == STOPPED && ret == -ENODATA) {
5389            mDisableWaitCnt = 1;
5390        }
5391
5392        // clear auxiliary effect input buffer for next accumulation
5393        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5394            memset(mConfig.inputCfg.buffer.raw, 0, mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5395        }
5396    } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
5397                mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw){
5398        // If an insert effect is idle and input buffer is different from output buffer, copy input to
5399        // output
5400        sp<EffectChain> chain = mChain.promote();
5401        if (chain != 0 && chain->activeTracks() != 0) {
5402            size_t size = mConfig.inputCfg.buffer.frameCount * sizeof(int16_t);
5403            if (mConfig.inputCfg.channels == CHANNEL_STEREO) {
5404                size *= 2;
5405            }
5406            memcpy(mConfig.outputCfg.buffer.raw, mConfig.inputCfg.buffer.raw, size);
5407        }
5408    }
5409}
5410
5411void AudioFlinger::EffectModule::reset_l()
5412{
5413    if (mEffectInterface == NULL) {
5414        return;
5415    }
5416    (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5417}
5418
5419status_t AudioFlinger::EffectModule::configure()
5420{
5421    uint32_t channels;
5422    if (mEffectInterface == NULL) {
5423        return NO_INIT;
5424    }
5425
5426    sp<ThreadBase> thread = mThread.promote();
5427    if (thread == 0) {
5428        return DEAD_OBJECT;
5429    }
5430
5431    // TODO: handle configuration of effects replacing track process
5432    if (thread->channelCount() == 1) {
5433        channels = CHANNEL_MONO;
5434    } else {
5435        channels = CHANNEL_STEREO;
5436    }
5437
5438    if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5439        mConfig.inputCfg.channels = CHANNEL_MONO;
5440    } else {
5441        mConfig.inputCfg.channels = channels;
5442    }
5443    mConfig.outputCfg.channels = channels;
5444    mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5445    mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
5446    mConfig.inputCfg.samplingRate = thread->sampleRate();
5447    mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5448    mConfig.inputCfg.bufferProvider.cookie = NULL;
5449    mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5450    mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5451    mConfig.outputCfg.bufferProvider.cookie = NULL;
5452    mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5453    mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5454    mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5455    // Insert effect:
5456    // - in session AudioSystem::SESSION_OUTPUT_MIX or AudioSystem::SESSION_OUTPUT_STAGE,
5457    // always overwrites output buffer: input buffer == output buffer
5458    // - in other sessions:
5459    //      last effect in the chain accumulates in output buffer: input buffer != output buffer
5460    //      other effect: overwrites output buffer: input buffer == output buffer
5461    // Auxiliary effect:
5462    //      accumulates in output buffer: input buffer != output buffer
5463    // Therefore: accumulate <=> input buffer != output buffer
5464    if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5465        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5466    } else {
5467        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5468    }
5469    mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5470    mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5471    mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5472    mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5473
5474    LOGV("configure() %p thread %p buffer %p framecount %d",
5475            this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5476
5477    status_t cmdStatus;
5478    uint32_t size = sizeof(int);
5479    status_t status = (*mEffectInterface)->command(mEffectInterface,
5480                                                   EFFECT_CMD_CONFIGURE,
5481                                                   sizeof(effect_config_t),
5482                                                   &mConfig,
5483                                                   &size,
5484                                                   &cmdStatus);
5485    if (status == 0) {
5486        status = cmdStatus;
5487    }
5488
5489    mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5490            (1000 * mConfig.outputCfg.buffer.frameCount);
5491
5492    return status;
5493}
5494
5495status_t AudioFlinger::EffectModule::init()
5496{
5497    Mutex::Autolock _l(mLock);
5498    if (mEffectInterface == NULL) {
5499        return NO_INIT;
5500    }
5501    status_t cmdStatus;
5502    uint32_t size = sizeof(status_t);
5503    status_t status = (*mEffectInterface)->command(mEffectInterface,
5504                                                   EFFECT_CMD_INIT,
5505                                                   0,
5506                                                   NULL,
5507                                                   &size,
5508                                                   &cmdStatus);
5509    if (status == 0) {
5510        status = cmdStatus;
5511    }
5512    return status;
5513}
5514
5515status_t AudioFlinger::EffectModule::start_l()
5516{
5517    if (mEffectInterface == NULL) {
5518        return NO_INIT;
5519    }
5520    status_t cmdStatus;
5521    uint32_t size = sizeof(status_t);
5522    status_t status = (*mEffectInterface)->command(mEffectInterface,
5523                                                   EFFECT_CMD_ENABLE,
5524                                                   0,
5525                                                   NULL,
5526                                                   &size,
5527                                                   &cmdStatus);
5528    if (status == 0) {
5529        status = cmdStatus;
5530    }
5531    return status;
5532}
5533
5534status_t AudioFlinger::EffectModule::stop_l()
5535{
5536    if (mEffectInterface == NULL) {
5537        return NO_INIT;
5538    }
5539    status_t cmdStatus;
5540    uint32_t size = sizeof(status_t);
5541    status_t status = (*mEffectInterface)->command(mEffectInterface,
5542                                                   EFFECT_CMD_DISABLE,
5543                                                   0,
5544                                                   NULL,
5545                                                   &size,
5546                                                   &cmdStatus);
5547    if (status == 0) {
5548        status = cmdStatus;
5549    }
5550    return status;
5551}
5552
5553status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5554                                             uint32_t cmdSize,
5555                                             void *pCmdData,
5556                                             uint32_t *replySize,
5557                                             void *pReplyData)
5558{
5559    Mutex::Autolock _l(mLock);
5560//    LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
5561
5562    if (mEffectInterface == NULL) {
5563        return NO_INIT;
5564    }
5565    status_t status = (*mEffectInterface)->command(mEffectInterface,
5566                                                   cmdCode,
5567                                                   cmdSize,
5568                                                   pCmdData,
5569                                                   replySize,
5570                                                   pReplyData);
5571    if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
5572        uint32_t size = (replySize == NULL) ? 0 : *replySize;
5573        for (size_t i = 1; i < mHandles.size(); i++) {
5574            sp<EffectHandle> h = mHandles[i].promote();
5575            if (h != 0) {
5576                h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5577            }
5578        }
5579    }
5580    return status;
5581}
5582
5583status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5584{
5585    Mutex::Autolock _l(mLock);
5586    LOGV("setEnabled %p enabled %d", this, enabled);
5587
5588    if (enabled != isEnabled()) {
5589        switch (mState) {
5590        // going from disabled to enabled
5591        case IDLE:
5592            mState = STARTING;
5593            break;
5594        case STOPPED:
5595            mState = RESTART;
5596            break;
5597        case STOPPING:
5598            mState = ACTIVE;
5599            break;
5600
5601        // going from enabled to disabled
5602        case RESTART:
5603        case STARTING:
5604            mState = IDLE;
5605            break;
5606        case ACTIVE:
5607            mState = STOPPING;
5608            break;
5609        }
5610        for (size_t i = 1; i < mHandles.size(); i++) {
5611            sp<EffectHandle> h = mHandles[i].promote();
5612            if (h != 0) {
5613                h->setEnabled(enabled);
5614            }
5615        }
5616    }
5617    return NO_ERROR;
5618}
5619
5620bool AudioFlinger::EffectModule::isEnabled()
5621{
5622    switch (mState) {
5623    case RESTART:
5624    case STARTING:
5625    case ACTIVE:
5626        return true;
5627    case IDLE:
5628    case STOPPING:
5629    case STOPPED:
5630    default:
5631        return false;
5632    }
5633}
5634
5635status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5636{
5637    Mutex::Autolock _l(mLock);
5638    status_t status = NO_ERROR;
5639
5640    // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5641    // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
5642    if ((mState >= ACTIVE) &&
5643            ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5644            (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
5645        status_t cmdStatus;
5646        uint32_t volume[2];
5647        uint32_t *pVolume = NULL;
5648        uint32_t size = sizeof(volume);
5649        volume[0] = *left;
5650        volume[1] = *right;
5651        if (controller) {
5652            pVolume = volume;
5653        }
5654        status = (*mEffectInterface)->command(mEffectInterface,
5655                                              EFFECT_CMD_SET_VOLUME,
5656                                              size,
5657                                              volume,
5658                                              &size,
5659                                              pVolume);
5660        if (controller && status == NO_ERROR && size == sizeof(volume)) {
5661            *left = volume[0];
5662            *right = volume[1];
5663        }
5664    }
5665    return status;
5666}
5667
5668status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5669{
5670    Mutex::Autolock _l(mLock);
5671    status_t status = NO_ERROR;
5672    if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5673        // convert device bit field from AudioSystem to EffectApi format.
5674        device = deviceAudioSystemToEffectApi(device);
5675        if (device == 0) {
5676            return BAD_VALUE;
5677        }
5678        status_t cmdStatus;
5679        uint32_t size = sizeof(status_t);
5680        status = (*mEffectInterface)->command(mEffectInterface,
5681                                              EFFECT_CMD_SET_DEVICE,
5682                                              sizeof(uint32_t),
5683                                              &device,
5684                                              &size,
5685                                              &cmdStatus);
5686        if (status == NO_ERROR) {
5687            status = cmdStatus;
5688        }
5689    }
5690    return status;
5691}
5692
5693status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5694{
5695    Mutex::Autolock _l(mLock);
5696    status_t status = NO_ERROR;
5697    if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5698        // convert audio mode from AudioSystem to EffectApi format.
5699        int effectMode = modeAudioSystemToEffectApi(mode);
5700        if (effectMode < 0) {
5701            return BAD_VALUE;
5702        }
5703        status_t cmdStatus;
5704        uint32_t size = sizeof(status_t);
5705        status = (*mEffectInterface)->command(mEffectInterface,
5706                                              EFFECT_CMD_SET_AUDIO_MODE,
5707                                              sizeof(int),
5708                                              &effectMode,
5709                                              &size,
5710                                              &cmdStatus);
5711        if (status == NO_ERROR) {
5712            status = cmdStatus;
5713        }
5714    }
5715    return status;
5716}
5717
5718// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5719const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
5720    DEVICE_EARPIECE, // AudioSystem::DEVICE_OUT_EARPIECE
5721    DEVICE_SPEAKER, // AudioSystem::DEVICE_OUT_SPEAKER
5722    DEVICE_WIRED_HEADSET, // case AudioSystem::DEVICE_OUT_WIRED_HEADSET
5723    DEVICE_WIRED_HEADPHONE, // AudioSystem::DEVICE_OUT_WIRED_HEADPHONE
5724    DEVICE_BLUETOOTH_SCO, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO
5725    DEVICE_BLUETOOTH_SCO_HEADSET, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5726    DEVICE_BLUETOOTH_SCO_CARKIT, //  AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5727    DEVICE_BLUETOOTH_A2DP, //  AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP
5728    DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5729    DEVICE_BLUETOOTH_A2DP_SPEAKER, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5730    DEVICE_AUX_DIGITAL // AudioSystem::DEVICE_OUT_AUX_DIGITAL
5731};
5732
5733uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5734{
5735    uint32_t deviceOut = 0;
5736    while (device) {
5737        const uint32_t i = 31 - __builtin_clz(device);
5738        device &= ~(1 << i);
5739        if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
5740            LOGE("device convertion error for AudioSystem device 0x%08x", device);
5741            return 0;
5742        }
5743        deviceOut |= (uint32_t)sDeviceConvTable[i];
5744    }
5745    return deviceOut;
5746}
5747
5748// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5749const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
5750    AUDIO_MODE_NORMAL,   // AudioSystem::MODE_NORMAL
5751    AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
5752    AUDIO_MODE_IN_CALL   // AudioSystem::MODE_IN_CALL
5753};
5754
5755int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5756{
5757    int modeOut = -1;
5758    if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5759        modeOut = (int)sModeConvTable[mode];
5760    }
5761    return modeOut;
5762}
5763
5764status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5765{
5766    const size_t SIZE = 256;
5767    char buffer[SIZE];
5768    String8 result;
5769
5770    snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5771    result.append(buffer);
5772
5773    bool locked = tryLock(mLock);
5774    // failed to lock - AudioFlinger is probably deadlocked
5775    if (!locked) {
5776        result.append("\t\tCould not lock Fx mutex:\n");
5777    }
5778
5779    result.append("\t\tSession Status State Engine:\n");
5780    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   0x%08x\n",
5781            mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5782    result.append(buffer);
5783
5784    result.append("\t\tDescriptor:\n");
5785    snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5786            mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5787            mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5788            mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5789    result.append(buffer);
5790    snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5791                mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5792                mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5793                mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5794    result.append(buffer);
5795    snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5796            mDescriptor.apiVersion,
5797            mDescriptor.flags);
5798    result.append(buffer);
5799    snprintf(buffer, SIZE, "\t\t- name: %s\n",
5800            mDescriptor.name);
5801    result.append(buffer);
5802    snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5803            mDescriptor.implementor);
5804    result.append(buffer);
5805
5806    result.append("\t\t- Input configuration:\n");
5807    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
5808    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
5809            (uint32_t)mConfig.inputCfg.buffer.raw,
5810            mConfig.inputCfg.buffer.frameCount,
5811            mConfig.inputCfg.samplingRate,
5812            mConfig.inputCfg.channels,
5813            mConfig.inputCfg.format);
5814    result.append(buffer);
5815
5816    result.append("\t\t- Output configuration:\n");
5817    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
5818    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
5819            (uint32_t)mConfig.outputCfg.buffer.raw,
5820            mConfig.outputCfg.buffer.frameCount,
5821            mConfig.outputCfg.samplingRate,
5822            mConfig.outputCfg.channels,
5823            mConfig.outputCfg.format);
5824    result.append(buffer);
5825
5826    snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5827    result.append(buffer);
5828    result.append("\t\t\tPid   Priority Ctrl Locked client server\n");
5829    for (size_t i = 0; i < mHandles.size(); ++i) {
5830        sp<EffectHandle> handle = mHandles[i].promote();
5831        if (handle != 0) {
5832            handle->dump(buffer, SIZE);
5833            result.append(buffer);
5834        }
5835    }
5836
5837    result.append("\n");
5838
5839    write(fd, result.string(), result.length());
5840
5841    if (locked) {
5842        mLock.unlock();
5843    }
5844
5845    return NO_ERROR;
5846}
5847
5848// ----------------------------------------------------------------------------
5849//  EffectHandle implementation
5850// ----------------------------------------------------------------------------
5851
5852#undef LOG_TAG
5853#define LOG_TAG "AudioFlinger::EffectHandle"
5854
5855AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5856                                        const sp<AudioFlinger::Client>& client,
5857                                        const sp<IEffectClient>& effectClient,
5858                                        int32_t priority)
5859    : BnEffect(),
5860    mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5861{
5862    LOGV("constructor %p", this);
5863
5864    int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5865    mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5866    if (mCblkMemory != 0) {
5867        mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5868
5869        if (mCblk) {
5870            new(mCblk) effect_param_cblk_t();
5871            mBuffer = (uint8_t *)mCblk + bufOffset;
5872         }
5873    } else {
5874        LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5875        return;
5876    }
5877}
5878
5879AudioFlinger::EffectHandle::~EffectHandle()
5880{
5881    LOGV("Destructor %p", this);
5882    disconnect();
5883}
5884
5885status_t AudioFlinger::EffectHandle::enable()
5886{
5887    if (!mHasControl) return INVALID_OPERATION;
5888    if (mEffect == 0) return DEAD_OBJECT;
5889
5890    return mEffect->setEnabled(true);
5891}
5892
5893status_t AudioFlinger::EffectHandle::disable()
5894{
5895    if (!mHasControl) return INVALID_OPERATION;
5896    if (mEffect == NULL) return DEAD_OBJECT;
5897
5898    return mEffect->setEnabled(false);
5899}
5900
5901void AudioFlinger::EffectHandle::disconnect()
5902{
5903    if (mEffect == 0) {
5904        return;
5905    }
5906    mEffect->disconnect(this);
5907    // release sp on module => module destructor can be called now
5908    mEffect.clear();
5909    if (mCblk) {
5910        mCblk->~effect_param_cblk_t();   // destroy our shared-structure.
5911    }
5912    mCblkMemory.clear();            // and free the shared memory
5913    if (mClient != 0) {
5914        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5915        mClient.clear();
5916    }
5917}
5918
5919status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
5920                                             uint32_t cmdSize,
5921                                             void *pCmdData,
5922                                             uint32_t *replySize,
5923                                             void *pReplyData)
5924{
5925//    LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
5926//              cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
5927
5928    // only get parameter command is permitted for applications not controlling the effect
5929    if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5930        return INVALID_OPERATION;
5931    }
5932    if (mEffect == 0) return DEAD_OBJECT;
5933
5934    // handle commands that are not forwarded transparently to effect engine
5935    if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5936        // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5937        // no risk to block the whole media server process or mixer threads is we are stuck here
5938        Mutex::Autolock _l(mCblk->lock);
5939        if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5940            mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5941            mCblk->serverIndex = 0;
5942            mCblk->clientIndex = 0;
5943            return BAD_VALUE;
5944        }
5945        status_t status = NO_ERROR;
5946        while (mCblk->serverIndex < mCblk->clientIndex) {
5947            int reply;
5948            uint32_t rsize = sizeof(int);
5949            int *p = (int *)(mBuffer + mCblk->serverIndex);
5950            int size = *p++;
5951            if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
5952                LOGW("command(): invalid parameter block size");
5953                break;
5954            }
5955            effect_param_t *param = (effect_param_t *)p;
5956            if (param->psize == 0 || param->vsize == 0) {
5957                LOGW("command(): null parameter or value size");
5958                mCblk->serverIndex += size;
5959                continue;
5960            }
5961            uint32_t psize = sizeof(effect_param_t) +
5962                             ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
5963                             param->vsize;
5964            status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
5965                                            psize,
5966                                            p,
5967                                            &rsize,
5968                                            &reply);
5969            if (ret == NO_ERROR) {
5970                if (reply != NO_ERROR) {
5971                    status = reply;
5972                }
5973            } else {
5974                status = ret;
5975            }
5976            mCblk->serverIndex += size;
5977        }
5978        mCblk->serverIndex = 0;
5979        mCblk->clientIndex = 0;
5980        return status;
5981    } else if (cmdCode == EFFECT_CMD_ENABLE) {
5982        return enable();
5983    } else if (cmdCode == EFFECT_CMD_DISABLE) {
5984        return disable();
5985    }
5986
5987    return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5988}
5989
5990sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
5991    return mCblkMemory;
5992}
5993
5994void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
5995{
5996    LOGV("setControl %p control %d", this, hasControl);
5997
5998    mHasControl = hasControl;
5999    if (signal && mEffectClient != 0) {
6000        mEffectClient->controlStatusChanged(hasControl);
6001    }
6002}
6003
6004void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6005                                                 uint32_t cmdSize,
6006                                                 void *pCmdData,
6007                                                 uint32_t replySize,
6008                                                 void *pReplyData)
6009{
6010    if (mEffectClient != 0) {
6011        mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6012    }
6013}
6014
6015
6016
6017void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6018{
6019    if (mEffectClient != 0) {
6020        mEffectClient->enableStatusChanged(enabled);
6021    }
6022}
6023
6024status_t AudioFlinger::EffectHandle::onTransact(
6025    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6026{
6027    return BnEffect::onTransact(code, data, reply, flags);
6028}
6029
6030
6031void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6032{
6033    bool locked = tryLock(mCblk->lock);
6034
6035    snprintf(buffer, size, "\t\t\t%05d %05d    %01u    %01u      %05u  %05u\n",
6036            (mClient == NULL) ? getpid() : mClient->pid(),
6037            mPriority,
6038            mHasControl,
6039            !locked,
6040            mCblk->clientIndex,
6041            mCblk->serverIndex
6042            );
6043
6044    if (locked) {
6045        mCblk->lock.unlock();
6046    }
6047}
6048
6049#undef LOG_TAG
6050#define LOG_TAG "AudioFlinger::EffectChain"
6051
6052AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6053                                        int sessionId)
6054    : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mOwnInBuffer(false),
6055            mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6056            mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
6057{
6058    mStrategy = AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
6059}
6060
6061AudioFlinger::EffectChain::~EffectChain()
6062{
6063    if (mOwnInBuffer) {
6064        delete mInBuffer;
6065    }
6066
6067}
6068
6069// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6070sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
6071{
6072    sp<EffectModule> effect;
6073    size_t size = mEffects.size();
6074
6075    for (size_t i = 0; i < size; i++) {
6076        if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6077            effect = mEffects[i];
6078            break;
6079        }
6080    }
6081    return effect;
6082}
6083
6084// getEffectFromId_l() must be called with PlaybackThread::mLock held
6085sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
6086{
6087    sp<EffectModule> effect;
6088    size_t size = mEffects.size();
6089
6090    for (size_t i = 0; i < size; i++) {
6091        // by convention, return first effect if id provided is 0 (0 is never a valid id)
6092        if (id == 0 || mEffects[i]->id() == id) {
6093            effect = mEffects[i];
6094            break;
6095        }
6096    }
6097    return effect;
6098}
6099
6100// Must be called with EffectChain::mLock locked
6101void AudioFlinger::EffectChain::process_l()
6102{
6103    size_t size = mEffects.size();
6104    for (size_t i = 0; i < size; i++) {
6105        mEffects[i]->process();
6106    }
6107    for (size_t i = 0; i < size; i++) {
6108        mEffects[i]->updateState();
6109    }
6110    // if no track is active, input buffer must be cleared here as the mixer process
6111    // will not do it
6112    if (mSessionId > 0 && activeTracks() == 0) {
6113        sp<ThreadBase> thread = mThread.promote();
6114        if (thread != 0) {
6115            size_t numSamples = thread->frameCount() * thread->channelCount();
6116            memset(mInBuffer, 0, numSamples * sizeof(int16_t));
6117        }
6118    }
6119}
6120
6121// addEffect_l() must be called with PlaybackThread::mLock held
6122status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
6123{
6124    effect_descriptor_t desc = effect->desc();
6125    uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6126
6127    Mutex::Autolock _l(mLock);
6128    effect->setChain(this);
6129    sp<ThreadBase> thread = mThread.promote();
6130    if (thread == 0) {
6131        return NO_INIT;
6132    }
6133    effect->setThread(thread);
6134
6135    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6136        // Auxiliary effects are inserted at the beginning of mEffects vector as
6137        // they are processed first and accumulated in chain input buffer
6138        mEffects.insertAt(effect, 0);
6139
6140        // the input buffer for auxiliary effect contains mono samples in
6141        // 32 bit format. This is to avoid saturation in AudoMixer
6142        // accumulation stage. Saturation is done in EffectModule::process() before
6143        // calling the process in effect engine
6144        size_t numSamples = thread->frameCount();
6145        int32_t *buffer = new int32_t[numSamples];
6146        memset(buffer, 0, numSamples * sizeof(int32_t));
6147        effect->setInBuffer((int16_t *)buffer);
6148        // auxiliary effects output samples to chain input buffer for further processing
6149        // by insert effects
6150        effect->setOutBuffer(mInBuffer);
6151    } else {
6152        // Insert effects are inserted at the end of mEffects vector as they are processed
6153        //  after track and auxiliary effects.
6154        // Insert effect order as a function of indicated preference:
6155        //  if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6156        //  another effect is present
6157        //  else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6158        //  last effect claiming first position
6159        //  else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6160        //  first effect claiming last position
6161        //  else if EFFECT_FLAG_INSERT_ANY insert after first or before last
6162        // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6163        // already present
6164
6165        int size = (int)mEffects.size();
6166        int idx_insert = size;
6167        int idx_insert_first = -1;
6168        int idx_insert_last = -1;
6169
6170        for (int i = 0; i < size; i++) {
6171            effect_descriptor_t d = mEffects[i]->desc();
6172            uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6173            uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6174            if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6175                // check invalid effect chaining combinations
6176                if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
6177                    iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
6178                    LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
6179                    return INVALID_OPERATION;
6180                }
6181                // remember position of first insert effect and by default
6182                // select this as insert position for new effect
6183                if (idx_insert == size) {
6184                    idx_insert = i;
6185                }
6186                // remember position of last insert effect claiming
6187                // first position
6188                if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6189                    idx_insert_first = i;
6190                }
6191                // remember position of first insert effect claiming
6192                // last position
6193                if (iPref == EFFECT_FLAG_INSERT_LAST &&
6194                    idx_insert_last == -1) {
6195                    idx_insert_last = i;
6196                }
6197            }
6198        }
6199
6200        // modify idx_insert from first position if needed
6201        if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6202            if (idx_insert_last != -1) {
6203                idx_insert = idx_insert_last;
6204            } else {
6205                idx_insert = size;
6206            }
6207        } else {
6208            if (idx_insert_first != -1) {
6209                idx_insert = idx_insert_first + 1;
6210            }
6211        }
6212
6213        // always read samples from chain input buffer
6214        effect->setInBuffer(mInBuffer);
6215
6216        // if last effect in the chain, output samples to chain
6217        // output buffer, otherwise to chain input buffer
6218        if (idx_insert == size) {
6219            if (idx_insert != 0) {
6220                mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6221                mEffects[idx_insert-1]->configure();
6222            }
6223            effect->setOutBuffer(mOutBuffer);
6224        } else {
6225            effect->setOutBuffer(mInBuffer);
6226        }
6227        mEffects.insertAt(effect, idx_insert);
6228
6229        LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
6230    }
6231    effect->configure();
6232    return NO_ERROR;
6233}
6234
6235// removeEffect_l() must be called with PlaybackThread::mLock held
6236size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
6237{
6238    Mutex::Autolock _l(mLock);
6239    int size = (int)mEffects.size();
6240    int i;
6241    uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6242
6243    for (i = 0; i < size; i++) {
6244        if (effect == mEffects[i]) {
6245            if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6246                delete[] effect->inBuffer();
6247            } else {
6248                if (i == size - 1 && i != 0) {
6249                    mEffects[i - 1]->setOutBuffer(mOutBuffer);
6250                    mEffects[i - 1]->configure();
6251                }
6252            }
6253            mEffects.removeAt(i);
6254            LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
6255            break;
6256        }
6257    }
6258
6259    return mEffects.size();
6260}
6261
6262// setDevice_l() must be called with PlaybackThread::mLock held
6263void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
6264{
6265    size_t size = mEffects.size();
6266    for (size_t i = 0; i < size; i++) {
6267        mEffects[i]->setDevice(device);
6268    }
6269}
6270
6271// setMode_l() must be called with PlaybackThread::mLock held
6272void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
6273{
6274    size_t size = mEffects.size();
6275    for (size_t i = 0; i < size; i++) {
6276        mEffects[i]->setMode(mode);
6277    }
6278}
6279
6280// setVolume_l() must be called with PlaybackThread::mLock held
6281bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
6282{
6283    uint32_t newLeft = *left;
6284    uint32_t newRight = *right;
6285    bool hasControl = false;
6286    int ctrlIdx = -1;
6287    size_t size = mEffects.size();
6288
6289    // first update volume controller
6290    for (size_t i = size; i > 0; i--) {
6291        if ((mEffects[i - 1]->state() >= EffectModule::ACTIVE) &&
6292            (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6293            ctrlIdx = i - 1;
6294            hasControl = true;
6295            break;
6296        }
6297    }
6298
6299    if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
6300        if (hasControl) {
6301            *left = mNewLeftVolume;
6302            *right = mNewRightVolume;
6303        }
6304        return hasControl;
6305    }
6306
6307    if (mVolumeCtrlIdx != -1) {
6308        hasControl = true;
6309    }
6310    mVolumeCtrlIdx = ctrlIdx;
6311    mLeftVolume = newLeft;
6312    mRightVolume = newRight;
6313
6314    // second get volume update from volume controller
6315    if (ctrlIdx >= 0) {
6316        mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
6317        mNewLeftVolume = newLeft;
6318        mNewRightVolume = newRight;
6319    }
6320    // then indicate volume to all other effects in chain.
6321    // Pass altered volume to effects before volume controller
6322    // and requested volume to effects after controller
6323    uint32_t lVol = newLeft;
6324    uint32_t rVol = newRight;
6325
6326    for (size_t i = 0; i < size; i++) {
6327        if ((int)i == ctrlIdx) continue;
6328        // this also works for ctrlIdx == -1 when there is no volume controller
6329        if ((int)i > ctrlIdx) {
6330            lVol = *left;
6331            rVol = *right;
6332        }
6333        mEffects[i]->setVolume(&lVol, &rVol, false);
6334    }
6335    *left = newLeft;
6336    *right = newRight;
6337
6338    return hasControl;
6339}
6340
6341status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6342{
6343    const size_t SIZE = 256;
6344    char buffer[SIZE];
6345    String8 result;
6346
6347    snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6348    result.append(buffer);
6349
6350    bool locked = tryLock(mLock);
6351    // failed to lock - AudioFlinger is probably deadlocked
6352    if (!locked) {
6353        result.append("\tCould not lock mutex:\n");
6354    }
6355
6356    result.append("\tNum fx In buffer   Out buffer   Active tracks:\n");
6357    snprintf(buffer, SIZE, "\t%02d     0x%08x  0x%08x   %d\n",
6358            mEffects.size(),
6359            (uint32_t)mInBuffer,
6360            (uint32_t)mOutBuffer,
6361            mActiveTrackCnt);
6362    result.append(buffer);
6363    write(fd, result.string(), result.size());
6364
6365    for (size_t i = 0; i < mEffects.size(); ++i) {
6366        sp<EffectModule> effect = mEffects[i];
6367        if (effect != 0) {
6368            effect->dump(fd, args);
6369        }
6370    }
6371
6372    if (locked) {
6373        mLock.unlock();
6374    }
6375
6376    return NO_ERROR;
6377}
6378
6379#undef LOG_TAG
6380#define LOG_TAG "AudioFlinger"
6381
6382// ----------------------------------------------------------------------------
6383
6384status_t AudioFlinger::onTransact(
6385        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6386{
6387    return BnAudioFlinger::onTransact(code, data, reply, flags);
6388}
6389
6390}; // namespace android
6391