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