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