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