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