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