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