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