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