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