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