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