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