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