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