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