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