AudioFlinger.cpp revision 435dbe6c3ecd04bcb4bd80584064e287ebccd720
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() const
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    mixer_state 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
2088AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2089        const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2090{
2091
2092    mixer_state mixerStatus = MIXER_IDLE;
2093    // find out which tracks need to be processed
2094    size_t count = activeTracks.size();
2095    size_t mixedTracks = 0;
2096    size_t tracksWithEffect = 0;
2097
2098    float masterVolume = mMasterVolume;
2099    bool  masterMute = mMasterMute;
2100
2101    if (masterMute) {
2102        masterVolume = 0;
2103    }
2104    // Delegate master volume control to effect in output mix effect chain if needed
2105    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2106    if (chain != 0) {
2107        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2108        chain->setVolume_l(&v, &v);
2109        masterVolume = (float)((v + (1 << 23)) >> 24);
2110        chain.clear();
2111    }
2112
2113    for (size_t i=0 ; i<count ; i++) {
2114        sp<Track> t = activeTracks[i].promote();
2115        if (t == 0) continue;
2116
2117        // this const just means the local variable doesn't change
2118        Track* const track = t.get();
2119        audio_track_cblk_t* cblk = track->cblk();
2120
2121        // The first time a track is added we wait
2122        // for all its buffers to be filled before processing it
2123        int name = track->name();
2124        // make sure that we have enough frames to mix one full buffer.
2125        // enforce this condition only once to enable draining the buffer in case the client
2126        // app does not call stop() and relies on underrun to stop:
2127        // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2128        // during last round
2129        uint32_t minFrames = 1;
2130        if (!track->isStopped() && !track->isPausing() &&
2131                (mPrevMixerStatus == MIXER_TRACKS_READY)) {
2132            if (t->sampleRate() == (int)mSampleRate) {
2133                minFrames = mFrameCount;
2134            } else {
2135                // +1 for rounding and +1 for additional sample needed for interpolation
2136                minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2137                // add frames already consumed but not yet released by the resampler
2138                // because cblk->framesReady() will  include these frames
2139                minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2140                // the minimum track buffer size is normally twice the number of frames necessary
2141                // to fill one buffer and the resampler should not leave more than one buffer worth
2142                // of unreleased frames after each pass, but just in case...
2143                ALOG_ASSERT(minFrames <= cblk->frameCount);
2144            }
2145        }
2146        if ((cblk->framesReady() >= minFrames) && track->isReady() &&
2147                !track->isPaused() && !track->isTerminated())
2148        {
2149            //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
2150
2151            mixedTracks++;
2152
2153            // track->mainBuffer() != mMixBuffer means there is an effect chain
2154            // connected to the track
2155            chain.clear();
2156            if (track->mainBuffer() != mMixBuffer) {
2157                chain = getEffectChain_l(track->sessionId());
2158                // Delegate volume control to effect in track effect chain if needed
2159                if (chain != 0) {
2160                    tracksWithEffect++;
2161                } else {
2162                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
2163                            name, track->sessionId());
2164                }
2165            }
2166
2167
2168            int param = AudioMixer::VOLUME;
2169            if (track->mFillingUpStatus == Track::FS_FILLED) {
2170                // no ramp for the first volume setting
2171                track->mFillingUpStatus = Track::FS_ACTIVE;
2172                if (track->mState == TrackBase::RESUMING) {
2173                    track->mState = TrackBase::ACTIVE;
2174                    param = AudioMixer::RAMP_VOLUME;
2175                }
2176                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
2177            } else if (cblk->server != 0) {
2178                // If the track is stopped before the first frame was mixed,
2179                // do not apply ramp
2180                param = AudioMixer::RAMP_VOLUME;
2181            }
2182
2183            // compute volume for this track
2184            uint32_t vl, vr, va;
2185            if (track->isMuted() || track->isPausing() ||
2186                mStreamTypes[track->type()].mute) {
2187                vl = vr = va = 0;
2188                if (track->isPausing()) {
2189                    track->setPaused();
2190                }
2191            } else {
2192
2193                // read original volumes with volume control
2194                float typeVolume = mStreamTypes[track->type()].volume;
2195                float v = masterVolume * typeVolume;
2196                uint32_t vlr = cblk->volumeLR;
2197                vl = vlr & 0xFFFF;
2198                vr = vlr >> 16;
2199                // track volumes come from shared memory, so can't be trusted and must be clamped
2200                if (vl > MAX_GAIN_INT) {
2201                    ALOGV("Track left volume out of range: %04X", vl);
2202                    vl = MAX_GAIN_INT;
2203                }
2204                if (vr > MAX_GAIN_INT) {
2205                    ALOGV("Track right volume out of range: %04X", vr);
2206                    vr = MAX_GAIN_INT;
2207                }
2208                // now apply the master volume and stream type volume
2209                vl = (uint32_t)(v * vl) << 12;
2210                vr = (uint32_t)(v * vr) << 12;
2211                // assuming master volume and stream type volume each go up to 1.0,
2212                // vl and vr are now in 8.24 format
2213
2214                uint16_t sendLevel = cblk->getSendLevel_U4_12();
2215                // send level comes from shared memory and so may be corrupt
2216                if (sendLevel >= MAX_GAIN_INT) {
2217                    ALOGV("Track send level out of range: %04X", sendLevel);
2218                    sendLevel = MAX_GAIN_INT;
2219                }
2220                va = (uint32_t)(v * sendLevel);
2221            }
2222            // Delegate volume control to effect in track effect chain if needed
2223            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2224                // Do not ramp volume if volume is controlled by effect
2225                param = AudioMixer::VOLUME;
2226                track->mHasVolumeController = true;
2227            } else {
2228                // force no volume ramp when volume controller was just disabled or removed
2229                // from effect chain to avoid volume spike
2230                if (track->mHasVolumeController) {
2231                    param = AudioMixer::VOLUME;
2232                }
2233                track->mHasVolumeController = false;
2234            }
2235
2236            // Convert volumes from 8.24 to 4.12 format
2237            int16_t left, right, aux;
2238            // This additional clamping is needed in case chain->setVolume_l() overshot
2239            uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2240            if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2241            left = int16_t(v_clamped);
2242            v_clamped = (vr + (1 << 11)) >> 12;
2243            if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2244            right = int16_t(v_clamped);
2245
2246            if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2247            aux = int16_t(va);
2248
2249            // XXX: these things DON'T need to be done each time
2250            mAudioMixer->setBufferProvider(name, track);
2251            mAudioMixer->enable(name);
2252
2253            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2254            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2255            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
2256            mAudioMixer->setParameter(
2257                name,
2258                AudioMixer::TRACK,
2259                AudioMixer::FORMAT, (void *)track->format());
2260            mAudioMixer->setParameter(
2261                name,
2262                AudioMixer::TRACK,
2263                AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
2264            mAudioMixer->setParameter(
2265                name,
2266                AudioMixer::RESAMPLE,
2267                AudioMixer::SAMPLE_RATE,
2268                (void *)(cblk->sampleRate));
2269            mAudioMixer->setParameter(
2270                name,
2271                AudioMixer::TRACK,
2272                AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2273            mAudioMixer->setParameter(
2274                name,
2275                AudioMixer::TRACK,
2276                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2277
2278            // reset retry count
2279            track->mRetryCount = kMaxTrackRetries;
2280            // If one track is ready, set the mixer ready if:
2281            //  - the mixer was not ready during previous round OR
2282            //  - no other track is not ready
2283            if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2284                    mixerStatus != MIXER_TRACKS_ENABLED) {
2285                mixerStatus = MIXER_TRACKS_READY;
2286            }
2287        } else {
2288            //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
2289            if (track->isStopped()) {
2290                track->reset();
2291            }
2292            if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2293                // We have consumed all the buffers of this track.
2294                // Remove it from the list of active tracks.
2295                tracksToRemove->add(track);
2296            } else {
2297                // No buffers for this track. Give it a few chances to
2298                // fill a buffer, then remove it from active list.
2299                if (--(track->mRetryCount) <= 0) {
2300                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
2301                    tracksToRemove->add(track);
2302                    // indicate to client process that the track was disabled because of underrun
2303                    android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
2304                // If one track is not ready, mark the mixer also not ready if:
2305                //  - the mixer was ready during previous round OR
2306                //  - no other track is ready
2307                } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2308                                mixerStatus != MIXER_TRACKS_READY) {
2309                    mixerStatus = MIXER_TRACKS_ENABLED;
2310                }
2311            }
2312            mAudioMixer->disable(name);
2313        }
2314    }
2315
2316    // remove all the tracks that need to be...
2317    count = tracksToRemove->size();
2318    if (CC_UNLIKELY(count)) {
2319        for (size_t i=0 ; i<count ; i++) {
2320            const sp<Track>& track = tracksToRemove->itemAt(i);
2321            mActiveTracks.remove(track);
2322            if (track->mainBuffer() != mMixBuffer) {
2323                chain = getEffectChain_l(track->sessionId());
2324                if (chain != 0) {
2325                    ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
2326                    chain->decActiveTrackCnt();
2327                }
2328            }
2329            if (track->isTerminated()) {
2330                removeTrack_l(track);
2331            }
2332        }
2333    }
2334
2335    // mix buffer must be cleared if all tracks are connected to an
2336    // effect chain as in this case the mixer will not write to
2337    // mix buffer and track effects will accumulate into it
2338    if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2339        memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2340    }
2341
2342    mPrevMixerStatus = mixerStatus;
2343    return mixerStatus;
2344}
2345
2346void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
2347{
2348    ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2349            this,  streamType, mTracks.size());
2350    Mutex::Autolock _l(mLock);
2351
2352    size_t size = mTracks.size();
2353    for (size_t i = 0; i < size; i++) {
2354        sp<Track> t = mTracks[i];
2355        if (t->type() == streamType) {
2356            android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
2357            t->mCblk->cv.signal();
2358        }
2359    }
2360}
2361
2362void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
2363{
2364    ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2365            this,  streamType, valid);
2366    Mutex::Autolock _l(mLock);
2367
2368    mStreamTypes[streamType].valid = valid;
2369}
2370
2371// getTrackName_l() must be called with ThreadBase::mLock held
2372int AudioFlinger::MixerThread::getTrackName_l()
2373{
2374    return mAudioMixer->getTrackName();
2375}
2376
2377// deleteTrackName_l() must be called with ThreadBase::mLock held
2378void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2379{
2380    ALOGV("remove track (%d) and delete from mixer", name);
2381    mAudioMixer->deleteTrackName(name);
2382}
2383
2384// checkForNewParameters_l() must be called with ThreadBase::mLock held
2385bool AudioFlinger::MixerThread::checkForNewParameters_l()
2386{
2387    bool reconfig = false;
2388
2389    while (!mNewParameters.isEmpty()) {
2390        status_t status = NO_ERROR;
2391        String8 keyValuePair = mNewParameters[0];
2392        AudioParameter param = AudioParameter(keyValuePair);
2393        int value;
2394
2395        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2396            reconfig = true;
2397        }
2398        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
2399            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
2400                status = BAD_VALUE;
2401            } else {
2402                reconfig = true;
2403            }
2404        }
2405        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
2406            if (value != AUDIO_CHANNEL_OUT_STEREO) {
2407                status = BAD_VALUE;
2408            } else {
2409                reconfig = true;
2410            }
2411        }
2412        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2413            // do not accept frame count changes if tracks are open as the track buffer
2414            // size depends on frame count and correct behavior would not be guaranteed
2415            // if frame count is changed after track creation
2416            if (!mTracks.isEmpty()) {
2417                status = INVALID_OPERATION;
2418            } else {
2419                reconfig = true;
2420            }
2421        }
2422        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
2423            // when changing the audio output device, call addBatteryData to notify
2424            // the change
2425            if ((int)mDevice != value) {
2426                uint32_t params = 0;
2427                // check whether speaker is on
2428                if (value & AUDIO_DEVICE_OUT_SPEAKER) {
2429                    params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2430                }
2431
2432                int deviceWithoutSpeaker
2433                    = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
2434                // check if any other device (except speaker) is on
2435                if (value & deviceWithoutSpeaker ) {
2436                    params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2437                }
2438
2439                if (params != 0) {
2440                    addBatteryData(params);
2441                }
2442            }
2443
2444            // forward device change to effects that have requested to be
2445            // aware of attached audio device.
2446            mDevice = (uint32_t)value;
2447            for (size_t i = 0; i < mEffectChains.size(); i++) {
2448                mEffectChains[i]->setDevice_l(mDevice);
2449            }
2450        }
2451
2452        if (status == NO_ERROR) {
2453            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2454                                                    keyValuePair.string());
2455            if (!mStandby && status == INVALID_OPERATION) {
2456               mOutput->stream->common.standby(&mOutput->stream->common);
2457               mStandby = true;
2458               mBytesWritten = 0;
2459               status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2460                                                       keyValuePair.string());
2461            }
2462            if (status == NO_ERROR && reconfig) {
2463                delete mAudioMixer;
2464                readOutputParameters();
2465                mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2466                for (size_t i = 0; i < mTracks.size() ; i++) {
2467                    int name = getTrackName_l();
2468                    if (name < 0) break;
2469                    mTracks[i]->mName = name;
2470                    // limit track sample rate to 2 x new output sample rate
2471                    if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2472                        mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2473                    }
2474                }
2475                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2476            }
2477        }
2478
2479        mNewParameters.removeAt(0);
2480
2481        mParamStatus = status;
2482        mParamCond.signal();
2483        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2484        // already timed out waiting for the status and will never signal the condition.
2485        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
2486    }
2487    return reconfig;
2488}
2489
2490status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2491{
2492    const size_t SIZE = 256;
2493    char buffer[SIZE];
2494    String8 result;
2495
2496    PlaybackThread::dumpInternals(fd, args);
2497
2498    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2499    result.append(buffer);
2500    write(fd, result.string(), result.size());
2501    return NO_ERROR;
2502}
2503
2504uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2505{
2506    return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
2507}
2508
2509uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2510{
2511    return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2512}
2513
2514// ----------------------------------------------------------------------------
2515AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
2516    :   PlaybackThread(audioFlinger, output, id, device)
2517{
2518    mType = ThreadBase::DIRECT;
2519}
2520
2521AudioFlinger::DirectOutputThread::~DirectOutputThread()
2522{
2523}
2524
2525static inline
2526int32_t mul(int16_t in, int16_t v)
2527{
2528#if defined(__arm__) && !defined(__thumb__)
2529    int32_t out;
2530    asm( "smulbb %[out], %[in], %[v] \n"
2531         : [out]"=r"(out)
2532         : [in]"%r"(in), [v]"r"(v)
2533         : );
2534    return out;
2535#else
2536    return in * int32_t(v);
2537#endif
2538}
2539
2540void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2541{
2542    // Do not apply volume on compressed audio
2543    if (!audio_is_linear_pcm(mFormat)) {
2544        return;
2545    }
2546
2547    // convert to signed 16 bit before volume calculation
2548    if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2549        size_t count = mFrameCount * mChannelCount;
2550        uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2551        int16_t *dst = mMixBuffer + count-1;
2552        while(count--) {
2553            *dst-- = (int16_t)(*src--^0x80) << 8;
2554        }
2555    }
2556
2557    size_t frameCount = mFrameCount;
2558    int16_t *out = mMixBuffer;
2559    if (ramp) {
2560        if (mChannelCount == 1) {
2561            int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2562            int32_t vlInc = d / (int32_t)frameCount;
2563            int32_t vl = ((int32_t)mLeftVolShort << 16);
2564            do {
2565                out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2566                out++;
2567                vl += vlInc;
2568            } while (--frameCount);
2569
2570        } else {
2571            int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2572            int32_t vlInc = d / (int32_t)frameCount;
2573            d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2574            int32_t vrInc = d / (int32_t)frameCount;
2575            int32_t vl = ((int32_t)mLeftVolShort << 16);
2576            int32_t vr = ((int32_t)mRightVolShort << 16);
2577            do {
2578                out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2579                out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2580                out += 2;
2581                vl += vlInc;
2582                vr += vrInc;
2583            } while (--frameCount);
2584        }
2585    } else {
2586        if (mChannelCount == 1) {
2587            do {
2588                out[0] = clamp16(mul(out[0], leftVol) >> 12);
2589                out++;
2590            } while (--frameCount);
2591        } else {
2592            do {
2593                out[0] = clamp16(mul(out[0], leftVol) >> 12);
2594                out[1] = clamp16(mul(out[1], rightVol) >> 12);
2595                out += 2;
2596            } while (--frameCount);
2597        }
2598    }
2599
2600    // convert back to unsigned 8 bit after volume calculation
2601    if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2602        size_t count = mFrameCount * mChannelCount;
2603        int16_t *src = mMixBuffer;
2604        uint8_t *dst = (uint8_t *)mMixBuffer;
2605        while(count--) {
2606            *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2607        }
2608    }
2609
2610    mLeftVolShort = leftVol;
2611    mRightVolShort = rightVol;
2612}
2613
2614bool AudioFlinger::DirectOutputThread::threadLoop()
2615{
2616    mixer_state mixerStatus = MIXER_IDLE;
2617    sp<Track> trackToRemove;
2618    sp<Track> activeTrack;
2619    nsecs_t standbyTime = systemTime();
2620    int8_t *curBuf;
2621    size_t mixBufferSize = mFrameCount*mFrameSize;
2622    uint32_t activeSleepTime = activeSleepTimeUs();
2623    uint32_t idleSleepTime = idleSleepTimeUs();
2624    uint32_t sleepTime = idleSleepTime;
2625    // use shorter standby delay as on normal output to release
2626    // hardware resources as soon as possible
2627    nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2628
2629    acquireWakeLock();
2630
2631    while (!exitPending())
2632    {
2633        bool rampVolume;
2634        uint16_t leftVol;
2635        uint16_t rightVol;
2636        Vector< sp<EffectChain> > effectChains;
2637
2638        processConfigEvents();
2639
2640        mixerStatus = MIXER_IDLE;
2641
2642        { // scope for the mLock
2643
2644            Mutex::Autolock _l(mLock);
2645
2646            if (checkForNewParameters_l()) {
2647                mixBufferSize = mFrameCount*mFrameSize;
2648                activeSleepTime = activeSleepTimeUs();
2649                idleSleepTime = idleSleepTimeUs();
2650                standbyDelay = microseconds(activeSleepTime*2);
2651            }
2652
2653            // put audio hardware into standby after short delay
2654            if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2655                        mSuspended)) {
2656                // wait until we have something to do...
2657                if (!mStandby) {
2658                    ALOGV("Audio hardware entering standby, mixer %p\n", this);
2659                    mOutput->stream->common.standby(&mOutput->stream->common);
2660                    mStandby = true;
2661                    mBytesWritten = 0;
2662                }
2663
2664                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2665                    // we're about to wait, flush the binder command buffer
2666                    IPCThreadState::self()->flushCommands();
2667
2668                    if (exitPending()) break;
2669
2670                    releaseWakeLock_l();
2671                    ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2672                    mWaitWorkCV.wait(mLock);
2673                    ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2674                    acquireWakeLock_l();
2675
2676                    if (!mMasterMute) {
2677                        char value[PROPERTY_VALUE_MAX];
2678                        property_get("ro.audio.silent", value, "0");
2679                        if (atoi(value)) {
2680                            ALOGD("Silence is golden");
2681                            setMasterMute(true);
2682                        }
2683                    }
2684
2685                    standbyTime = systemTime() + standbyDelay;
2686                    sleepTime = idleSleepTime;
2687                    continue;
2688                }
2689            }
2690
2691            effectChains = mEffectChains;
2692
2693            // find out which tracks need to be processed
2694            if (mActiveTracks.size() != 0) {
2695                sp<Track> t = mActiveTracks[0].promote();
2696                if (t == 0) continue;
2697
2698                Track* const track = t.get();
2699                audio_track_cblk_t* cblk = track->cblk();
2700
2701                // The first time a track is added we wait
2702                // for all its buffers to be filled before processing it
2703                if (cblk->framesReady() && track->isReady() &&
2704                        !track->isPaused() && !track->isTerminated())
2705                {
2706                    //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2707
2708                    if (track->mFillingUpStatus == Track::FS_FILLED) {
2709                        track->mFillingUpStatus = Track::FS_ACTIVE;
2710                        mLeftVolFloat = mRightVolFloat = 0;
2711                        mLeftVolShort = mRightVolShort = 0;
2712                        if (track->mState == TrackBase::RESUMING) {
2713                            track->mState = TrackBase::ACTIVE;
2714                            rampVolume = true;
2715                        }
2716                    } else if (cblk->server != 0) {
2717                        // If the track is stopped before the first frame was mixed,
2718                        // do not apply ramp
2719                        rampVolume = true;
2720                    }
2721                    // compute volume for this track
2722                    float left, right;
2723                    if (track->isMuted() || mMasterMute || track->isPausing() ||
2724                        mStreamTypes[track->type()].mute) {
2725                        left = right = 0;
2726                        if (track->isPausing()) {
2727                            track->setPaused();
2728                        }
2729                    } else {
2730                        float typeVolume = mStreamTypes[track->type()].volume;
2731                        float v = mMasterVolume * typeVolume;
2732                        uint32_t vlr = cblk->volumeLR;
2733                        float v_clamped = v * (vlr & 0xFFFF);
2734                        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2735                        left = v_clamped/MAX_GAIN;
2736                        v_clamped = v * (vlr >> 16);
2737                        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2738                        right = v_clamped/MAX_GAIN;
2739                    }
2740
2741                    if (left != mLeftVolFloat || right != mRightVolFloat) {
2742                        mLeftVolFloat = left;
2743                        mRightVolFloat = right;
2744
2745                        // If audio HAL implements volume control,
2746                        // force software volume to nominal value
2747                        if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2748                            left = 1.0f;
2749                            right = 1.0f;
2750                        }
2751
2752                        // Convert volumes from float to 8.24
2753                        uint32_t vl = (uint32_t)(left * (1 << 24));
2754                        uint32_t vr = (uint32_t)(right * (1 << 24));
2755
2756                        // Delegate volume control to effect in track effect chain if needed
2757                        // only one effect chain can be present on DirectOutputThread, so if
2758                        // there is one, the track is connected to it
2759                        if (!effectChains.isEmpty()) {
2760                            // Do not ramp volume if volume is controlled by effect
2761                            if(effectChains[0]->setVolume_l(&vl, &vr)) {
2762                                rampVolume = false;
2763                            }
2764                        }
2765
2766                        // Convert volumes from 8.24 to 4.12 format
2767                        uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2768                        if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2769                        leftVol = (uint16_t)v_clamped;
2770                        v_clamped = (vr + (1 << 11)) >> 12;
2771                        if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2772                        rightVol = (uint16_t)v_clamped;
2773                    } else {
2774                        leftVol = mLeftVolShort;
2775                        rightVol = mRightVolShort;
2776                        rampVolume = false;
2777                    }
2778
2779                    // reset retry count
2780                    track->mRetryCount = kMaxTrackRetriesDirect;
2781                    activeTrack = t;
2782                    mixerStatus = MIXER_TRACKS_READY;
2783                } else {
2784                    //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2785                    if (track->isStopped()) {
2786                        track->reset();
2787                    }
2788                    if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2789                        // We have consumed all the buffers of this track.
2790                        // Remove it from the list of active tracks.
2791                        trackToRemove = track;
2792                    } else {
2793                        // No buffers for this track. Give it a few chances to
2794                        // fill a buffer, then remove it from active list.
2795                        if (--(track->mRetryCount) <= 0) {
2796                            ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2797                            trackToRemove = track;
2798                        } else {
2799                            mixerStatus = MIXER_TRACKS_ENABLED;
2800                        }
2801                    }
2802                }
2803            }
2804
2805            // remove all the tracks that need to be...
2806            if (CC_UNLIKELY(trackToRemove != 0)) {
2807                mActiveTracks.remove(trackToRemove);
2808                if (!effectChains.isEmpty()) {
2809                    ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2810                            trackToRemove->sessionId());
2811                    effectChains[0]->decActiveTrackCnt();
2812                }
2813                if (trackToRemove->isTerminated()) {
2814                    removeTrack_l(trackToRemove);
2815                }
2816            }
2817
2818            lockEffectChains_l(effectChains);
2819       }
2820
2821        if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2822            AudioBufferProvider::Buffer buffer;
2823            size_t frameCount = mFrameCount;
2824            curBuf = (int8_t *)mMixBuffer;
2825            // output audio to hardware
2826            while (frameCount) {
2827                buffer.frameCount = frameCount;
2828                activeTrack->getNextBuffer(&buffer);
2829                if (CC_UNLIKELY(buffer.raw == NULL)) {
2830                    memset(curBuf, 0, frameCount * mFrameSize);
2831                    break;
2832                }
2833                memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2834                frameCount -= buffer.frameCount;
2835                curBuf += buffer.frameCount * mFrameSize;
2836                activeTrack->releaseBuffer(&buffer);
2837            }
2838            sleepTime = 0;
2839            standbyTime = systemTime() + standbyDelay;
2840        } else {
2841            if (sleepTime == 0) {
2842                if (mixerStatus == MIXER_TRACKS_ENABLED) {
2843                    sleepTime = activeSleepTime;
2844                } else {
2845                    sleepTime = idleSleepTime;
2846                }
2847            } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
2848                memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2849                sleepTime = 0;
2850            }
2851        }
2852
2853        if (mSuspended) {
2854            sleepTime = suspendSleepTimeUs();
2855        }
2856        // sleepTime == 0 means we must write to audio hardware
2857        if (sleepTime == 0) {
2858            if (mixerStatus == MIXER_TRACKS_READY) {
2859                applyVolume(leftVol, rightVol, rampVolume);
2860            }
2861            for (size_t i = 0; i < effectChains.size(); i ++) {
2862                effectChains[i]->process_l();
2863            }
2864            unlockEffectChains(effectChains);
2865
2866            mLastWriteTime = systemTime();
2867            mInWrite = true;
2868            mBytesWritten += mixBufferSize;
2869            int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2870            if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2871            mNumWrites++;
2872            mInWrite = false;
2873            mStandby = false;
2874        } else {
2875            unlockEffectChains(effectChains);
2876            usleep(sleepTime);
2877        }
2878
2879        // finally let go of removed track, without the lock held
2880        // since we can't guarantee the destructors won't acquire that
2881        // same lock.
2882        trackToRemove.clear();
2883        activeTrack.clear();
2884
2885        // Effect chains will be actually deleted here if they were removed from
2886        // mEffectChains list during mixing or effects processing
2887        effectChains.clear();
2888    }
2889
2890    if (!mStandby) {
2891        mOutput->stream->common.standby(&mOutput->stream->common);
2892    }
2893
2894    releaseWakeLock();
2895
2896    ALOGV("DirectOutputThread %p exiting", this);
2897    return false;
2898}
2899
2900// getTrackName_l() must be called with ThreadBase::mLock held
2901int AudioFlinger::DirectOutputThread::getTrackName_l()
2902{
2903    return 0;
2904}
2905
2906// deleteTrackName_l() must be called with ThreadBase::mLock held
2907void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2908{
2909}
2910
2911// checkForNewParameters_l() must be called with ThreadBase::mLock held
2912bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2913{
2914    bool reconfig = false;
2915
2916    while (!mNewParameters.isEmpty()) {
2917        status_t status = NO_ERROR;
2918        String8 keyValuePair = mNewParameters[0];
2919        AudioParameter param = AudioParameter(keyValuePair);
2920        int value;
2921
2922        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2923            // do not accept frame count changes if tracks are open as the track buffer
2924            // size depends on frame count and correct behavior would not be garantied
2925            // if frame count is changed after track creation
2926            if (!mTracks.isEmpty()) {
2927                status = INVALID_OPERATION;
2928            } else {
2929                reconfig = true;
2930            }
2931        }
2932        if (status == NO_ERROR) {
2933            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2934                                                    keyValuePair.string());
2935            if (!mStandby && status == INVALID_OPERATION) {
2936               mOutput->stream->common.standby(&mOutput->stream->common);
2937               mStandby = true;
2938               mBytesWritten = 0;
2939               status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2940                                                       keyValuePair.string());
2941            }
2942            if (status == NO_ERROR && reconfig) {
2943                readOutputParameters();
2944                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2945            }
2946        }
2947
2948        mNewParameters.removeAt(0);
2949
2950        mParamStatus = status;
2951        mParamCond.signal();
2952        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2953        // already timed out waiting for the status and will never signal the condition.
2954        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
2955    }
2956    return reconfig;
2957}
2958
2959uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2960{
2961    uint32_t time;
2962    if (audio_is_linear_pcm(mFormat)) {
2963        time = PlaybackThread::activeSleepTimeUs();
2964    } else {
2965        time = 10000;
2966    }
2967    return time;
2968}
2969
2970uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2971{
2972    uint32_t time;
2973    if (audio_is_linear_pcm(mFormat)) {
2974        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
2975    } else {
2976        time = 10000;
2977    }
2978    return time;
2979}
2980
2981uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2982{
2983    uint32_t time;
2984    if (audio_is_linear_pcm(mFormat)) {
2985        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2986    } else {
2987        time = 10000;
2988    }
2989    return time;
2990}
2991
2992
2993// ----------------------------------------------------------------------------
2994
2995AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2996    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2997{
2998    mType = ThreadBase::DUPLICATING;
2999    addOutputTrack(mainThread);
3000}
3001
3002AudioFlinger::DuplicatingThread::~DuplicatingThread()
3003{
3004    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3005        mOutputTracks[i]->destroy();
3006    }
3007    mOutputTracks.clear();
3008}
3009
3010bool AudioFlinger::DuplicatingThread::threadLoop()
3011{
3012    Vector< sp<Track> > tracksToRemove;
3013    mixer_state mixerStatus = MIXER_IDLE;
3014    nsecs_t standbyTime = systemTime();
3015    size_t mixBufferSize = mFrameCount*mFrameSize;
3016    SortedVector< sp<OutputTrack> > outputTracks;
3017    uint32_t writeFrames = 0;
3018    uint32_t activeSleepTime = activeSleepTimeUs();
3019    uint32_t idleSleepTime = idleSleepTimeUs();
3020    uint32_t sleepTime = idleSleepTime;
3021    Vector< sp<EffectChain> > effectChains;
3022
3023    acquireWakeLock();
3024
3025    while (!exitPending())
3026    {
3027        processConfigEvents();
3028
3029        mixerStatus = MIXER_IDLE;
3030        { // scope for the mLock
3031
3032            Mutex::Autolock _l(mLock);
3033
3034            if (checkForNewParameters_l()) {
3035                mixBufferSize = mFrameCount*mFrameSize;
3036                updateWaitTime();
3037                activeSleepTime = activeSleepTimeUs();
3038                idleSleepTime = idleSleepTimeUs();
3039            }
3040
3041            const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3042
3043            for (size_t i = 0; i < mOutputTracks.size(); i++) {
3044                outputTracks.add(mOutputTracks[i]);
3045            }
3046
3047            // put audio hardware into standby after short delay
3048            if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3049                         mSuspended)) {
3050                if (!mStandby) {
3051                    for (size_t i = 0; i < outputTracks.size(); i++) {
3052                        outputTracks[i]->stop();
3053                    }
3054                    mStandby = true;
3055                    mBytesWritten = 0;
3056                }
3057
3058                if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3059                    // we're about to wait, flush the binder command buffer
3060                    IPCThreadState::self()->flushCommands();
3061                    outputTracks.clear();
3062
3063                    if (exitPending()) break;
3064
3065                    releaseWakeLock_l();
3066                    ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
3067                    mWaitWorkCV.wait(mLock);
3068                    ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
3069                    acquireWakeLock_l();
3070
3071                    mPrevMixerStatus = MIXER_IDLE;
3072                    if (!mMasterMute) {
3073                        char value[PROPERTY_VALUE_MAX];
3074                        property_get("ro.audio.silent", value, "0");
3075                        if (atoi(value)) {
3076                            ALOGD("Silence is golden");
3077                            setMasterMute(true);
3078                        }
3079                    }
3080
3081                    standbyTime = systemTime() + kStandbyTimeInNsecs;
3082                    sleepTime = idleSleepTime;
3083                    continue;
3084                }
3085            }
3086
3087            mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3088
3089            // prevent any changes in effect chain list and in each effect chain
3090            // during mixing and effect process as the audio buffers could be deleted
3091            // or modified if an effect is created or deleted
3092            lockEffectChains_l(effectChains);
3093        }
3094
3095        if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
3096            // mix buffers...
3097            if (outputsReady(outputTracks)) {
3098                mAudioMixer->process();
3099            } else {
3100                memset(mMixBuffer, 0, mixBufferSize);
3101            }
3102            sleepTime = 0;
3103            writeFrames = mFrameCount;
3104        } else {
3105            if (sleepTime == 0) {
3106                if (mixerStatus == MIXER_TRACKS_ENABLED) {
3107                    sleepTime = activeSleepTime;
3108                } else {
3109                    sleepTime = idleSleepTime;
3110                }
3111            } else if (mBytesWritten != 0) {
3112                // flush remaining overflow buffers in output tracks
3113                for (size_t i = 0; i < outputTracks.size(); i++) {
3114                    if (outputTracks[i]->isActive()) {
3115                        sleepTime = 0;
3116                        writeFrames = 0;
3117                        memset(mMixBuffer, 0, mixBufferSize);
3118                        break;
3119                    }
3120                }
3121            }
3122        }
3123
3124        if (mSuspended) {
3125            sleepTime = suspendSleepTimeUs();
3126        }
3127        // sleepTime == 0 means we must write to audio hardware
3128        if (sleepTime == 0) {
3129            for (size_t i = 0; i < effectChains.size(); i ++) {
3130                effectChains[i]->process_l();
3131            }
3132            // enable changes in effect chain
3133            unlockEffectChains(effectChains);
3134
3135            standbyTime = systemTime() + kStandbyTimeInNsecs;
3136            for (size_t i = 0; i < outputTracks.size(); i++) {
3137                outputTracks[i]->write(mMixBuffer, writeFrames);
3138            }
3139            mStandby = false;
3140            mBytesWritten += mixBufferSize;
3141        } else {
3142            // enable changes in effect chain
3143            unlockEffectChains(effectChains);
3144            usleep(sleepTime);
3145        }
3146
3147        // finally let go of all our tracks, without the lock held
3148        // since we can't guarantee the destructors won't acquire that
3149        // same lock.
3150        tracksToRemove.clear();
3151        outputTracks.clear();
3152
3153        // Effect chains will be actually deleted here if they were removed from
3154        // mEffectChains list during mixing or effects processing
3155        effectChains.clear();
3156    }
3157
3158    releaseWakeLock();
3159
3160    return false;
3161}
3162
3163void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3164{
3165    int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3166    OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3167                                            this,
3168                                            mSampleRate,
3169                                            mFormat,
3170                                            mChannelMask,
3171                                            frameCount);
3172    if (outputTrack->cblk() != NULL) {
3173        thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
3174        mOutputTracks.add(outputTrack);
3175        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3176        updateWaitTime();
3177    }
3178}
3179
3180void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3181{
3182    Mutex::Autolock _l(mLock);
3183    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3184        if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3185            mOutputTracks[i]->destroy();
3186            mOutputTracks.removeAt(i);
3187            updateWaitTime();
3188            return;
3189        }
3190    }
3191    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3192}
3193
3194void AudioFlinger::DuplicatingThread::updateWaitTime()
3195{
3196    mWaitTimeMs = UINT_MAX;
3197    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3198        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3199        if (strong != NULL) {
3200            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3201            if (waitTimeMs < mWaitTimeMs) {
3202                mWaitTimeMs = waitTimeMs;
3203            }
3204        }
3205    }
3206}
3207
3208
3209bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3210{
3211    for (size_t i = 0; i < outputTracks.size(); i++) {
3212        sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3213        if (thread == 0) {
3214            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3215            return false;
3216        }
3217        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3218        if (playbackThread->standby() && !playbackThread->isSuspended()) {
3219            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3220            return false;
3221        }
3222    }
3223    return true;
3224}
3225
3226uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3227{
3228    return (mWaitTimeMs * 1000) / 2;
3229}
3230
3231// ----------------------------------------------------------------------------
3232
3233// TrackBase constructor must be called with AudioFlinger::mLock held
3234AudioFlinger::ThreadBase::TrackBase::TrackBase(
3235            const wp<ThreadBase>& thread,
3236            const sp<Client>& client,
3237            uint32_t sampleRate,
3238            audio_format_t format,
3239            uint32_t channelMask,
3240            int frameCount,
3241            uint32_t flags,
3242            const sp<IMemory>& sharedBuffer,
3243            int sessionId)
3244    :   RefBase(),
3245        mThread(thread),
3246        mClient(client),
3247        mCblk(0),
3248        mFrameCount(0),
3249        mState(IDLE),
3250        mClientTid(-1),
3251        mFormat(format),
3252        mFlags(flags & ~SYSTEM_FLAGS_MASK),
3253        mSessionId(sessionId)
3254{
3255    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3256
3257    // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3258   size_t size = sizeof(audio_track_cblk_t);
3259   uint8_t channelCount = popcount(channelMask);
3260   size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3261   if (sharedBuffer == 0) {
3262       size += bufferSize;
3263   }
3264
3265   if (client != NULL) {
3266        mCblkMemory = client->heap()->allocate(size);
3267        if (mCblkMemory != 0) {
3268            mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3269            if (mCblk) { // construct the shared structure in-place.
3270                new(mCblk) audio_track_cblk_t();
3271                // clear all buffers
3272                mCblk->frameCount = frameCount;
3273                mCblk->sampleRate = sampleRate;
3274                mChannelCount = channelCount;
3275                mChannelMask = channelMask;
3276                if (sharedBuffer == 0) {
3277                    mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3278                    memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3279                    // Force underrun condition to avoid false underrun callback until first data is
3280                    // written to buffer (other flags are cleared)
3281                    mCblk->flags = CBLK_UNDERRUN_ON;
3282                } else {
3283                    mBuffer = sharedBuffer->pointer();
3284                }
3285                mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3286            }
3287        } else {
3288            ALOGE("not enough memory for AudioTrack size=%u", size);
3289            client->heap()->dump("AudioTrack");
3290            return;
3291        }
3292   } else {
3293       mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3294           // construct the shared structure in-place.
3295           new(mCblk) audio_track_cblk_t();
3296           // clear all buffers
3297           mCblk->frameCount = frameCount;
3298           mCblk->sampleRate = sampleRate;
3299           mChannelCount = channelCount;
3300           mChannelMask = channelMask;
3301           mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3302           memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3303           // Force underrun condition to avoid false underrun callback until first data is
3304           // written to buffer (other flags are cleared)
3305           mCblk->flags = CBLK_UNDERRUN_ON;
3306           mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3307   }
3308}
3309
3310AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3311{
3312    if (mCblk) {
3313        mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
3314        if (mClient == NULL) {
3315            delete mCblk;
3316        }
3317    }
3318    mCblkMemory.clear();            // and free the shared memory
3319    if (mClient != NULL) {
3320        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3321        mClient.clear();
3322    }
3323}
3324
3325void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3326{
3327    buffer->raw = NULL;
3328    mFrameCount = buffer->frameCount;
3329    step();
3330    buffer->frameCount = 0;
3331}
3332
3333bool AudioFlinger::ThreadBase::TrackBase::step() {
3334    bool result;
3335    audio_track_cblk_t* cblk = this->cblk();
3336
3337    result = cblk->stepServer(mFrameCount);
3338    if (!result) {
3339        ALOGV("stepServer failed acquiring cblk mutex");
3340        mFlags |= STEPSERVER_FAILED;
3341    }
3342    return result;
3343}
3344
3345void AudioFlinger::ThreadBase::TrackBase::reset() {
3346    audio_track_cblk_t* cblk = this->cblk();
3347
3348    cblk->user = 0;
3349    cblk->server = 0;
3350    cblk->userBase = 0;
3351    cblk->serverBase = 0;
3352    mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3353    ALOGV("TrackBase::reset");
3354}
3355
3356sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3357{
3358    return mCblkMemory;
3359}
3360
3361int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3362    return (int)mCblk->sampleRate;
3363}
3364
3365int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
3366    return (const int)mChannelCount;
3367}
3368
3369uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3370    return mChannelMask;
3371}
3372
3373void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3374    audio_track_cblk_t* cblk = this->cblk();
3375    size_t frameSize = cblk->frameSize;
3376    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3377    int8_t *bufferEnd = bufferStart + frames * frameSize;
3378
3379    // Check validity of returned pointer in case the track control block would have been corrupted.
3380    if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3381        ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
3382        ALOGE("TrackBase::getBuffer buffer out of range:\n    start: %p, end %p , mBuffer %p mBufferEnd %p\n    \
3383                server %d, serverBase %d, user %d, userBase %d",
3384                bufferStart, bufferEnd, mBuffer, mBufferEnd,
3385                cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
3386        return 0;
3387    }
3388
3389    return bufferStart;
3390}
3391
3392// ----------------------------------------------------------------------------
3393
3394// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3395AudioFlinger::PlaybackThread::Track::Track(
3396            const wp<ThreadBase>& thread,
3397            const sp<Client>& client,
3398            audio_stream_type_t streamType,
3399            uint32_t sampleRate,
3400            audio_format_t format,
3401            uint32_t channelMask,
3402            int frameCount,
3403            const sp<IMemory>& sharedBuffer,
3404            int sessionId)
3405    :   TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
3406    mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3407    mAuxEffectId(0), mHasVolumeController(false)
3408{
3409    if (mCblk != NULL) {
3410        sp<ThreadBase> baseThread = thread.promote();
3411        if (baseThread != 0) {
3412            PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3413            mName = playbackThread->getTrackName_l();
3414            mMainBuffer = playbackThread->mixBuffer();
3415        }
3416        ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3417        if (mName < 0) {
3418            ALOGE("no more track names available");
3419        }
3420        mStreamType = streamType;
3421        // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3422        // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
3423        mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
3424    }
3425}
3426
3427AudioFlinger::PlaybackThread::Track::~Track()
3428{
3429    ALOGV("PlaybackThread::Track destructor");
3430    sp<ThreadBase> thread = mThread.promote();
3431    if (thread != 0) {
3432        Mutex::Autolock _l(thread->mLock);
3433        mState = TERMINATED;
3434    }
3435}
3436
3437void AudioFlinger::PlaybackThread::Track::destroy()
3438{
3439    // NOTE: destroyTrack_l() can remove a strong reference to this Track
3440    // by removing it from mTracks vector, so there is a risk that this Tracks's
3441    // desctructor is called. As the destructor needs to lock mLock,
3442    // we must acquire a strong reference on this Track before locking mLock
3443    // here so that the destructor is called only when exiting this function.
3444    // On the other hand, as long as Track::destroy() is only called by
3445    // TrackHandle destructor, the TrackHandle still holds a strong ref on
3446    // this Track with its member mTrack.
3447    sp<Track> keep(this);
3448    { // scope for mLock
3449        sp<ThreadBase> thread = mThread.promote();
3450        if (thread != 0) {
3451            if (!isOutputTrack()) {
3452                if (mState == ACTIVE || mState == RESUMING) {
3453                    AudioSystem::stopOutput(thread->id(),
3454                                            (audio_stream_type_t)mStreamType,
3455                                            mSessionId);
3456
3457                    // to track the speaker usage
3458                    addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3459                }
3460                AudioSystem::releaseOutput(thread->id());
3461            }
3462            Mutex::Autolock _l(thread->mLock);
3463            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3464            playbackThread->destroyTrack_l(this);
3465        }
3466    }
3467}
3468
3469void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3470{
3471    uint32_t vlr = mCblk->volumeLR;
3472    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",
3473            mName - AudioMixer::TRACK0,
3474            (mClient == NULL) ? getpid() : mClient->pid(),
3475            mStreamType,
3476            mFormat,
3477            mChannelMask,
3478            mSessionId,
3479            mFrameCount,
3480            mState,
3481            mMute,
3482            mFillingUpStatus,
3483            mCblk->sampleRate,
3484            vlr & 0xFFFF,
3485            vlr >> 16,
3486            mCblk->server,
3487            mCblk->user,
3488            (int)mMainBuffer,
3489            (int)mAuxBuffer);
3490}
3491
3492status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3493{
3494     audio_track_cblk_t* cblk = this->cblk();
3495     uint32_t framesReady;
3496     uint32_t framesReq = buffer->frameCount;
3497
3498     // Check if last stepServer failed, try to step now
3499     if (mFlags & TrackBase::STEPSERVER_FAILED) {
3500         if (!step())  goto getNextBuffer_exit;
3501         ALOGV("stepServer recovered");
3502         mFlags &= ~TrackBase::STEPSERVER_FAILED;
3503     }
3504
3505     framesReady = cblk->framesReady();
3506
3507     if (CC_LIKELY(framesReady)) {
3508        uint32_t s = cblk->server;
3509        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3510
3511        bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3512        if (framesReq > framesReady) {
3513            framesReq = framesReady;
3514        }
3515        if (s + framesReq > bufferEnd) {
3516            framesReq = bufferEnd - s;
3517        }
3518
3519         buffer->raw = getBuffer(s, framesReq);
3520         if (buffer->raw == NULL) goto getNextBuffer_exit;
3521
3522         buffer->frameCount = framesReq;
3523        return NO_ERROR;
3524     }
3525
3526getNextBuffer_exit:
3527     buffer->raw = NULL;
3528     buffer->frameCount = 0;
3529     ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3530     return NOT_ENOUGH_DATA;
3531}
3532
3533bool AudioFlinger::PlaybackThread::Track::isReady() const {
3534    if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
3535
3536    if (mCblk->framesReady() >= mCblk->frameCount ||
3537            (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3538        mFillingUpStatus = FS_FILLED;
3539        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3540        return true;
3541    }
3542    return false;
3543}
3544
3545status_t AudioFlinger::PlaybackThread::Track::start()
3546{
3547    status_t status = NO_ERROR;
3548    ALOGV("start(%d), calling thread %d session %d",
3549            mName, IPCThreadState::self()->getCallingPid(), mSessionId);
3550    sp<ThreadBase> thread = mThread.promote();
3551    if (thread != 0) {
3552        Mutex::Autolock _l(thread->mLock);
3553        track_state state = mState;
3554        // here the track could be either new, or restarted
3555        // in both cases "unstop" the track
3556        if (mState == PAUSED) {
3557            mState = TrackBase::RESUMING;
3558            ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3559        } else {
3560            mState = TrackBase::ACTIVE;
3561            ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
3562        }
3563
3564        if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3565            thread->mLock.unlock();
3566            status = AudioSystem::startOutput(thread->id(),
3567                                              (audio_stream_type_t)mStreamType,
3568                                              mSessionId);
3569            thread->mLock.lock();
3570
3571            // to track the speaker usage
3572            if (status == NO_ERROR) {
3573                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3574            }
3575        }
3576        if (status == NO_ERROR) {
3577            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3578            playbackThread->addTrack_l(this);
3579        } else {
3580            mState = state;
3581        }
3582    } else {
3583        status = BAD_VALUE;
3584    }
3585    return status;
3586}
3587
3588void AudioFlinger::PlaybackThread::Track::stop()
3589{
3590    ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3591    sp<ThreadBase> thread = mThread.promote();
3592    if (thread != 0) {
3593        Mutex::Autolock _l(thread->mLock);
3594        track_state state = mState;
3595        if (mState > STOPPED) {
3596            mState = STOPPED;
3597            // If the track is not active (PAUSED and buffers full), flush buffers
3598            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3599            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3600                reset();
3601            }
3602            ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3603        }
3604        if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3605            thread->mLock.unlock();
3606            AudioSystem::stopOutput(thread->id(),
3607                                    (audio_stream_type_t)mStreamType,
3608                                    mSessionId);
3609            thread->mLock.lock();
3610
3611            // to track the speaker usage
3612            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3613        }
3614    }
3615}
3616
3617void AudioFlinger::PlaybackThread::Track::pause()
3618{
3619    ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3620    sp<ThreadBase> thread = mThread.promote();
3621    if (thread != 0) {
3622        Mutex::Autolock _l(thread->mLock);
3623        if (mState == ACTIVE || mState == RESUMING) {
3624            mState = PAUSING;
3625            ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3626            if (!isOutputTrack()) {
3627                thread->mLock.unlock();
3628                AudioSystem::stopOutput(thread->id(),
3629                                        (audio_stream_type_t)mStreamType,
3630                                        mSessionId);
3631                thread->mLock.lock();
3632
3633                // to track the speaker usage
3634                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3635            }
3636        }
3637    }
3638}
3639
3640void AudioFlinger::PlaybackThread::Track::flush()
3641{
3642    ALOGV("flush(%d)", mName);
3643    sp<ThreadBase> thread = mThread.promote();
3644    if (thread != 0) {
3645        Mutex::Autolock _l(thread->mLock);
3646        if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3647            return;
3648        }
3649        // No point remaining in PAUSED state after a flush => go to
3650        // STOPPED state
3651        mState = STOPPED;
3652
3653        // do not reset the track if it is still in the process of being stopped or paused.
3654        // this will be done by prepareTracks_l() when the track is stopped.
3655        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3656        if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3657            reset();
3658        }
3659    }
3660}
3661
3662void AudioFlinger::PlaybackThread::Track::reset()
3663{
3664    // Do not reset twice to avoid discarding data written just after a flush and before
3665    // the audioflinger thread detects the track is stopped.
3666    if (!mResetDone) {
3667        TrackBase::reset();
3668        // Force underrun condition to avoid false underrun callback until first data is
3669        // written to buffer
3670        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3671        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
3672        mFillingUpStatus = FS_FILLING;
3673        mResetDone = true;
3674    }
3675}
3676
3677void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3678{
3679    mMute = muted;
3680}
3681
3682status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3683{
3684    status_t status = DEAD_OBJECT;
3685    sp<ThreadBase> thread = mThread.promote();
3686    if (thread != 0) {
3687       PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3688       status = playbackThread->attachAuxEffect(this, EffectId);
3689    }
3690    return status;
3691}
3692
3693void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3694{
3695    mAuxEffectId = EffectId;
3696    mAuxBuffer = buffer;
3697}
3698
3699// ----------------------------------------------------------------------------
3700
3701// RecordTrack constructor must be called with AudioFlinger::mLock held
3702AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3703            const wp<ThreadBase>& thread,
3704            const sp<Client>& client,
3705            uint32_t sampleRate,
3706            audio_format_t format,
3707            uint32_t channelMask,
3708            int frameCount,
3709            uint32_t flags,
3710            int sessionId)
3711    :   TrackBase(thread, client, sampleRate, format,
3712                  channelMask, frameCount, flags, 0, sessionId),
3713        mOverflow(false)
3714{
3715    if (mCblk != NULL) {
3716       ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3717       if (format == AUDIO_FORMAT_PCM_16_BIT) {
3718           mCblk->frameSize = mChannelCount * sizeof(int16_t);
3719       } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
3720           mCblk->frameSize = mChannelCount * sizeof(int8_t);
3721       } else {
3722           mCblk->frameSize = sizeof(int8_t);
3723       }
3724    }
3725}
3726
3727AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3728{
3729    sp<ThreadBase> thread = mThread.promote();
3730    if (thread != 0) {
3731        AudioSystem::releaseInput(thread->id());
3732    }
3733}
3734
3735status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3736{
3737    audio_track_cblk_t* cblk = this->cblk();
3738    uint32_t framesAvail;
3739    uint32_t framesReq = buffer->frameCount;
3740
3741     // Check if last stepServer failed, try to step now
3742    if (mFlags & TrackBase::STEPSERVER_FAILED) {
3743        if (!step()) goto getNextBuffer_exit;
3744        ALOGV("stepServer recovered");
3745        mFlags &= ~TrackBase::STEPSERVER_FAILED;
3746    }
3747
3748    framesAvail = cblk->framesAvailable_l();
3749
3750    if (CC_LIKELY(framesAvail)) {
3751        uint32_t s = cblk->server;
3752        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3753
3754        if (framesReq > framesAvail) {
3755            framesReq = framesAvail;
3756        }
3757        if (s + framesReq > bufferEnd) {
3758            framesReq = bufferEnd - s;
3759        }
3760
3761        buffer->raw = getBuffer(s, framesReq);
3762        if (buffer->raw == NULL) goto getNextBuffer_exit;
3763
3764        buffer->frameCount = framesReq;
3765        return NO_ERROR;
3766    }
3767
3768getNextBuffer_exit:
3769    buffer->raw = NULL;
3770    buffer->frameCount = 0;
3771    return NOT_ENOUGH_DATA;
3772}
3773
3774status_t AudioFlinger::RecordThread::RecordTrack::start()
3775{
3776    sp<ThreadBase> thread = mThread.promote();
3777    if (thread != 0) {
3778        RecordThread *recordThread = (RecordThread *)thread.get();
3779        return recordThread->start(this);
3780    } else {
3781        return BAD_VALUE;
3782    }
3783}
3784
3785void AudioFlinger::RecordThread::RecordTrack::stop()
3786{
3787    sp<ThreadBase> thread = mThread.promote();
3788    if (thread != 0) {
3789        RecordThread *recordThread = (RecordThread *)thread.get();
3790        recordThread->stop(this);
3791        TrackBase::reset();
3792        // Force overerrun condition to avoid false overrun callback until first data is
3793        // read from buffer
3794        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
3795    }
3796}
3797
3798void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3799{
3800    snprintf(buffer, size, "   %05d %03u 0x%08x %05d   %04u %01d %05u  %08x %08x\n",
3801            (mClient == NULL) ? getpid() : mClient->pid(),
3802            mFormat,
3803            mChannelMask,
3804            mSessionId,
3805            mFrameCount,
3806            mState,
3807            mCblk->sampleRate,
3808            mCblk->server,
3809            mCblk->user);
3810}
3811
3812
3813// ----------------------------------------------------------------------------
3814
3815AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3816            const wp<ThreadBase>& thread,
3817            DuplicatingThread *sourceThread,
3818            uint32_t sampleRate,
3819            audio_format_t format,
3820            uint32_t channelMask,
3821            int frameCount)
3822    :   Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
3823    mActive(false), mSourceThread(sourceThread)
3824{
3825
3826    PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3827    if (mCblk != NULL) {
3828        mCblk->flags |= CBLK_DIRECTION_OUT;
3829        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3830        mCblk->volumeLR = (MAX_GAIN_INT << 16) | MAX_GAIN_INT;
3831        mOutBuffer.frameCount = 0;
3832        playbackThread->mTracks.add(this);
3833        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3834                "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3835                mCblk, mBuffer, mCblk->buffers,
3836                mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
3837    } else {
3838        ALOGW("Error creating output track on thread %p", playbackThread);
3839    }
3840}
3841
3842AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3843{
3844    clearBufferQueue();
3845}
3846
3847status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3848{
3849    status_t status = Track::start();
3850    if (status != NO_ERROR) {
3851        return status;
3852    }
3853
3854    mActive = true;
3855    mRetryCount = 127;
3856    return status;
3857}
3858
3859void AudioFlinger::PlaybackThread::OutputTrack::stop()
3860{
3861    Track::stop();
3862    clearBufferQueue();
3863    mOutBuffer.frameCount = 0;
3864    mActive = false;
3865}
3866
3867bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3868{
3869    Buffer *pInBuffer;
3870    Buffer inBuffer;
3871    uint32_t channelCount = mChannelCount;
3872    bool outputBufferFull = false;
3873    inBuffer.frameCount = frames;
3874    inBuffer.i16 = data;
3875
3876    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3877
3878    if (!mActive && frames != 0) {
3879        start();
3880        sp<ThreadBase> thread = mThread.promote();
3881        if (thread != 0) {
3882            MixerThread *mixerThread = (MixerThread *)thread.get();
3883            if (mCblk->frameCount > frames){
3884                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3885                    uint32_t startFrames = (mCblk->frameCount - frames);
3886                    pInBuffer = new Buffer;
3887                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3888                    pInBuffer->frameCount = startFrames;
3889                    pInBuffer->i16 = pInBuffer->mBuffer;
3890                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3891                    mBufferQueue.add(pInBuffer);
3892                } else {
3893                    ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
3894                }
3895            }
3896        }
3897    }
3898
3899    while (waitTimeLeftMs) {
3900        // First write pending buffers, then new data
3901        if (mBufferQueue.size()) {
3902            pInBuffer = mBufferQueue.itemAt(0);
3903        } else {
3904            pInBuffer = &inBuffer;
3905        }
3906
3907        if (pInBuffer->frameCount == 0) {
3908            break;
3909        }
3910
3911        if (mOutBuffer.frameCount == 0) {
3912            mOutBuffer.frameCount = pInBuffer->frameCount;
3913            nsecs_t startTime = systemTime();
3914            if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
3915                ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3916                outputBufferFull = true;
3917                break;
3918            }
3919            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3920            if (waitTimeLeftMs >= waitTimeMs) {
3921                waitTimeLeftMs -= waitTimeMs;
3922            } else {
3923                waitTimeLeftMs = 0;
3924            }
3925        }
3926
3927        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3928        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3929        mCblk->stepUser(outFrames);
3930        pInBuffer->frameCount -= outFrames;
3931        pInBuffer->i16 += outFrames * channelCount;
3932        mOutBuffer.frameCount -= outFrames;
3933        mOutBuffer.i16 += outFrames * channelCount;
3934
3935        if (pInBuffer->frameCount == 0) {
3936            if (mBufferQueue.size()) {
3937                mBufferQueue.removeAt(0);
3938                delete [] pInBuffer->mBuffer;
3939                delete pInBuffer;
3940                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3941            } else {
3942                break;
3943            }
3944        }
3945    }
3946
3947    // If we could not write all frames, allocate a buffer and queue it for next time.
3948    if (inBuffer.frameCount) {
3949        sp<ThreadBase> thread = mThread.promote();
3950        if (thread != 0 && !thread->standby()) {
3951            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3952                pInBuffer = new Buffer;
3953                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3954                pInBuffer->frameCount = inBuffer.frameCount;
3955                pInBuffer->i16 = pInBuffer->mBuffer;
3956                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3957                mBufferQueue.add(pInBuffer);
3958                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3959            } else {
3960                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3961            }
3962        }
3963    }
3964
3965    // Calling write() with a 0 length buffer, means that no more data will be written:
3966    // If no more buffers are pending, fill output track buffer to make sure it is started
3967    // by output mixer.
3968    if (frames == 0 && mBufferQueue.size() == 0) {
3969        if (mCblk->user < mCblk->frameCount) {
3970            frames = mCblk->frameCount - mCblk->user;
3971            pInBuffer = new Buffer;
3972            pInBuffer->mBuffer = new int16_t[frames * channelCount];
3973            pInBuffer->frameCount = frames;
3974            pInBuffer->i16 = pInBuffer->mBuffer;
3975            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3976            mBufferQueue.add(pInBuffer);
3977        } else if (mActive) {
3978            stop();
3979        }
3980    }
3981
3982    return outputBufferFull;
3983}
3984
3985status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3986{
3987    int active;
3988    status_t result;
3989    audio_track_cblk_t* cblk = mCblk;
3990    uint32_t framesReq = buffer->frameCount;
3991
3992//    ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3993    buffer->frameCount  = 0;
3994
3995    uint32_t framesAvail = cblk->framesAvailable();
3996
3997
3998    if (framesAvail == 0) {
3999        Mutex::Autolock _l(cblk->lock);
4000        goto start_loop_here;
4001        while (framesAvail == 0) {
4002            active = mActive;
4003            if (CC_UNLIKELY(!active)) {
4004                ALOGV("Not active and NO_MORE_BUFFERS");
4005                return NO_MORE_BUFFERS;
4006            }
4007            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4008            if (result != NO_ERROR) {
4009                return NO_MORE_BUFFERS;
4010            }
4011            // read the server count again
4012        start_loop_here:
4013            framesAvail = cblk->framesAvailable_l();
4014        }
4015    }
4016
4017//    if (framesAvail < framesReq) {
4018//        return NO_MORE_BUFFERS;
4019//    }
4020
4021    if (framesReq > framesAvail) {
4022        framesReq = framesAvail;
4023    }
4024
4025    uint32_t u = cblk->user;
4026    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4027
4028    if (u + framesReq > bufferEnd) {
4029        framesReq = bufferEnd - u;
4030    }
4031
4032    buffer->frameCount  = framesReq;
4033    buffer->raw         = (void *)cblk->buffer(u);
4034    return NO_ERROR;
4035}
4036
4037
4038void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4039{
4040    size_t size = mBufferQueue.size();
4041    Buffer *pBuffer;
4042
4043    for (size_t i = 0; i < size; i++) {
4044        pBuffer = mBufferQueue.itemAt(i);
4045        delete [] pBuffer->mBuffer;
4046        delete pBuffer;
4047    }
4048    mBufferQueue.clear();
4049}
4050
4051// ----------------------------------------------------------------------------
4052
4053AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4054    :   RefBase(),
4055        mAudioFlinger(audioFlinger),
4056        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4057        mPid(pid)
4058{
4059    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4060}
4061
4062// Client destructor must be called with AudioFlinger::mLock held
4063AudioFlinger::Client::~Client()
4064{
4065    mAudioFlinger->removeClient_l(mPid);
4066}
4067
4068sp<MemoryDealer> AudioFlinger::Client::heap() const
4069{
4070    return mMemoryDealer;
4071}
4072
4073// ----------------------------------------------------------------------------
4074
4075AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4076                                                     const sp<IAudioFlingerClient>& client,
4077                                                     pid_t pid)
4078    : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4079{
4080}
4081
4082AudioFlinger::NotificationClient::~NotificationClient()
4083{
4084    mClient.clear();
4085}
4086
4087void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4088{
4089    sp<NotificationClient> keep(this);
4090    {
4091        mAudioFlinger->removeNotificationClient(mPid);
4092    }
4093}
4094
4095// ----------------------------------------------------------------------------
4096
4097AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4098    : BnAudioTrack(),
4099      mTrack(track)
4100{
4101}
4102
4103AudioFlinger::TrackHandle::~TrackHandle() {
4104    // just stop the track on deletion, associated resources
4105    // will be freed from the main thread once all pending buffers have
4106    // been played. Unless it's not in the active track list, in which
4107    // case we free everything now...
4108    mTrack->destroy();
4109}
4110
4111sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4112    return mTrack->getCblk();
4113}
4114
4115status_t AudioFlinger::TrackHandle::start() {
4116    return mTrack->start();
4117}
4118
4119void AudioFlinger::TrackHandle::stop() {
4120    mTrack->stop();
4121}
4122
4123void AudioFlinger::TrackHandle::flush() {
4124    mTrack->flush();
4125}
4126
4127void AudioFlinger::TrackHandle::mute(bool e) {
4128    mTrack->mute(e);
4129}
4130
4131void AudioFlinger::TrackHandle::pause() {
4132    mTrack->pause();
4133}
4134
4135status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4136{
4137    return mTrack->attachAuxEffect(EffectId);
4138}
4139
4140status_t AudioFlinger::TrackHandle::onTransact(
4141    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4142{
4143    return BnAudioTrack::onTransact(code, data, reply, flags);
4144}
4145
4146// ----------------------------------------------------------------------------
4147
4148sp<IAudioRecord> AudioFlinger::openRecord(
4149        pid_t pid,
4150        int input,
4151        uint32_t sampleRate,
4152        audio_format_t format,
4153        uint32_t channelMask,
4154        int frameCount,
4155        uint32_t flags,
4156        int *sessionId,
4157        status_t *status)
4158{
4159    sp<RecordThread::RecordTrack> recordTrack;
4160    sp<RecordHandle> recordHandle;
4161    sp<Client> client;
4162    wp<Client> wclient;
4163    status_t lStatus;
4164    RecordThread *thread;
4165    size_t inFrameCount;
4166    int lSessionId;
4167
4168    // check calling permissions
4169    if (!recordingAllowed()) {
4170        lStatus = PERMISSION_DENIED;
4171        goto Exit;
4172    }
4173
4174    // add client to list
4175    { // scope for mLock
4176        Mutex::Autolock _l(mLock);
4177        thread = checkRecordThread_l(input);
4178        if (thread == NULL) {
4179            lStatus = BAD_VALUE;
4180            goto Exit;
4181        }
4182
4183        wclient = mClients.valueFor(pid);
4184        if (wclient != NULL) {
4185            client = wclient.promote();
4186        } else {
4187            client = new Client(this, pid);
4188            mClients.add(pid, client);
4189        }
4190
4191        // If no audio session id is provided, create one here
4192        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
4193            lSessionId = *sessionId;
4194        } else {
4195            lSessionId = nextUniqueId();
4196            if (sessionId != NULL) {
4197                *sessionId = lSessionId;
4198            }
4199        }
4200        // create new record track. The record track uses one track in mHardwareMixerThread by convention.
4201        recordTrack = thread->createRecordTrack_l(client,
4202                                                sampleRate,
4203                                                format,
4204                                                channelMask,
4205                                                frameCount,
4206                                                flags,
4207                                                lSessionId,
4208                                                &lStatus);
4209    }
4210    if (lStatus != NO_ERROR) {
4211        // remove local strong reference to Client before deleting the RecordTrack so that the Client
4212        // destructor is called by the TrackBase destructor with mLock held
4213        client.clear();
4214        recordTrack.clear();
4215        goto Exit;
4216    }
4217
4218    // return to handle to client
4219    recordHandle = new RecordHandle(recordTrack);
4220    lStatus = NO_ERROR;
4221
4222Exit:
4223    if (status) {
4224        *status = lStatus;
4225    }
4226    return recordHandle;
4227}
4228
4229// ----------------------------------------------------------------------------
4230
4231AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4232    : BnAudioRecord(),
4233    mRecordTrack(recordTrack)
4234{
4235}
4236
4237AudioFlinger::RecordHandle::~RecordHandle() {
4238    stop();
4239}
4240
4241sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4242    return mRecordTrack->getCblk();
4243}
4244
4245status_t AudioFlinger::RecordHandle::start() {
4246    ALOGV("RecordHandle::start()");
4247    return mRecordTrack->start();
4248}
4249
4250void AudioFlinger::RecordHandle::stop() {
4251    ALOGV("RecordHandle::stop()");
4252    mRecordTrack->stop();
4253}
4254
4255status_t AudioFlinger::RecordHandle::onTransact(
4256    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4257{
4258    return BnAudioRecord::onTransact(code, data, reply, flags);
4259}
4260
4261// ----------------------------------------------------------------------------
4262
4263AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4264                                         AudioStreamIn *input,
4265                                         uint32_t sampleRate,
4266                                         uint32_t channels,
4267                                         int id,
4268                                         uint32_t device) :
4269    ThreadBase(audioFlinger, id, device),
4270    mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
4271{
4272    mType = ThreadBase::RECORD;
4273
4274    snprintf(mName, kNameLength, "AudioIn_%d", id);
4275
4276    mReqChannelCount = popcount(channels);
4277    mReqSampleRate = sampleRate;
4278    readInputParameters();
4279}
4280
4281
4282AudioFlinger::RecordThread::~RecordThread()
4283{
4284    delete[] mRsmpInBuffer;
4285    if (mResampler != NULL) {
4286        delete mResampler;
4287        delete[] mRsmpOutBuffer;
4288    }
4289}
4290
4291void AudioFlinger::RecordThread::onFirstRef()
4292{
4293    run(mName, PRIORITY_URGENT_AUDIO);
4294}
4295
4296status_t AudioFlinger::RecordThread::readyToRun()
4297{
4298    status_t status = initCheck();
4299    ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4300    return status;
4301}
4302
4303bool AudioFlinger::RecordThread::threadLoop()
4304{
4305    AudioBufferProvider::Buffer buffer;
4306    sp<RecordTrack> activeTrack;
4307    Vector< sp<EffectChain> > effectChains;
4308
4309    nsecs_t lastWarning = 0;
4310
4311    acquireWakeLock();
4312
4313    // start recording
4314    while (!exitPending()) {
4315
4316        processConfigEvents();
4317
4318        { // scope for mLock
4319            Mutex::Autolock _l(mLock);
4320            checkForNewParameters_l();
4321            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4322                if (!mStandby) {
4323                    mInput->stream->common.standby(&mInput->stream->common);
4324                    mStandby = true;
4325                }
4326
4327                if (exitPending()) break;
4328
4329                releaseWakeLock_l();
4330                ALOGV("RecordThread: loop stopping");
4331                // go to sleep
4332                mWaitWorkCV.wait(mLock);
4333                ALOGV("RecordThread: loop starting");
4334                acquireWakeLock_l();
4335                continue;
4336            }
4337            if (mActiveTrack != 0) {
4338                if (mActiveTrack->mState == TrackBase::PAUSING) {
4339                    if (!mStandby) {
4340                        mInput->stream->common.standby(&mInput->stream->common);
4341                        mStandby = true;
4342                    }
4343                    mActiveTrack.clear();
4344                    mStartStopCond.broadcast();
4345                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4346                    if (mReqChannelCount != mActiveTrack->channelCount()) {
4347                        mActiveTrack.clear();
4348                        mStartStopCond.broadcast();
4349                    } else if (mBytesRead != 0) {
4350                        // record start succeeds only if first read from audio input
4351                        // succeeds
4352                        if (mBytesRead > 0) {
4353                            mActiveTrack->mState = TrackBase::ACTIVE;
4354                        } else {
4355                            mActiveTrack.clear();
4356                        }
4357                        mStartStopCond.broadcast();
4358                    }
4359                    mStandby = false;
4360                }
4361            }
4362            lockEffectChains_l(effectChains);
4363        }
4364
4365        if (mActiveTrack != 0) {
4366            if (mActiveTrack->mState != TrackBase::ACTIVE &&
4367                mActiveTrack->mState != TrackBase::RESUMING) {
4368                unlockEffectChains(effectChains);
4369                usleep(kRecordThreadSleepUs);
4370                continue;
4371            }
4372            for (size_t i = 0; i < effectChains.size(); i ++) {
4373                effectChains[i]->process_l();
4374            }
4375
4376            buffer.frameCount = mFrameCount;
4377            if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4378                size_t framesOut = buffer.frameCount;
4379                if (mResampler == NULL) {
4380                    // no resampling
4381                    while (framesOut) {
4382                        size_t framesIn = mFrameCount - mRsmpInIndex;
4383                        if (framesIn) {
4384                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4385                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4386                            if (framesIn > framesOut)
4387                                framesIn = framesOut;
4388                            mRsmpInIndex += framesIn;
4389                            framesOut -= framesIn;
4390                            if ((int)mChannelCount == mReqChannelCount ||
4391                                mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4392                                memcpy(dst, src, framesIn * mFrameSize);
4393                            } else {
4394                                int16_t *src16 = (int16_t *)src;
4395                                int16_t *dst16 = (int16_t *)dst;
4396                                if (mChannelCount == 1) {
4397                                    while (framesIn--) {
4398                                        *dst16++ = *src16;
4399                                        *dst16++ = *src16++;
4400                                    }
4401                                } else {
4402                                    while (framesIn--) {
4403                                        *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4404                                        src16 += 2;
4405                                    }
4406                                }
4407                            }
4408                        }
4409                        if (framesOut && mFrameCount == mRsmpInIndex) {
4410                            if (framesOut == mFrameCount &&
4411                                ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
4412                                mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
4413                                framesOut = 0;
4414                            } else {
4415                                mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
4416                                mRsmpInIndex = 0;
4417                            }
4418                            if (mBytesRead < 0) {
4419                                ALOGE("Error reading audio input");
4420                                if (mActiveTrack->mState == TrackBase::ACTIVE) {
4421                                    // Force input into standby so that it tries to
4422                                    // recover at next read attempt
4423                                    mInput->stream->common.standby(&mInput->stream->common);
4424                                    usleep(kRecordThreadSleepUs);
4425                                }
4426                                mRsmpInIndex = mFrameCount;
4427                                framesOut = 0;
4428                                buffer.frameCount = 0;
4429                            }
4430                        }
4431                    }
4432                } else {
4433                    // resampling
4434
4435                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4436                    // alter output frame count as if we were expecting stereo samples
4437                    if (mChannelCount == 1 && mReqChannelCount == 1) {
4438                        framesOut >>= 1;
4439                    }
4440                    mResampler->resample(mRsmpOutBuffer, framesOut, this);
4441                    // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4442                    // are 32 bit aligned which should be always true.
4443                    if (mChannelCount == 2 && mReqChannelCount == 1) {
4444                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4445                        // the resampler always outputs stereo samples: do post stereo to mono conversion
4446                        int16_t *src = (int16_t *)mRsmpOutBuffer;
4447                        int16_t *dst = buffer.i16;
4448                        while (framesOut--) {
4449                            *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4450                            src += 2;
4451                        }
4452                    } else {
4453                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4454                    }
4455
4456                }
4457                mActiveTrack->releaseBuffer(&buffer);
4458                mActiveTrack->overflow();
4459            }
4460            // client isn't retrieving buffers fast enough
4461            else {
4462                if (!mActiveTrack->setOverflow()) {
4463                    nsecs_t now = systemTime();
4464                    if ((now - lastWarning) > kWarningThrottleNs) {
4465                        ALOGW("RecordThread: buffer overflow");
4466                        lastWarning = now;
4467                    }
4468                }
4469                // Release the processor for a while before asking for a new buffer.
4470                // This will give the application more chance to read from the buffer and
4471                // clear the overflow.
4472                usleep(kRecordThreadSleepUs);
4473            }
4474        }
4475        // enable changes in effect chain
4476        unlockEffectChains(effectChains);
4477        effectChains.clear();
4478    }
4479
4480    if (!mStandby) {
4481        mInput->stream->common.standby(&mInput->stream->common);
4482    }
4483    mActiveTrack.clear();
4484
4485    mStartStopCond.broadcast();
4486
4487    releaseWakeLock();
4488
4489    ALOGV("RecordThread %p exiting", this);
4490    return false;
4491}
4492
4493
4494sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
4495        const sp<AudioFlinger::Client>& client,
4496        uint32_t sampleRate,
4497        audio_format_t format,
4498        int channelMask,
4499        int frameCount,
4500        uint32_t flags,
4501        int sessionId,
4502        status_t *status)
4503{
4504    sp<RecordTrack> track;
4505    status_t lStatus;
4506
4507    lStatus = initCheck();
4508    if (lStatus != NO_ERROR) {
4509        ALOGE("Audio driver not initialized.");
4510        goto Exit;
4511    }
4512
4513    { // scope for mLock
4514        Mutex::Autolock _l(mLock);
4515
4516        track = new RecordTrack(this, client, sampleRate,
4517                      format, channelMask, frameCount, flags, sessionId);
4518
4519        if (track->getCblk() == NULL) {
4520            lStatus = NO_MEMORY;
4521            goto Exit;
4522        }
4523
4524        mTrack = track.get();
4525        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4526        bool suspend = audio_is_bluetooth_sco_device(
4527                (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
4528        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4529        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
4530    }
4531    lStatus = NO_ERROR;
4532
4533Exit:
4534    if (status) {
4535        *status = lStatus;
4536    }
4537    return track;
4538}
4539
4540status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4541{
4542    ALOGV("RecordThread::start");
4543    sp <ThreadBase> strongMe = this;
4544    status_t status = NO_ERROR;
4545    {
4546        AutoMutex lock(mLock);
4547        if (mActiveTrack != 0) {
4548            if (recordTrack != mActiveTrack.get()) {
4549                status = -EBUSY;
4550            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4551                mActiveTrack->mState = TrackBase::ACTIVE;
4552            }
4553            return status;
4554        }
4555
4556        recordTrack->mState = TrackBase::IDLE;
4557        mActiveTrack = recordTrack;
4558        mLock.unlock();
4559        status_t status = AudioSystem::startInput(mId);
4560        mLock.lock();
4561        if (status != NO_ERROR) {
4562            mActiveTrack.clear();
4563            return status;
4564        }
4565        mRsmpInIndex = mFrameCount;
4566        mBytesRead = 0;
4567        if (mResampler != NULL) {
4568            mResampler->reset();
4569        }
4570        mActiveTrack->mState = TrackBase::RESUMING;
4571        // signal thread to start
4572        ALOGV("Signal record thread");
4573        mWaitWorkCV.signal();
4574        // do not wait for mStartStopCond if exiting
4575        if (mExiting) {
4576            mActiveTrack.clear();
4577            status = INVALID_OPERATION;
4578            goto startError;
4579        }
4580        mStartStopCond.wait(mLock);
4581        if (mActiveTrack == 0) {
4582            ALOGV("Record failed to start");
4583            status = BAD_VALUE;
4584            goto startError;
4585        }
4586        ALOGV("Record started OK");
4587        return status;
4588    }
4589startError:
4590    AudioSystem::stopInput(mId);
4591    return status;
4592}
4593
4594void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4595    ALOGV("RecordThread::stop");
4596    sp <ThreadBase> strongMe = this;
4597    {
4598        AutoMutex lock(mLock);
4599        if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4600            mActiveTrack->mState = TrackBase::PAUSING;
4601            // do not wait for mStartStopCond if exiting
4602            if (mExiting) {
4603                return;
4604            }
4605            mStartStopCond.wait(mLock);
4606            // if we have been restarted, recordTrack == mActiveTrack.get() here
4607            if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4608                mLock.unlock();
4609                AudioSystem::stopInput(mId);
4610                mLock.lock();
4611                ALOGV("Record stopped OK");
4612            }
4613        }
4614    }
4615}
4616
4617status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4618{
4619    const size_t SIZE = 256;
4620    char buffer[SIZE];
4621    String8 result;
4622    pid_t pid = 0;
4623
4624    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4625    result.append(buffer);
4626
4627    if (mActiveTrack != 0) {
4628        result.append("Active Track:\n");
4629        result.append("   Clien Fmt Chn mask   Session Buf  S SRate  Serv     User\n");
4630        mActiveTrack->dump(buffer, SIZE);
4631        result.append(buffer);
4632
4633        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4634        result.append(buffer);
4635        snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4636        result.append(buffer);
4637        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4638        result.append(buffer);
4639        snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4640        result.append(buffer);
4641        snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4642        result.append(buffer);
4643
4644
4645    } else {
4646        result.append("No record client\n");
4647    }
4648    write(fd, result.string(), result.size());
4649
4650    dumpBase(fd, args);
4651    dumpEffectChains(fd, args);
4652
4653    return NO_ERROR;
4654}
4655
4656status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4657{
4658    size_t framesReq = buffer->frameCount;
4659    size_t framesReady = mFrameCount - mRsmpInIndex;
4660    int channelCount;
4661
4662    if (framesReady == 0) {
4663        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
4664        if (mBytesRead < 0) {
4665            ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4666            if (mActiveTrack->mState == TrackBase::ACTIVE) {
4667                // Force input into standby so that it tries to
4668                // recover at next read attempt
4669                mInput->stream->common.standby(&mInput->stream->common);
4670                usleep(kRecordThreadSleepUs);
4671            }
4672            buffer->raw = NULL;
4673            buffer->frameCount = 0;
4674            return NOT_ENOUGH_DATA;
4675        }
4676        mRsmpInIndex = 0;
4677        framesReady = mFrameCount;
4678    }
4679
4680    if (framesReq > framesReady) {
4681        framesReq = framesReady;
4682    }
4683
4684    if (mChannelCount == 1 && mReqChannelCount == 2) {
4685        channelCount = 1;
4686    } else {
4687        channelCount = 2;
4688    }
4689    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4690    buffer->frameCount = framesReq;
4691    return NO_ERROR;
4692}
4693
4694void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4695{
4696    mRsmpInIndex += buffer->frameCount;
4697    buffer->frameCount = 0;
4698}
4699
4700bool AudioFlinger::RecordThread::checkForNewParameters_l()
4701{
4702    bool reconfig = false;
4703
4704    while (!mNewParameters.isEmpty()) {
4705        status_t status = NO_ERROR;
4706        String8 keyValuePair = mNewParameters[0];
4707        AudioParameter param = AudioParameter(keyValuePair);
4708        int value;
4709        audio_format_t reqFormat = mFormat;
4710        int reqSamplingRate = mReqSampleRate;
4711        int reqChannelCount = mReqChannelCount;
4712
4713        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4714            reqSamplingRate = value;
4715            reconfig = true;
4716        }
4717        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4718            reqFormat = (audio_format_t) value;
4719            reconfig = true;
4720        }
4721        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4722            reqChannelCount = popcount(value);
4723            reconfig = true;
4724        }
4725        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4726            // do not accept frame count changes if tracks are open as the track buffer
4727            // size depends on frame count and correct behavior would not be garantied
4728            // if frame count is changed after track creation
4729            if (mActiveTrack != 0) {
4730                status = INVALID_OPERATION;
4731            } else {
4732                reconfig = true;
4733            }
4734        }
4735        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4736            // forward device change to effects that have requested to be
4737            // aware of attached audio device.
4738            for (size_t i = 0; i < mEffectChains.size(); i++) {
4739                mEffectChains[i]->setDevice_l(value);
4740            }
4741            // store input device and output device but do not forward output device to audio HAL.
4742            // Note that status is ignored by the caller for output device
4743            // (see AudioFlinger::setParameters()
4744            if (value & AUDIO_DEVICE_OUT_ALL) {
4745                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4746                status = BAD_VALUE;
4747            } else {
4748                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
4749                // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4750                if (mTrack != NULL) {
4751                    bool suspend = audio_is_bluetooth_sco_device(
4752                            (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
4753                    setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4754                    setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4755                }
4756            }
4757            mDevice |= (uint32_t)value;
4758        }
4759        if (status == NO_ERROR) {
4760            status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
4761            if (status == INVALID_OPERATION) {
4762               mInput->stream->common.standby(&mInput->stream->common);
4763               status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
4764            }
4765            if (reconfig) {
4766                if (status == BAD_VALUE &&
4767                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4768                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
4769                    ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4770                    (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
4771                    (reqChannelCount < 3)) {
4772                    status = NO_ERROR;
4773                }
4774                if (status == NO_ERROR) {
4775                    readInputParameters();
4776                    sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4777                }
4778            }
4779        }
4780
4781        mNewParameters.removeAt(0);
4782
4783        mParamStatus = status;
4784        mParamCond.signal();
4785        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4786        // already timed out waiting for the status and will never signal the condition.
4787        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4788    }
4789    return reconfig;
4790}
4791
4792String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4793{
4794    char *s;
4795    String8 out_s8 = String8();
4796
4797    Mutex::Autolock _l(mLock);
4798    if (initCheck() != NO_ERROR) {
4799        return out_s8;
4800    }
4801
4802    s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
4803    out_s8 = String8(s);
4804    free(s);
4805    return out_s8;
4806}
4807
4808void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4809    AudioSystem::OutputDescriptor desc;
4810    void *param2 = 0;
4811
4812    switch (event) {
4813    case AudioSystem::INPUT_OPENED:
4814    case AudioSystem::INPUT_CONFIG_CHANGED:
4815        desc.channels = mChannelMask;
4816        desc.samplingRate = mSampleRate;
4817        desc.format = mFormat;
4818        desc.frameCount = mFrameCount;
4819        desc.latency = 0;
4820        param2 = &desc;
4821        break;
4822
4823    case AudioSystem::INPUT_CLOSED:
4824    default:
4825        break;
4826    }
4827    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4828}
4829
4830void AudioFlinger::RecordThread::readInputParameters()
4831{
4832    if (mRsmpInBuffer) delete mRsmpInBuffer;
4833    if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4834    if (mResampler) delete mResampler;
4835    mResampler = NULL;
4836
4837    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
4838    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4839    mChannelCount = (uint16_t)popcount(mChannelMask);
4840    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4841    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
4842    mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
4843    mFrameCount = mInputBytes / mFrameSize;
4844    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4845
4846    if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4847    {
4848        int channelCount;
4849         // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4850         // stereo to mono post process as the resampler always outputs stereo.
4851        if (mChannelCount == 1 && mReqChannelCount == 2) {
4852            channelCount = 1;
4853        } else {
4854            channelCount = 2;
4855        }
4856        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4857        mResampler->setSampleRate(mSampleRate);
4858        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4859        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4860
4861        // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4862        if (mChannelCount == 1 && mReqChannelCount == 1) {
4863            mFrameCount >>= 1;
4864        }
4865
4866    }
4867    mRsmpInIndex = mFrameCount;
4868}
4869
4870unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4871{
4872    Mutex::Autolock _l(mLock);
4873    if (initCheck() != NO_ERROR) {
4874        return 0;
4875    }
4876
4877    return mInput->stream->get_input_frames_lost(mInput->stream);
4878}
4879
4880uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4881{
4882    Mutex::Autolock _l(mLock);
4883    uint32_t result = 0;
4884    if (getEffectChain_l(sessionId) != 0) {
4885        result = EFFECT_SESSION;
4886    }
4887
4888    if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4889        result |= TRACK_SESSION;
4890    }
4891
4892    return result;
4893}
4894
4895AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4896{
4897    Mutex::Autolock _l(mLock);
4898    return mTrack;
4899}
4900
4901AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
4902{
4903    Mutex::Autolock _l(mLock);
4904    return mInput;
4905}
4906
4907AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4908{
4909    Mutex::Autolock _l(mLock);
4910    AudioStreamIn *input = mInput;
4911    mInput = NULL;
4912    return input;
4913}
4914
4915// this method must always be called either with ThreadBase mLock held or inside the thread loop
4916audio_stream_t* AudioFlinger::RecordThread::stream()
4917{
4918    if (mInput == NULL) {
4919        return NULL;
4920    }
4921    return &mInput->stream->common;
4922}
4923
4924
4925// ----------------------------------------------------------------------------
4926
4927int AudioFlinger::openOutput(uint32_t *pDevices,
4928                                uint32_t *pSamplingRate,
4929                                audio_format_t *pFormat,
4930                                uint32_t *pChannels,
4931                                uint32_t *pLatencyMs,
4932                                uint32_t flags)
4933{
4934    status_t status;
4935    PlaybackThread *thread = NULL;
4936    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4937    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4938    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
4939    uint32_t channels = pChannels ? *pChannels : 0;
4940    uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4941    audio_stream_out_t *outStream;
4942    audio_hw_device_t *outHwDev;
4943
4944    ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4945            pDevices ? *pDevices : 0,
4946            samplingRate,
4947            format,
4948            channels,
4949            flags);
4950
4951    if (pDevices == NULL || *pDevices == 0) {
4952        return 0;
4953    }
4954
4955    Mutex::Autolock _l(mLock);
4956
4957    outHwDev = findSuitableHwDev_l(*pDevices);
4958    if (outHwDev == NULL)
4959        return 0;
4960
4961    status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
4962                                          &channels, &samplingRate, &outStream);
4963    ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4964            outStream,
4965            samplingRate,
4966            format,
4967            channels,
4968            status);
4969
4970    mHardwareStatus = AUDIO_HW_IDLE;
4971    if (outStream != NULL) {
4972        AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
4973        int id = nextUniqueId();
4974
4975        if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4976            (format != AUDIO_FORMAT_PCM_16_BIT) ||
4977            (channels != AUDIO_CHANNEL_OUT_STEREO)) {
4978            thread = new DirectOutputThread(this, output, id, *pDevices);
4979            ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4980        } else {
4981            thread = new MixerThread(this, output, id, *pDevices);
4982            ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
4983        }
4984        mPlaybackThreads.add(id, thread);
4985
4986        if (pSamplingRate) *pSamplingRate = samplingRate;
4987        if (pFormat) *pFormat = format;
4988        if (pChannels) *pChannels = channels;
4989        if (pLatencyMs) *pLatencyMs = thread->latency();
4990
4991        // notify client processes of the new output creation
4992        thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4993        return id;
4994    }
4995
4996    return 0;
4997}
4998
4999int AudioFlinger::openDuplicateOutput(int output1, int output2)
5000{
5001    Mutex::Autolock _l(mLock);
5002    MixerThread *thread1 = checkMixerThread_l(output1);
5003    MixerThread *thread2 = checkMixerThread_l(output2);
5004
5005    if (thread1 == NULL || thread2 == NULL) {
5006        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
5007        return 0;
5008    }
5009
5010    int id = nextUniqueId();
5011    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5012    thread->addOutputTrack(thread2);
5013    mPlaybackThreads.add(id, thread);
5014    // notify client processes of the new output creation
5015    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5016    return id;
5017}
5018
5019status_t AudioFlinger::closeOutput(int output)
5020{
5021    // keep strong reference on the playback thread so that
5022    // it is not destroyed while exit() is executed
5023    sp <PlaybackThread> thread;
5024    {
5025        Mutex::Autolock _l(mLock);
5026        thread = checkPlaybackThread_l(output);
5027        if (thread == NULL) {
5028            return BAD_VALUE;
5029        }
5030
5031        ALOGV("closeOutput() %d", output);
5032
5033        if (thread->type() == ThreadBase::MIXER) {
5034            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5035                if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
5036                    DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5037                    dupThread->removeOutputTrack((MixerThread *)thread.get());
5038                }
5039            }
5040        }
5041        void *param2 = 0;
5042        audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5043        mPlaybackThreads.removeItem(output);
5044    }
5045    thread->exit();
5046
5047    if (thread->type() != ThreadBase::DUPLICATING) {
5048        AudioStreamOut *out = thread->clearOutput();
5049        assert(out != NULL);
5050        // from now on thread->mOutput is NULL
5051        out->hwDev->close_output_stream(out->hwDev, out->stream);
5052        delete out;
5053    }
5054    return NO_ERROR;
5055}
5056
5057status_t AudioFlinger::suspendOutput(int output)
5058{
5059    Mutex::Autolock _l(mLock);
5060    PlaybackThread *thread = checkPlaybackThread_l(output);
5061
5062    if (thread == NULL) {
5063        return BAD_VALUE;
5064    }
5065
5066    ALOGV("suspendOutput() %d", output);
5067    thread->suspend();
5068
5069    return NO_ERROR;
5070}
5071
5072status_t AudioFlinger::restoreOutput(int output)
5073{
5074    Mutex::Autolock _l(mLock);
5075    PlaybackThread *thread = checkPlaybackThread_l(output);
5076
5077    if (thread == NULL) {
5078        return BAD_VALUE;
5079    }
5080
5081    ALOGV("restoreOutput() %d", output);
5082
5083    thread->restore();
5084
5085    return NO_ERROR;
5086}
5087
5088int AudioFlinger::openInput(uint32_t *pDevices,
5089                                uint32_t *pSamplingRate,
5090                                audio_format_t *pFormat,
5091                                uint32_t *pChannels,
5092                                uint32_t acoustics)
5093{
5094    status_t status;
5095    RecordThread *thread = NULL;
5096    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5097    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
5098    uint32_t channels = pChannels ? *pChannels : 0;
5099    uint32_t reqSamplingRate = samplingRate;
5100    audio_format_t reqFormat = format;
5101    uint32_t reqChannels = channels;
5102    audio_stream_in_t *inStream;
5103    audio_hw_device_t *inHwDev;
5104
5105    if (pDevices == NULL || *pDevices == 0) {
5106        return 0;
5107    }
5108
5109    Mutex::Autolock _l(mLock);
5110
5111    inHwDev = findSuitableHwDev_l(*pDevices);
5112    if (inHwDev == NULL)
5113        return 0;
5114
5115    status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
5116                                        &channels, &samplingRate,
5117                                        (audio_in_acoustics_t)acoustics,
5118                                        &inStream);
5119    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
5120            inStream,
5121            samplingRate,
5122            format,
5123            channels,
5124            acoustics,
5125            status);
5126
5127    // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5128    // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5129    // or stereo to mono conversions on 16 bit PCM inputs.
5130    if (inStream == NULL && status == BAD_VALUE &&
5131        reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
5132        (samplingRate <= 2 * reqSamplingRate) &&
5133        (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
5134        ALOGV("openInput() reopening with proposed sampling rate and channels");
5135        status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
5136                                            &channels, &samplingRate,
5137                                            (audio_in_acoustics_t)acoustics,
5138                                            &inStream);
5139    }
5140
5141    if (inStream != NULL) {
5142        AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5143
5144        int id = nextUniqueId();
5145        // Start record thread
5146        // RecorThread require both input and output device indication to forward to audio
5147        // pre processing modules
5148        uint32_t device = (*pDevices) | primaryOutputDevice_l();
5149        thread = new RecordThread(this,
5150                                  input,
5151                                  reqSamplingRate,
5152                                  reqChannels,
5153                                  id,
5154                                  device);
5155        mRecordThreads.add(id, thread);
5156        ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
5157        if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5158        if (pFormat) *pFormat = format;
5159        if (pChannels) *pChannels = reqChannels;
5160
5161        input->stream->common.standby(&input->stream->common);
5162
5163        // notify client processes of the new input creation
5164        thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5165        return id;
5166    }
5167
5168    return 0;
5169}
5170
5171status_t AudioFlinger::closeInput(int input)
5172{
5173    // keep strong reference on the record thread so that
5174    // it is not destroyed while exit() is executed
5175    sp <RecordThread> thread;
5176    {
5177        Mutex::Autolock _l(mLock);
5178        thread = checkRecordThread_l(input);
5179        if (thread == NULL) {
5180            return BAD_VALUE;
5181        }
5182
5183        ALOGV("closeInput() %d", input);
5184        void *param2 = 0;
5185        audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5186        mRecordThreads.removeItem(input);
5187    }
5188    thread->exit();
5189
5190    AudioStreamIn *in = thread->clearInput();
5191    assert(in != NULL);
5192    // from now on thread->mInput is NULL
5193    in->hwDev->close_input_stream(in->hwDev, in->stream);
5194    delete in;
5195
5196    return NO_ERROR;
5197}
5198
5199status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
5200{
5201    Mutex::Autolock _l(mLock);
5202    MixerThread *dstThread = checkMixerThread_l(output);
5203    if (dstThread == NULL) {
5204        ALOGW("setStreamOutput() bad output id %d", output);
5205        return BAD_VALUE;
5206    }
5207
5208    ALOGV("setStreamOutput() stream %d to output %d", stream, output);
5209    audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5210
5211    dstThread->setStreamValid(stream, true);
5212
5213    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5214        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5215        if (thread != dstThread &&
5216            thread->type() != ThreadBase::DIRECT) {
5217            MixerThread *srcThread = (MixerThread *)thread;
5218            srcThread->setStreamValid(stream, false);
5219            srcThread->invalidateTracks(stream);
5220        }
5221    }
5222
5223    return NO_ERROR;
5224}
5225
5226
5227int AudioFlinger::newAudioSessionId()
5228{
5229    return nextUniqueId();
5230}
5231
5232void AudioFlinger::acquireAudioSessionId(int audioSession)
5233{
5234    Mutex::Autolock _l(mLock);
5235    int caller = IPCThreadState::self()->getCallingPid();
5236    ALOGV("acquiring %d from %d", audioSession, caller);
5237    int num = mAudioSessionRefs.size();
5238    for (int i = 0; i< num; i++) {
5239        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5240        if (ref->sessionid == audioSession && ref->pid == caller) {
5241            ref->cnt++;
5242            ALOGV(" incremented refcount to %d", ref->cnt);
5243            return;
5244        }
5245    }
5246    AudioSessionRef *ref = new AudioSessionRef();
5247    ref->sessionid = audioSession;
5248    ref->pid = caller;
5249    ref->cnt = 1;
5250    mAudioSessionRefs.push(ref);
5251    ALOGV(" added new entry for %d", ref->sessionid);
5252}
5253
5254void AudioFlinger::releaseAudioSessionId(int audioSession)
5255{
5256    Mutex::Autolock _l(mLock);
5257    int caller = IPCThreadState::self()->getCallingPid();
5258    ALOGV("releasing %d from %d", audioSession, caller);
5259    int num = mAudioSessionRefs.size();
5260    for (int i = 0; i< num; i++) {
5261        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5262        if (ref->sessionid == audioSession && ref->pid == caller) {
5263            ref->cnt--;
5264            ALOGV(" decremented refcount to %d", ref->cnt);
5265            if (ref->cnt == 0) {
5266                mAudioSessionRefs.removeAt(i);
5267                delete ref;
5268                purgeStaleEffects_l();
5269            }
5270            return;
5271        }
5272    }
5273    ALOGW("session id %d not found for pid %d", audioSession, caller);
5274}
5275
5276void AudioFlinger::purgeStaleEffects_l() {
5277
5278    ALOGV("purging stale effects");
5279
5280    Vector< sp<EffectChain> > chains;
5281
5282    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5283        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5284        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5285            sp<EffectChain> ec = t->mEffectChains[j];
5286            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5287                chains.push(ec);
5288            }
5289        }
5290    }
5291    for (size_t i = 0; i < mRecordThreads.size(); i++) {
5292        sp<RecordThread> t = mRecordThreads.valueAt(i);
5293        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5294            sp<EffectChain> ec = t->mEffectChains[j];
5295            chains.push(ec);
5296        }
5297    }
5298
5299    for (size_t i = 0; i < chains.size(); i++) {
5300        sp<EffectChain> ec = chains[i];
5301        int sessionid = ec->sessionId();
5302        sp<ThreadBase> t = ec->mThread.promote();
5303        if (t == 0) {
5304            continue;
5305        }
5306        size_t numsessionrefs = mAudioSessionRefs.size();
5307        bool found = false;
5308        for (size_t k = 0; k < numsessionrefs; k++) {
5309            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5310            if (ref->sessionid == sessionid) {
5311                ALOGV(" session %d still exists for %d with %d refs",
5312                     sessionid, ref->pid, ref->cnt);
5313                found = true;
5314                break;
5315            }
5316        }
5317        if (!found) {
5318            // remove all effects from the chain
5319            while (ec->mEffects.size()) {
5320                sp<EffectModule> effect = ec->mEffects[0];
5321                effect->unPin();
5322                Mutex::Autolock _l (t->mLock);
5323                t->removeEffect_l(effect);
5324                for (size_t j = 0; j < effect->mHandles.size(); j++) {
5325                    sp<EffectHandle> handle = effect->mHandles[j].promote();
5326                    if (handle != 0) {
5327                        handle->mEffect.clear();
5328                        if (handle->mHasControl && handle->mEnabled) {
5329                            t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5330                        }
5331                    }
5332                }
5333                AudioSystem::unregisterEffect(effect->id());
5334            }
5335        }
5336    }
5337    return;
5338}
5339
5340// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5341AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5342{
5343    PlaybackThread *thread = NULL;
5344    if (mPlaybackThreads.indexOfKey(output) >= 0) {
5345        thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5346    }
5347    return thread;
5348}
5349
5350// checkMixerThread_l() must be called with AudioFlinger::mLock held
5351AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5352{
5353    PlaybackThread *thread = checkPlaybackThread_l(output);
5354    if (thread != NULL) {
5355        if (thread->type() == ThreadBase::DIRECT) {
5356            thread = NULL;
5357        }
5358    }
5359    return (MixerThread *)thread;
5360}
5361
5362// checkRecordThread_l() must be called with AudioFlinger::mLock held
5363AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5364{
5365    RecordThread *thread = NULL;
5366    if (mRecordThreads.indexOfKey(input) >= 0) {
5367        thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5368    }
5369    return thread;
5370}
5371
5372uint32_t AudioFlinger::nextUniqueId()
5373{
5374    return android_atomic_inc(&mNextUniqueId);
5375}
5376
5377AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5378{
5379    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5380        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5381        AudioStreamOut *output = thread->getOutput();
5382        if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
5383            return thread;
5384        }
5385    }
5386    return NULL;
5387}
5388
5389uint32_t AudioFlinger::primaryOutputDevice_l()
5390{
5391    PlaybackThread *thread = primaryPlaybackThread_l();
5392
5393    if (thread == NULL) {
5394        return 0;
5395    }
5396
5397    return thread->device();
5398}
5399
5400
5401// ----------------------------------------------------------------------------
5402//  Effect management
5403// ----------------------------------------------------------------------------
5404
5405
5406status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5407{
5408    Mutex::Autolock _l(mLock);
5409    return EffectQueryNumberEffects(numEffects);
5410}
5411
5412status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5413{
5414    Mutex::Autolock _l(mLock);
5415    return EffectQueryEffect(index, descriptor);
5416}
5417
5418status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5419{
5420    Mutex::Autolock _l(mLock);
5421    return EffectGetDescriptor(pUuid, descriptor);
5422}
5423
5424
5425sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5426        effect_descriptor_t *pDesc,
5427        const sp<IEffectClient>& effectClient,
5428        int32_t priority,
5429        int io,
5430        int sessionId,
5431        status_t *status,
5432        int *id,
5433        int *enabled)
5434{
5435    status_t lStatus = NO_ERROR;
5436    sp<EffectHandle> handle;
5437    effect_descriptor_t desc;
5438    sp<Client> client;
5439    wp<Client> wclient;
5440
5441    ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5442            pid, effectClient.get(), priority, sessionId, io);
5443
5444    if (pDesc == NULL) {
5445        lStatus = BAD_VALUE;
5446        goto Exit;
5447    }
5448
5449    // check audio settings permission for global effects
5450    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
5451        lStatus = PERMISSION_DENIED;
5452        goto Exit;
5453    }
5454
5455    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
5456    // that can only be created by audio policy manager (running in same process)
5457    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
5458        lStatus = PERMISSION_DENIED;
5459        goto Exit;
5460    }
5461
5462    if (io == 0) {
5463        if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
5464            // output must be specified by AudioPolicyManager when using session
5465            // AUDIO_SESSION_OUTPUT_STAGE
5466            lStatus = BAD_VALUE;
5467            goto Exit;
5468        } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
5469            // if the output returned by getOutputForEffect() is removed before we lock the
5470            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
5471            // and we will exit safely
5472            io = AudioSystem::getOutputForEffect(&desc);
5473        }
5474    }
5475
5476    {
5477        Mutex::Autolock _l(mLock);
5478
5479
5480        if (!EffectIsNullUuid(&pDesc->uuid)) {
5481            // if uuid is specified, request effect descriptor
5482            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5483            if (lStatus < 0) {
5484                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5485                goto Exit;
5486            }
5487        } else {
5488            // if uuid is not specified, look for an available implementation
5489            // of the required type in effect factory
5490            if (EffectIsNullUuid(&pDesc->type)) {
5491                ALOGW("createEffect() no effect type");
5492                lStatus = BAD_VALUE;
5493                goto Exit;
5494            }
5495            uint32_t numEffects = 0;
5496            effect_descriptor_t d;
5497            d.flags = 0; // prevent compiler warning
5498            bool found = false;
5499
5500            lStatus = EffectQueryNumberEffects(&numEffects);
5501            if (lStatus < 0) {
5502                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5503                goto Exit;
5504            }
5505            for (uint32_t i = 0; i < numEffects; i++) {
5506                lStatus = EffectQueryEffect(i, &desc);
5507                if (lStatus < 0) {
5508                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5509                    continue;
5510                }
5511                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5512                    // If matching type found save effect descriptor. If the session is
5513                    // 0 and the effect is not auxiliary, continue enumeration in case
5514                    // an auxiliary version of this effect type is available
5515                    found = true;
5516                    memcpy(&d, &desc, sizeof(effect_descriptor_t));
5517                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
5518                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5519                        break;
5520                    }
5521                }
5522            }
5523            if (!found) {
5524                lStatus = BAD_VALUE;
5525                ALOGW("createEffect() effect not found");
5526                goto Exit;
5527            }
5528            // For same effect type, chose auxiliary version over insert version if
5529            // connect to output mix (Compliance to OpenSL ES)
5530            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
5531                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5532                memcpy(&desc, &d, sizeof(effect_descriptor_t));
5533            }
5534        }
5535
5536        // Do not allow auxiliary effects on a session different from 0 (output mix)
5537        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
5538             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5539            lStatus = INVALID_OPERATION;
5540            goto Exit;
5541        }
5542
5543        // check recording permission for visualizer
5544        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5545            !recordingAllowed()) {
5546            lStatus = PERMISSION_DENIED;
5547            goto Exit;
5548        }
5549
5550        // return effect descriptor
5551        memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5552
5553        // If output is not specified try to find a matching audio session ID in one of the
5554        // output threads.
5555        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5556        // because of code checking output when entering the function.
5557        // Note: io is never 0 when creating an effect on an input
5558        if (io == 0) {
5559             // look for the thread where the specified audio session is present
5560            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5561                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5562                    io = mPlaybackThreads.keyAt(i);
5563                    break;
5564                }
5565            }
5566            if (io == 0) {
5567               for (size_t i = 0; i < mRecordThreads.size(); i++) {
5568                   if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5569                       io = mRecordThreads.keyAt(i);
5570                       break;
5571                   }
5572               }
5573            }
5574            // If no output thread contains the requested session ID, default to
5575            // first output. The effect chain will be moved to the correct output
5576            // thread when a track with the same session ID is created
5577            if (io == 0 && mPlaybackThreads.size()) {
5578                io = mPlaybackThreads.keyAt(0);
5579            }
5580            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
5581        }
5582        ThreadBase *thread = checkRecordThread_l(io);
5583        if (thread == NULL) {
5584            thread = checkPlaybackThread_l(io);
5585            if (thread == NULL) {
5586                ALOGE("createEffect() unknown output thread");
5587                lStatus = BAD_VALUE;
5588                goto Exit;
5589            }
5590        }
5591
5592        wclient = mClients.valueFor(pid);
5593
5594        if (wclient != NULL) {
5595            client = wclient.promote();
5596        } else {
5597            client = new Client(this, pid);
5598            mClients.add(pid, client);
5599        }
5600
5601        // create effect on selected output thread
5602        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5603                &desc, enabled, &lStatus);
5604        if (handle != 0 && id != NULL) {
5605            *id = handle->id();
5606        }
5607    }
5608
5609Exit:
5610    if(status) {
5611        *status = lStatus;
5612    }
5613    return handle;
5614}
5615
5616status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
5617{
5618    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
5619            sessionId, srcOutput, dstOutput);
5620    Mutex::Autolock _l(mLock);
5621    if (srcOutput == dstOutput) {
5622        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
5623        return NO_ERROR;
5624    }
5625    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5626    if (srcThread == NULL) {
5627        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
5628        return BAD_VALUE;
5629    }
5630    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5631    if (dstThread == NULL) {
5632        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
5633        return BAD_VALUE;
5634    }
5635
5636    Mutex::Autolock _dl(dstThread->mLock);
5637    Mutex::Autolock _sl(srcThread->mLock);
5638    moveEffectChain_l(sessionId, srcThread, dstThread, false);
5639
5640    return NO_ERROR;
5641}
5642
5643// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
5644status_t AudioFlinger::moveEffectChain_l(int sessionId,
5645                                   AudioFlinger::PlaybackThread *srcThread,
5646                                   AudioFlinger::PlaybackThread *dstThread,
5647                                   bool reRegister)
5648{
5649    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
5650            sessionId, srcThread, dstThread);
5651
5652    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
5653    if (chain == 0) {
5654        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
5655                sessionId, srcThread);
5656        return INVALID_OPERATION;
5657    }
5658
5659    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
5660    // so that a new chain is created with correct parameters when first effect is added. This is
5661    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
5662    // removed.
5663    srcThread->removeEffectChain_l(chain);
5664
5665    // transfer all effects one by one so that new effect chain is created on new thread with
5666    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
5667    int dstOutput = dstThread->id();
5668    sp<EffectChain> dstChain;
5669    uint32_t strategy = 0; // prevent compiler warning
5670    sp<EffectModule> effect = chain->getEffectFromId_l(0);
5671    while (effect != 0) {
5672        srcThread->removeEffect_l(effect);
5673        dstThread->addEffect_l(effect);
5674        // removeEffect_l() has stopped the effect if it was active so it must be restarted
5675        if (effect->state() == EffectModule::ACTIVE ||
5676                effect->state() == EffectModule::STOPPING) {
5677            effect->start();
5678        }
5679        // if the move request is not received from audio policy manager, the effect must be
5680        // re-registered with the new strategy and output
5681        if (dstChain == 0) {
5682            dstChain = effect->chain().promote();
5683            if (dstChain == 0) {
5684                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5685                srcThread->addEffect_l(effect);
5686                return NO_INIT;
5687            }
5688            strategy = dstChain->strategy();
5689        }
5690        if (reRegister) {
5691            AudioSystem::unregisterEffect(effect->id());
5692            AudioSystem::registerEffect(&effect->desc(),
5693                                        dstOutput,
5694                                        strategy,
5695                                        sessionId,
5696                                        effect->id());
5697        }
5698        effect = chain->getEffectFromId_l(0);
5699    }
5700
5701    return NO_ERROR;
5702}
5703
5704
5705// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
5706sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
5707        const sp<AudioFlinger::Client>& client,
5708        const sp<IEffectClient>& effectClient,
5709        int32_t priority,
5710        int sessionId,
5711        effect_descriptor_t *desc,
5712        int *enabled,
5713        status_t *status
5714        )
5715{
5716    sp<EffectModule> effect;
5717    sp<EffectHandle> handle;
5718    status_t lStatus;
5719    sp<EffectChain> chain;
5720    bool chainCreated = false;
5721    bool effectCreated = false;
5722    bool effectRegistered = false;
5723
5724    lStatus = initCheck();
5725    if (lStatus != NO_ERROR) {
5726        ALOGW("createEffect_l() Audio driver not initialized.");
5727        goto Exit;
5728    }
5729
5730    // Do not allow effects with session ID 0 on direct output or duplicating threads
5731    // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
5732    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
5733        ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5734                desc->name, sessionId);
5735        lStatus = BAD_VALUE;
5736        goto Exit;
5737    }
5738    // Only Pre processor effects are allowed on input threads and only on input threads
5739    if ((mType == RECORD &&
5740            (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5741            (mType != RECORD &&
5742                    (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5743        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5744                desc->name, desc->flags, mType);
5745        lStatus = BAD_VALUE;
5746        goto Exit;
5747    }
5748
5749    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5750
5751    { // scope for mLock
5752        Mutex::Autolock _l(mLock);
5753
5754        // check for existing effect chain with the requested audio session
5755        chain = getEffectChain_l(sessionId);
5756        if (chain == 0) {
5757            // create a new chain for this session
5758            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
5759            chain = new EffectChain(this, sessionId);
5760            addEffectChain_l(chain);
5761            chain->setStrategy(getStrategyForSession_l(sessionId));
5762            chainCreated = true;
5763        } else {
5764            effect = chain->getEffectFromDesc_l(desc);
5765        }
5766
5767        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
5768
5769        if (effect == 0) {
5770            int id = mAudioFlinger->nextUniqueId();
5771            // Check CPU and memory usage
5772            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
5773            if (lStatus != NO_ERROR) {
5774                goto Exit;
5775            }
5776            effectRegistered = true;
5777            // create a new effect module if none present in the chain
5778            effect = new EffectModule(this, chain, desc, id, sessionId);
5779            lStatus = effect->status();
5780            if (lStatus != NO_ERROR) {
5781                goto Exit;
5782            }
5783            lStatus = chain->addEffect_l(effect);
5784            if (lStatus != NO_ERROR) {
5785                goto Exit;
5786            }
5787            effectCreated = true;
5788
5789            effect->setDevice(mDevice);
5790            effect->setMode(mAudioFlinger->getMode());
5791        }
5792        // create effect handle and connect it to effect module
5793        handle = new EffectHandle(effect, client, effectClient, priority);
5794        lStatus = effect->addHandle(handle);
5795        if (enabled) {
5796            *enabled = (int)effect->isEnabled();
5797        }
5798    }
5799
5800Exit:
5801    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
5802        Mutex::Autolock _l(mLock);
5803        if (effectCreated) {
5804            chain->removeEffect_l(effect);
5805        }
5806        if (effectRegistered) {
5807            AudioSystem::unregisterEffect(effect->id());
5808        }
5809        if (chainCreated) {
5810            removeEffectChain_l(chain);
5811        }
5812        handle.clear();
5813    }
5814
5815    if(status) {
5816        *status = lStatus;
5817    }
5818    return handle;
5819}
5820
5821sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5822{
5823    sp<EffectModule> effect;
5824
5825    sp<EffectChain> chain = getEffectChain_l(sessionId);
5826    if (chain != 0) {
5827        effect = chain->getEffectFromId_l(effectId);
5828    }
5829    return effect;
5830}
5831
5832// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5833// PlaybackThread::mLock held
5834status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
5835{
5836    // check for existing effect chain with the requested audio session
5837    int sessionId = effect->sessionId();
5838    sp<EffectChain> chain = getEffectChain_l(sessionId);
5839    bool chainCreated = false;
5840
5841    if (chain == 0) {
5842        // create a new chain for this session
5843        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
5844        chain = new EffectChain(this, sessionId);
5845        addEffectChain_l(chain);
5846        chain->setStrategy(getStrategyForSession_l(sessionId));
5847        chainCreated = true;
5848    }
5849    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5850
5851    if (chain->getEffectFromId_l(effect->id()) != 0) {
5852        ALOGW("addEffect_l() %p effect %s already present in chain %p",
5853                this, effect->desc().name, chain.get());
5854        return BAD_VALUE;
5855    }
5856
5857    status_t status = chain->addEffect_l(effect);
5858    if (status != NO_ERROR) {
5859        if (chainCreated) {
5860            removeEffectChain_l(chain);
5861        }
5862        return status;
5863    }
5864
5865    effect->setDevice(mDevice);
5866    effect->setMode(mAudioFlinger->getMode());
5867    return NO_ERROR;
5868}
5869
5870void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
5871
5872    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
5873    effect_descriptor_t desc = effect->desc();
5874    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5875        detachAuxEffect_l(effect->id());
5876    }
5877
5878    sp<EffectChain> chain = effect->chain().promote();
5879    if (chain != 0) {
5880        // remove effect chain if removing last effect
5881        if (chain->removeEffect_l(effect) == 0) {
5882            removeEffectChain_l(chain);
5883        }
5884    } else {
5885        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5886    }
5887}
5888
5889void AudioFlinger::ThreadBase::lockEffectChains_l(
5890        Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5891{
5892    effectChains = mEffectChains;
5893    for (size_t i = 0; i < mEffectChains.size(); i++) {
5894        mEffectChains[i]->lock();
5895    }
5896}
5897
5898void AudioFlinger::ThreadBase::unlockEffectChains(
5899        Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5900{
5901    for (size_t i = 0; i < effectChains.size(); i++) {
5902        effectChains[i]->unlock();
5903    }
5904}
5905
5906sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5907{
5908    Mutex::Autolock _l(mLock);
5909    return getEffectChain_l(sessionId);
5910}
5911
5912sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5913{
5914    sp<EffectChain> chain;
5915
5916    size_t size = mEffectChains.size();
5917    for (size_t i = 0; i < size; i++) {
5918        if (mEffectChains[i]->sessionId() == sessionId) {
5919            chain = mEffectChains[i];
5920            break;
5921        }
5922    }
5923    return chain;
5924}
5925
5926void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
5927{
5928    Mutex::Autolock _l(mLock);
5929    size_t size = mEffectChains.size();
5930    for (size_t i = 0; i < size; i++) {
5931        mEffectChains[i]->setMode_l(mode);
5932    }
5933}
5934
5935void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
5936                                                    const wp<EffectHandle>& handle,
5937                                                    bool unpiniflast) {
5938
5939    Mutex::Autolock _l(mLock);
5940    ALOGV("disconnectEffect() %p effect %p", this, effect.get());
5941    // delete the effect module if removing last handle on it
5942    if (effect->removeHandle(handle) == 0) {
5943        if (!effect->isPinned() || unpiniflast) {
5944            removeEffect_l(effect);
5945            AudioSystem::unregisterEffect(effect->id());
5946        }
5947    }
5948}
5949
5950status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5951{
5952    int session = chain->sessionId();
5953    int16_t *buffer = mMixBuffer;
5954    bool ownsBuffer = false;
5955
5956    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5957    if (session > 0) {
5958        // Only one effect chain can be present in direct output thread and it uses
5959        // the mix buffer as input
5960        if (mType != DIRECT) {
5961            size_t numSamples = mFrameCount * mChannelCount;
5962            buffer = new int16_t[numSamples];
5963            memset(buffer, 0, numSamples * sizeof(int16_t));
5964            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5965            ownsBuffer = true;
5966        }
5967
5968        // Attach all tracks with same session ID to this chain.
5969        for (size_t i = 0; i < mTracks.size(); ++i) {
5970            sp<Track> track = mTracks[i];
5971            if (session == track->sessionId()) {
5972                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5973                track->setMainBuffer(buffer);
5974                chain->incTrackCnt();
5975            }
5976        }
5977
5978        // indicate all active tracks in the chain
5979        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5980            sp<Track> track = mActiveTracks[i].promote();
5981            if (track == 0) continue;
5982            if (session == track->sessionId()) {
5983                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5984                chain->incActiveTrackCnt();
5985            }
5986        }
5987    }
5988
5989    chain->setInBuffer(buffer, ownsBuffer);
5990    chain->setOutBuffer(mMixBuffer);
5991    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
5992    // chains list in order to be processed last as it contains output stage effects
5993    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5994    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
5995    // after track specific effects and before output stage
5996    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5997    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
5998    // Effect chain for other sessions are inserted at beginning of effect
5999    // chains list to be processed before output mix effects. Relative order between other
6000    // sessions is not important
6001    size_t size = mEffectChains.size();
6002    size_t i = 0;
6003    for (i = 0; i < size; i++) {
6004        if (mEffectChains[i]->sessionId() < session) break;
6005    }
6006    mEffectChains.insertAt(chain, i);
6007    checkSuspendOnAddEffectChain_l(chain);
6008
6009    return NO_ERROR;
6010}
6011
6012size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6013{
6014    int session = chain->sessionId();
6015
6016    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
6017
6018    for (size_t i = 0; i < mEffectChains.size(); i++) {
6019        if (chain == mEffectChains[i]) {
6020            mEffectChains.removeAt(i);
6021            // detach all active tracks from the chain
6022            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6023                sp<Track> track = mActiveTracks[i].promote();
6024                if (track == 0) continue;
6025                if (session == track->sessionId()) {
6026                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
6027                            chain.get(), session);
6028                    chain->decActiveTrackCnt();
6029                }
6030            }
6031
6032            // detach all tracks with same session ID from this chain
6033            for (size_t i = 0; i < mTracks.size(); ++i) {
6034                sp<Track> track = mTracks[i];
6035                if (session == track->sessionId()) {
6036                    track->setMainBuffer(mMixBuffer);
6037                    chain->decTrackCnt();
6038                }
6039            }
6040            break;
6041        }
6042    }
6043    return mEffectChains.size();
6044}
6045
6046status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6047        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
6048{
6049    Mutex::Autolock _l(mLock);
6050    return attachAuxEffect_l(track, EffectId);
6051}
6052
6053status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6054        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
6055{
6056    status_t status = NO_ERROR;
6057
6058    if (EffectId == 0) {
6059        track->setAuxBuffer(0, NULL);
6060    } else {
6061        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6062        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
6063        if (effect != 0) {
6064            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6065                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6066            } else {
6067                status = INVALID_OPERATION;
6068            }
6069        } else {
6070            status = BAD_VALUE;
6071        }
6072    }
6073    return status;
6074}
6075
6076void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6077{
6078     for (size_t i = 0; i < mTracks.size(); ++i) {
6079        sp<Track> track = mTracks[i];
6080        if (track->auxEffectId() == effectId) {
6081            attachAuxEffect_l(track, 0);
6082        }
6083    }
6084}
6085
6086status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6087{
6088    // only one chain per input thread
6089    if (mEffectChains.size() != 0) {
6090        return INVALID_OPERATION;
6091    }
6092    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6093
6094    chain->setInBuffer(NULL);
6095    chain->setOutBuffer(NULL);
6096
6097    checkSuspendOnAddEffectChain_l(chain);
6098
6099    mEffectChains.add(chain);
6100
6101    return NO_ERROR;
6102}
6103
6104size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6105{
6106    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6107    ALOGW_IF(mEffectChains.size() != 1,
6108            "removeEffectChain_l() %p invalid chain size %d on thread %p",
6109            chain.get(), mEffectChains.size(), this);
6110    if (mEffectChains.size() == 1) {
6111        mEffectChains.removeAt(0);
6112    }
6113    return 0;
6114}
6115
6116// ----------------------------------------------------------------------------
6117//  EffectModule implementation
6118// ----------------------------------------------------------------------------
6119
6120#undef LOG_TAG
6121#define LOG_TAG "AudioFlinger::EffectModule"
6122
6123AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6124                                        const wp<AudioFlinger::EffectChain>& chain,
6125                                        effect_descriptor_t *desc,
6126                                        int id,
6127                                        int sessionId)
6128    : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
6129      mStatus(NO_INIT), mState(IDLE), mSuspended(false)
6130{
6131    ALOGV("Constructor %p", this);
6132    int lStatus;
6133    sp<ThreadBase> thread = mThread.promote();
6134    if (thread == 0) {
6135        return;
6136    }
6137
6138    memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6139
6140    // create effect engine from effect factory
6141    mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
6142
6143    if (mStatus != NO_ERROR) {
6144        return;
6145    }
6146    lStatus = init();
6147    if (lStatus < 0) {
6148        mStatus = lStatus;
6149        goto Error;
6150    }
6151
6152    if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6153        mPinned = true;
6154    }
6155    ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6156    return;
6157Error:
6158    EffectRelease(mEffectInterface);
6159    mEffectInterface = NULL;
6160    ALOGV("Constructor Error %d", mStatus);
6161}
6162
6163AudioFlinger::EffectModule::~EffectModule()
6164{
6165    ALOGV("Destructor %p", this);
6166    if (mEffectInterface != NULL) {
6167        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6168                (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6169            sp<ThreadBase> thread = mThread.promote();
6170            if (thread != 0) {
6171                audio_stream_t *stream = thread->stream();
6172                if (stream != NULL) {
6173                    stream->remove_audio_effect(stream, mEffectInterface);
6174                }
6175            }
6176        }
6177        // release effect engine
6178        EffectRelease(mEffectInterface);
6179    }
6180}
6181
6182status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
6183{
6184    status_t status;
6185
6186    Mutex::Autolock _l(mLock);
6187    // First handle in mHandles has highest priority and controls the effect module
6188    int priority = handle->priority();
6189    size_t size = mHandles.size();
6190    sp<EffectHandle> h;
6191    size_t i;
6192    for (i = 0; i < size; i++) {
6193        h = mHandles[i].promote();
6194        if (h == 0) continue;
6195        if (h->priority() <= priority) break;
6196    }
6197    // if inserted in first place, move effect control from previous owner to this handle
6198    if (i == 0) {
6199        bool enabled = false;
6200        if (h != 0) {
6201            enabled = h->enabled();
6202            h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
6203        }
6204        handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
6205        status = NO_ERROR;
6206    } else {
6207        status = ALREADY_EXISTS;
6208    }
6209    ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
6210    mHandles.insertAt(handle, i);
6211    return status;
6212}
6213
6214size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6215{
6216    Mutex::Autolock _l(mLock);
6217    size_t size = mHandles.size();
6218    size_t i;
6219    for (i = 0; i < size; i++) {
6220        if (mHandles[i] == handle) break;
6221    }
6222    if (i == size) {
6223        return size;
6224    }
6225    ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6226
6227    bool enabled = false;
6228    EffectHandle *hdl = handle.unsafe_get();
6229    if (hdl) {
6230        ALOGV("removeHandle() unsafe_get OK");
6231        enabled = hdl->enabled();
6232    }
6233    mHandles.removeAt(i);
6234    size = mHandles.size();
6235    // if removed from first place, move effect control from this handle to next in line
6236    if (i == 0 && size != 0) {
6237        sp<EffectHandle> h = mHandles[0].promote();
6238        if (h != 0) {
6239            h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
6240        }
6241    }
6242
6243    // Prevent calls to process() and other functions on effect interface from now on.
6244    // The effect engine will be released by the destructor when the last strong reference on
6245    // this object is released which can happen after next process is called.
6246    if (size == 0 && !mPinned) {
6247        mState = DESTROYED;
6248    }
6249
6250    return size;
6251}
6252
6253sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6254{
6255    Mutex::Autolock _l(mLock);
6256    sp<EffectHandle> handle;
6257    if (mHandles.size() != 0) {
6258        handle = mHandles[0].promote();
6259    }
6260    return handle;
6261}
6262
6263void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
6264{
6265    ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
6266    // keep a strong reference on this EffectModule to avoid calling the
6267    // destructor before we exit
6268    sp<EffectModule> keep(this);
6269    {
6270        sp<ThreadBase> thread = mThread.promote();
6271        if (thread != 0) {
6272            thread->disconnectEffect(keep, handle, unpiniflast);
6273        }
6274    }
6275}
6276
6277void AudioFlinger::EffectModule::updateState() {
6278    Mutex::Autolock _l(mLock);
6279
6280    switch (mState) {
6281    case RESTART:
6282        reset_l();
6283        // FALL THROUGH
6284
6285    case STARTING:
6286        // clear auxiliary effect input buffer for next accumulation
6287        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6288            memset(mConfig.inputCfg.buffer.raw,
6289                   0,
6290                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6291        }
6292        start_l();
6293        mState = ACTIVE;
6294        break;
6295    case STOPPING:
6296        stop_l();
6297        mDisableWaitCnt = mMaxDisableWaitCnt;
6298        mState = STOPPED;
6299        break;
6300    case STOPPED:
6301        // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6302        // turn off sequence.
6303        if (--mDisableWaitCnt == 0) {
6304            reset_l();
6305            mState = IDLE;
6306        }
6307        break;
6308    default: //IDLE , ACTIVE, DESTROYED
6309        break;
6310    }
6311}
6312
6313void AudioFlinger::EffectModule::process()
6314{
6315    Mutex::Autolock _l(mLock);
6316
6317    if (mState == DESTROYED || mEffectInterface == NULL ||
6318            mConfig.inputCfg.buffer.raw == NULL ||
6319            mConfig.outputCfg.buffer.raw == NULL) {
6320        return;
6321    }
6322
6323    if (isProcessEnabled()) {
6324        // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6325        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6326            ditherAndClamp(mConfig.inputCfg.buffer.s32,
6327                                        mConfig.inputCfg.buffer.s32,
6328                                        mConfig.inputCfg.buffer.frameCount/2);
6329        }
6330
6331        // do the actual processing in the effect engine
6332        int ret = (*mEffectInterface)->process(mEffectInterface,
6333                                               &mConfig.inputCfg.buffer,
6334                                               &mConfig.outputCfg.buffer);
6335
6336        // force transition to IDLE state when engine is ready
6337        if (mState == STOPPED && ret == -ENODATA) {
6338            mDisableWaitCnt = 1;
6339        }
6340
6341        // clear auxiliary effect input buffer for next accumulation
6342        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6343            memset(mConfig.inputCfg.buffer.raw, 0,
6344                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6345        }
6346    } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
6347                mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6348        // If an insert effect is idle and input buffer is different from output buffer,
6349        // accumulate input onto output
6350        sp<EffectChain> chain = mChain.promote();
6351        if (chain != 0 && chain->activeTrackCnt() != 0) {
6352            size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2;  //always stereo here
6353            int16_t *in = mConfig.inputCfg.buffer.s16;
6354            int16_t *out = mConfig.outputCfg.buffer.s16;
6355            for (size_t i = 0; i < frameCnt; i++) {
6356                out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
6357            }
6358        }
6359    }
6360}
6361
6362void AudioFlinger::EffectModule::reset_l()
6363{
6364    if (mEffectInterface == NULL) {
6365        return;
6366    }
6367    (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6368}
6369
6370status_t AudioFlinger::EffectModule::configure()
6371{
6372    uint32_t channels;
6373    if (mEffectInterface == NULL) {
6374        return NO_INIT;
6375    }
6376
6377    sp<ThreadBase> thread = mThread.promote();
6378    if (thread == 0) {
6379        return DEAD_OBJECT;
6380    }
6381
6382    // TODO: handle configuration of effects replacing track process
6383    if (thread->channelCount() == 1) {
6384        channels = AUDIO_CHANNEL_OUT_MONO;
6385    } else {
6386        channels = AUDIO_CHANNEL_OUT_STEREO;
6387    }
6388
6389    if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6390        mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
6391    } else {
6392        mConfig.inputCfg.channels = channels;
6393    }
6394    mConfig.outputCfg.channels = channels;
6395    mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6396    mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6397    mConfig.inputCfg.samplingRate = thread->sampleRate();
6398    mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6399    mConfig.inputCfg.bufferProvider.cookie = NULL;
6400    mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6401    mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6402    mConfig.outputCfg.bufferProvider.cookie = NULL;
6403    mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6404    mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6405    mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6406    // Insert effect:
6407    // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
6408    // always overwrites output buffer: input buffer == output buffer
6409    // - in other sessions:
6410    //      last effect in the chain accumulates in output buffer: input buffer != output buffer
6411    //      other effect: overwrites output buffer: input buffer == output buffer
6412    // Auxiliary effect:
6413    //      accumulates in output buffer: input buffer != output buffer
6414    // Therefore: accumulate <=> input buffer != output buffer
6415    if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6416        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6417    } else {
6418        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6419    }
6420    mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6421    mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6422    mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6423    mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6424
6425    ALOGV("configure() %p thread %p buffer %p framecount %d",
6426            this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6427
6428    status_t cmdStatus;
6429    uint32_t size = sizeof(int);
6430    status_t status = (*mEffectInterface)->command(mEffectInterface,
6431                                                   EFFECT_CMD_SET_CONFIG,
6432                                                   sizeof(effect_config_t),
6433                                                   &mConfig,
6434                                                   &size,
6435                                                   &cmdStatus);
6436    if (status == 0) {
6437        status = cmdStatus;
6438    }
6439
6440    mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6441            (1000 * mConfig.outputCfg.buffer.frameCount);
6442
6443    return status;
6444}
6445
6446status_t AudioFlinger::EffectModule::init()
6447{
6448    Mutex::Autolock _l(mLock);
6449    if (mEffectInterface == NULL) {
6450        return NO_INIT;
6451    }
6452    status_t cmdStatus;
6453    uint32_t size = sizeof(status_t);
6454    status_t status = (*mEffectInterface)->command(mEffectInterface,
6455                                                   EFFECT_CMD_INIT,
6456                                                   0,
6457                                                   NULL,
6458                                                   &size,
6459                                                   &cmdStatus);
6460    if (status == 0) {
6461        status = cmdStatus;
6462    }
6463    return status;
6464}
6465
6466status_t AudioFlinger::EffectModule::start()
6467{
6468    Mutex::Autolock _l(mLock);
6469    return start_l();
6470}
6471
6472status_t AudioFlinger::EffectModule::start_l()
6473{
6474    if (mEffectInterface == NULL) {
6475        return NO_INIT;
6476    }
6477    status_t cmdStatus;
6478    uint32_t size = sizeof(status_t);
6479    status_t status = (*mEffectInterface)->command(mEffectInterface,
6480                                                   EFFECT_CMD_ENABLE,
6481                                                   0,
6482                                                   NULL,
6483                                                   &size,
6484                                                   &cmdStatus);
6485    if (status == 0) {
6486        status = cmdStatus;
6487    }
6488    if (status == 0 &&
6489            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6490             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6491        sp<ThreadBase> thread = mThread.promote();
6492        if (thread != 0) {
6493            audio_stream_t *stream = thread->stream();
6494            if (stream != NULL) {
6495                stream->add_audio_effect(stream, mEffectInterface);
6496            }
6497        }
6498    }
6499    return status;
6500}
6501
6502status_t AudioFlinger::EffectModule::stop()
6503{
6504    Mutex::Autolock _l(mLock);
6505    return stop_l();
6506}
6507
6508status_t AudioFlinger::EffectModule::stop_l()
6509{
6510    if (mEffectInterface == NULL) {
6511        return NO_INIT;
6512    }
6513    status_t cmdStatus;
6514    uint32_t size = sizeof(status_t);
6515    status_t status = (*mEffectInterface)->command(mEffectInterface,
6516                                                   EFFECT_CMD_DISABLE,
6517                                                   0,
6518                                                   NULL,
6519                                                   &size,
6520                                                   &cmdStatus);
6521    if (status == 0) {
6522        status = cmdStatus;
6523    }
6524    if (status == 0 &&
6525            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6526             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6527        sp<ThreadBase> thread = mThread.promote();
6528        if (thread != 0) {
6529            audio_stream_t *stream = thread->stream();
6530            if (stream != NULL) {
6531                stream->remove_audio_effect(stream, mEffectInterface);
6532            }
6533        }
6534    }
6535    return status;
6536}
6537
6538status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6539                                             uint32_t cmdSize,
6540                                             void *pCmdData,
6541                                             uint32_t *replySize,
6542                                             void *pReplyData)
6543{
6544    Mutex::Autolock _l(mLock);
6545//    ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6546
6547    if (mState == DESTROYED || mEffectInterface == NULL) {
6548        return NO_INIT;
6549    }
6550    status_t status = (*mEffectInterface)->command(mEffectInterface,
6551                                                   cmdCode,
6552                                                   cmdSize,
6553                                                   pCmdData,
6554                                                   replySize,
6555                                                   pReplyData);
6556    if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
6557        uint32_t size = (replySize == NULL) ? 0 : *replySize;
6558        for (size_t i = 1; i < mHandles.size(); i++) {
6559            sp<EffectHandle> h = mHandles[i].promote();
6560            if (h != 0) {
6561                h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6562            }
6563        }
6564    }
6565    return status;
6566}
6567
6568status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6569{
6570
6571    Mutex::Autolock _l(mLock);
6572    ALOGV("setEnabled %p enabled %d", this, enabled);
6573
6574    if (enabled != isEnabled()) {
6575        status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6576        if (enabled && status != NO_ERROR) {
6577            return status;
6578        }
6579
6580        switch (mState) {
6581        // going from disabled to enabled
6582        case IDLE:
6583            mState = STARTING;
6584            break;
6585        case STOPPED:
6586            mState = RESTART;
6587            break;
6588        case STOPPING:
6589            mState = ACTIVE;
6590            break;
6591
6592        // going from enabled to disabled
6593        case RESTART:
6594            mState = STOPPED;
6595            break;
6596        case STARTING:
6597            mState = IDLE;
6598            break;
6599        case ACTIVE:
6600            mState = STOPPING;
6601            break;
6602        case DESTROYED:
6603            return NO_ERROR; // simply ignore as we are being destroyed
6604        }
6605        for (size_t i = 1; i < mHandles.size(); i++) {
6606            sp<EffectHandle> h = mHandles[i].promote();
6607            if (h != 0) {
6608                h->setEnabled(enabled);
6609            }
6610        }
6611    }
6612    return NO_ERROR;
6613}
6614
6615bool AudioFlinger::EffectModule::isEnabled()
6616{
6617    switch (mState) {
6618    case RESTART:
6619    case STARTING:
6620    case ACTIVE:
6621        return true;
6622    case IDLE:
6623    case STOPPING:
6624    case STOPPED:
6625    case DESTROYED:
6626    default:
6627        return false;
6628    }
6629}
6630
6631bool AudioFlinger::EffectModule::isProcessEnabled()
6632{
6633    switch (mState) {
6634    case RESTART:
6635    case ACTIVE:
6636    case STOPPING:
6637    case STOPPED:
6638        return true;
6639    case IDLE:
6640    case STARTING:
6641    case DESTROYED:
6642    default:
6643        return false;
6644    }
6645}
6646
6647status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6648{
6649    Mutex::Autolock _l(mLock);
6650    status_t status = NO_ERROR;
6651
6652    // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6653    // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
6654    if (isProcessEnabled() &&
6655            ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6656            (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
6657        status_t cmdStatus;
6658        uint32_t volume[2];
6659        uint32_t *pVolume = NULL;
6660        uint32_t size = sizeof(volume);
6661        volume[0] = *left;
6662        volume[1] = *right;
6663        if (controller) {
6664            pVolume = volume;
6665        }
6666        status = (*mEffectInterface)->command(mEffectInterface,
6667                                              EFFECT_CMD_SET_VOLUME,
6668                                              size,
6669                                              volume,
6670                                              &size,
6671                                              pVolume);
6672        if (controller && status == NO_ERROR && size == sizeof(volume)) {
6673            *left = volume[0];
6674            *right = volume[1];
6675        }
6676    }
6677    return status;
6678}
6679
6680status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6681{
6682    Mutex::Autolock _l(mLock);
6683    status_t status = NO_ERROR;
6684    if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6685        // audio pre processing modules on RecordThread can receive both output and
6686        // input device indication in the same call
6687        uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6688        if (dev) {
6689            status_t cmdStatus;
6690            uint32_t size = sizeof(status_t);
6691
6692            status = (*mEffectInterface)->command(mEffectInterface,
6693                                                  EFFECT_CMD_SET_DEVICE,
6694                                                  sizeof(uint32_t),
6695                                                  &dev,
6696                                                  &size,
6697                                                  &cmdStatus);
6698            if (status == NO_ERROR) {
6699                status = cmdStatus;
6700            }
6701        }
6702        dev = device & AUDIO_DEVICE_IN_ALL;
6703        if (dev) {
6704            status_t cmdStatus;
6705            uint32_t size = sizeof(status_t);
6706
6707            status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6708                                                  EFFECT_CMD_SET_INPUT_DEVICE,
6709                                                  sizeof(uint32_t),
6710                                                  &dev,
6711                                                  &size,
6712                                                  &cmdStatus);
6713            if (status2 == NO_ERROR) {
6714                status2 = cmdStatus;
6715            }
6716            if (status == NO_ERROR) {
6717                status = status2;
6718            }
6719        }
6720    }
6721    return status;
6722}
6723
6724status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
6725{
6726    Mutex::Autolock _l(mLock);
6727    status_t status = NO_ERROR;
6728    if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
6729        status_t cmdStatus;
6730        uint32_t size = sizeof(status_t);
6731        status = (*mEffectInterface)->command(mEffectInterface,
6732                                              EFFECT_CMD_SET_AUDIO_MODE,
6733                                              sizeof(audio_mode_t),
6734                                              &mode,
6735                                              &size,
6736                                              &cmdStatus);
6737        if (status == NO_ERROR) {
6738            status = cmdStatus;
6739        }
6740    }
6741    return status;
6742}
6743
6744void AudioFlinger::EffectModule::setSuspended(bool suspended)
6745{
6746    Mutex::Autolock _l(mLock);
6747    mSuspended = suspended;
6748}
6749
6750bool AudioFlinger::EffectModule::suspended() const
6751{
6752    Mutex::Autolock _l(mLock);
6753    return mSuspended;
6754}
6755
6756status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6757{
6758    const size_t SIZE = 256;
6759    char buffer[SIZE];
6760    String8 result;
6761
6762    snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6763    result.append(buffer);
6764
6765    bool locked = tryLock(mLock);
6766    // failed to lock - AudioFlinger is probably deadlocked
6767    if (!locked) {
6768        result.append("\t\tCould not lock Fx mutex:\n");
6769    }
6770
6771    result.append("\t\tSession Status State Engine:\n");
6772    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   0x%08x\n",
6773            mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6774    result.append(buffer);
6775
6776    result.append("\t\tDescriptor:\n");
6777    snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6778            mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6779            mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6780            mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6781    result.append(buffer);
6782    snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6783                mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6784                mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6785                mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6786    result.append(buffer);
6787    snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
6788            mDescriptor.apiVersion,
6789            mDescriptor.flags);
6790    result.append(buffer);
6791    snprintf(buffer, SIZE, "\t\t- name: %s\n",
6792            mDescriptor.name);
6793    result.append(buffer);
6794    snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6795            mDescriptor.implementor);
6796    result.append(buffer);
6797
6798    result.append("\t\t- Input configuration:\n");
6799    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
6800    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
6801            (uint32_t)mConfig.inputCfg.buffer.raw,
6802            mConfig.inputCfg.buffer.frameCount,
6803            mConfig.inputCfg.samplingRate,
6804            mConfig.inputCfg.channels,
6805            mConfig.inputCfg.format);
6806    result.append(buffer);
6807
6808    result.append("\t\t- Output configuration:\n");
6809    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
6810    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
6811            (uint32_t)mConfig.outputCfg.buffer.raw,
6812            mConfig.outputCfg.buffer.frameCount,
6813            mConfig.outputCfg.samplingRate,
6814            mConfig.outputCfg.channels,
6815            mConfig.outputCfg.format);
6816    result.append(buffer);
6817
6818    snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6819    result.append(buffer);
6820    result.append("\t\t\tPid   Priority Ctrl Locked client server\n");
6821    for (size_t i = 0; i < mHandles.size(); ++i) {
6822        sp<EffectHandle> handle = mHandles[i].promote();
6823        if (handle != 0) {
6824            handle->dump(buffer, SIZE);
6825            result.append(buffer);
6826        }
6827    }
6828
6829    result.append("\n");
6830
6831    write(fd, result.string(), result.length());
6832
6833    if (locked) {
6834        mLock.unlock();
6835    }
6836
6837    return NO_ERROR;
6838}
6839
6840// ----------------------------------------------------------------------------
6841//  EffectHandle implementation
6842// ----------------------------------------------------------------------------
6843
6844#undef LOG_TAG
6845#define LOG_TAG "AudioFlinger::EffectHandle"
6846
6847AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6848                                        const sp<AudioFlinger::Client>& client,
6849                                        const sp<IEffectClient>& effectClient,
6850                                        int32_t priority)
6851    : BnEffect(),
6852    mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
6853    mPriority(priority), mHasControl(false), mEnabled(false)
6854{
6855    ALOGV("constructor %p", this);
6856
6857    if (client == 0) {
6858        return;
6859    }
6860    int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6861    mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6862    if (mCblkMemory != 0) {
6863        mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6864
6865        if (mCblk) {
6866            new(mCblk) effect_param_cblk_t();
6867            mBuffer = (uint8_t *)mCblk + bufOffset;
6868         }
6869    } else {
6870        ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6871        return;
6872    }
6873}
6874
6875AudioFlinger::EffectHandle::~EffectHandle()
6876{
6877    ALOGV("Destructor %p", this);
6878    disconnect(false);
6879    ALOGV("Destructor DONE %p", this);
6880}
6881
6882status_t AudioFlinger::EffectHandle::enable()
6883{
6884    ALOGV("enable %p", this);
6885    if (!mHasControl) return INVALID_OPERATION;
6886    if (mEffect == 0) return DEAD_OBJECT;
6887
6888    if (mEnabled) {
6889        return NO_ERROR;
6890    }
6891
6892    mEnabled = true;
6893
6894    sp<ThreadBase> thread = mEffect->thread().promote();
6895    if (thread != 0) {
6896        thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6897    }
6898
6899    // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6900    if (mEffect->suspended()) {
6901        return NO_ERROR;
6902    }
6903
6904    status_t status = mEffect->setEnabled(true);
6905    if (status != NO_ERROR) {
6906        if (thread != 0) {
6907            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6908        }
6909        mEnabled = false;
6910    }
6911    return status;
6912}
6913
6914status_t AudioFlinger::EffectHandle::disable()
6915{
6916    ALOGV("disable %p", this);
6917    if (!mHasControl) return INVALID_OPERATION;
6918    if (mEffect == 0) return DEAD_OBJECT;
6919
6920    if (!mEnabled) {
6921        return NO_ERROR;
6922    }
6923    mEnabled = false;
6924
6925    if (mEffect->suspended()) {
6926        return NO_ERROR;
6927    }
6928
6929    status_t status = mEffect->setEnabled(false);
6930
6931    sp<ThreadBase> thread = mEffect->thread().promote();
6932    if (thread != 0) {
6933        thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6934    }
6935
6936    return status;
6937}
6938
6939void AudioFlinger::EffectHandle::disconnect()
6940{
6941    disconnect(true);
6942}
6943
6944void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6945{
6946    ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
6947    if (mEffect == 0) {
6948        return;
6949    }
6950    mEffect->disconnect(this, unpiniflast);
6951
6952    if (mHasControl && mEnabled) {
6953        sp<ThreadBase> thread = mEffect->thread().promote();
6954        if (thread != 0) {
6955            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6956        }
6957    }
6958
6959    // release sp on module => module destructor can be called now
6960    mEffect.clear();
6961    if (mClient != 0) {
6962        if (mCblk) {
6963            mCblk->~effect_param_cblk_t();   // destroy our shared-structure.
6964        }
6965        mCblkMemory.clear();            // and free the shared memory
6966        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6967        mClient.clear();
6968    }
6969}
6970
6971status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6972                                             uint32_t cmdSize,
6973                                             void *pCmdData,
6974                                             uint32_t *replySize,
6975                                             void *pReplyData)
6976{
6977//    ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6978//              cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
6979
6980    // only get parameter command is permitted for applications not controlling the effect
6981    if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6982        return INVALID_OPERATION;
6983    }
6984    if (mEffect == 0) return DEAD_OBJECT;
6985    if (mClient == 0) return INVALID_OPERATION;
6986
6987    // handle commands that are not forwarded transparently to effect engine
6988    if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6989        // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6990        // no risk to block the whole media server process or mixer threads is we are stuck here
6991        Mutex::Autolock _l(mCblk->lock);
6992        if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6993            mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6994            mCblk->serverIndex = 0;
6995            mCblk->clientIndex = 0;
6996            return BAD_VALUE;
6997        }
6998        status_t status = NO_ERROR;
6999        while (mCblk->serverIndex < mCblk->clientIndex) {
7000            int reply;
7001            uint32_t rsize = sizeof(int);
7002            int *p = (int *)(mBuffer + mCblk->serverIndex);
7003            int size = *p++;
7004            if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
7005                ALOGW("command(): invalid parameter block size");
7006                break;
7007            }
7008            effect_param_t *param = (effect_param_t *)p;
7009            if (param->psize == 0 || param->vsize == 0) {
7010                ALOGW("command(): null parameter or value size");
7011                mCblk->serverIndex += size;
7012                continue;
7013            }
7014            uint32_t psize = sizeof(effect_param_t) +
7015                             ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7016                             param->vsize;
7017            status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7018                                            psize,
7019                                            p,
7020                                            &rsize,
7021                                            &reply);
7022            // stop at first error encountered
7023            if (ret != NO_ERROR) {
7024                status = ret;
7025                *(int *)pReplyData = reply;
7026                break;
7027            } else if (reply != NO_ERROR) {
7028                *(int *)pReplyData = reply;
7029                break;
7030            }
7031            mCblk->serverIndex += size;
7032        }
7033        mCblk->serverIndex = 0;
7034        mCblk->clientIndex = 0;
7035        return status;
7036    } else if (cmdCode == EFFECT_CMD_ENABLE) {
7037        *(int *)pReplyData = NO_ERROR;
7038        return enable();
7039    } else if (cmdCode == EFFECT_CMD_DISABLE) {
7040        *(int *)pReplyData = NO_ERROR;
7041        return disable();
7042    }
7043
7044    return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7045}
7046
7047sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7048    return mCblkMemory;
7049}
7050
7051void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
7052{
7053    ALOGV("setControl %p control %d", this, hasControl);
7054
7055    mHasControl = hasControl;
7056    mEnabled = enabled;
7057
7058    if (signal && mEffectClient != 0) {
7059        mEffectClient->controlStatusChanged(hasControl);
7060    }
7061}
7062
7063void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7064                                                 uint32_t cmdSize,
7065                                                 void *pCmdData,
7066                                                 uint32_t replySize,
7067                                                 void *pReplyData)
7068{
7069    if (mEffectClient != 0) {
7070        mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7071    }
7072}
7073
7074
7075
7076void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7077{
7078    if (mEffectClient != 0) {
7079        mEffectClient->enableStatusChanged(enabled);
7080    }
7081}
7082
7083status_t AudioFlinger::EffectHandle::onTransact(
7084    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7085{
7086    return BnEffect::onTransact(code, data, reply, flags);
7087}
7088
7089
7090void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7091{
7092    bool locked = mCblk ? tryLock(mCblk->lock) : false;
7093
7094    snprintf(buffer, size, "\t\t\t%05d %05d    %01u    %01u      %05u  %05u\n",
7095            (mClient == NULL) ? getpid() : mClient->pid(),
7096            mPriority,
7097            mHasControl,
7098            !locked,
7099            mCblk ? mCblk->clientIndex : 0,
7100            mCblk ? mCblk->serverIndex : 0
7101            );
7102
7103    if (locked) {
7104        mCblk->lock.unlock();
7105    }
7106}
7107
7108#undef LOG_TAG
7109#define LOG_TAG "AudioFlinger::EffectChain"
7110
7111AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7112                                        int sessionId)
7113    : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
7114      mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7115      mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
7116{
7117    mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
7118    sp<ThreadBase> thread = mThread.promote();
7119    if (thread == 0) {
7120        return;
7121    }
7122    mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7123                                    thread->frameCount();
7124}
7125
7126AudioFlinger::EffectChain::~EffectChain()
7127{
7128    if (mOwnInBuffer) {
7129        delete mInBuffer;
7130    }
7131
7132}
7133
7134// getEffectFromDesc_l() must be called with ThreadBase::mLock held
7135sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
7136{
7137    sp<EffectModule> effect;
7138    size_t size = mEffects.size();
7139
7140    for (size_t i = 0; i < size; i++) {
7141        if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7142            effect = mEffects[i];
7143            break;
7144        }
7145    }
7146    return effect;
7147}
7148
7149// getEffectFromId_l() must be called with ThreadBase::mLock held
7150sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
7151{
7152    sp<EffectModule> effect;
7153    size_t size = mEffects.size();
7154
7155    for (size_t i = 0; i < size; i++) {
7156        // by convention, return first effect if id provided is 0 (0 is never a valid id)
7157        if (id == 0 || mEffects[i]->id() == id) {
7158            effect = mEffects[i];
7159            break;
7160        }
7161    }
7162    return effect;
7163}
7164
7165// getEffectFromType_l() must be called with ThreadBase::mLock held
7166sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7167        const effect_uuid_t *type)
7168{
7169    sp<EffectModule> effect;
7170    size_t size = mEffects.size();
7171
7172    for (size_t i = 0; i < size; i++) {
7173        if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7174            effect = mEffects[i];
7175            break;
7176        }
7177    }
7178    return effect;
7179}
7180
7181// Must be called with EffectChain::mLock locked
7182void AudioFlinger::EffectChain::process_l()
7183{
7184    sp<ThreadBase> thread = mThread.promote();
7185    if (thread == 0) {
7186        ALOGW("process_l(): cannot promote mixer thread");
7187        return;
7188    }
7189    bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7190            (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
7191    // always process effects unless no more tracks are on the session and the effect tail
7192    // has been rendered
7193    bool doProcess = true;
7194    if (!isGlobalSession) {
7195        bool tracksOnSession = (trackCnt() != 0);
7196
7197        if (!tracksOnSession && mTailBufferCount == 0) {
7198            doProcess = false;
7199        }
7200
7201        if (activeTrackCnt() == 0) {
7202            // if no track is active and the effect tail has not been rendered,
7203            // the input buffer must be cleared here as the mixer process will not do it
7204            if (tracksOnSession || mTailBufferCount > 0) {
7205                size_t numSamples = thread->frameCount() * thread->channelCount();
7206                memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7207                if (mTailBufferCount > 0) {
7208                    mTailBufferCount--;
7209                }
7210            }
7211        }
7212    }
7213
7214    size_t size = mEffects.size();
7215    if (doProcess) {
7216        for (size_t i = 0; i < size; i++) {
7217            mEffects[i]->process();
7218        }
7219    }
7220    for (size_t i = 0; i < size; i++) {
7221        mEffects[i]->updateState();
7222    }
7223}
7224
7225// addEffect_l() must be called with PlaybackThread::mLock held
7226status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
7227{
7228    effect_descriptor_t desc = effect->desc();
7229    uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7230
7231    Mutex::Autolock _l(mLock);
7232    effect->setChain(this);
7233    sp<ThreadBase> thread = mThread.promote();
7234    if (thread == 0) {
7235        return NO_INIT;
7236    }
7237    effect->setThread(thread);
7238
7239    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7240        // Auxiliary effects are inserted at the beginning of mEffects vector as
7241        // they are processed first and accumulated in chain input buffer
7242        mEffects.insertAt(effect, 0);
7243
7244        // the input buffer for auxiliary effect contains mono samples in
7245        // 32 bit format. This is to avoid saturation in AudoMixer
7246        // accumulation stage. Saturation is done in EffectModule::process() before
7247        // calling the process in effect engine
7248        size_t numSamples = thread->frameCount();
7249        int32_t *buffer = new int32_t[numSamples];
7250        memset(buffer, 0, numSamples * sizeof(int32_t));
7251        effect->setInBuffer((int16_t *)buffer);
7252        // auxiliary effects output samples to chain input buffer for further processing
7253        // by insert effects
7254        effect->setOutBuffer(mInBuffer);
7255    } else {
7256        // Insert effects are inserted at the end of mEffects vector as they are processed
7257        //  after track and auxiliary effects.
7258        // Insert effect order as a function of indicated preference:
7259        //  if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7260        //  another effect is present
7261        //  else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7262        //  last effect claiming first position
7263        //  else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7264        //  first effect claiming last position
7265        //  else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7266        // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7267        // already present
7268
7269        int size = (int)mEffects.size();
7270        int idx_insert = size;
7271        int idx_insert_first = -1;
7272        int idx_insert_last = -1;
7273
7274        for (int i = 0; i < size; i++) {
7275            effect_descriptor_t d = mEffects[i]->desc();
7276            uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7277            uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7278            if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7279                // check invalid effect chaining combinations
7280                if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7281                    iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
7282                    ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
7283                    return INVALID_OPERATION;
7284                }
7285                // remember position of first insert effect and by default
7286                // select this as insert position for new effect
7287                if (idx_insert == size) {
7288                    idx_insert = i;
7289                }
7290                // remember position of last insert effect claiming
7291                // first position
7292                if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7293                    idx_insert_first = i;
7294                }
7295                // remember position of first insert effect claiming
7296                // last position
7297                if (iPref == EFFECT_FLAG_INSERT_LAST &&
7298                    idx_insert_last == -1) {
7299                    idx_insert_last = i;
7300                }
7301            }
7302        }
7303
7304        // modify idx_insert from first position if needed
7305        if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7306            if (idx_insert_last != -1) {
7307                idx_insert = idx_insert_last;
7308            } else {
7309                idx_insert = size;
7310            }
7311        } else {
7312            if (idx_insert_first != -1) {
7313                idx_insert = idx_insert_first + 1;
7314            }
7315        }
7316
7317        // always read samples from chain input buffer
7318        effect->setInBuffer(mInBuffer);
7319
7320        // if last effect in the chain, output samples to chain
7321        // output buffer, otherwise to chain input buffer
7322        if (idx_insert == size) {
7323            if (idx_insert != 0) {
7324                mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7325                mEffects[idx_insert-1]->configure();
7326            }
7327            effect->setOutBuffer(mOutBuffer);
7328        } else {
7329            effect->setOutBuffer(mInBuffer);
7330        }
7331        mEffects.insertAt(effect, idx_insert);
7332
7333        ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
7334    }
7335    effect->configure();
7336    return NO_ERROR;
7337}
7338
7339// removeEffect_l() must be called with PlaybackThread::mLock held
7340size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
7341{
7342    Mutex::Autolock _l(mLock);
7343    int size = (int)mEffects.size();
7344    int i;
7345    uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7346
7347    for (i = 0; i < size; i++) {
7348        if (effect == mEffects[i]) {
7349            // calling stop here will remove pre-processing effect from the audio HAL.
7350            // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7351            // the middle of a read from audio HAL
7352            if (mEffects[i]->state() == EffectModule::ACTIVE ||
7353                    mEffects[i]->state() == EffectModule::STOPPING) {
7354                mEffects[i]->stop();
7355            }
7356            if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7357                delete[] effect->inBuffer();
7358            } else {
7359                if (i == size - 1 && i != 0) {
7360                    mEffects[i - 1]->setOutBuffer(mOutBuffer);
7361                    mEffects[i - 1]->configure();
7362                }
7363            }
7364            mEffects.removeAt(i);
7365            ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
7366            break;
7367        }
7368    }
7369
7370    return mEffects.size();
7371}
7372
7373// setDevice_l() must be called with PlaybackThread::mLock held
7374void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
7375{
7376    size_t size = mEffects.size();
7377    for (size_t i = 0; i < size; i++) {
7378        mEffects[i]->setDevice(device);
7379    }
7380}
7381
7382// setMode_l() must be called with PlaybackThread::mLock held
7383void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
7384{
7385    size_t size = mEffects.size();
7386    for (size_t i = 0; i < size; i++) {
7387        mEffects[i]->setMode(mode);
7388    }
7389}
7390
7391// setVolume_l() must be called with PlaybackThread::mLock held
7392bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
7393{
7394    uint32_t newLeft = *left;
7395    uint32_t newRight = *right;
7396    bool hasControl = false;
7397    int ctrlIdx = -1;
7398    size_t size = mEffects.size();
7399
7400    // first update volume controller
7401    for (size_t i = size; i > 0; i--) {
7402        if (mEffects[i - 1]->isProcessEnabled() &&
7403            (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7404            ctrlIdx = i - 1;
7405            hasControl = true;
7406            break;
7407        }
7408    }
7409
7410    if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
7411        if (hasControl) {
7412            *left = mNewLeftVolume;
7413            *right = mNewRightVolume;
7414        }
7415        return hasControl;
7416    }
7417
7418    mVolumeCtrlIdx = ctrlIdx;
7419    mLeftVolume = newLeft;
7420    mRightVolume = newRight;
7421
7422    // second get volume update from volume controller
7423    if (ctrlIdx >= 0) {
7424        mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
7425        mNewLeftVolume = newLeft;
7426        mNewRightVolume = newRight;
7427    }
7428    // then indicate volume to all other effects in chain.
7429    // Pass altered volume to effects before volume controller
7430    // and requested volume to effects after controller
7431    uint32_t lVol = newLeft;
7432    uint32_t rVol = newRight;
7433
7434    for (size_t i = 0; i < size; i++) {
7435        if ((int)i == ctrlIdx) continue;
7436        // this also works for ctrlIdx == -1 when there is no volume controller
7437        if ((int)i > ctrlIdx) {
7438            lVol = *left;
7439            rVol = *right;
7440        }
7441        mEffects[i]->setVolume(&lVol, &rVol, false);
7442    }
7443    *left = newLeft;
7444    *right = newRight;
7445
7446    return hasControl;
7447}
7448
7449status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7450{
7451    const size_t SIZE = 256;
7452    char buffer[SIZE];
7453    String8 result;
7454
7455    snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7456    result.append(buffer);
7457
7458    bool locked = tryLock(mLock);
7459    // failed to lock - AudioFlinger is probably deadlocked
7460    if (!locked) {
7461        result.append("\tCould not lock mutex:\n");
7462    }
7463
7464    result.append("\tNum fx In buffer   Out buffer   Active tracks:\n");
7465    snprintf(buffer, SIZE, "\t%02d     0x%08x  0x%08x   %d\n",
7466            mEffects.size(),
7467            (uint32_t)mInBuffer,
7468            (uint32_t)mOutBuffer,
7469            mActiveTrackCnt);
7470    result.append(buffer);
7471    write(fd, result.string(), result.size());
7472
7473    for (size_t i = 0; i < mEffects.size(); ++i) {
7474        sp<EffectModule> effect = mEffects[i];
7475        if (effect != 0) {
7476            effect->dump(fd, args);
7477        }
7478    }
7479
7480    if (locked) {
7481        mLock.unlock();
7482    }
7483
7484    return NO_ERROR;
7485}
7486
7487// must be called with ThreadBase::mLock held
7488void AudioFlinger::EffectChain::setEffectSuspended_l(
7489        const effect_uuid_t *type, bool suspend)
7490{
7491    sp<SuspendedEffectDesc> desc;
7492    // use effect type UUID timelow as key as there is no real risk of identical
7493    // timeLow fields among effect type UUIDs.
7494    int index = mSuspendedEffects.indexOfKey(type->timeLow);
7495    if (suspend) {
7496        if (index >= 0) {
7497            desc = mSuspendedEffects.valueAt(index);
7498        } else {
7499            desc = new SuspendedEffectDesc();
7500            memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7501            mSuspendedEffects.add(type->timeLow, desc);
7502            ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7503        }
7504        if (desc->mRefCount++ == 0) {
7505            sp<EffectModule> effect = getEffectIfEnabled(type);
7506            if (effect != 0) {
7507                desc->mEffect = effect;
7508                effect->setSuspended(true);
7509                effect->setEnabled(false);
7510            }
7511        }
7512    } else {
7513        if (index < 0) {
7514            return;
7515        }
7516        desc = mSuspendedEffects.valueAt(index);
7517        if (desc->mRefCount <= 0) {
7518            ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7519            desc->mRefCount = 1;
7520        }
7521        if (--desc->mRefCount == 0) {
7522            ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7523            if (desc->mEffect != 0) {
7524                sp<EffectModule> effect = desc->mEffect.promote();
7525                if (effect != 0) {
7526                    effect->setSuspended(false);
7527                    sp<EffectHandle> handle = effect->controlHandle();
7528                    if (handle != 0) {
7529                        effect->setEnabled(handle->enabled());
7530                    }
7531                }
7532                desc->mEffect.clear();
7533            }
7534            mSuspendedEffects.removeItemsAt(index);
7535        }
7536    }
7537}
7538
7539// must be called with ThreadBase::mLock held
7540void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7541{
7542    sp<SuspendedEffectDesc> desc;
7543
7544    int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7545    if (suspend) {
7546        if (index >= 0) {
7547            desc = mSuspendedEffects.valueAt(index);
7548        } else {
7549            desc = new SuspendedEffectDesc();
7550            mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7551            ALOGV("setEffectSuspendedAll_l() add entry for 0");
7552        }
7553        if (desc->mRefCount++ == 0) {
7554            Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7555            for (size_t i = 0; i < effects.size(); i++) {
7556                setEffectSuspended_l(&effects[i]->desc().type, true);
7557            }
7558        }
7559    } else {
7560        if (index < 0) {
7561            return;
7562        }
7563        desc = mSuspendedEffects.valueAt(index);
7564        if (desc->mRefCount <= 0) {
7565            ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7566            desc->mRefCount = 1;
7567        }
7568        if (--desc->mRefCount == 0) {
7569            Vector<const effect_uuid_t *> types;
7570            for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7571                if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7572                    continue;
7573                }
7574                types.add(&mSuspendedEffects.valueAt(i)->mType);
7575            }
7576            for (size_t i = 0; i < types.size(); i++) {
7577                setEffectSuspended_l(types[i], false);
7578            }
7579            ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7580            mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7581        }
7582    }
7583}
7584
7585
7586// The volume effect is used for automated tests only
7587#ifndef OPENSL_ES_H_
7588static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7589                                            { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7590const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7591#endif //OPENSL_ES_H_
7592
7593bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7594{
7595    // auxiliary effects and visualizer are never suspended on output mix
7596    if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7597        (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
7598         (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7599         (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
7600        return false;
7601    }
7602    return true;
7603}
7604
7605Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7606{
7607    Vector< sp<EffectModule> > effects;
7608    for (size_t i = 0; i < mEffects.size(); i++) {
7609        if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
7610            continue;
7611        }
7612        effects.add(mEffects[i]);
7613    }
7614    return effects;
7615}
7616
7617sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7618                                                            const effect_uuid_t *type)
7619{
7620    sp<EffectModule> effect;
7621    effect = getEffectFromType_l(type);
7622    if (effect != 0 && !effect->isEnabled()) {
7623        effect.clear();
7624    }
7625    return effect;
7626}
7627
7628void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7629                                                            bool enabled)
7630{
7631    int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7632    if (enabled) {
7633        if (index < 0) {
7634            // if the effect is not suspend check if all effects are suspended
7635            index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7636            if (index < 0) {
7637                return;
7638            }
7639            if (!isEffectEligibleForSuspend(effect->desc())) {
7640                return;
7641            }
7642            setEffectSuspended_l(&effect->desc().type, enabled);
7643            index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7644            if (index < 0) {
7645                ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7646                return;
7647            }
7648        }
7649        ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7650             effect->desc().type.timeLow);
7651        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7652        // if effect is requested to suspended but was not yet enabled, supend it now.
7653        if (desc->mEffect == 0) {
7654            desc->mEffect = effect;
7655            effect->setEnabled(false);
7656            effect->setSuspended(true);
7657        }
7658    } else {
7659        if (index < 0) {
7660            return;
7661        }
7662        ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7663             effect->desc().type.timeLow);
7664        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7665        desc->mEffect.clear();
7666        effect->setSuspended(false);
7667    }
7668}
7669
7670#undef LOG_TAG
7671#define LOG_TAG "AudioFlinger"
7672
7673// ----------------------------------------------------------------------------
7674
7675status_t AudioFlinger::onTransact(
7676        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7677{
7678    return BnAudioFlinger::onTransact(code, data, reply, flags);
7679}
7680
7681}; // namespace android
7682