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