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