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