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