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