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